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
lk-eternal/AI-Assistant-Plus
src/main/java/lk/eternal/ai/controller/LKController.java
[ { "identifier": "User", "path": "src/main/java/lk/eternal/ai/domain/User.java", "snippet": "public class User {\n\n private final String id;\n private final LinkedList<Message> messages;\n private final Map<String, Object> properties;\n private Status status;\n\n public User(String id) {\n this.id = id;\n this.messages = new LinkedList<>();\n this.properties = new HashMap<>();\n this.status = Status.WAITING;\n }\n\n public String getId() {\n return id;\n }\n\n public synchronized Status getStatus() {\n return status;\n }\n\n public synchronized void setStatus(Status status) {\n this.status = status;\n }\n\n public LinkedList<Message> getMessages() {\n return messages;\n }\n\n public void putProperty(String key, Object value) {\n this.properties.put(key, value);\n }\n\n public Object getProperty(String key) {\n return this.properties.get(key);\n }\n\n public String getAiModel() {\n return getProperty(\"aiModel\").toString();\n }\n\n public String getPluginModel() {\n return getProperty(\"pluginModel\").toString();\n }\n\n public String getGpt4Code() {\n return getProperty(\"gpt4Code\").toString();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<String> getPlugins(){\n return (List<String>) Optional.ofNullable(getProperty(\"plugins\"))\n .filter(ps -> ps instanceof List)\n .orElse(null);\n }\n\n public void clear(){\n this.messages.clear();\n }\n\n public Map<String, Object> getPluginProperties(String pluginName) {\n final var keyPre = \"plugin-%s-\".formatted(pluginName);\n return this.properties.entrySet().stream()\n .filter(e -> e.getKey().startsWith(keyPre))\n .collect(Collectors.toMap(e -> e.getKey().substring(keyPre.length()), Map.Entry::getValue));\n }\n\n public enum Status {\n TYING,\n STOPPING,\n WAITING\n }\n}" }, { "identifier": "Message", "path": "src/main/java/lk/eternal/ai/dto/req/Message.java", "snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\n@JsonIgnoreProperties(\"think\")\npublic final class Message {\n private String role;\n private String content;\n private List<GPTResp.ToolCall> tool_calls;\n private String tool_call_id;\n private String name;\n private Boolean think;\n\n public Message() {\n }\n\n public Message(String role, String content, List<GPTResp.ToolCall> tool_calls, String tool_call_id, String name,\n Boolean think) {\n this.role = role;\n this.content = content;\n this.tool_calls = tool_calls;\n this.tool_call_id = tool_call_id;\n this.name = name;\n this.think = think;\n }\n\n public static Message create(String role, String content, boolean isThink) {\n return new Message(role, content, null, null, null, isThink);\n }\n\n public static Message create(String role, String content, List<GPTResp.ToolCall> tool_calls) {\n return new Message(role, content, tool_calls, null, null, true);\n }\n\n public static Message create(String role, String id, String name, String content) {\n return new Message(role, content, null, id, name, true);\n }\n\n public static Message user(String content) {\n return new Message(\"user\", content, null, null, null, false);\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 List<GPTResp.ToolCall> getTool_calls() {\n return tool_calls;\n }\n\n public void setTool_calls(List<GPTResp.ToolCall> tool_calls) {\n this.tool_calls = tool_calls;\n }\n\n public String getTool_call_id() {\n return tool_call_id;\n }\n\n public void setTool_call_id(String tool_call_id) {\n this.tool_call_id = tool_call_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 Boolean getThink() {\n return think;\n }\n\n public void setThink(Boolean think) {\n this.think = think;\n }\n}" }, { "identifier": "ApiUnauthorizedException", "path": "src/main/java/lk/eternal/ai/exception/ApiUnauthorizedException.java", "snippet": "public class ApiUnauthorizedException extends RuntimeException {\n public ApiUnauthorizedException(String message) {\n super(message);\n }\n}" }, { "identifier": "ApiValidationException", "path": "src/main/java/lk/eternal/ai/exception/ApiValidationException.java", "snippet": "public class ApiValidationException extends RuntimeException {\n\n public ApiValidationException(String message) {\n super(message);\n }\n}" }, { "identifier": "AiModel", "path": "src/main/java/lk/eternal/ai/model/ai/AiModel.java", "snippet": "public interface AiModel {\n\n String getName();\n\n void request(String prompt, List<Message> messages, List<String> stop, List<Tool> tools, Supplier<Boolean> stopCheck, Consumer<GPTResp> respConsumer) throws GPTException;\n\n String getToolRole();\n\n String getModelRole();\n}" }, { "identifier": "ChatGPTAiModel", "path": "src/main/java/lk/eternal/ai/model/ai/ChatGPTAiModel.java", "snippet": "public class ChatGPTAiModel implements AiModel {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ChatGPTAiModel.class);\n\n private static final HttpClient HTTP_CLIENT;\n\n static {\n final var builder = HttpClient.newBuilder()\n .version(HttpClient.Version.HTTP_1_1)\n .connectTimeout(Duration.ofMinutes(1));\n if (ProxySelector.getDefault() != null) {\n builder.proxy(ProxySelector.getDefault());\n }\n HTTP_CLIENT = builder.build();\n }\n\n private final String openaiApiKey;\n private final String openaiApiUrl;\n private final String name;\n private final String model;\n\n public ChatGPTAiModel(String openaiApiKey, String openaiApiUrl, String name, String model) {\n this.openaiApiKey = openaiApiKey;\n this.openaiApiUrl = openaiApiUrl;\n this.name = name;\n this.model = model;\n }\n\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public void request(String prompt, List<Message> messages, List<String> stop, List<Tool> tools, Supplier<Boolean> stopCheck, Consumer<GPTResp> respConsumer) throws GPTException {\n final var requestMessages = new LinkedList<>(messages);\n if (prompt != null) {\n requestMessages.addFirst(Message.create(\"system\", prompt, false));\n }\n final var gptReq = new GPTReq(this.model, requestMessages, stop, tools, true);\n final var reqStr = Optional.ofNullable(Mapper.writeAsStringNotError(gptReq))\n .orElseThrow(() -> new GPTException(\"req can not be null\"));\n\n final HttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(this.openaiApiUrl))\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", \"Bearer \" + this.openaiApiKey)\n .POST(HttpRequest.BodyPublishers.ofString(reqStr))\n .build();\n\n final HttpResponse<InputStream> response;\n try {\n response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofInputStream());\n\n // 读取返回的流式数据\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {\n String line;\n while (!stopCheck.get() && (line = reader.readLine()) != null) {\n if (line.isBlank()) {\n continue;\n }\n final var gptResp = Mapper.readValueNotError(line.substring(line.indexOf(\"{\")), GPTResp.class);\n if (gptResp == null) {\n continue;\n }\n if (gptResp.choices().get(0).getFinish_reason() != null) {\n break;\n }\n respConsumer.accept(gptResp);\n }\n }\n } catch (IOException | InterruptedException e) {\n LOGGER.error(\"请求OpenAI失败: {}\", e.getMessage(), e);\n throw new GPTException(\"请求OpenAI失败: \" + e.getMessage());\n }\n }\n\n @Override\n public String getToolRole() {\n return \"system\";\n }\n\n @Override\n public String getModelRole() {\n return \"assistant\";\n }\n}" }, { "identifier": "GeminiAiModel", "path": "src/main/java/lk/eternal/ai/model/ai/GeminiAiModel.java", "snippet": "@Component\npublic class GeminiAiModel implements AiModel {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(GeminiAiModel.class);\n\n private final HttpClient HTTP_CLIENT;\n\n @Value(\"${google.gemini.key}\")\n private String key;\n\n public GeminiAiModel(ProxySelector proxySelector) {\n HTTP_CLIENT = HttpClient.newBuilder()\n .version(HttpClient.Version.HTTP_1_1)\n .connectTimeout(Duration.ofMinutes(1))\n .proxy(proxySelector).build();\n }\n\n @Override\n public String getName() {\n return \"gemini\";\n }\n\n @Override\n public void request(String prompt, List<Message> messages, List<String> stop, List<Tool> tools, Supplier<Boolean> stopCheck, Consumer<GPTResp> respConsumer) throws GPTException {\n final var contents = messages.stream().map(m -> GeminiReq.Content.create(m.getRole(), m.getContent())).collect(Collectors.toList());\n final var requestMessages = new LinkedList<>(contents);\n if (prompt != null) {\n requestMessages.addFirst(GeminiReq.Content.create(\"user\", prompt));\n requestMessages.add(1, GeminiReq.Content.create(\"model\", \"好的,我明白了.\"));\n }\n final var geminiReq = new GeminiReq(requestMessages);\n final var reqStr = Optional.ofNullable(Mapper.writeAsStringNotError(geminiReq))\n .orElseThrow(() -> new GPTException(\"req can not be null\"));\n\n final HttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(\"https://generativelanguage.googleapis.com/v1beta/models/\" + \"gemini-pro\" + \":streamGenerateContent?key=\" + this.key))\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(reqStr))\n .build();\n\n final HttpResponse<InputStream> response;\n try {\n response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofInputStream());\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {\n StringBuilder jsonText = new StringBuilder();\n String line;\n while (!stopCheck.get() && (line = reader.readLine()) != null) {\n if (line.isBlank()) {\n continue;\n }\n if (line.equals(\",\")) {\n jsonText = new StringBuilder();\n continue;\n }\n if (line.equals(\"[{\")) {\n jsonText.append(\"{\");\n } else {\n jsonText.append(line);\n }\n if (line.equals(\"}\")) {\n final var geminiResp = Mapper.readValueNotError(jsonText.toString(), GeminiResp.class);\n if (geminiResp == null) {\n throw new RuntimeException(\"Not response\");\n }\n if (geminiResp.getError() != null) {\n throw new RuntimeException(geminiResp.getError().getMessage());\n }\n respConsumer.accept(new GPTResp(null, null, System.currentTimeMillis(), \"gemini\"\n , Optional.ofNullable(geminiResp.getCandidates()).orElseGet(Collections::emptyList)\n .stream()\n .map(c -> new GPTResp.Choice(1, null, new lk.eternal.ai.dto.req.Message(c.getContent().getRole(), c.getContent().getParts().stream().map(GeminiResp.Part::getText).collect(Collectors.joining()), null, null, null, null), c.getFinishReason()))\n .collect(Collectors.toList())\n , null, null, null));\n }\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"请求Gemini失败: {}\", e.getMessage(), e);\n throw new GPTException(\"请求Gemini失败: \" + e.getMessage());\n }\n }\n\n @Override\n public String getToolRole() {\n return \"user\";\n }\n\n @Override\n public String getModelRole() {\n return \"model\";\n }\n}" }, { "identifier": "TongYiQianWenAiModel", "path": "src/main/java/lk/eternal/ai/model/ai/TongYiQianWenAiModel.java", "snippet": "@Component\npublic class TongYiQianWenAiModel implements AiModel {\n\n private final Generation gen;\n\n public TongYiQianWenAiModel(@Value(\"${tyqw.key}\") String tyqwApiKey) {\n Constants.apiKey = tyqwApiKey;\n gen = new Generation();\n }\n\n @Override\n public String getName() {\n return \"tyqw\";\n }\n\n @Override\n public void request(String prompt, List<lk.eternal.ai.dto.req.Message> messages, List<String> stop, List<Tool> tools, Supplier<Boolean> stopCheck, Consumer<GPTResp> respConsumer) throws GPTException {\n MessageManager msgManager = new MessageManager(10);\n if (prompt != null) {\n msgManager.add(Message.builder().role(Role.SYSTEM.getValue()).content(prompt).build());\n }\n final List<Message> msgs = messages.stream().map(m -> Message.builder().role(m.getRole()).content(m.getContent()).build()).collect(Collectors.toList());\n msgs.forEach(msgManager::add);\n QwenParam param = QwenParam.builder().model(Generation.Models.QWEN_PLUS)\n .messages(msgManager.get())\n .resultFormat(QwenParam.ResultFormat.MESSAGE)\n .topP(0.8)\n .enableSearch(false)\n .incrementalOutput(true)\n .build();\n try {\n Flowable<GenerationResult> result = gen.streamCall(param);\n result.blockingForEach(message -> {\n if (stopCheck.get()) {\n throw new RuntimeException(\"用户停止\");\n }\n respConsumer.accept(new GPTResp(message.getRequestId(), null, System.currentTimeMillis(), \"tyqw\"\n , message.getOutput().getChoices()\n .stream()\n .map(c -> new GPTResp.Choice(1, null, new lk.eternal.ai.dto.req.Message(c.getMessage().getRole(), c.getMessage().getContent(), null, null, null, null), c.getFinishReason()))\n .collect(Collectors.toList())\n , new GPTResp.Usage(message.getUsage().getInputTokens(), message.getUsage().getOutputTokens(), message.getUsage().getInputTokens() + message.getUsage().getOutputTokens())\n , null, null));\n });\n } catch (Exception e) {\n if (!e.getMessage().equals(\"用户停止\")) {\n throw new GPTException(e.getMessage());\n }\n }\n }\n\n @Override\n public String getToolRole() {\n return \"user\";\n }\n\n @Override\n public String getModelRole() {\n return \"assistant\";\n }\n}" }, { "identifier": "Assert", "path": "src/main/java/lk/eternal/ai/util/Assert.java", "snippet": "public class Assert {\n\n public static void hasText(String str, String errMsg) {\n if (!StringUtils.hasText(str)) {\n throw new ApiValidationException(errMsg);\n }\n }\n\n public static void hasText(String str, RuntimeException exception) {\n if (!StringUtils.hasText(str)) {\n throw exception;\n }\n }\n\n public static void notNull(Object o, String errMsg) {\n if (o == null) {\n throw new ApiValidationException(errMsg);\n }\n }\n\n public static void notNull(Object o, RuntimeException exception) {\n if (o == null) {\n throw exception;\n }\n }\n\n public static void isTrue(boolean flag, String errMsg) {\n if (!flag) {\n throw new ApiValidationException(errMsg);\n }\n }\n\n public static void isTrue(boolean flag, RuntimeException exception) {\n if (!flag) {\n throw exception;\n }\n }\n\n}" }, { "identifier": "Mapper", "path": "src/main/java/lk/eternal/ai/util/Mapper.java", "snippet": "public class Mapper {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Mapper.class);\n\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n static {\n OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);\n OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);\n OBJECT_MAPPER.disable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);\n OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);\n OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);\n OBJECT_MAPPER.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);\n OBJECT_MAPPER.findAndRegisterModules();\n }\n\n public static ObjectMapper getObjectMapper() {\n return Mapper.OBJECT_MAPPER;\n }\n\n\n public static <T> T readValueNotError(String json, TypeReference<T> reference) {\n try {\n return OBJECT_MAPPER.readValue(json, reference);\n } catch (IOException e) {\n LOGGER.error(\"jackson mapper read value error: {}\", json, e);\n return null;\n }\n }\n\n public static <T> T readValueNotError(String json, Class<T> clazz) {\n try {\n return OBJECT_MAPPER.readValue(json, clazz);\n } catch (IOException e) {\n LOGGER.error(\"jackson mapper read value error: {}\", json, e);\n return null;\n }\n }\n\n public static String writeAsStringNotError(Object data) {\n try {\n return OBJECT_MAPPER.writeValueAsString(data);\n } catch (IOException e) {\n LOGGER.error(\"jackson mapper write as string error: {}\", data, e);\n return null;\n }\n }\n\n}" } ]
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import lk.eternal.ai.domain.User; import lk.eternal.ai.dto.req.QuestionReq; import lk.eternal.ai.dto.req.Message; import lk.eternal.ai.dto.resp.PluginResp; import lk.eternal.ai.exception.ApiUnauthorizedException; import lk.eternal.ai.exception.ApiValidationException; import lk.eternal.ai.model.ai.AiModel; import lk.eternal.ai.model.ai.ChatGPTAiModel; import lk.eternal.ai.model.ai.GeminiAiModel; import lk.eternal.ai.model.ai.TongYiQianWenAiModel; import lk.eternal.ai.model.plugin.*; import lk.eternal.ai.plugin.*; import lk.eternal.ai.util.Assert; import lk.eternal.ai.util.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.net.ProxySelector; import java.util.*; import java.util.concurrent.*;
4,658
package lk.eternal.ai.controller; @RestController @RequestMapping("/api") public class LKController { private static final Logger LOGGER = LoggerFactory.getLogger(LKController.class); private final Map<String, User> userMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ScheduledFuture<?>> autoRemoveUserMap = new ConcurrentHashMap<>(); private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private final Map<String, Plugin> pluginsMap = new HashMap<>(); private final Map<String, PluginModel> pluginModelMap = new HashMap<>();
package lk.eternal.ai.controller; @RestController @RequestMapping("/api") public class LKController { private static final Logger LOGGER = LoggerFactory.getLogger(LKController.class); private final Map<String, User> userMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ScheduledFuture<?>> autoRemoveUserMap = new ConcurrentHashMap<>(); private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private final Map<String, Plugin> pluginsMap = new HashMap<>(); private final Map<String, PluginModel> pluginModelMap = new HashMap<>();
private final Map<String, AiModel> aiModelMap = new HashMap<>();
4
2023-11-23 01:12:34+00:00
8k
Neelesh-Janga/23-Java-Design-Patterns
src/com/neelesh/design/patterns/creational/builder/BuilderTest.java
[ { "identifier": "MobileBuilder", "path": "src/com/neelesh/design/patterns/creational/builder/builders/MobileBuilder.java", "snippet": "public class MobileBuilder implements Builder {\n private Battery battery;\n private Camera camera;\n private Display display;\n private Network network;\n\n @Override\n public MobileBuilder buildDisplay(Display display) {\n this.display = display;\n return this;\n }\n\n @Override\n public MobileBuilder buildBattery(Battery battery) {\n this.battery = battery;\n return this;\n }\n\n @Override\n public MobileBuilder buildCamera(Camera camera) {\n this.camera = camera;\n return this;\n }\n\n @Override\n public MobileBuilder buildNetwork(Network network) {\n this.network = network;\n return this;\n }\n\n public Mobile build() {\n return new Mobile(battery, camera, display, network);\n }\n}" }, { "identifier": "Battery", "path": "src/com/neelesh/design/patterns/creational/builder/components/Battery.java", "snippet": "public class Battery {\n private int capacitymAh;\n private int currentChargePercentage;\n private boolean isCharging;\n private BatteryHealth health;\n private String manufacturer;\n private double temperatureCelsius;\n private int cycleCount;\n private BatteryTechnology technology;\n private String serialNumber;\n\n public Battery(int capacitymAh, int currentChargePercentage, boolean isCharging,\n BatteryHealth health, String manufacturer, double temperatureCelsius,\n int cycleCount, BatteryTechnology technology, String serialNumber) {\n this.capacitymAh = capacitymAh;\n this.currentChargePercentage = currentChargePercentage;\n this.isCharging = isCharging;\n this.health = health;\n this.manufacturer = manufacturer;\n this.temperatureCelsius = temperatureCelsius;\n this.cycleCount = cycleCount;\n this.technology = technology;\n this.serialNumber = serialNumber;\n }\n\n public int getCapacitymAh() {\n return capacitymAh;\n }\n\n public void setCapacitymAh(int capacitymAh) {\n this.capacitymAh = capacitymAh;\n }\n\n public int getCurrentChargePercentage() {\n return currentChargePercentage;\n }\n\n public void setCurrentChargePercentage(int currentChargePercentage) {\n this.currentChargePercentage = currentChargePercentage;\n }\n\n public boolean isCharging() {\n return isCharging;\n }\n\n public void setCharging(boolean charging) {\n isCharging = charging;\n }\n\n public BatteryHealth getHealth() {\n return health;\n }\n\n public void setHealth(BatteryHealth health) {\n this.health = health;\n }\n\n public String getManufacturer() {\n return manufacturer;\n }\n\n public void setManufacturer(String manufacturer) {\n this.manufacturer = manufacturer;\n }\n\n public double getTemperatureCelsius() {\n return temperatureCelsius;\n }\n\n public void setTemperatureCelsius(double temperatureCelsius) {\n this.temperatureCelsius = temperatureCelsius;\n }\n\n public int getCycleCount() {\n return cycleCount;\n }\n\n public void setCycleCount(int cycleCount) {\n this.cycleCount = cycleCount;\n }\n\n public BatteryTechnology getTechnology() {\n return technology;\n }\n\n public void setTechnology(BatteryTechnology technology) {\n this.technology = technology;\n }\n\n public String getSerialNumber() {\n return serialNumber;\n }\n\n public void setSerialNumber(String serialNumber) {\n this.serialNumber = serialNumber;\n }\n\n @Override\n public String toString() {\n return \"Battery{\" +\n \"capacitymAh=\" + capacitymAh +\n \", currentChargePercentage=\" + currentChargePercentage +\n \", isCharging=\" + isCharging +\n \", health=\" + health +\n \", manufacturer='\" + manufacturer + '\\'' +\n \", temperatureCelsius=\" + temperatureCelsius +\n \", cycleCount=\" + cycleCount +\n \", technology=\" + technology +\n \", serialNumber='\" + serialNumber + '\\'' +\n '}';\n }\n}" }, { "identifier": "Camera", "path": "src/com/neelesh/design/patterns/creational/builder/components/Camera.java", "snippet": "public class Camera {\n private String brand;\n private int megapixels;\n private boolean opticalImageStabilization;\n private boolean nightMode;\n private String videoResolution;\n private boolean wideAngleLens;\n private int digitalZoom;\n\n public Camera(String brand, int megapixels, boolean opticalImageStabilization, boolean nightMode,\n String videoResolution, boolean wideAngleLens, int digitalZoom) {\n this.brand = brand;\n this.megapixels = megapixels;\n this.opticalImageStabilization = opticalImageStabilization;\n this.nightMode = nightMode;\n this.videoResolution = videoResolution;\n this.wideAngleLens = wideAngleLens;\n this.digitalZoom = digitalZoom;\n }\n\n public String getBrand() {\n return brand;\n }\n\n public void setBrand(String brand) {\n this.brand = brand;\n }\n\n public int getMegapixels() {\n return megapixels;\n }\n\n public void setMegapixels(int megapixels) {\n this.megapixels = megapixels;\n }\n\n public boolean isOpticalImageStabilization() {\n return opticalImageStabilization;\n }\n\n public void setOpticalImageStabilization(boolean opticalImageStabilization) {\n this.opticalImageStabilization = opticalImageStabilization;\n }\n\n public boolean isNightMode() {\n return nightMode;\n }\n\n public void setNightMode(boolean nightMode) {\n this.nightMode = nightMode;\n }\n\n public String getVideoResolution() {\n return videoResolution;\n }\n\n public void setVideoResolution(String videoResolution) {\n this.videoResolution = videoResolution;\n }\n\n public boolean isWideAngleLens() {\n return wideAngleLens;\n }\n\n public void setWideAngleLens(boolean wideAngleLens) {\n this.wideAngleLens = wideAngleLens;\n }\n\n public int getDigitalZoom() {\n return digitalZoom;\n }\n\n public void setDigitalZoom(int digitalZoom) {\n this.digitalZoom = digitalZoom;\n }\n\n @Override\n public String toString() {\n return \"Camera{\" +\n \"brand='\" + brand + '\\'' +\n \", megapixels=\" + megapixels +\n \", opticalImageStabilization=\" + opticalImageStabilization +\n \", nightMode=\" + nightMode +\n \", videoResolution='\" + videoResolution + '\\'' +\n \", wideAngleLens=\" + wideAngleLens +\n \", digitalZoom=\" + digitalZoom + '\\'' +\n '}';\n }\n}" }, { "identifier": "Display", "path": "src/com/neelesh/design/patterns/creational/builder/components/Display.java", "snippet": "public class Display {\n private DisplayType type;\n private double sizeInInches;\n private int refreshRate;\n private boolean curved;\n private boolean hdrSupport;\n\n public Display(DisplayType type, double sizeInInches, int refreshRate, boolean curved, boolean hdrSupport) {\n this.type = type;\n this.sizeInInches = sizeInInches;\n this.refreshRate = refreshRate;\n this.curved = curved;\n this.hdrSupport = hdrSupport;\n }\n\n public DisplayType getType() {\n return type;\n }\n\n public void setType(DisplayType type) {\n this.type = type;\n }\n\n public double getSizeInInches() {\n return sizeInInches;\n }\n\n public void setSizeInInches(double sizeInInches) {\n this.sizeInInches = sizeInInches;\n }\n\n public int getRefreshRate() {\n return refreshRate;\n }\n\n public void setRefreshRate(int refreshRate) {\n this.refreshRate = refreshRate;\n }\n\n public boolean isCurved() {\n return curved;\n }\n\n public void setCurved(boolean curved) {\n this.curved = curved;\n }\n\n public boolean isHdrSupport() {\n return hdrSupport;\n }\n\n public void setHdrSupport(boolean hdrSupport) {\n this.hdrSupport = hdrSupport;\n }\n\n @Override\n public String toString() {\n return \"Display{\" +\n \"type=\" + type +\n \", sizeInInches=\" + sizeInInches +\n \", refreshRate=\" + refreshRate +\n \", curved=\" + curved +\n \", hdrSupport=\" + hdrSupport +\n '}';\n }\n}" }, { "identifier": "Network", "path": "src/com/neelesh/design/patterns/creational/builder/components/Network.java", "snippet": "public class Network {\n private NetworkTechnology technology;\n private int maxDownloadSpeed;\n private int maxUploadSpeed;\n private boolean is5GSupported;\n private boolean dualSimSupported;\n\n public Network(NetworkTechnology technology, int maxDownloadSpeed, int maxUploadSpeed, boolean is5GSupported,\n boolean dualSimSupported) {\n this.technology = technology;\n this.maxDownloadSpeed = maxDownloadSpeed;\n this.maxUploadSpeed = maxUploadSpeed;\n this.is5GSupported = is5GSupported;\n this.dualSimSupported = dualSimSupported;\n }\n\n public NetworkTechnology getTechnology() {\n return technology;\n }\n\n public void setTechnology(NetworkTechnology technology) {\n this.technology = technology;\n }\n\n public int getMaxDownloadSpeed() {\n return maxDownloadSpeed;\n }\n\n public void setMaxDownloadSpeed(int maxDownloadSpeed) {\n this.maxDownloadSpeed = maxDownloadSpeed;\n }\n\n public int getMaxUploadSpeed() {\n return maxUploadSpeed;\n }\n\n public void setMaxUploadSpeed(int maxUploadSpeed) {\n this.maxUploadSpeed = maxUploadSpeed;\n }\n\n public boolean isIs5GSupported() {\n return is5GSupported;\n }\n\n public void setIs5GSupported(boolean is5GSupported) {\n this.is5GSupported = is5GSupported;\n }\n\n public boolean isDualSimSupported() {\n return dualSimSupported;\n }\n\n public void setDualSimSupported(boolean dualSimSupported) {\n this.dualSimSupported = dualSimSupported;\n }\n\n @Override\n public String toString() {\n return \"Network{\" +\n \"technology=\" + technology +\n \", maxDownloadSpeed=\" + maxDownloadSpeed +\n \", maxUploadSpeed=\" + maxUploadSpeed +\n \", is5GSupported=\" + is5GSupported +\n \", dualSimSupported=\" + dualSimSupported +\n '}';\n }\n}" }, { "identifier": "BatteryHealth", "path": "src/com/neelesh/design/patterns/creational/builder/components/enums/BatteryHealth.java", "snippet": "public enum BatteryHealth {\n EXCELLENT,\n GOOD,\n AVERAGE,\n POOR,\n WORST\n}" }, { "identifier": "BatteryTechnology", "path": "src/com/neelesh/design/patterns/creational/builder/components/enums/BatteryTechnology.java", "snippet": "public enum BatteryTechnology {\n LITHIUM_ION,\n LITHIUM_POLYMER,\n NICKEL_CADMIUM\n}" }, { "identifier": "DisplayType", "path": "src/com/neelesh/design/patterns/creational/builder/components/enums/DisplayType.java", "snippet": "public enum DisplayType {\n AMOLED,\n QHD,\n OLED,\n RETINA\n}" }, { "identifier": "NetworkTechnology", "path": "src/com/neelesh/design/patterns/creational/builder/components/enums/NetworkTechnology.java", "snippet": "public enum NetworkTechnology {\n FIVE_G,\n FOUR_G,\n THREE_G,\n TWO_G\n}" }, { "identifier": "Mobile", "path": "src/com/neelesh/design/patterns/creational/builder/products/Mobile.java", "snippet": "public class Mobile {\n private String color;\n private boolean isWaterResistant;\n private boolean hasScreenProtection;\n private Battery battery;\n private Camera camera;\n private Display display;\n private Network network;\n\n public Mobile(Battery battery, Camera camera, Display display, Network network) {\n this.battery = battery;\n this.camera = camera;\n this.display = display;\n this.network = network;\n }\n\n public String getColor() {\n return color;\n }\n\n public void setColor(String color) {\n this.color = color;\n }\n\n public boolean isWaterResistant() {\n return isWaterResistant;\n }\n\n public void setWaterResistant(boolean waterResistant) {\n isWaterResistant = waterResistant;\n }\n\n public boolean hasScreenProtection() {\n return hasScreenProtection;\n }\n\n public void setHasScreenProtection(boolean hasScreenProtection) {\n this.hasScreenProtection = hasScreenProtection;\n }\n\n public Battery getBattery() {\n return battery;\n }\n\n public Camera getCamera() {\n return camera;\n }\n\n public Display getDisplay() {\n return display;\n }\n\n public Network getNetwork() {\n return network;\n }\n\n @Override\n public String toString() {\n return \"Mobile{\" +\n \"color='\" + color + '\\'' +\n \", isWaterResistant=\" + isWaterResistant +\n \", hasScreenProtection=\" + hasScreenProtection +\n \", battery=\" + battery +\n \", camera=\" + camera +\n \", display=\" + display +\n \", network=\" + network +\n '}';\n }\n}" } ]
import com.neelesh.design.patterns.creational.builder.builders.MobileBuilder; import com.neelesh.design.patterns.creational.builder.components.Battery; import com.neelesh.design.patterns.creational.builder.components.Camera; import com.neelesh.design.patterns.creational.builder.components.Display; import com.neelesh.design.patterns.creational.builder.components.Network; import com.neelesh.design.patterns.creational.builder.components.enums.BatteryHealth; import com.neelesh.design.patterns.creational.builder.components.enums.BatteryTechnology; import com.neelesh.design.patterns.creational.builder.components.enums.DisplayType; import com.neelesh.design.patterns.creational.builder.components.enums.NetworkTechnology; import com.neelesh.design.patterns.creational.builder.products.Mobile; import java.util.UUID;
3,639
package com.neelesh.design.patterns.creational.builder; public class BuilderTest { public static void main(String[] args) { Mobile oneplus = buildMobile(); oneplus.setColor("Glossy Black"); oneplus.setWaterResistant(false); oneplus.setHasScreenProtection(false); System.out.println("*** Mobile: OnePlus ***"); System.out.println("Color = " + oneplus.getColor()); System.out.println("Water Resistant = " + oneplus.isWaterResistant()); System.out.println("Screen Protection = " + oneplus.hasScreenProtection()); System.out.println("Battery = " + oneplus.getBattery()); System.out.println("Network = " + oneplus.getNetwork()); System.out.println("Camera = " + oneplus.getCamera()); System.out.println("Display = " + oneplus.getDisplay()); } public static Mobile buildMobile(){
package com.neelesh.design.patterns.creational.builder; public class BuilderTest { public static void main(String[] args) { Mobile oneplus = buildMobile(); oneplus.setColor("Glossy Black"); oneplus.setWaterResistant(false); oneplus.setHasScreenProtection(false); System.out.println("*** Mobile: OnePlus ***"); System.out.println("Color = " + oneplus.getColor()); System.out.println("Water Resistant = " + oneplus.isWaterResistant()); System.out.println("Screen Protection = " + oneplus.hasScreenProtection()); System.out.println("Battery = " + oneplus.getBattery()); System.out.println("Network = " + oneplus.getNetwork()); System.out.println("Camera = " + oneplus.getCamera()); System.out.println("Display = " + oneplus.getDisplay()); } public static Mobile buildMobile(){
MobileBuilder builder = new MobileBuilder();
0
2023-11-22 10:19:01+00:00
8k
angga7togk/LuckyCrates-PNX
src/main/java/angga7togk/luckycrates/menu/ChestMenu.java
[ { "identifier": "LuckyCrates", "path": "src/main/java/angga7togk/luckycrates/LuckyCrates.java", "snippet": "public class LuckyCrates extends PluginBase {\r\n\r\n @Getter\r\n private static LuckyCrates instance;\r\n public static Config crates, pos;\r\n public static int offsetIdEntity = 1;\r\n public static Map<Player, String> setMode = new HashMap<>();\r\n public static String prefix;\r\n\r\n @Override\r\n public void onLoad() {\r\n instance = this;\r\n }\r\n\r\n @Override\r\n public void onEnable() {\r\n for (String filename : Arrays.asList(\"crates.yml\", \"position.yml\")) {\r\n saveResource(filename);\r\n }\r\n saveDefaultConfig();\r\n crates = new Config(this.getDataFolder() + \"/crates.yml\", Config.YAML);\r\n pos = new Config(this.getDataFolder() + \"/position.yml\", Config.YAML);\r\n\r\n if (!pos.exists(\"crates\", true)){\r\n pos.set(\"crates\", new HashMap<>());\r\n pos.save();\r\n }\r\n\r\n prefix = getConfig().getString(\"prefix\");\r\n\r\n this.checkDepend();\r\n this.checkCratesConfig();\r\n\r\n this.getServer().getPluginManager().registerEvents(new Listeners(), this);\r\n\r\n this.getServer().getCommandMap().registerAll(getName(), List.of(\r\n new GiveKey(),\r\n new KeyAll(),\r\n new SetCrates()\r\n ));\r\n\r\n this.getServer().getScheduler().scheduleRepeatingTask(this, new FloatingTextTask(), 20 * 5, true);\r\n }\r\n\r\n private void checkDepend(){\r\n Plugin depend = this.getServer().getPluginManager().getPlugin(\"FakeInventories\");\r\n if (depend != null) {\r\n String version = depend.getDescription().getVersion();\r\n if(!version.equalsIgnoreCase(\"1.1.5\")){\r\n MainLogger.getLogger().warning(prefix + TextFormat.RED + \"please download the depend first, with version 1.1.5 https://github.com/IWareQ/FakeInventories/releases/tag/v1.1.5\");\r\n this.getServer().getPluginManager().disablePlugin(this);\r\n }\r\n } else {\r\n MainLogger.getLogger().warning(prefix + TextFormat.RED + \"please download the depend first https://github.com/IWareQ/FakeInventories/releases/tag/v1.1.5\");\r\n this.getServer().getPluginManager().disablePlugin(this);\r\n }\r\n }\r\n\r\n private void checkCratesConfig(){\r\n try {\r\n for (String crateName : crates.getKeys(false)){\r\n ConfigSection crateSect = LuckyCrates.crates.getSection(crateName);\r\n if(!crateSect.exists(\"drops\", true)) throw new RuntimeException(\"crates.yml key \" + crateName + \":drops: not found!\");\r\n if(!crateSect.exists(\"amount\", true)) throw new RuntimeException(\"crates.yml key \" + crateName + \":amount: not found!\");\r\n if(!crateSect.exists(\"floating-text\", true)) throw new RuntimeException(\"crates.yml key \" + crateName + \":floating-text: not found!\");\r\n List<Map<String, Object>> dropsList = crateSect.getList(\"drops\");\r\n for (Map<String, Object> drop : dropsList){\r\n if(!drop.containsKey(\"id\")) throw new RuntimeException(\"crates.yml key \" + crateName + \":drops:id: not found!\");\r\n if(!drop.containsKey(\"meta\")) throw new RuntimeException(\"crates.yml key \" + crateName + \":drops:meta: not found!\");\r\n if(!drop.containsKey(\"amount\")) throw new RuntimeException(\"crates.yml key \" + crateName + \":drops:amount: not found!\");\r\n if(!drop.containsKey(\"chance\")) throw new RuntimeException(\"crates.yml key \" + crateName + \":drops:chance: not found!\");\r\n int id = (int) drop.get(\"id\");\r\n int meta = (int) drop.get(\"meta\");\r\n int amount = (int) drop.get(\"amount\");\r\n Item item = new Item(id, meta, amount);\r\n if(item.isNull()) throw new RuntimeException(\"Item ID:\" + id + \" META:\" +meta + \" not found!\");\r\n if(drop.containsKey(\"enchantments\")){\r\n List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get(\"enchantments\");\r\n for (Map<String, Object> enchant : enchantList){\r\n String enchantName = (String) enchant.get(\"name\");\r\n if(getEnchantmentByName(enchantName) == null) throw new RuntimeException(\"Error Enchantment not found : \" + enchantName);\r\n }\r\n }\r\n }\r\n }\r\n }catch (RuntimeException e){\r\n MainLogger.getLogger().error(\"LuckyCrates Error: \" + e.getMessage());\r\n }\r\n }\r\n \r\n public static Integer getEnchantmentByName(String enchant){\r\n Map<String, Integer> enchantmentsMap = new HashMap<>();\r\n enchantmentsMap.put(\"protection\", 0);\r\n enchantmentsMap.put(\"fire_protection\", 1);\r\n enchantmentsMap.put(\"feather_falling\", 2);\r\n enchantmentsMap.put(\"blast_protection\", 3);\r\n enchantmentsMap.put(\"projectile_protection\", 4);\r\n enchantmentsMap.put(\"thorns\", 5);\r\n enchantmentsMap.put(\"respiration\", 6);\r\n enchantmentsMap.put(\"aqua_affinity\", 7);\r\n enchantmentsMap.put(\"depth_strider\", 8);\r\n enchantmentsMap.put(\"sharpness\", 9);\r\n enchantmentsMap.put(\"smite\", 10);\r\n enchantmentsMap.put(\"bane_of_arthropods\", 11);\r\n enchantmentsMap.put(\"knockback\", 12);\r\n enchantmentsMap.put(\"fire_aspect\", 13);\r\n enchantmentsMap.put(\"looting\", 14);\r\n enchantmentsMap.put(\"efficiency\", 15);\r\n enchantmentsMap.put(\"silk_touch\", 16);\r\n enchantmentsMap.put(\"unbreaking\", 17);\r\n enchantmentsMap.put(\"fortune\", 18);\r\n enchantmentsMap.put(\"power\", 19);\r\n enchantmentsMap.put(\"punch\", 20);\r\n enchantmentsMap.put(\"flame\", 21);\r\n enchantmentsMap.put(\"infinity\", 22);\r\n enchantmentsMap.put(\"luck_of_the_sea\", 23);\r\n enchantmentsMap.put(\"lure\", 24);\r\n enchantmentsMap.put(\"frost_walker\", 25);\r\n enchantmentsMap.put(\"mending\", 26);\r\n enchantmentsMap.put(\"binding\", 27);\r\n enchantmentsMap.put(\"vanishing\", 28);\r\n enchantmentsMap.put(\"impaling\", 29);\r\n enchantmentsMap.put(\"riptide\", 30);\r\n enchantmentsMap.put(\"loyalty\", 31);\r\n enchantmentsMap.put(\"channeling\", 32);\r\n enchantmentsMap.put(\"multishot\", 33);\r\n enchantmentsMap.put(\"piercing\", 34);\r\n enchantmentsMap.put(\"quick_charge\", 35);\r\n enchantmentsMap.put(\"soul_speed\", 36);\r\n enchantmentsMap.put(\"swift_sneak\", 37);\r\n if(enchantmentsMap.containsKey(enchant)) return enchantmentsMap.get(enchant);\r\n return null;\r\n }\r\n}" }, { "identifier": "Keys", "path": "src/main/java/angga7togk/luckycrates/crates/Keys.java", "snippet": "public class Keys{\r\n private final int id;\r\n private final int meta;\r\n private final String name;\r\n private final String lore;\r\n public Keys(){\r\n this.id = LuckyCrates.getInstance().getConfig().getInt(\"keys.id\", 131);\r\n this.meta = LuckyCrates.getInstance().getConfig().getInt(\"keys.meta\", 0);\r\n this.name = LuckyCrates.getInstance().getConfig().getString(\"keys.name\", \"{crate} Key\");\r\n this.lore = LuckyCrates.getInstance().getConfig().getString(\"keys.lore\", \"Claim rewards from a {crate} Crate\");\r\n }\r\n\r\n public boolean isKeys(Item item) {\r\n int id = item.getId();\r\n int meta = item.getDamage();\r\n CompoundTag nameTag = item.hasCompoundTag() ? item.getNamedTag() : null;\r\n \r\n return id == LuckyCrates.getInstance().getConfig().getInt(\"keys.id\", 131)\r\n && meta == LuckyCrates.getInstance().getConfig().getInt(\"keys.meta\", 0)\r\n && nameTag != null\r\n && nameTag.contains(\"isKeys\");\r\n }\r\n\r\n public String getCrateName(Item item){\r\n if(isKeys(item)){\r\n return item.getNamedTag().getString(\"crateName\");\r\n }\r\n return null;\r\n }\r\n\r\n public boolean crateExists(String crateName) {\r\n return LuckyCrates.crates.exists(crateName);\r\n }\r\n\r\n public boolean giveKey(Player player, String crateName, int amount){\r\n if (crateExists(crateName)){\r\n String customName = this.name.replace(\"{crate}\", crateName);\r\n String lore = this.lore.replace(\"{crate}\", crateName);\r\n Item item = new Item(this.id, this.meta, amount)\r\n .setNamedTag(new CompoundTag()\r\n .putBoolean(\"isKeys\", true)\r\n .putString(\"crateName\", crateName));\r\n item.addEnchantment(Enchantment.getEnchantment(Enchantment.ID_BINDING_CURSE));\r\n if(isKeys(item)){\r\n player.getInventory().addItem(item.setCustomName(customName).setLore(lore));\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n}" }, { "identifier": "Languages", "path": "src/main/java/angga7togk/luckycrates/language/Languages.java", "snippet": "@Getter\r\npublic class Languages {\r\n\r\n private final String lang;\r\n public Languages(){\r\n String lang = LuckyCrates.getInstance().getConfig().getString(\"language\");\r\n if(lang.equalsIgnoreCase(\"id\") || lang.equalsIgnoreCase(\"en\")){\r\n this.lang = lang;\r\n }else{\r\n this.lang = \"en\";\r\n }\r\n }\r\n\r\n public Map<String, String> getLanguage() {\r\n Map<String, Map<String, String>> lang = new HashMap<>();\r\n\r\n Map<String, String> id = new HashMap<>();\r\n Map<String, String> en = new HashMap<>();\r\n\r\n // Bahasa Indonesia (id)\r\n id.put(\"crate-notfound\", \"§cCrate tidak ditemukan!\");\r\n id.put(\"player-notfound\", \"§cPemain tidak ditemukan.\");\r\n id.put(\"setmode\", \"§eSilakan hancurkan blok untuk mengubahnya menjadi Crates.\");\r\n id.put(\"amount-number\", \"§cJumlah harus angka.\");\r\n id.put(\"give-key\", \"§aBerhasil memberikan kunci {crate} sejumlah {amount} kepada {player}.\");\r\n id.put(\"accept-key\", \"§aKamu menerima kunci {crate} sejumlah {amount}.\");\r\n id.put(\"key-all\", \"§aBerhasil memberikan kunci {crate} sejumlah {amount} kepada semua pemain.\");\r\n id.put(\"setted-crate\", \"§eBerhasil memasang crate {crate}\");\r\n id.put(\"break-crate\", \"§cBerhasil menghancurkan crate {crate}\");\r\n\r\n // Bahasa Inggris (en)\r\n en.put(\"crate-notfound\", \"§cCrate not found!\");\r\n en.put(\"player-notfound\", \"§cPlayer not found.\");\r\n en.put(\"setmode\", \"§ePlease break the block to change it into Crates.\");\r\n en.put(\"amount-number\", \"§cAmount must be a number.\");\r\n en.put(\"give-key\", \"§aSuccessfully gave {amount} {crate} key(s) to {player}.\");\r\n en.put(\"accept-key\", \"§aYou accepted {amount} {crate} key(s).\");\r\n en.put(\"key-all\", \"§aSuccessfully gave {amount} {crate} key(s) to all players.\");\r\n en.put(\"setted-crate\", \"§eSuccessfully set up the {crate} crate.\");\r\n en.put(\"break-crate\", \"§cSuccessfully broke the {crate} crate.\");\r\n\r\n lang.put(\"id\", id);\r\n lang.put(\"en\", en);\r\n\r\n return lang.get(this.lang);\r\n }\r\n}\r" }, { "identifier": "InstantTask", "path": "src/main/java/angga7togk/luckycrates/task/InstantTask.java", "snippet": "public class InstantTask extends Task {\r\n @Getter\r\n private final Player player;\r\n private final List<Map<String, Object>> safeDrops = new ArrayList<>();\r\n private final String crateName;\r\n public InstantTask(Player player, String crateName){\r\n this.crateName = crateName;\r\n this.player = player;\r\n ConfigSection crateSect = LuckyCrates.crates.getSection(crateName);\r\n List<Map<String, Object>> drops = crateSect.getList(\"drops\");\r\n drops.forEach((objectMap -> {\r\n int chance = Math.min((int) objectMap.get(\"chance\"), 100);\r\n for (int ii = 0; ii <= ((chance > 30) ? chance * 2 : chance); ii++) {\r\n this.safeDrops.add(objectMap);\r\n }\r\n }));\r\n }\r\n\r\n @Override\r\n public void onRun(int i) {\r\n Collections.shuffle(this.safeDrops);\r\n Random random = new Random();\r\n int randomIndex = random.nextInt(this.safeDrops.size());\r\n Map<String, Object> drop = this.safeDrops.get(randomIndex);\r\n\r\n Item item = createItem(drop);\r\n if(item != null){\r\n player.getInventory().addItem(item);\r\n if(drop.containsKey(\"commands\")){\r\n for (String command : (List<String>) drop.get(\"commands\")){\r\n Server.getInstance().executeCommand(Server.getInstance().getConsoleSender(), command.replace(\"{player}\", this.getPlayer().getName()));\r\n }\r\n }\r\n Server.getInstance().getPluginManager().callEvent(new PlayerOpenCrateEvent(player, item, crateName));\r\n }\r\n }\r\n\r\n private Item createItem(Map<String, Object> drop) {\r\n int id = (int) drop.get(\"id\");\r\n int meta = (int) drop.get(\"meta\");\r\n int amount = (int) drop.get(\"amount\");\r\n String customName = drop.containsKey(\"name\") ? (String) drop.get(\"name\") : null;\r\n String lore = drop.containsKey(\"lore\") ? (String) drop.get(\"lore\") : null;\r\n Item item = new Item(id, meta, amount);\r\n if(customName != null){\r\n item.setCustomName(customName);\r\n }\r\n if(lore != null){\r\n item.setLore(lore);\r\n }\r\n if(drop.containsKey(\"enchantments\")){\r\n List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get(\"enchantments\");\r\n for (Map<String, Object> enchant : enchantList){\r\n String enchantName = (String) enchant.get(\"name\");\r\n int enchantLevel = (int) enchant.get(\"level\");\r\n Integer enchantId = LuckyCrates.getEnchantmentByName(enchantName);\r\n if(enchantId == null){\r\n this.getPlayer().sendMessage(\"§cError Enchantment not found : \" + enchantName);\r\n return null;\r\n }\r\n item.addEnchantment(Enchantment.getEnchantment(enchantId).setLevel(enchantLevel));\r\n }\r\n }\r\n return item;\r\n }\r\n}\r" }, { "identifier": "RouletteTask", "path": "src/main/java/angga7togk/luckycrates/task/RouletteTask.java", "snippet": "public class RouletteTask extends AsyncTask {\r\n private final FakeInventory inv;\r\n private final int round;\r\n @Getter\r\n private final Player player;\r\n private final List<Map<String, Object>> safeDrops = new ArrayList<>();\r\n private final String crateName;\r\n private final long speed;\r\n\r\n public RouletteTask(Player player, String crateName, FakeInventory inv, long speed) {\r\n this.crateName = crateName;\r\n this.player = player;\r\n this.speed = speed;\r\n this.round = LuckyCrates.getInstance().getConfig().getInt(\"crates.roulette.round\", 25);\r\n ConfigSection crateSection = LuckyCrates.crates.getSection(crateName);\r\n this.inv = inv;\r\n this.inv.clearAll();\r\n this.inv.setItem(4, Item.get(208, 0, 1));\r\n this.inv.setItem(22, Item.get(208, 0, 1));\r\n\r\n List<Map<String, Object>> drops = crateSection.getList(\"drops\");\r\n List<Map<String, Object>> cache = new ArrayList<>();\r\n drops.forEach((objectMap -> {\r\n int chance = Math.min((int) objectMap.get(\"chance\"), 100);\r\n for (int i = 0; i <= chance * 2; i++) {\r\n cache.add(objectMap);\r\n }\r\n }));\r\n Collections.shuffle(cache);\r\n int i = 0;\r\n for (Map<String, Object> objectMap : cache){\r\n this.safeDrops.add(objectMap);\r\n if (i == 17){\r\n break;\r\n }\r\n i++;\r\n }\r\n }\r\n\r\n @Override\r\n public void onRun() {\r\n try {\r\n for (int i = 0; i <= round;i++){\r\n if (i < round) {\r\n spinRoulette();\r\n } else {\r\n this.getPlayer().getLevel().addSound(player.getPosition(), Sound.RANDOM_TOTEM, 1.0F, 1.0F, player);\r\n Item item = this.inv.getItem(13);\r\n setDisplayGift(item);\r\n }\r\n Thread.sleep(speed);\r\n }\r\n } catch (InterruptedException e) {\r\n throw new RuntimeException(e);\r\n }\r\n\r\n }\r\n\r\n private void spinRoulette() {\r\n Random random = new Random();\r\n Collections.shuffle(this.safeDrops);\r\n\r\n updateRouletteDisplay(random);\r\n }\r\n\r\n private void setDisplayGift(Item item) throws InterruptedException {\r\n for (int i = 10; i <= 16; i++) {\r\n this.inv.setItem(i, item);\r\n }\r\n for (int i = 25; i <= 34; i += 9) {\r\n this.inv.setItem(i, item);\r\n }\r\n for (int i = 43; i >= 37; i--) {\r\n this.inv.setItem(i, item);\r\n }\r\n for (int i = 28; i >= 19; i -= 9) {\r\n this.inv.setItem(i, item);\r\n }\r\n this.inv.setDefaultItemHandler((items, event) -> event.setCancelled());\r\n this.getPlayer().addWindow(this.inv);\r\n Thread.sleep(1000);\r\n this.setResult(item);\r\n }\r\n\r\n private void updateRouletteDisplay(Random random) {\r\n for (int i = 10; i <= 16; i++) {\r\n setRouletteItem(random, i);\r\n }\r\n for (int i = 25; i <= 34; i += 9) {\r\n setRouletteItem(random, i);\r\n }\r\n for (int i = 43; i >= 37; i--) {\r\n setRouletteItem(random, i);\r\n }\r\n for (int i = 28; i >= 19; i -= 9) {\r\n setRouletteItem(random, i);\r\n }\r\n this.inv.setDefaultItemHandler((item, event) -> event.setCancelled());\r\n this.getPlayer().getLevel().addSound(player.getPosition(), Sound.RANDOM_CLICK, 1.0F, 1.0F, player);\r\n this.getPlayer().addWindow(this.inv);\r\n }\r\n\r\n private void setRouletteItem(Random random, int slot) {\r\n int randomIndex = random.nextInt(this.safeDrops.size());\r\n Map<String, Object> drop = this.safeDrops.get(randomIndex);\r\n\r\n Item item = createItemFromDrop(drop);\r\n this.inv.setItem(slot, item);\r\n }\r\n\r\n private Item createItemFromDrop(Map<String, Object> drop) {\r\n int id = (int) drop.get(\"id\");\r\n int meta = (int) drop.get(\"meta\");\r\n int amount = (int) drop.get(\"amount\");\r\n\r\n Item item = new Item(id, meta, amount);\r\n\r\n setItemDetails(drop, item);\r\n\r\n return item;\r\n }\r\n\r\n private void setItemDetails(Map<String, Object> drop, Item item) {\r\n String customName = drop.containsKey(\"name\") ? (String) drop.get(\"name\") : null;\r\n String lore = drop.containsKey(\"lore\") ? (String) drop.get(\"lore\") : null;\r\n\r\n if (customName != null) {\r\n item.setCustomName(customName);\r\n }\r\n if(lore != null){\r\n item.setLore(lore);\r\n }\r\n\r\n if (drop.containsKey(\"enchantments\")) {\r\n List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get(\"enchantments\");\r\n for (Map<String, Object> enchant : enchantList) {\r\n addEnchantmentToItem(item, enchant);\r\n }\r\n }\r\n\r\n if (drop.containsKey(\"broadcast\")){\r\n addBroadcastToItem(item, drop.get(\"broadcast\").toString().replace(\"{reward}\", (customName == null) ? Objects.requireNonNull(item.getName()) : customName));\r\n }\r\n\r\n if(drop.containsKey(\"commands\")){\r\n List<String> commands = (List<String>) drop.get(\"commands\");\r\n addCommandToItem(item, commands);\r\n }\r\n }\r\n\r\n private void addBroadcastToItem(Item item, String msg){\r\n CompoundTag namedTag = (item.hasCompoundTag()) ? item.getNamedTag() : new CompoundTag();\r\n namedTag.putString(\"broadcast\", msg.replace(\"{player}\", player.getName()));\r\n item.setNamedTag(namedTag);\r\n }\r\n private String getBroadcastFromItem(Item item){\r\n CompoundTag namedTag = (item.hasCompoundTag()) ? item.getNamedTag() : new CompoundTag();\r\n if (namedTag.contains(\"broadcast\")){\r\n String broadcast = namedTag.getString(\"broadcast\");\r\n namedTag.remove(\"broadcast\");\r\n return broadcast;\r\n }\r\n return null;\r\n }\r\n\r\n private void addEnchantmentToItem(Item item, Map<String, Object> enchant) {\r\n String enchantName = (String) enchant.get(\"name\");\r\n int enchantLevel = (int) enchant.get(\"level\");\r\n Integer enchantId = LuckyCrates.getEnchantmentByName(enchantName);\r\n\r\n if (enchantId == null) {\r\n player.sendMessage(\"§cError Enchantment not found : \" + enchantName);\r\n return;\r\n }\r\n Enchantment enchantment = Enchantment.getEnchantment(enchantId);\r\n item.addEnchantment(enchantment.setLevel(enchantLevel));\r\n }\r\n\r\n private void addCommandToItem(Item item, List<String> commands) {\r\n if (commands == null || commands.isEmpty()) {\r\n return;\r\n }\r\n CompoundTag namedTag = (item.hasCompoundTag()) ? item.getNamedTag() : new CompoundTag();\r\n StringBuilder commandString = new StringBuilder();\r\n int lastIndex = commands.size() - 1;\r\n for (int i = 0; i < lastIndex; i++) {\r\n commandString.append(commands.get(i).replace(\"{player}\", this.getPlayer().getName())).append(\",\");\r\n }\r\n commandString.append(commands.get(lastIndex).replace(\"{player}\", this.getPlayer().getName()));\r\n\r\n item.setNamedTag(namedTag.putString(\"commands\", commandString.toString()));\r\n }\r\n\r\n\r\n private List<String> getCommandsFromItem(Item item) {\r\n CompoundTag namedTag = (item.hasCompoundTag()) ? item.getNamedTag() : new CompoundTag();\r\n if (namedTag.contains(\"commands\")) {\r\n List<String> commands = List.of(namedTag.getString(\"commands\").split(\",\"));\r\n\r\n namedTag.remove(\"commands\");\r\n item.setNamedTag(namedTag);\r\n return commands;\r\n }\r\n return null;\r\n }\r\n\r\n @Override\r\n public void onCompletion(Server server) {\r\n Item item = (Item) this.getResult();\r\n if (item != null){\r\n player.getInventory().addItem(item);\r\n List<String> commands = getCommandsFromItem(item);\r\n if(commands != null){\r\n for (String command : commands){\r\n Server.getInstance().executeCommand(Server.getInstance().getConsoleSender(), command.replace(\"{player}\", this.getPlayer().getName()));\r\n }\r\n }\r\n String broadcast = getBroadcastFromItem(item);\r\n if (broadcast != null) Server.getInstance().broadcastMessage(LuckyCrates.prefix + \"§r\" + broadcast);\r\n Server.getInstance().getPluginManager().callEvent(new PlayerOpenCrateEvent(player, item, crateName));\r\n }\r\n ChestMenu menu = new ChestMenu();\r\n menu.mainMenu(player, crateName);\r\n }\r\n}\r" } ]
import angga7togk.luckycrates.LuckyCrates; import angga7togk.luckycrates.crates.Keys; import angga7togk.luckycrates.language.Languages; import angga7togk.luckycrates.task.InstantTask; import angga7togk.luckycrates.task.RouletteTask; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.InventoryType; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.plugin.Plugin; import cn.nukkit.utils.ConfigSection; import cn.nukkit.utils.TextFormat; import me.iwareq.fakeinventories.FakeInventory; import java.util.ArrayList; import java.util.List; import java.util.Map;
6,645
package angga7togk.luckycrates.menu; public class ChestMenu { private final Map<String, String> lang; public ChestMenu() { this.lang = new Languages().getLanguage(); } public void mainMenu(Player player, String crateName) { LuckyCrates.crates.reload(); FakeInventory inv = new FakeInventory(InventoryType.DOUBLE_CHEST, TextFormat.BOLD + crateName); if (!LuckyCrates.crates.exists(crateName)) { player.sendMessage(LuckyCrates.prefix + lang.get("crate-notfound")); return; } ConfigSection crateSect = LuckyCrates.crates.getSection(crateName); List<Map<String, Object>> dropsList = crateSect.getList("drops"); int i = 0; for (Map<String, Object> drop : dropsList) { int id = (int) drop.get("id"); int meta = (int) drop.get("meta"); int amount = (int) drop.get("amount"); int chance = (int) drop.get("chance"); String customName = drop.containsKey("name") ? (String) drop.get("name") : null; String lore = drop.containsKey("lore") ? (String) drop.get("lore") : null; Item item = new Item(id, meta, amount); if (customName != null) { item.setCustomName(customName); } if (lore != null) { item.setLore(lore, "", "§eChance, §r" + chance); } else { item.setLore("", "§eChance, §r" + chance); } if (drop.containsKey("enchantments")) { List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get("enchantments"); for (Map<String, Object> enchant : enchantList) { String enchantName = (String) enchant.get("name"); int enchantLevel = (int) enchant.get("level"); Integer enchantId = LuckyCrates.getEnchantmentByName(enchantName); if (enchantId == null) { player.sendMessage("§cError Enchantment not found : " + enchantName); return; } item.addEnchantment(Enchantment.getEnchantment(enchantId).setLevel(enchantLevel)); } } inv.addItem(item); i++; if (i > 35) break; } inv.setItem(49, new Item(130, 0, 1) .setNamedTag(new CompoundTag() .putString("button", "openCrate")) .setCustomName("§l§aOpen Crates") .setLore("", "§eNeed Key, §r" + crateSect.getInt("amount"), "§eMy Key, §r" + getKeysCount(player, crateName))); inv.setDefaultItemHandler((item, event) -> { event.setCancelled(); Player target = event.getTransaction().getSource(); int myKey = getKeysCount(target, crateName); int needKey = crateSect.getInt("amount"); if (target.getInventory().isFull()) { target.sendMessage("<Inventory kamu full>"); return; } if (item.hasCompoundTag() && item.getNamedTag().exist("button")) { if (myKey >= needKey) { if (crateSect.exists("commands", true)) { for (String command : crateSect.getStringList("commands")) { Server.getInstance().executeCommand(Server.getInstance().getConsoleSender(), command.replace("{player}", target.getName())); } } reduceKey(target, crateName, needKey); String type = LuckyCrates.getInstance().getConfig().getString("crates.type", "roulette"); if (type.equalsIgnoreCase("instant")) { target.removeWindow(inv);
package angga7togk.luckycrates.menu; public class ChestMenu { private final Map<String, String> lang; public ChestMenu() { this.lang = new Languages().getLanguage(); } public void mainMenu(Player player, String crateName) { LuckyCrates.crates.reload(); FakeInventory inv = new FakeInventory(InventoryType.DOUBLE_CHEST, TextFormat.BOLD + crateName); if (!LuckyCrates.crates.exists(crateName)) { player.sendMessage(LuckyCrates.prefix + lang.get("crate-notfound")); return; } ConfigSection crateSect = LuckyCrates.crates.getSection(crateName); List<Map<String, Object>> dropsList = crateSect.getList("drops"); int i = 0; for (Map<String, Object> drop : dropsList) { int id = (int) drop.get("id"); int meta = (int) drop.get("meta"); int amount = (int) drop.get("amount"); int chance = (int) drop.get("chance"); String customName = drop.containsKey("name") ? (String) drop.get("name") : null; String lore = drop.containsKey("lore") ? (String) drop.get("lore") : null; Item item = new Item(id, meta, amount); if (customName != null) { item.setCustomName(customName); } if (lore != null) { item.setLore(lore, "", "§eChance, §r" + chance); } else { item.setLore("", "§eChance, §r" + chance); } if (drop.containsKey("enchantments")) { List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get("enchantments"); for (Map<String, Object> enchant : enchantList) { String enchantName = (String) enchant.get("name"); int enchantLevel = (int) enchant.get("level"); Integer enchantId = LuckyCrates.getEnchantmentByName(enchantName); if (enchantId == null) { player.sendMessage("§cError Enchantment not found : " + enchantName); return; } item.addEnchantment(Enchantment.getEnchantment(enchantId).setLevel(enchantLevel)); } } inv.addItem(item); i++; if (i > 35) break; } inv.setItem(49, new Item(130, 0, 1) .setNamedTag(new CompoundTag() .putString("button", "openCrate")) .setCustomName("§l§aOpen Crates") .setLore("", "§eNeed Key, §r" + crateSect.getInt("amount"), "§eMy Key, §r" + getKeysCount(player, crateName))); inv.setDefaultItemHandler((item, event) -> { event.setCancelled(); Player target = event.getTransaction().getSource(); int myKey = getKeysCount(target, crateName); int needKey = crateSect.getInt("amount"); if (target.getInventory().isFull()) { target.sendMessage("<Inventory kamu full>"); return; } if (item.hasCompoundTag() && item.getNamedTag().exist("button")) { if (myKey >= needKey) { if (crateSect.exists("commands", true)) { for (String command : crateSect.getStringList("commands")) { Server.getInstance().executeCommand(Server.getInstance().getConsoleSender(), command.replace("{player}", target.getName())); } } reduceKey(target, crateName, needKey); String type = LuckyCrates.getInstance().getConfig().getString("crates.type", "roulette"); if (type.equalsIgnoreCase("instant")) { target.removeWindow(inv);
Server.getInstance().getScheduler().scheduleDelayedTask(new InstantTask(target, crateName), 5, true);
3
2023-11-20 08:04:22+00:00
8k
ca-webdev/exchange-backed-java
src/main/java/ca/webdev/exchange/web/websocket/Publisher.java
[ { "identifier": "MatchingEngine", "path": "src/main/java/ca/webdev/exchange/matching/MatchingEngine.java", "snippet": "public class MatchingEngine {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(MatchingEngine.class);\n private final double tickSize;\n private final int tickSizeInPrecision;\n\n private final SortedMap<Double, Queue<Order>> bidOrderBook = new ConcurrentSkipListMap<>(Collections.reverseOrder());\n private final SortedMap<Double, Queue<Order>> askOrderBook = new ConcurrentSkipListMap<>();\n private final SortedMap<Double, Queue<Order>> readOnlyBidOrderBook = Collections.unmodifiableSortedMap(bidOrderBook);\n private final SortedMap<Double, Queue<Order>> readOnlyAskOrderBook = Collections.unmodifiableSortedMap(askOrderBook);\n private final Map<UUID, Order> orderIdToOrderMap = new HashMap<>();\n\n private final ExecutorService executor = Executors.newSingleThreadExecutor();\n\n private final List<OrderBookListener> orderBookListeners = new ArrayList<>();\n private final Map<String, List<TradeListener>> tradeListeners = new HashMap<>();\n private final List<MarketTradeListener> marketTradeListeners = new ArrayList<>();\n private final Map<String, List<OrderStateListener>> orderStateListeners = new HashMap<>();\n\n private int incrementingTradeId = 1;\n\n public MatchingEngine(double tickSize, int tickSizeInPrecision) {\n this.tickSize = tickSize;\n this.tickSizeInPrecision = tickSizeInPrecision;\n }\n\n public double getTickSize() {\n return tickSize;\n }\n\n public int getTickSizeInPrecision() {\n return tickSizeInPrecision;\n }\n\n public void registerOrderBookListener(OrderBookListener orderBookListener) {\n orderBookListeners.add(orderBookListener);\n }\n\n public void registerTradeListener(String userName, TradeListener tradeListener) {\n tradeListeners.computeIfAbsent(userName, k -> new ArrayList<>()).add(tradeListener);\n }\n\n public void registerMarketTradeListener(MarketTradeListener marketTradeListener) {\n marketTradeListeners.add(marketTradeListener);\n }\n\n public void registerOrderStateListener(String userName, OrderStateListener orderStateListener) {\n orderStateListeners.computeIfAbsent(userName, k -> new ArrayList<>()).add(orderStateListener);\n }\n\n public SortedMap<Double, Queue<Order>> getReadOnlyBidOrderBook() {\n return readOnlyBidOrderBook;\n }\n\n public SortedMap<Double, Queue<Order>> getReadOnlyAskOrderBook() {\n return readOnlyAskOrderBook;\n }\n\n public UUID insertBuyLimitOrder(String owner, double price, int size) {\n UUID orderId = UUID.randomUUID();\n executor.execute(() -> handlerLimitOrder(true, owner, price, size, orderId, askOrderBook, bidOrderBook));\n return orderId;\n }\n\n public UUID insertSellLimitOrder(String owner, double price, int size) {\n UUID orderId = UUID.randomUUID();\n executor.execute(() -> handlerLimitOrder(false, owner, price, size, orderId, bidOrderBook, askOrderBook));\n return orderId;\n }\n\n private void handlerLimitOrder(boolean isBuyOrder, String owner, double price, int size, UUID orderId, SortedMap<Double, Queue<Order>> matchingOrderBook, SortedMap<Double, Queue<Order>> orderBook) {\n Order order = new Order(orderId, owner, isBuyOrder, price, size, Double.NaN, size);\n publishOrderState(order, OrderStatus.InsertAccepted);\n int remainingSize = match(order, matchingOrderBook);\n\n if (remainingSize == 0) {\n publishOrderBook();\n return;\n }\n orderBook.computeIfAbsent(price, k -> new ConcurrentLinkedQueue<>()).add(order);\n orderIdToOrderMap.put(orderId, order);\n LOGGER.debug((isBuyOrder ? \"bid\" : \"ask\") + \"OrderBook={}\", orderBook);\n publishOrderBook();\n }\n\n public CompletableFuture<String> cancelOrder(UUID orderId) {\n CompletableFuture<String> future = new CompletableFuture<>();\n executor.execute(() -> {\n if (!orderIdToOrderMap.containsKey(orderId)) {\n LOGGER.warn(\"invalid order cancel with unknown orderId={}\", orderId);\n future.complete(\"Invalid order cancel with unknown orderId. This order may already be cancelled\");\n return;\n }\n Order order = orderIdToOrderMap.get(orderId);\n if (order.getRemainingSize() == 0) {\n future.complete(\"Rejected order cancel as the order is already fully filled.\");\n return;\n }\n double priceLevel = order.getOrderPrice();\n if (!bidOrderBook.isEmpty() && priceLevel > bidOrderBook.firstKey() && askOrderBook.containsKey(priceLevel)) {\n askOrderBook.get(priceLevel).removeIf(o -> orderId.equals(o.getOrderId()));\n if (askOrderBook.get(priceLevel).isEmpty()) {\n askOrderBook.remove(priceLevel);\n }\n } else if (bidOrderBook.containsKey(priceLevel)) {\n bidOrderBook.get(priceLevel).removeIf(o -> orderId.equals(o.getOrderId()));\n if (bidOrderBook.get(priceLevel).isEmpty()) {\n bidOrderBook.remove(priceLevel);\n }\n }\n orderIdToOrderMap.remove(orderId);\n publishOrderState(order, OrderStatus.Cancelled);\n publishOrderBook();\n future.complete(\"Order is successfully cancelled.\");\n });\n return future;\n }\n\n public CompletableFuture<Order> lookUpOrder(UUID orderId) {\n CompletableFuture<Order> future = new CompletableFuture<>();\n executor.execute(() -> {\n future.complete(orderIdToOrderMap.get(orderId));\n });\n return future;\n }\n\n private int match(Order aggressingOrder, SortedMap<Double, Queue<Order>> matchingOrderBook) {\n boolean isBuyOrder = aggressingOrder.isBuyOrder();\n String owner = aggressingOrder.getOwner();\n double aggressingOrderPrice = aggressingOrder.getOrderPrice();\n int initialSize = aggressingOrder.getOrderSize();\n int remainingSize = initialSize;\n for (double priceLevel : matchingOrderBook.keySet()) {\n if (isBuyOrder && aggressingOrderPrice < priceLevel) {\n break;\n }\n if (!isBuyOrder && aggressingOrderPrice > priceLevel) {\n break;\n }\n for (Order order : matchingOrderBook.get(priceLevel)) {\n if (remainingSize == 0) {\n break;\n }\n int orderRemainingSize = order.getRemainingSize();\n int tradedSize = Math.min(remainingSize, orderRemainingSize);\n remainingSize -= tradedSize;\n order.setLastFilledPrice(priceLevel);\n order.setRemainingSize(orderRemainingSize - tradedSize);\n publishOrderState(order, order.getRemainingSize() == 0 ? OrderStatus.FullyFilled : OrderStatus.PartiallyFilled);\n aggressingOrder.setLastFilledPrice(priceLevel);\n aggressingOrder.setRemainingSize(remainingSize);\n publishOrderState(aggressingOrder, remainingSize == 0 ? OrderStatus.FullyFilled : OrderStatus.PartiallyFilled);\n String buyer = isBuyOrder ? owner : order.getOwner();\n String seller = isBuyOrder ? order.getOwner() : owner;\n publishTrade(priceLevel, tradedSize, buyer, seller, isBuyOrder);\n LOGGER.info(\"matched \" + tradedSize + \"@$\" + priceLevel + \" Buyer: \" + buyer + \" Seller: \" + seller);\n }\n matchingOrderBook.get(priceLevel).removeIf(o -> o.getRemainingSize() == 0);\n if (remainingSize == 0) {\n break;\n }\n }\n matchingOrderBook.values().removeIf(Queue::isEmpty);\n return remainingSize;\n }\n\n private void publishOrderState(Order order, OrderStatus orderStatus) {\n UUID orderId = order.getOrderId();\n String owner = order.getOwner();\n boolean isBuyOrder = order.isBuyOrder();\n double price = order.getOrderPrice();\n int size = order.getOrderSize();\n double filledPrice = order.getLastFilledPrice();\n int filledSize = order.getOrderSize() - order.getRemainingSize();\n orderStateListeners.computeIfPresent(owner, (user, listeners) -> {\n listeners.forEach(l -> l.handleOrderState(orderId, System.currentTimeMillis(), isBuyOrder, price, size, filledPrice, filledSize, orderStatus));\n return listeners;\n });\n }\n\n private void publishOrderBook() {\n orderBookListeners.forEach(l -> l.handleOrderBook(readOnlyBidOrderBook, readOnlyAskOrderBook));\n }\n\n private void publishTrade(double price, int size, String buyer, String seller, boolean isTakerSideBuy) {\n long tradeTime = System.currentTimeMillis();\n if (tradeListeners.containsKey(buyer)) {\n tradeListeners.get(buyer).forEach(l -> l.handleTrade(tradeTime, true, price, size, buyer, seller));\n }\n if (tradeListeners.containsKey(seller)) {\n tradeListeners.get(seller).forEach(l -> l.handleTrade(tradeTime, false, price, -size, buyer, seller));\n }\n marketTradeListeners.forEach(l -> l.handleMarketTrade(incrementingTradeId, tradeTime, price, size, buyer, seller, isTakerSideBuy));\n incrementingTradeId++;\n }\n\n}" }, { "identifier": "Order", "path": "src/main/java/ca/webdev/exchange/matching/Order.java", "snippet": "public class Order {\n private final UUID orderId;\n private final String owner;\n private final boolean isBuyOrder;\n private final double orderPrice;\n private final int orderSize;\n private double lastFilledPrice;\n private int remainingSize;\n\n public Order(UUID orderId, String owner, boolean isBuyOrder, double orderPrice, int orderSize, double lastFilledPrice, int remainingSize) {\n this.orderId = orderId;\n this.owner = owner;\n this.isBuyOrder = isBuyOrder;\n this.orderPrice = orderPrice;\n this.orderSize = orderSize;\n this.lastFilledPrice = lastFilledPrice;\n this.remainingSize = remainingSize;\n }\n\n public UUID getOrderId() {\n return orderId;\n }\n\n public String getOwner() {\n return owner;\n }\n\n public boolean isBuyOrder() {\n return isBuyOrder;\n }\n\n public double getOrderPrice() {\n return orderPrice;\n }\n\n public int getOrderSize() {\n return orderSize;\n }\n\n public double getLastFilledPrice() {\n return lastFilledPrice;\n }\n\n public void setLastFilledPrice(double lastFilledPrice) {\n this.lastFilledPrice = lastFilledPrice;\n }\n\n public int getRemainingSize() {\n return remainingSize;\n }\n\n public void setRemainingSize(int remainingSize) {\n this.remainingSize = remainingSize;\n }\n\n @Override\n public String toString() {\n return \"Order{\" +\n \"orderId=\" + orderId +\n \", owner='\" + owner + '\\'' +\n \", isBuyOrder=\" + isBuyOrder +\n \", orderPrice=\" + orderPrice +\n \", orderSize=\" + orderSize +\n \", lastFilledPrice=\" + lastFilledPrice +\n \", remainingSize=\" + remainingSize +\n '}';\n }\n}" }, { "identifier": "OpenHighLowClose", "path": "src/main/java/ca/webdev/exchange/web/model/OpenHighLowClose.java", "snippet": "public class OpenHighLowClose {\n private long time;\n private double open;\n private double high;\n private double low;\n private double close;\n\n public OpenHighLowClose() {\n }\n\n public OpenHighLowClose(long time, double open, double high, double low, double close) {\n this.time = time;\n this.open = open;\n this.high = high;\n this.low = low;\n this.close = close;\n }\n\n public long getTime() {\n return time;\n }\n\n public double getOpen() {\n return open;\n }\n\n public double getHigh() {\n return high;\n }\n\n public double getLow() {\n return low;\n }\n\n public double getClose() {\n return close;\n }\n\n public void setTime(long time) {\n this.time = time;\n }\n\n public void setOpen(double open) {\n this.open = open;\n }\n\n public void setHigh(double high) {\n this.high = high;\n }\n\n public void setLow(double low) {\n this.low = low;\n }\n\n public void setClose(double close) {\n this.close = close;\n }\n}" }, { "identifier": "OrderBookUpdate", "path": "src/main/java/ca/webdev/exchange/web/model/OrderBookUpdate.java", "snippet": "public class OrderBookUpdate {\n private Map<Double, Integer> bidOrderBook;\n private Map<Double, Integer> askOrderBook;\n\n public OrderBookUpdate() {\n\n }\n\n public OrderBookUpdate(Map<Double, Integer> bidOrderBook, Map<Double, Integer> askOrderBook) {\n this.bidOrderBook = bidOrderBook;\n this.askOrderBook = askOrderBook;\n }\n\n public Map<Double, Integer> getBidOrderBook() {\n return bidOrderBook;\n }\n\n public Map<Double, Integer> getAskOrderBook() {\n return askOrderBook;\n }\n\n public void setBidOrderBook(Map<Double, Integer> bidOrderBook) {\n this.bidOrderBook = bidOrderBook;\n }\n\n public void setAskOrderBook(Map<Double, Integer> askOrderBook) {\n this.askOrderBook = askOrderBook;\n }\n}" }, { "identifier": "OrderUpdate", "path": "src/main/java/ca/webdev/exchange/web/model/OrderUpdate.java", "snippet": "public class OrderUpdate {\n private String orderId;\n private long orderUpdateTime;\n private String side;\n private double price;\n private int size;\n private double filledPrice;\n private int filledSize;\n private String orderStatus;\n\n public OrderUpdate() {\n }\n\n public OrderUpdate(String orderId, long orderUpdateTime, String side, double price, int size, double filledPrice, int filledSize, String orderStatus) {\n this.orderId = orderId;\n this.orderUpdateTime = orderUpdateTime;\n this.side = side;\n this.price = price;\n this.size = size;\n this.filledPrice = filledPrice;\n this.filledSize = filledSize;\n this.orderStatus = orderStatus;\n }\n\n public String getOrderId() {\n return orderId;\n }\n\n public void setOrderId(String orderId) {\n this.orderId = orderId;\n }\n\n public long getOrderUpdateTime() {\n return orderUpdateTime;\n }\n\n public void setOrderUpdateTime(long orderUpdateTime) {\n this.orderUpdateTime = orderUpdateTime;\n }\n\n public String getSide() {\n return side;\n }\n\n public void setSide(String side) {\n this.side = side;\n }\n\n public double getPrice() {\n return price;\n }\n\n public void setPrice(double price) {\n this.price = price;\n }\n\n public int getSize() {\n return size;\n }\n\n public void setSize(int size) {\n this.size = size;\n }\n\n public double getFilledPrice() {\n return filledPrice;\n }\n\n public void setFilledPrice(double filledPrice) {\n this.filledPrice = filledPrice;\n }\n\n public int getFilledSize() {\n return filledSize;\n }\n\n public void setFilledSize(int filledSize) {\n this.filledSize = filledSize;\n }\n\n public String getOrderStatus() {\n return orderStatus;\n }\n\n public void setOrderStatus(String orderStatus) {\n this.orderStatus = orderStatus;\n }\n}" }, { "identifier": "RecentTrade", "path": "src/main/java/ca/webdev/exchange/web/model/RecentTrade.java", "snippet": "public class RecentTrade {\n\n private long tradeTime;\n private double price;\n private int size;\n private String takerSide;\n\n public RecentTrade() {\n }\n\n public RecentTrade(long tradeTime, double price, int size, String takerSide) {\n this.tradeTime = tradeTime;\n this.price = price;\n this.size = size;\n this.takerSide = takerSide;\n }\n\n public long getTradeTime() {\n return tradeTime;\n }\n\n public double getPrice() {\n return price;\n }\n\n public int getSize() {\n return size;\n }\n\n public String getTakerSide() {\n return takerSide;\n }\n\n public void setTradeTime(long tradeTime) {\n this.tradeTime = tradeTime;\n }\n\n public void setPrice(double price) {\n this.price = price;\n }\n\n public void setSize(int size) {\n this.size = size;\n }\n\n public void setTakerSide(String takerSide) {\n this.takerSide = takerSide;\n }\n}" }, { "identifier": "UserTrade", "path": "src/main/java/ca/webdev/exchange/web/model/UserTrade.java", "snippet": "public class UserTrade {\n\n private long tradeTime;\n private String side;\n private double price;\n private int size;\n\n public UserTrade() {\n }\n\n public UserTrade(long tradeTime, String side, double price, int size) {\n this.tradeTime = tradeTime;\n this.side = side;\n this.price = price;\n this.size = size;\n }\n\n public long getTradeTime() {\n return tradeTime;\n }\n\n public double getPrice() {\n return price;\n }\n\n public int getSize() {\n return size;\n }\n\n public String getSide() {\n return side;\n }\n\n public void setTradeTime(long tradeTime) {\n this.tradeTime = tradeTime;\n }\n\n public void setPrice(double price) {\n this.price = price;\n }\n\n public void setSize(int size) {\n this.size = size;\n }\n\n public void setSide(String side) {\n this.side = side;\n }\n}" }, { "identifier": "sumSizes", "path": "src/main/java/ca/webdev/exchange/web/OrderBookUtil.java", "snippet": "public static Map<Double, Integer> sumSizes(SortedMap<Double, Integer> sizeSummedOrderBook, Map<Double, Queue<Order>> orderBook) {\n\n orderBook.forEach((priceLevel, orders) -> {\n int sum = orders.stream().mapToInt(Order::getRemainingSize).sum();\n sizeSummedOrderBook.put(priceLevel, sum);\n });\n\n return sizeSummedOrderBook;\n}" } ]
import ca.webdev.exchange.matching.MatchingEngine; import ca.webdev.exchange.matching.Order; import ca.webdev.exchange.web.model.OpenHighLowClose; import ca.webdev.exchange.web.model.OrderBookUpdate; import ca.webdev.exchange.web.model.OrderUpdate; import ca.webdev.exchange.web.model.RecentTrade; import ca.webdev.exchange.web.model.UserTrade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Component; import java.util.Comparator; import java.util.Queue; import java.util.SortedMap; import java.util.TreeMap; import static ca.webdev.exchange.web.OrderBookUtil.sumSizes;
4,634
package ca.webdev.exchange.web.websocket; @Component public class Publisher { @Autowired private SimpMessagingTemplate template; public Publisher(MatchingEngine matchingEngine) { matchingEngine.registerOrderBookListener(this::handleOrderBook); matchingEngine.registerMarketTradeListener(this::handleMarketTrade); } public void handleOrderBook(SortedMap<Double, Queue<Order>> bidOrderBook, SortedMap<Double, Queue<Order>> askOrderBook) {
package ca.webdev.exchange.web.websocket; @Component public class Publisher { @Autowired private SimpMessagingTemplate template; public Publisher(MatchingEngine matchingEngine) { matchingEngine.registerOrderBookListener(this::handleOrderBook); matchingEngine.registerMarketTradeListener(this::handleMarketTrade); } public void handleOrderBook(SortedMap<Double, Queue<Order>> bidOrderBook, SortedMap<Double, Queue<Order>> askOrderBook) {
template.convertAndSend("/topic/orderbookupdates", new OrderBookUpdate(sumSizes(new TreeMap<>(Comparator.reverseOrder()), bidOrderBook), sumSizes(new TreeMap<>(), askOrderBook)));
3
2023-11-20 16:03:59+00:00
8k
FalkorDB/JFalkorDB
src/test/java/com/falkordb/GraphAPITest.java
[ { "identifier": "Label", "path": "src/main/java/com/falkordb/Statistics.java", "snippet": "enum Label{\n\tLABELS_ADDED(\"Labels added\"),\n\tINDICES_ADDED(\"Indices created\"),\n\tINDICES_DELETED(\"Indices deleted\"),\n\tNODES_CREATED(\"Nodes created\"),\n\tNODES_DELETED(\"Nodes deleted\"),\n\tRELATIONSHIPS_DELETED(\"Relationships deleted\"),\n\tPROPERTIES_SET(\"Properties set\"),\n\tRELATIONSHIPS_CREATED(\"Relationships created\"),\n\tCACHED_EXECUTION(\"Cached execution\"),\n\tQUERY_INTERNAL_EXECUTION_TIME(\"Query internal execution time\");\n\n private final String text;\n\n\tLabel(String text) {\n\t\tthis.text = text;\n\t}\n\t\t\n\t@Override\n\tpublic String toString() {\n return this.text;\n }\n\n\t/**\n\t * Get a Label by label text\n\t * \n\t * @param value label text\n\t * @return the matching Label\n\t */\n public static Label getEnum(String value) {\n for(Label v : values()) {\n if(v.toString().equalsIgnoreCase(value)) return v;\n }\n return null;\n }\n}" }, { "identifier": "GraphException", "path": "src/main/java/com/falkordb/exceptions/GraphException.java", "snippet": "public class GraphException extends JedisDataException {\n private static final long serialVersionUID = -476099681322055468L;\n\n public GraphException(String message) {\n super(message);\n }\n\n public GraphException(Throwable cause) {\n super(cause);\n }\n\n public GraphException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "Edge", "path": "src/main/java/com/falkordb/graph_entities/Edge.java", "snippet": "public class Edge extends GraphEntity {\n\n //members\n private String relationshipType;\n private long source;\n private long destination;\n\n public Edge() {\n super();\n }\n\n /**\n * Use this constructor to reduce memory allocations\n * when properties are added to the edge\n * @param propertiesCapacity preallocate the capacity for the properties\n */\n public Edge(int propertiesCapacity) {\n super(propertiesCapacity);\n }\n //getters & setters\n\n /**\n * @return the edge relationship type\n */\n public String getRelationshipType() {\n return relationshipType;\n }\n\n /**\n * @param relationshipType - the relationship type to be set.\n */\n public void setRelationshipType(String relationshipType) {\n this.relationshipType = relationshipType;\n }\n\n\n /**\n * @return The id of the source node\n */\n public long getSource() {\n return source;\n }\n\n /**\n * @param source - The id of the source node to be set\n */\n public void setSource(long source) {\n this.source = source;\n }\n\n /**\n *\n * @return the id of the destination node\n */\n public long getDestination() {\n return destination;\n }\n\n /**\n *\n * @param destination - The id of the destination node to be set\n */\n public void setDestination(long destination) {\n this.destination = destination;\n }\n\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Edge)) return false;\n if (!super.equals(o)) return false;\n Edge edge = (Edge) o;\n return source == edge.source &&\n destination == edge.destination &&\n Objects.equals(relationshipType, edge.relationshipType);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), relationshipType, source, destination);\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"Edge{\");\n sb.append(\"relationshipType='\").append(relationshipType).append('\\'');\n sb.append(\", source=\").append(source);\n sb.append(\", destination=\").append(destination);\n sb.append(\", id=\").append(id);\n sb.append(\", propertyMap=\").append(propertyMap);\n sb.append('}');\n return sb.toString();\n }\n}" }, { "identifier": "Node", "path": "src/main/java/com/falkordb/graph_entities/Node.java", "snippet": "public class Node extends GraphEntity {\n\n //members\n private final List<String> labels;\n\n public Node() {\n super();\n labels = new ArrayList<>();\n }\n\n /**\n * Use this constructor to reduce memory allocations \n * when labels or properties are added to the node\n * @param labelsCapacity preallocate the capacity for the node labels\n * @param propertiesCapacity preallocate the capacity for the properties\n */\n public Node(int labelsCapacity, int propertiesCapacity) {\n super(propertiesCapacity);\n this.labels = new ArrayList<>(labelsCapacity);\n }\n\n\n /**\n * @param label - a label to be add\n */\n public void addLabel(String label) {\n labels.add(label);\n }\n\n /**\n * @param label - a label to be removed\n */\n public void removeLabel(String label) {\n labels.remove(label);\n }\n\n /**\n * @param index - label index\n * @return the property label\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= getNumberOfLabels()})\n */\n public String getLabel(int index){\n return labels.get(index);\n }\n\n /**\n *\n * @return the number of labels\n */\n public int getNumberOfLabels() {\n return labels.size();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Node)) return false;\n if (!super.equals(o)) return false;\n Node node = (Node) o;\n return Objects.equals(labels, node.labels);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), labels);\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"Node{\");\n sb.append(\"labels=\").append(labels);\n sb.append(\", id=\").append(id);\n sb.append(\", propertyMap=\").append(propertyMap);\n sb.append('}');\n return sb.toString();\n }\n}" }, { "identifier": "Path", "path": "src/main/java/com/falkordb/graph_entities/Path.java", "snippet": "public final class Path {\n\n private final List<Node> nodes;\n private final List<Edge> edges;\n\n\n /**\n * Parametrized constructor\n * @param nodes - List of nodes.\n * @param edges - List of edges.\n */\n public Path(List<Node> nodes, List<Edge> edges) {\n this.nodes = nodes;\n this.edges = edges;\n }\n\n /**\n * Returns the nodes of the path.\n * @return List of nodes.\n */\n public List<Node> getNodes() {\n return nodes;\n }\n\n /**\n * Returns the edges of the path.\n * @return List of edges.\n */\n public List<Edge> getEdges() {\n return edges;\n }\n\n /**\n * Returns the length of the path - number of edges.\n * @return Number of edges.\n */\n public int length() {\n return edges.size();\n }\n\n /**\n * Return the number of nodes in the path.\n * @return Number of nodes.\n */\n public int nodeCount(){\n return nodes.size();\n }\n\n /**\n * Returns the first node in the path.\n * @return First nodes in the path.\n * @throws IndexOutOfBoundsException if the path is empty.\n */\n public Node firstNode(){\n return nodes.get(0);\n }\n\n /**\n * Returns the last node in the path.\n * @return Last nodes in the path.\n * @throws IndexOutOfBoundsException if the path is empty.\n */\n public Node lastNode(){\n return nodes.get(nodes.size() - 1);\n }\n\n /**\n * Returns a node with specified index in the path.\n * @param index index of the node.\n * @return Node.\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= nodesCount()})\n */\n public Node getNode(int index){\n return nodes.get(index);\n }\n\n /**\n * Returns an edge with specified index in the path.\n * @param index index of the edge.\n * @return Edge.\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= length()})\n */\n public Edge getEdge(int index){\n return edges.get(index);\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 Path path = (Path) o;\n return Objects.equals(nodes, path.nodes) &&\n Objects.equals(edges, path.edges);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(nodes, edges);\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"Path{\");\n sb.append(\"nodes=\").append(nodes);\n sb.append(\", edges=\").append(edges);\n sb.append('}');\n return sb.toString();\n }\n}" }, { "identifier": "Point", "path": "src/main/java/com/falkordb/graph_entities/Point.java", "snippet": "public final class Point {\n\n private static final double EPSILON = 1e-5;\n\n private final double latitude;\n private final double longitude;\n\n /**\n * @param latitude The latitude in degrees. It must be in the range [-90.0, +90.0]\n * @param longitude The longitude in degrees. It must be in the range [-180.0, +180.0]\n */\n public Point(double latitude, double longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n /**\n * @param values {@code [latitude, longitude]}\n */\n public Point(List<Double> values) {\n if (values == null || values.size() != 2) {\n throw new IllegalArgumentException(\"Point requires two doubles.\");\n }\n this.latitude = values.get(0);\n this.longitude = values.get(1);\n }\n\n /**\n * Get the latitude in degrees\n * @return latitude\n */\n public double getLatitude() {\n return latitude;\n }\n\n /**\n * Get the longitude in degrees\n * @return longitude\n */\n public double getLongitude() {\n return longitude;\n }\n\n @Override\n public boolean equals(Object other) {\n if (this == other){ \n return true;\n } \n if (!(other instanceof Point)){\n return false; \n } \n Point o = (Point) other;\n return Math.abs(latitude - o.latitude) < EPSILON &&\n Math.abs(longitude - o.longitude) < EPSILON;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(latitude, longitude);\n }\n\n @Override\n public String toString() {\n return \"Point{latitude=\" + latitude + \", longitude=\" + longitude + \"}\";\n }\n}" }, { "identifier": "Property", "path": "src/main/java/com/falkordb/graph_entities/Property.java", "snippet": "public class Property <T> {\n\n //members\n private String name;\n private T value;\n\n /**\n * Default constructor\n */\n public Property() {}\n \n /**\n * Parameterized constructor\n *\n * @param name property name\n * @param value property value\n */\n public Property(String name, T value) {\n this.name = name;\n this.value = value;\n }\n\n /**\n * @return property name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name property name to be set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n\n /**\n * @return property value\n */\n public T getValue() {\n return value;\n }\n\n\n /**\n * @param value property value to be set\n */\n public void setValue(T value) {\n this.value = value;\n }\n\n private boolean valueEquals(Object value1, Object value2) {\n if(value1 instanceof Integer) value1 = Long.valueOf(((Integer) value1).longValue());\n if(value2 instanceof Integer) value2 = Long.valueOf(((Integer) value2).longValue());\n return Objects.equals(value1, value2);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Property)) return false;\n Property<?> property = (Property<?>) o;\n return Objects.equals(name, property.name) &&\n valueEquals(value, property.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n /**\n * Default toString implementation\n * @return string representation of the property\n */\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"Property{\");\n sb.append(\"name='\").append(name).append('\\'');\n sb.append(\", value=\").append(value);\n sb.append('}');\n return sb.toString();\n }\n}" }, { "identifier": "PathBuilder", "path": "src/test/java/com/falkordb/test/utils/PathBuilder.java", "snippet": "public final class PathBuilder{\n private final List<Node> nodes;\n private final List<Edge> edges;\n private Class<?> currentAppendClass = Node.class;\n\n public PathBuilder() {\n this(0);\n }\n\n public PathBuilder(int nodesCount){\n this.nodes = new ArrayList<>(nodesCount);\n this.edges = new ArrayList<>(nodesCount > 0 ? nodesCount - 1 : 0);\n }\n\n public PathBuilder append(Object object){\n Class<? extends Object> c = object.getClass();\n if(!currentAppendClass.equals(c)){\n throw new IllegalArgumentException(\"Path Builder expected \" + currentAppendClass.getSimpleName() + \" but was \" + c.getSimpleName());\n }\n if(c.equals(Node.class)) {\n return appendNode((Node)object);\n }\n return appendEdge((Edge)object);\n }\n\n private PathBuilder appendEdge(Edge edge) {\n edges.add(edge);\n currentAppendClass = Node.class;\n return this;\n }\n\n private PathBuilder appendNode(Node node){\n nodes.add(node);\n currentAppendClass = Edge.class;\n return this;\n }\n\n public Path build(){\n if(nodes.size() != edges.size() + 1){\n throw new IllegalArgumentException(\"Path builder nodes count should be edge count + 1\");\n }\n return new Path(nodes, edges);\n }\n}" } ]
import static org.junit.Assert.fail; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.falkordb.Statistics.Label; import com.falkordb.exceptions.GraphException; import com.falkordb.graph_entities.Edge; import com.falkordb.graph_entities.Node; import com.falkordb.graph_entities.Path; import com.falkordb.graph_entities.Point; import com.falkordb.graph_entities.Property; import com.falkordb.test.utils.PathBuilder;
5,780
Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertEquals(1, deleteResult.getStatistics().nodesDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testDeleteRelationship() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet deleteResult = client.query("MATCH (a:person)-[e]->() WHERE (a.name = 'roi') DELETE e"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_DELETED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testIndex() { // Create both source and destination nodes Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); ResultSet createIndexResult = client.query("CREATE INDEX ON :person(age)"); Assert.assertFalse(createIndexResult.iterator().hasNext()); Assert.assertEquals(1, createIndexResult.getStatistics().indicesAdded()); // since RediSearch as index, those action are allowed ResultSet createNonExistingIndexResult = client.query("CREATE INDEX ON :person(age1)"); Assert.assertFalse(createNonExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(createNonExistingIndexResult.getStatistics().getStringValue(Label.INDICES_ADDED)); Assert.assertEquals(1, createNonExistingIndexResult.getStatistics().indicesAdded()); try { client.query("CREATE INDEX ON :person(age)"); fail("Expected Exception was not thrown."); } catch (Exception e) { } ResultSet deleteExistingIndexResult = client.query("DROP INDEX ON :person(age)"); Assert.assertFalse(deleteExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(deleteExistingIndexResult.getStatistics().getStringValue(Label.INDICES_DELETED)); Assert.assertEquals(1, deleteExistingIndexResult.getStatistics().indicesDeleted()); } @Test public void testHeader() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet queryResult = client.query("MATCH (a:person)-[r:knows]->(b:person) RETURN a,r, a.age"); Header header = queryResult.getHeader(); Assert.assertNotNull(header); Assert.assertEquals("HeaderImpl{" + "schemaTypes=[COLUMN_SCALAR, COLUMN_SCALAR, COLUMN_SCALAR], " + "schemaNames=[a, r, a.age]}", header.toString()); List<String> schemaNames = header.getSchemaNames(); Assert.assertNotNull(schemaNames); Assert.assertEquals(3, schemaNames.size()); Assert.assertEquals("a", schemaNames.get(0)); Assert.assertEquals("r", schemaNames.get(1)); Assert.assertEquals("a.age", schemaNames.get(2)); } @Test public void testRecord() { String name = "roi"; int age = 32; double doubleValue = 3.14; boolean boolValue = true; String place = "TLV"; int since = 2000; Property<String> nameProperty = new Property<>("name", name); Property<Integer> ageProperty = new Property<>("age", age); Property<Double> doubleProperty = new Property<>("doubleValue", doubleValue); Property<Boolean> trueBooleanProperty = new Property<>("boolValue", true); Property<Boolean> falseBooleanProperty = new Property<>("boolValue", false); Node expectedNode = new Node(); expectedNode.setId(0); expectedNode.addLabel("person"); expectedNode.addProperty(nameProperty); expectedNode.addProperty(ageProperty); expectedNode.addProperty(doubleProperty); expectedNode.addProperty(trueBooleanProperty); Assert.assertEquals( "Node{labels=[person], id=0, " + "propertyMap={name=Property{name='name', value=roi}, " + "boolValue=Property{name='boolValue', value=true}, " + "doubleValue=Property{name='doubleValue', value=3.14}, " + "age=Property{name='age', value=32}}}", expectedNode.toString()); Assert.assertEquals( 4, expectedNode.getNumberOfProperties());
package com.falkordb; public class GraphAPITest { private GraphContextGenerator client; @Before public void createApi() { client = FalkorDB.driver().graph("social"); } @After public void deleteGraph() { client.deleteGraph(); client.close(); } @Test public void testCreateNode() { // Create a node ResultSet resultSet = client.query("CREATE ({name:'roi',age:32})"); Assert.assertEquals(1, resultSet.getStatistics().nodesCreated()); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.NODES_DELETED)); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.RELATIONSHIPS_DELETED)); Assert.assertEquals(2, resultSet.getStatistics().propertiesSet()); Assert.assertNotNull(resultSet.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Iterator<Record> iterator = resultSet.iterator(); Assert.assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException was not thrown."); } catch (NoSuchElementException ignored) { } } @Test public void testCreateLabeledNode() { // Create a node with a label ResultSet resultSet = client.query("CREATE (:human{name:'danny',age:12})"); Assert.assertFalse(resultSet.iterator().hasNext()); Assert.assertEquals("1", resultSet.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertEquals("2", resultSet.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNotNull(resultSet.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testConnectNodes() { // Create both source and destination nodes Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); // Connect source and destination nodes. ResultSet resultSet = client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(b)"); Assert.assertFalse(resultSet.iterator().hasNext()); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertEquals(1, resultSet.getStatistics().relationshipsCreated()); Assert.assertEquals(0, resultSet.getStatistics().relationshipsDeleted()); Assert.assertNotNull(resultSet.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testDeleteNodes() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); ResultSet deleteResult = client.query("MATCH (a:person) WHERE (a.name = 'roi') DELETE a"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_DELETED)); Assert.assertEquals(1, deleteResult.getStatistics().nodesDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(b)")); deleteResult = client.query("MATCH (a:person) WHERE (a.name = 'roi') DELETE a"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertEquals(1, deleteResult.getStatistics().nodesDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testDeleteRelationship() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet deleteResult = client.query("MATCH (a:person)-[e]->() WHERE (a.name = 'roi') DELETE e"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_DELETED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testIndex() { // Create both source and destination nodes Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); ResultSet createIndexResult = client.query("CREATE INDEX ON :person(age)"); Assert.assertFalse(createIndexResult.iterator().hasNext()); Assert.assertEquals(1, createIndexResult.getStatistics().indicesAdded()); // since RediSearch as index, those action are allowed ResultSet createNonExistingIndexResult = client.query("CREATE INDEX ON :person(age1)"); Assert.assertFalse(createNonExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(createNonExistingIndexResult.getStatistics().getStringValue(Label.INDICES_ADDED)); Assert.assertEquals(1, createNonExistingIndexResult.getStatistics().indicesAdded()); try { client.query("CREATE INDEX ON :person(age)"); fail("Expected Exception was not thrown."); } catch (Exception e) { } ResultSet deleteExistingIndexResult = client.query("DROP INDEX ON :person(age)"); Assert.assertFalse(deleteExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(deleteExistingIndexResult.getStatistics().getStringValue(Label.INDICES_DELETED)); Assert.assertEquals(1, deleteExistingIndexResult.getStatistics().indicesDeleted()); } @Test public void testHeader() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet queryResult = client.query("MATCH (a:person)-[r:knows]->(b:person) RETURN a,r, a.age"); Header header = queryResult.getHeader(); Assert.assertNotNull(header); Assert.assertEquals("HeaderImpl{" + "schemaTypes=[COLUMN_SCALAR, COLUMN_SCALAR, COLUMN_SCALAR], " + "schemaNames=[a, r, a.age]}", header.toString()); List<String> schemaNames = header.getSchemaNames(); Assert.assertNotNull(schemaNames); Assert.assertEquals(3, schemaNames.size()); Assert.assertEquals("a", schemaNames.get(0)); Assert.assertEquals("r", schemaNames.get(1)); Assert.assertEquals("a.age", schemaNames.get(2)); } @Test public void testRecord() { String name = "roi"; int age = 32; double doubleValue = 3.14; boolean boolValue = true; String place = "TLV"; int since = 2000; Property<String> nameProperty = new Property<>("name", name); Property<Integer> ageProperty = new Property<>("age", age); Property<Double> doubleProperty = new Property<>("doubleValue", doubleValue); Property<Boolean> trueBooleanProperty = new Property<>("boolValue", true); Property<Boolean> falseBooleanProperty = new Property<>("boolValue", false); Node expectedNode = new Node(); expectedNode.setId(0); expectedNode.addLabel("person"); expectedNode.addProperty(nameProperty); expectedNode.addProperty(ageProperty); expectedNode.addProperty(doubleProperty); expectedNode.addProperty(trueBooleanProperty); Assert.assertEquals( "Node{labels=[person], id=0, " + "propertyMap={name=Property{name='name', value=roi}, " + "boolValue=Property{name='boolValue', value=true}, " + "doubleValue=Property{name='doubleValue', value=3.14}, " + "age=Property{name='age', value=32}}}", expectedNode.toString()); Assert.assertEquals( 4, expectedNode.getNumberOfProperties());
Edge expectedEdge = new Edge();
2
2023-11-26 13:38:14+00:00
8k
EcoNetsTech/spore-spring-boot-starter
src/main/java/cn/econets/ximutech/spore/config/RetrofitAutoConfiguration.java
[ { "identifier": "GlobalInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/GlobalInterceptor.java", "snippet": "public interface GlobalInterceptor extends Interceptor {\n}" }, { "identifier": "RetryInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/retry/RetryInterceptor.java", "snippet": "public class RetryInterceptor implements Interceptor {\n\n private static final Logger logger = LoggerFactory.getLogger(RetryInterceptor.class);\n\n protected final GlobalRetryProperty globalRetryProperty;\n\n public RetryInterceptor(GlobalRetryProperty globalRetryProperty) {\n this.globalRetryProperty = globalRetryProperty;\n }\n\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n Method method = RetrofitUtils.getMethodFormRequest(request);\n if (method == null) {\n return chain.proceed(request);\n }\n // 获取重试配置\n Retry retry = AnnotationExtendUtils.findMergedAnnotation(method, method.getDeclaringClass(), Retry.class);\n if (!needRetry(retry)) {\n return chain.proceed(request);\n }\n // 重试\n int maxRetries = retry == null ? globalRetryProperty.getMaxRetries() : retry.maxRetries();\n int intervalMs = retry == null ? globalRetryProperty.getIntervalMs() : retry.intervalMs();\n RetryRule[] retryRules = retry == null ? globalRetryProperty.getRetryRules() : retry.retryRules();\n return retryIntercept(maxRetries, intervalMs, retryRules, chain);\n }\n\n protected boolean needRetry(Retry retry) {\n if (globalRetryProperty.isEnable()) {\n if (retry == null) {\n return true;\n }\n return retry.enable();\n } else {\n return retry != null && retry.enable();\n }\n }\n\n protected Response retryIntercept(int maxRetries, int intervalMs, RetryRule[] retryRules, Chain chain) {\n HashSet<RetryRule> retryRuleSet = (HashSet<RetryRule>)Arrays.stream(retryRules).collect(Collectors.toSet());\n RetryStrategy retryStrategy = new RetryStrategy(maxRetries, intervalMs);\n while (true) {\n try {\n Request request = chain.request();\n Response response = chain.proceed(request);\n // 如果响应状态码是2xx就不用重试,直接返回 response\n if (!retryRuleSet.contains(RetryRule.RESPONSE_STATUS_NOT_2XX) || response.isSuccessful()) {\n return response;\n } else {\n if (!retryStrategy.shouldRetry()) {\n // 最后一次还没成功,返回最后一次response\n return response;\n }\n // 执行重试\n retryStrategy.retry();\n logger.debug(\"The response fails, retry is performed! The response code is \" + response.code());\n response.close();\n }\n } catch (Exception e) {\n if (shouldThrowEx(retryRuleSet, e)) {\n throw new RuntimeException(e);\n } else {\n if (!retryStrategy.shouldRetry()) {\n // 最后一次还没成功,抛出异常\n throw new RetryFailedException(\"Retry Failed: Total \" + maxRetries + \" attempts made at interval \" + intervalMs + \"ms\");\n }\n retryStrategy.retry();\n }\n }\n }\n }\n\n protected boolean shouldThrowEx(HashSet<RetryRule> retryRuleSet, Exception e) {\n if (retryRuleSet.contains(RetryRule.OCCUR_EXCEPTION)) {\n return false;\n }\n if (retryRuleSet.contains(RetryRule.OCCUR_IO_EXCEPTION)) {\n return !(e instanceof IOException);\n }\n return true;\n }\n\n}" }, { "identifier": "OkHttpClientRegistry", "path": "src/main/java/cn/econets/ximutech/spore/okhttp/OkHttpClientRegistry.java", "snippet": "public class OkHttpClientRegistry {\n\n private final Map<String, OkHttpClient> okHttpClientMap;\n\n private final List<OkHttpClientRegistrar> registrars;\n\n public OkHttpClientRegistry(List<OkHttpClientRegistrar> registrars) {\n this.registrars = registrars;\n this.okHttpClientMap = new HashMap<>(4);\n }\n\n @PostConstruct\n public void init() {\n if (registrars == null) {\n return;\n }\n registrars.forEach(registrar -> registrar.register(this));\n }\n\n public void register(String name, OkHttpClient okHttpClient) {\n okHttpClientMap.put(name, okHttpClient);\n }\n\n public OkHttpClient get(String name) {\n OkHttpClient okHttpClient = okHttpClientMap.get(name);\n Assert.notNull(okHttpClient, \"Specified OkHttpClient not found! name=\" + name);\n return okHttpClient;\n }\n\n}" }, { "identifier": "ErrorDecoder", "path": "src/main/java/cn/econets/ximutech/spore/decoder/ErrorDecoder.java", "snippet": "public interface ErrorDecoder {\n\n /**\n * 当无效响应的时候,将HTTP信息解码到异常中,无效响应由业务自行判断。\n * <p>\n * When the response is invalid, decode the HTTP information into the exception, invalid response is determined by business.\n *\n * @param request request\n * @param response response\n * @return If it returns null, the processing is ignored and the processing continues with the original response.\n */\n default RuntimeException invalidRespDecode(Request request, Response response) {\n if (!response.isSuccessful()) {\n throw RetrofitException.errorStatus(request, response);\n }\n return null;\n }\n\n /**\n * 当请求发生IO异常时,将HTTP信息解码到异常中。\n * <p>\n * When an IO exception occurs in the request, the HTTP information is decoded into the exception.\n *\n * @param request request\n * @param cause IOException\n * @return 解码后的异常\n */\n default RuntimeException ioExceptionDecode(Request request, IOException cause) {\n return RetrofitException.errorExecuting(request, cause);\n }\n\n /**\n * 当请求发生除IO异常之外的其它异常时,将HTTP信息解码到异常中。\n * <p>\n * When the request has an exception other than the IO exception, the HTTP information is decoded into the exception.\n *\n * @param request request\n * @param cause Exception\n * @return 解码后的异常\n */\n default RuntimeException exceptionDecode(Request request, Exception cause) {\n return RetrofitException.errorUnknown(request, cause);\n }\n\n class DefaultErrorDecoder implements ErrorDecoder {}\n\n}" }, { "identifier": "ErrorDecoderInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/decoder/ErrorDecoderInterceptor.java", "snippet": "public class ErrorDecoderInterceptor implements Interceptor, ApplicationContextAware {\n\n protected ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n @SneakyThrows\n public Response intercept(Chain chain) {\n Request request = chain.request();\n Method method = RetrofitUtils.getMethodFormRequest(request);\n if (method == null) {\n return chain.proceed(request);\n }\n SporeClient retrofitClient = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), SporeClient.class);\n ErrorDecoder errorDecoder = AppContextUtils.getBeanOrNew(applicationContext, retrofitClient.errorDecoder());\n boolean decoded = false;\n try {\n Response response = chain.proceed(request);\n if (errorDecoder == null) {\n return response;\n }\n decoded = true;\n Exception exception = errorDecoder.invalidRespDecode(request, response);\n if (exception == null) {\n return response;\n }\n throw exception;\n } catch (IOException e) {\n if (decoded) {\n throw e;\n }\n throw errorDecoder.ioExceptionDecode(request, e);\n } catch (Exception e) {\n if (decoded && e instanceof RuntimeException) {\n throw (RuntimeException)e;\n }\n throw errorDecoder.exceptionDecode(request, e);\n }\n }\n}" }, { "identifier": "LoggingInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/log/LoggingInterceptor.java", "snippet": "public class LoggingInterceptor implements Interceptor {\n\n private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);\n\n protected final GlobalLogProperty globalLogProperty;\n\n public LoggingInterceptor(GlobalLogProperty globalLogProperty) {\n this.globalLogProperty = globalLogProperty;\n }\n\n @Override\n public Response intercept(Chain chain) throws IOException {\n SporeLogging logging = findLogging(chain);\n if (!needLog(logging)) {\n return chain.proceed(chain.request());\n }\n LogLevel logLevel = logging == null ? globalLogProperty.getLogLevel() : logging.logLevel();\n LogStrategy logStrategy = logging == null ? globalLogProperty.getLogStrategy() : logging.logStrategy();\n HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(matchLogger(logLevel))\n .setLevel(HttpLoggingInterceptor.Level.valueOf(logStrategy.name()));\n return httpLoggingInterceptor.intercept(chain);\n }\n\n protected SporeLogging findLogging(Chain chain) {\n Method method = RetrofitUtils.getMethodFormRequest(chain.request());\n if (method == null) {\n return null;\n }\n return AnnotationExtendUtils.findMergedAnnotation(method, method.getDeclaringClass(), SporeLogging.class);\n }\n\n protected boolean needLog(SporeLogging logging) {\n if (globalLogProperty.isEnable()) {\n if (logging == null) {\n return true;\n }\n return logging.enable();\n } else {\n return logging != null && logging.enable();\n }\n }\n\n protected HttpLoggingInterceptor.Logger matchLogger(LogLevel level) {\n if (level == LogLevel.DEBUG) {\n return logger::debug;\n } else if (level == LogLevel.ERROR) {\n return logger::error;\n } else if (level == LogLevel.INFO) {\n return logger::info;\n } else if (level == LogLevel.WARN) {\n return logger::warn;\n } else if (level == LogLevel.TRACE) {\n return logger::trace;\n }\n throw new UnsupportedOperationException(\"We don't support this log level currently.\");\n }\n}" }, { "identifier": "OkHttpClientRegistrar", "path": "src/main/java/cn/econets/ximutech/spore/okhttp/OkHttpClientRegistrar.java", "snippet": "public interface OkHttpClientRegistrar {\n\n /**\n * 向#{@link OkHttpClientRegistry}注册数据\n *\n * @param registry SourceOkHttpClientRegistry\n */\n void register(OkHttpClientRegistry registry);\n}" }, { "identifier": "BaseTypeConverterFactory", "path": "src/main/java/cn/econets/ximutech/spore/retrofit/converter/BaseTypeConverterFactory.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class BaseTypeConverterFactory extends Converter.Factory {\n\n public static final BaseTypeConverterFactory INSTANCE = new BaseTypeConverterFactory();\n\n @Override\n public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,\n Annotation[] methodAnnotations, Retrofit retrofit) {\n return null;\n }\n\n @Override\n public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {\n if (String.class.getTypeName().equals(type.getTypeName())) {\n return new StringResponseConverter();\n } else if (Integer.class.getTypeName().equals(type.getTypeName())) {\n return new IntegerResponseConverter();\n } else if (Long.class.getTypeName().equals(type.getTypeName())) {\n return new LongResponseConverter();\n } else if (Boolean.class.getTypeName().equals(type.getTypeName())) {\n return new BooleanResponseConverter();\n } else if (Float.class.getTypeName().equals(type.getTypeName())) {\n return new FloatResponseConverter();\n } else if (Double.class.getTypeName().equals(type.getTypeName())) {\n return new DoubleResponseConverter();\n } else {\n return null;\n }\n\n }\n\n private static final class StringResponseConverter implements Converter<ResponseBody, String> {\n\n @Override\n public String convert(ResponseBody value) throws IOException {\n return value.string();\n }\n }\n\n private static class IntegerResponseConverter implements Converter<ResponseBody, Integer> {\n\n @Override\n public Integer convert(ResponseBody value) throws IOException {\n return Integer.valueOf(value.string());\n }\n }\n\n private static class LongResponseConverter implements Converter<ResponseBody, Long> {\n @Override\n public Long convert(ResponseBody value) throws IOException {\n return Long.valueOf(value.string());\n }\n }\n\n private static class BooleanResponseConverter implements Converter<ResponseBody, Boolean> {\n @Override\n public Boolean convert(ResponseBody value) throws IOException {\n return Boolean.valueOf(value.string());\n }\n }\n\n private static class FloatResponseConverter implements Converter<ResponseBody, Float> {\n @Override\n public Float convert(ResponseBody value) throws IOException {\n return Float.valueOf(value.string());\n }\n }\n\n private static class DoubleResponseConverter implements Converter<ResponseBody, Double> {\n @Override\n public Double convert(ResponseBody value) throws IOException {\n return Double.valueOf(value.string());\n }\n }\n}" }, { "identifier": "ServiceChooseInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/service/ServiceChooseInterceptor.java", "snippet": "public class ServiceChooseInterceptor implements Interceptor {\n\n protected final ServiceInstanceChooser serviceInstanceChooser;\n\n public ServiceChooseInterceptor(ServiceInstanceChooser serviceDiscovery) {\n this.serviceInstanceChooser = serviceDiscovery;\n }\n\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n Method method = RetrofitUtils.getMethodFormRequest(request);\n if (method == null) {\n return chain.proceed(request);\n }\n Class<?> declaringClass = method.getDeclaringClass();\n SporeClient retrofitClient =\n AnnotatedElementUtils.findMergedAnnotation(declaringClass, SporeClient.class);\n String baseUrl = retrofitClient.baseUrl();\n if (StringUtils.hasText(baseUrl)) {\n return chain.proceed(request);\n }\n // serviceId服务发现\n String serviceId = retrofitClient.serviceId();\n URI uri = serviceInstanceChooser.choose(serviceId);\n HttpUrl url = request.url();\n HttpUrl newUrl = url.newBuilder()\n .scheme(uri.getScheme())\n .host(uri.getHost())\n .port(uri.getPort())\n .build();\n Request newReq = request.newBuilder()\n .url(newUrl)\n .build();\n return chain.proceed(newReq);\n }\n}" }, { "identifier": "ServiceInstanceChooser", "path": "src/main/java/cn/econets/ximutech/spore/service/ServiceInstanceChooser.java", "snippet": "@FunctionalInterface\npublic interface ServiceInstanceChooser {\n\n URI choose(String serviceId);\n\n class NoValidServiceInstanceChooser implements ServiceInstanceChooser {\n\n @Override\n public URI choose(String serviceId) {\n throw new ServiceInstanceChooseException(\"No valid service instance selector, Please configure it!\");\n }\n }\n}" } ]
import cn.econets.ximutech.spore.GlobalInterceptor; import cn.econets.ximutech.spore.retry.RetryInterceptor; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import cn.econets.ximutech.spore.okhttp.OkHttpClientRegistry; import cn.econets.ximutech.spore.decoder.ErrorDecoder; import cn.econets.ximutech.spore.decoder.ErrorDecoderInterceptor; import cn.econets.ximutech.spore.log.LoggingInterceptor; import cn.econets.ximutech.spore.okhttp.OkHttpClientRegistrar; import cn.econets.ximutech.spore.retrofit.converter.BaseTypeConverterFactory; import cn.econets.ximutech.spore.service.ServiceChooseInterceptor; import cn.econets.ximutech.spore.service.ServiceInstanceChooser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import retrofit2.converter.jackson.JacksonConverterFactory; import java.util.List;
3,827
package cn.econets.ximutech.spore.config; /** * @author ximu */ @AutoConfiguration @EnableConfigurationProperties(RetrofitProperties.class) public class RetrofitAutoConfiguration { private final RetrofitProperties retrofitProperties; public RetrofitAutoConfiguration(RetrofitProperties retrofitProperties) { this.retrofitProperties = retrofitProperties; } @Bean
package cn.econets.ximutech.spore.config; /** * @author ximu */ @AutoConfiguration @EnableConfigurationProperties(RetrofitProperties.class) public class RetrofitAutoConfiguration { private final RetrofitProperties retrofitProperties; public RetrofitAutoConfiguration(RetrofitProperties retrofitProperties) { this.retrofitProperties = retrofitProperties; } @Bean
public BaseTypeConverterFactory basicTypeConverterFactory() {
7
2023-11-21 18:00:50+00:00
8k
NBHZW/hnustDatabaseCourseDesign
ruoyi-test/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java
[ { "identifier": "DateUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java", "snippet": "public class DateUtils extends org.apache.commons.lang3.time.DateUtils\r\n{\r\n public static String YYYY = \"yyyy\";\r\n\r\n public static String YYYY_MM = \"yyyy-MM\";\r\n\r\n public static String YYYY_MM_DD = \"yyyy-MM-dd\";\r\n\r\n public static String YYYYMMDDHHMMSS = \"yyyyMMddHHmmss\";\r\n\r\n public static String YYYY_MM_DD_HH_MM_SS = \"yyyy-MM-dd HH:mm:ss\";\r\n\r\n private static String[] parsePatterns = {\r\n \"yyyy-MM-dd\", \"yyyy-MM-dd HH:mm:ss\", \"yyyy-MM-dd HH:mm\", \"yyyy-MM\", \r\n \"yyyy/MM/dd\", \"yyyy/MM/dd HH:mm:ss\", \"yyyy/MM/dd HH:mm\", \"yyyy/MM\",\r\n \"yyyy.MM.dd\", \"yyyy.MM.dd HH:mm:ss\", \"yyyy.MM.dd HH:mm\", \"yyyy.MM\"};\r\n\r\n /**\r\n * 获取当前Date型日期\r\n * \r\n * @return Date() 当前日期\r\n */\r\n public static Date getNowDate()\r\n {\r\n return new Date();\r\n }\r\n\r\n /**\r\n * 获取当前日期, 默认格式为yyyy-MM-dd\r\n * \r\n * @return String\r\n */\r\n public static String getDate()\r\n {\r\n return dateTimeNow(YYYY_MM_DD);\r\n }\r\n\r\n public static final String getTime()\r\n {\r\n return dateTimeNow(YYYY_MM_DD_HH_MM_SS);\r\n }\r\n\r\n public static final String dateTimeNow()\r\n {\r\n return dateTimeNow(YYYYMMDDHHMMSS);\r\n }\r\n\r\n public static final String dateTimeNow(final String format)\r\n {\r\n return parseDateToStr(format, new Date());\r\n }\r\n\r\n public static final String dateTime(final Date date)\r\n {\r\n return parseDateToStr(YYYY_MM_DD, date);\r\n }\r\n\r\n public static final String parseDateToStr(final String format, final Date date)\r\n {\r\n return new SimpleDateFormat(format).format(date);\r\n }\r\n\r\n public static final Date dateTime(final String format, final String ts)\r\n {\r\n try\r\n {\r\n return new SimpleDateFormat(format).parse(ts);\r\n }\r\n catch (ParseException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n\r\n /**\r\n * 日期路径 即年/月/日 如2018/08/08\r\n */\r\n public static final String datePath()\r\n {\r\n Date now = new Date();\r\n return DateFormatUtils.format(now, \"yyyy/MM/dd\");\r\n }\r\n\r\n /**\r\n * 日期路径 即年/月/日 如20180808\r\n */\r\n public static final String dateTime()\r\n {\r\n Date now = new Date();\r\n return DateFormatUtils.format(now, \"yyyyMMdd\");\r\n }\r\n\r\n /**\r\n * 日期型字符串转化为日期 格式\r\n */\r\n public static Date parseDate(Object str)\r\n {\r\n if (str == null)\r\n {\r\n return null;\r\n }\r\n try\r\n {\r\n return parseDate(str.toString(), parsePatterns);\r\n }\r\n catch (ParseException e)\r\n {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * 获取服务器启动时间\r\n */\r\n public static Date getServerStartDate()\r\n {\r\n long time = ManagementFactory.getRuntimeMXBean().getStartTime();\r\n return new Date(time);\r\n }\r\n\r\n /**\r\n * 计算相差天数\r\n */\r\n public static int differentDaysByMillisecond(Date date1, Date date2)\r\n {\r\n return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));\r\n }\r\n\r\n /**\r\n * 计算时间差\r\n *\r\n * @param endTime 最后时间\r\n * @param startTime 开始时间\r\n * @return 时间差(天/小时/分钟)\r\n */\r\n public static String timeDistance(Date endDate, Date startTime)\r\n {\r\n long nd = 1000 * 24 * 60 * 60;\r\n long nh = 1000 * 60 * 60;\r\n long nm = 1000 * 60;\r\n // long ns = 1000;\r\n // 获得两个时间的毫秒时间差异\r\n long diff = endDate.getTime() - startTime.getTime();\r\n // 计算差多少天\r\n long day = diff / nd;\r\n // 计算差多少小时\r\n long hour = diff % nd / nh;\r\n // 计算差多少分钟\r\n long min = diff % nd % nh / nm;\r\n // 计算差多少秒//输出结果\r\n // long sec = diff % nd % nh % nm / ns;\r\n return day + \"天\" + hour + \"小时\" + min + \"分钟\";\r\n }\r\n\r\n /**\r\n * 增加 LocalDateTime ==> Date\r\n */\r\n public static Date toDate(LocalDateTime temporalAccessor)\r\n {\r\n ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());\r\n return Date.from(zdt.toInstant());\r\n }\r\n\r\n /**\r\n * 增加 LocalDate ==> Date\r\n */\r\n public static Date toDate(LocalDate temporalAccessor)\r\n {\r\n LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));\r\n ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());\r\n return Date.from(zdt.toInstant());\r\n }\r\n}\r" }, { "identifier": "SysUserMapper", "path": "ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java", "snippet": "public interface SysUserMapper\r\n{\r\n /**\r\n * 根据条件分页查询用户列表\r\n * \r\n * @param sysUser 用户信息\r\n * @return 用户信息集合信息\r\n */\r\n public List<SysUser> selectUserList(SysUser sysUser);\r\n\r\n /**\r\n * 根据条件分页查询已配用户角色列表\r\n * \r\n * @param user 用户信息\r\n * @return 用户信息集合信息\r\n */\r\n public List<SysUser> selectAllocatedList(SysUser user);\r\n\r\n /**\r\n * 根据条件分页查询未分配用户角色列表\r\n * \r\n * @param user 用户信息\r\n * @return 用户信息集合信息\r\n */\r\n public List<SysUser> selectUnallocatedList(SysUser user);\r\n\r\n /**\r\n * 通过用户名查询用户\r\n * \r\n * @param userName 用户名\r\n * @return 用户对象信息\r\n */\r\n public SysUser selectUserByUserName(String userName);\r\n\r\n /**\r\n * 通过用户ID查询用户\r\n * \r\n * @param userId 用户ID\r\n * @return 用户对象信息\r\n */\r\n public SysUser selectUserById(Long userId);\r\n\r\n /**\r\n * 新增用户信息\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int insertUser(SysUser user);\r\n\r\n /**\r\n * 修改用户信息\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int updateUser(SysUser user);\r\n\r\n /**\r\n * 修改用户头像\r\n * \r\n * @param userName 用户名\r\n * @param avatar 头像地址\r\n * @return 结果\r\n */\r\n public int updateUserAvatar(@Param(\"userName\") String userName, @Param(\"avatar\") String avatar);\r\n\r\n /**\r\n * 重置用户密码\r\n * \r\n * @param userName 用户名\r\n * @param password 密码\r\n * @return 结果\r\n */\r\n public int resetUserPwd(@Param(\"userName\") String userName, @Param(\"password\") String password);\r\n\r\n /**\r\n * 通过用户ID删除用户\r\n * \r\n * @param userId 用户ID\r\n * @return 结果\r\n */\r\n public int deleteUserById(Long userId);\r\n\r\n /**\r\n * 批量删除用户信息\r\n * \r\n * @param userIds 需要删除的用户ID\r\n * @return 结果\r\n */\r\n public int deleteUserByIds(Long[] userIds);\r\n\r\n /**\r\n * 校验用户名称是否唯一\r\n * \r\n * @param userName 用户名称\r\n * @return 结果\r\n */\r\n public SysUser checkUserNameUnique(String userName);\r\n\r\n /**\r\n * 校验学号是否唯一\r\n *\r\n * @param phonenumber 学号\r\n * @return 结果\r\n */\r\n public SysUser checkPhoneUnique(String phonenumber);\r\n\r\n /**\r\n * 校验email是否唯一\r\n *\r\n * @param email 用户邮箱\r\n * @return 结果\r\n */\r\n public SysUser checkEmailUnique(String email);\r\n}\r" }, { "identifier": "SysUser", "path": "ruoyi-test/src/main/java/com/ruoyi/system/domain/SysUser.java", "snippet": "public class SysUser extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n private Long userId;\n\n /** 部门ID */\n @Excel(name = \"部门ID\")\n private Long deptId;\n\n /** 用户账号 */\n @Excel(name = \"用户账号\")\n private String userName;\n\n /** 用户昵称 */\n @Excel(name = \"用户昵称\")\n private String nickName;\n\n /** 用户类型(00系统用户) */\n @Excel(name = \"用户类型\", readConverterExp = \"0=0系统用户\")\n private String userType;\n\n /** 用户邮箱 */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /** 学号 */\n @Excel(name = \"学号\")\n private String phonenumber;\n\n /** 用户性别(0男 1女 2未知) */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /** 头像地址 */\n @Excel(name = \"头像地址\")\n private String avatar;\n\n /** 密码 */\n @Excel(name = \"密码\")\n private String password;\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\")\n private String loginIp;\n\n /** 最后登录时间 */\n @JsonFormat(pattern = \"yyyy-MM-dd\")\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd\")\n private Date loginDate;\n\n public void setUserId(Long userId) \n {\n this.userId = userId;\n }\n\n public Long getUserId() \n {\n return userId;\n }\n public void setDeptId(Long deptId) \n {\n this.deptId = deptId;\n }\n\n public Long getDeptId() \n {\n return deptId;\n }\n public void setUserName(String userName) \n {\n this.userName = userName;\n }\n\n public String getUserName() \n {\n return userName;\n }\n public void setNickName(String nickName) \n {\n this.nickName = nickName;\n }\n\n public String getNickName() \n {\n return nickName;\n }\n public void setUserType(String userType) \n {\n this.userType = userType;\n }\n\n public String getUserType() \n {\n return userType;\n }\n public void setEmail(String email) \n {\n this.email = email;\n }\n\n public String getEmail() \n {\n return email;\n }\n public void setPhonenumber(String phonenumber) \n {\n this.phonenumber = phonenumber;\n }\n\n public String getPhonenumber() \n {\n return phonenumber;\n }\n public void setSex(String sex) \n {\n this.sex = sex;\n }\n\n public String getSex() \n {\n return sex;\n }\n public void setAvatar(String avatar) \n {\n this.avatar = avatar;\n }\n\n public String getAvatar() \n {\n return avatar;\n }\n public void setPassword(String password) \n {\n this.password = password;\n }\n\n public String getPassword() \n {\n return password;\n }\n public void setStatus(String status) \n {\n this.status = status;\n }\n\n public String getStatus() \n {\n return status;\n }\n public void setDelFlag(String delFlag) \n {\n this.delFlag = delFlag;\n }\n\n public String getDelFlag() \n {\n return delFlag;\n }\n public void setLoginIp(String loginIp) \n {\n this.loginIp = loginIp;\n }\n\n public String getLoginIp() \n {\n return loginIp;\n }\n public void setLoginDate(Date loginDate) \n {\n this.loginDate = loginDate;\n }\n\n public Date getLoginDate() \n {\n return loginDate;\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(\"userName\", getUserName())\n .append(\"nickName\", getNickName())\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(\"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 .toString();\n }\n}" }, { "identifier": "ISysUserService", "path": "ruoyi-system/src/main/java/com/ruoyi/system/service/ISysUserService.java", "snippet": "public interface ISysUserService\r\n{\r\n /**\r\n * 根据条件分页查询用户列表\r\n * \r\n * @param user 用户信息\r\n * @return 用户信息集合信息\r\n */\r\n public List<SysUser> selectUserList(SysUser user);\r\n\r\n /**\r\n * 根据条件分页查询已分配用户角色列表\r\n * \r\n * @param user 用户信息\r\n * @return 用户信息集合信息\r\n */\r\n public List<SysUser> selectAllocatedList(SysUser user);\r\n\r\n /**\r\n * 根据条件分页查询未分配用户角色列表\r\n * \r\n * @param user 用户信息\r\n * @return 用户信息集合信息\r\n */\r\n public List<SysUser> selectUnallocatedList(SysUser user);\r\n\r\n /**\r\n * 通过用户名查询用户\r\n * \r\n * @param userName 用户名\r\n * @return 用户对象信息\r\n */\r\n public SysUser selectUserByUserName(String userName);\r\n\r\n /**\r\n * 通过用户ID查询用户\r\n * \r\n * @param userId 用户ID\r\n * @return 用户对象信息\r\n */\r\n public SysUser selectUserById(Long userId);\r\n\r\n /**\r\n * 根据用户ID查询用户所属角色组\r\n * \r\n * @param userName 用户名\r\n * @return 结果\r\n */\r\n public String selectUserRoleGroup(String userName);\r\n\r\n /**\r\n * 根据用户ID查询用户所属岗位组\r\n * \r\n * @param userName 用户名\r\n * @return 结果\r\n */\r\n public String selectUserPostGroup(String userName);\r\n\r\n /**\r\n * 校验用户名称是否唯一\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public boolean checkUserNameUnique(SysUser user);\r\n\r\n /**\r\n * 校验学号是否唯一\r\n *\r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public boolean checkPhoneUnique(SysUser user);\r\n\r\n /**\r\n * 校验email是否唯一\r\n *\r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public boolean checkEmailUnique(SysUser user);\r\n\r\n /**\r\n * 校验用户是否允许操作\r\n * \r\n * @param user 用户信息\r\n */\r\n public void checkUserAllowed(SysUser user);\r\n\r\n /**\r\n * 校验用户是否有数据权限\r\n * \r\n * @param userId 用户id\r\n */\r\n public void checkUserDataScope(Long userId);\r\n\r\n /**\r\n * 新增用户信息\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int insertUser(SysUser user);\r\n\r\n /**\r\n * 注册用户信息\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public boolean registerUser(SysUser user);\r\n\r\n /**\r\n * 修改用户信息\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int updateUser(SysUser user);\r\n\r\n /**\r\n * 用户授权角色\r\n * \r\n * @param userId 用户ID\r\n * @param roleIds 角色组\r\n */\r\n public void insertUserAuth(Long userId, Long[] roleIds);\r\n\r\n /**\r\n * 修改用户状态\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int updateUserStatus(SysUser user);\r\n\r\n /**\r\n * 修改用户基本信息\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int updateUserProfile(SysUser user);\r\n\r\n /**\r\n * 修改用户头像\r\n * \r\n * @param userName 用户名\r\n * @param avatar 头像地址\r\n * @return 结果\r\n */\r\n public boolean updateUserAvatar(String userName, String avatar);\r\n\r\n /**\r\n * 重置用户密码\r\n * \r\n * @param user 用户信息\r\n * @return 结果\r\n */\r\n public int resetPwd(SysUser user);\r\n\r\n /**\r\n * 重置用户密码\r\n * \r\n * @param userName 用户名\r\n * @param password 密码\r\n * @return 结果\r\n */\r\n public int resetUserPwd(String userName, String password);\r\n\r\n /**\r\n * 通过用户ID删除用户\r\n * \r\n * @param userId 用户ID\r\n * @return 结果\r\n */\r\n public int deleteUserById(Long userId);\r\n\r\n /**\r\n * 批量删除用户信息\r\n * \r\n * @param userIds 需要删除的用户ID\r\n * @return 结果\r\n */\r\n public int deleteUserByIds(Long[] userIds);\r\n\r\n /**\r\n * 导入用户数据\r\n * \r\n * @param userList 用户数据列表\r\n * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据\r\n * @param operName 操作用户\r\n * @return 结果\r\n */\r\n public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName);\r\n}\r" } ]
import java.util.List; import com.ruoyi.common.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.system.mapper.SysUserMapper; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.service.ISysUserService;
5,045
package com.ruoyi.system.service.impl; /** * 用户信息Service业务层处理 * * @author ruoyi * @date 2023-10-24 */ @Service public class SysUserServiceImpl implements ISysUserService { @Autowired
package com.ruoyi.system.service.impl; /** * 用户信息Service业务层处理 * * @author ruoyi * @date 2023-10-24 */ @Service public class SysUserServiceImpl implements ISysUserService { @Autowired
private SysUserMapper sysUserMapper;
1
2023-11-25 02:50:45+00:00
8k
isXander/YetAnotherUILib
src/testmod/java/dev/isxander/yaul3/test/TestScreen.java
[ { "identifier": "Animation", "path": "src/main/java/dev/isxander/yaul3/api/animation/Animation.java", "snippet": "public non-sealed interface Animation extends Animatable {\n /**\n * Creates a new instance of an animation.\n * All methods that configure something about the animation are locked\n * after {@link Animation#play()} is called.\n * <br>\n * {@link Animation#duration(int)} must be called for this to be a playable animation.\n *\n * @return a new animation instance\n */\n static Animation of() {\n return new AnimationImpl();\n }\n\n /**\n * Creates a new instance of an animation.\n * All methods that configure something about the animation are locked\n * after {@link Animation#play()} is called.\n *\n * @param durationTicks the amount of ticks the animation takes. shorthand of {@link Animation#duration(int)}\n * @return a new animation instance\n */\n static Animation of(int durationTicks) {\n return of().duration(durationTicks);\n }\n\n /**\n * Adds an integer consumer to the animation.\n *\n * @param consumer the current value of this consumer\n * @param start the starting point for this animation consumer\n * @param end the ending point for this animation consumer\n * @return this\n */\n Animation consumerI(Consumer<Integer> consumer, double start, double end);\n\n /**\n * Adds a float consumer to the animation.\n *\n * @param consumer the current value of this consumer\n * @param start the starting point for this animation consumer\n * @param end the ending point for this animation consumer\n * @return this\n */\n Animation consumerF(Consumer<Float> consumer, double start, double end);\n\n /**\n * Adds a double consumer to the animation.\n *\n * @param consumer the setter\n * @param start the starting point for this animation consumer\n * @param end the ending point for this animation consumer\n * @return this\n */\n Animation consumerD(Consumer<Double> consumer, double start, double end);\n\n /**\n * Adds an integer delta consumer to the animation.\n * A delta consumer is like a regular consumer but only consumes the delta since the\n * previous tick of the animation.\n *\n * @param consumer the setter\n * @param start the starting point for this consumer\n * @param end the ending point for this consumer\n * @return this\n */\n Animation deltaConsumerI(Consumer<Integer> consumer, double start, double end);\n\n /**\n * Adds a float delta consumer to the animation.\n * A delta consumer is like a regular consumer but only consumes the delta since the\n * previous tick of the animation.\n *\n * @param consumer the setter\n * @param start the starting point for this consumer\n * @param end the ending point for this consumer\n * @return this\n */\n Animation deltaConsumerF(Consumer<Float> consumer, double start, double end);\n\n /**\n * Adds a double delta consumer to the animation.\n * A delta consumer is like a regular consumer but only consumes the delta since the\n * previous tick of the animation.\n *\n * @param consumer the setter\n * @param start the starting point for this consumer\n * @param end the ending point for this consumer\n * @return this\n */\n Animation deltaConsumerD(Consumer<Double> consumer, double start, double end);\n\n /**\n * Specifies the duration of the animation, in ticks.\n * 20 ticks is equal to 1 second.\n * @param ticks length of animation, in ticks\n * @return this\n */\n Animation duration(int ticks);\n\n /**\n * Specify the easing function for all animation consumers.\n * @see EasingFunction\n * @param easing the easing function to use\n * @return this\n */\n Animation easing(EasingFunction easing);\n\n @Override\n Animation copy();\n\n @Override\n Animation play();\n}" }, { "identifier": "AbstractLayoutWidget", "path": "src/main/java/dev/isxander/yaul3/impl/ui/AbstractLayoutWidget.java", "snippet": "public abstract class AbstractLayoutWidget implements LayoutWidget {\n private IntState x = IntState.of(0), y = IntState.of(0), width = IntState.of(0), height = IntState.of(0);\n private final List<RenderLayer> renderLayers = new ArrayList<>();\n private @Nullable LayoutWidget parent;\n public boolean justifying = false;\n\n @Override\n public final <T extends GuiEventListener & NarratableEntry> void addToScreen(Consumer<T> widgetConsumer, Consumer<Renderable> renderableConsumer) {\n addRenderLayersPre(renderableConsumer);\n innerAddToScreen(widgetConsumer, renderableConsumer);\n addRenderLayersPost(renderableConsumer);\n }\n\n protected <T extends GuiEventListener & NarratableEntry> void innerAddToScreen(Consumer<T> widgetConsumer, Consumer<Renderable> renderableConsumer) {\n\n }\n\n protected void addRenderLayersPre(Consumer<Renderable> renderableConsumer) {\n for (int i = 0; i < renderLayers.size(); i++) {\n RenderLayer layer = renderLayers.get(i);\n int z = i;\n renderableConsumer.accept((gui, mouseX, mouseY, partialTick) ->\n layer.renderPre(this, gui, z, mouseX, mouseY, partialTick));\n }\n }\n\n protected void addRenderLayersPost(Consumer<Renderable> renderableConsumer) {\n for (int i = 0; i < renderLayers.size(); i++) {\n RenderLayer layer = renderLayers.get(i);\n int z = i;\n renderableConsumer.accept((gui, mouseX, mouseY, partialTick) ->\n layer.renderPost(this, gui, z, mouseX, mouseY, partialTick));\n }\n }\n\n @Override\n public void removeFromScreen(Consumer<GuiEventListener> widgetConsumer) {\n\n }\n\n @Override\n public void setup() {\n Validate.isTrue(parent == null, \"Only a root widget can be setup!\");\n\n int iterations = 0;\n justifying = true;\n while (propagateDown() && iterations++ <= 100) {}\n justifying = false;\n if (iterations >= 100) {\n throw new IllegalStateException(\"LayoutWidget#setup() took too long!\");\n }\n }\n\n @Override\n public void onStateUpdate() {\n if (parent != null) {\n parent.onStateUpdate();\n } else if (!justifying) {\n // reached the top of the tree\n justifying = true;\n while (propagateDown()) {}\n justifying = false;\n }\n }\n\n @Override\n public LayoutWidget setX(IntState x) {\n this.x = x;\n this.x.setOwner(this);\n return this;\n }\n\n @Override\n public IntState getX() {\n return x;\n }\n\n @Override\n public LayoutWidget setY(IntState y) {\n this.y = y;\n this.y.setOwner(this);\n return this;\n }\n\n @Override\n public IntState getY() {\n return y;\n }\n\n @Override\n public LayoutWidget setWidth(IntState width) {\n this.width = width;\n this.width.setOwner(this);\n return this;\n }\n\n @Override\n public IntState getWidth() {\n return width;\n }\n\n @Override\n public LayoutWidget setHeight(IntState height) {\n this.height = height;\n this.height.setOwner(this);\n return this;\n }\n\n @Override\n public IntState getHeight() {\n return height;\n }\n\n @Override\n public LayoutWidget appendRenderLayers(RenderLayer... layers) {\n renderLayers.addAll(List.of(layers));\n return this;\n }\n\n @Override\n public LayoutWidget insertRenderLayers(int index, RenderLayer... layers) {\n renderLayers.addAll(index, List.of(layers));\n return this;\n }\n\n @Override\n public void setParent(@Nullable LayoutWidget owner) {\n this.parent = owner;\n }\n\n @Nullable\n @Override\n public LayoutWidget getParent() {\n return parent;\n }\n}" }, { "identifier": "DynamicGridWidget", "path": "src/main/java/dev/isxander/yaul3/impl/widgets/DynamicGridWidget.java", "snippet": "public class DynamicGridWidget extends AbstractLayout {\n private final List<GridItem> children = new ArrayList<>();\n private int padding = 0;\n\n public DynamicGridWidget(int x, int y, int width, int height) {\n super(x, y, width, height);\n }\n\n public void addChild(AbstractWidget widget, int cellHeight, int cellWidth) {\n this.children.add(new GridItem(cellHeight, cellWidth, widget));\n }\n\n public void addChild(AbstractWidget widget) {\n this.children.add(new GridItem(-1, -1, widget));\n }\n\n public void setPadding(int padding) {\n this.padding = padding;\n }\n\n public int getPadding() {\n return padding;\n }\n\n public void setWidth(int width) {\n this.width = width;\n }\n\n public void setHeight(int height) {\n this.height = height;\n }\n\n private boolean canFit(int gridX, int gridY, int cellWidth, int cellHeight, int optimalCells, boolean[][] grid) {\n if (gridX >= optimalCells || gridY >= optimalCells) {\n return false;\n }\n\n for (int x = gridX; x < gridX + cellWidth; x++) {\n for (int y = gridY; y < gridY + cellHeight; y++) {\n if (x >= grid.length || y >= grid[x].length) {\n throw new RuntimeException(\"Impossible to fit widget in grid!\");\n }\n\n if (grid[x][y]) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Recalculates the layout of this widget.\n */\n public void calculateLayout() {\n int totalCells = 0;\n for (GridItem child : this.children) {\n int widgetCells = child.getCellWidth() * child.getCellHeight();\n totalCells += widgetCells;\n }\n\n int optimalCells = (int) Math.ceil(Math.sqrt(totalCells));\n\n // Modify this to include padding.\n int cellWidth = (this.width) / optimalCells;\n int cellHeight = (this.height) / optimalCells;\n\n boolean[][] grid = new boolean[optimalCells][optimalCells];\n\n int currentX = getX();\n int currentY = getY();\n\n for (GridItem child : this.children) {\n int gridX = currentX / cellWidth;\n int gridY = currentY / cellHeight;\n\n while (!canFit(gridX, gridY, Math.abs(child.getCellWidth()) , Math.abs(child.getCellHeight()), optimalCells, grid)) {\n currentX += cellWidth;\n if (currentX >= this.width) {\n currentX = getX();\n currentY += cellHeight;\n }\n\n gridX = currentX / cellWidth;\n gridY = currentY / cellHeight;\n }\n\n if (gridX > optimalCells || gridY > optimalCells) {\n throw new RuntimeException(\"Impossible to fit widget in grid!\");\n }\n\n if(grid[gridX][gridY]) {\n currentX += cellWidth;\n if (currentX >= this.width) {\n currentX = getX();\n currentY += cellHeight;\n }\n\n gridX = currentX / cellWidth;\n gridY = currentY / cellHeight;\n }\n\n int thisCellWidth = cellWidth;\n int thisCellHeight = cellHeight;\n\n boolean isMultiCell = child.getCellHeight() > 1 || child.getCellWidth() > 1;\n if (child.getCellWidth() != -1) {\n thisCellWidth = child.getCellWidth() * cellWidth;\n }\n\n if (child.getCellHeight() != -1) {\n thisCellHeight = child.getCellHeight() * cellHeight;\n }\n\n if(isMultiCell) {\n // Mark all cells this widget uses as taken.\n int minX = gridX;\n int minY = gridY;\n int maxX = gridX + child.getCellWidth();\n int maxY = gridY + child.getCellHeight();\n\n for(int x = minX; x < maxX; x++) {\n for(int y = minY; y < maxY; y++) {\n grid[x][y] = true;\n }\n }\n } else {\n grid[gridX][gridY] = true;\n }\n\n child.getWidget().setX(currentX);\n child.getWidget().setY(currentY);\n child.getWidget().setWidth(thisCellWidth - padding * 2);\n child.getWidget().setHeight(thisCellHeight - padding * 2);\n\n currentX += thisCellWidth;\n if (currentX >= this.width) {\n currentX = getX();\n currentY += thisCellHeight;\n }\n }\n\n }\n\n @Override\n public void visitChildren(Consumer<LayoutElement> widgetConsumer) {\n this.children.stream().map(GridItem::getWidget).forEach(widgetConsumer);\n }\n\n public static class GridItem {\n // -1 = don't care about size.\n private final int cellHeight;\n // -1 = don't care about size\n private final int cellWidth;\n private final AbstractWidget widget;\n\n public GridItem(int cellHeight, int cellWidth, AbstractWidget widget) {\n this.cellHeight = cellHeight;\n this.cellWidth = cellWidth;\n this.widget = widget;\n }\n\n public int getCellHeight() {\n return cellHeight;\n }\n\n public int getCellWidth() {\n return cellWidth;\n }\n\n public AbstractWidget getWidget() {\n return widget;\n }\n }\n}" }, { "identifier": "ImageButtonWidget", "path": "src/main/java/dev/isxander/yaul3/impl/widgets/ImageButtonWidget.java", "snippet": "public class ImageButtonWidget extends AbstractWidget {\n private AnimatedDynamicTextureImage image;\n private int contentHeight = this.height;\n\n public ImageButtonWidget(int x, int y, int width, int height, Component message, ResourceLocation image) {\n super(x, y, width, height, message);\n this.image = ImageRendererManager.getInstance().createPreloadedImage(image);\n }\n\n private float alpha = 0.9f;\n private int textXOffset = 20;\n private int textYOffset = 20;\n private Animatable animation;\n\n @Override\n public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) {\n graphics.enableScissor(getX(), getY(), getX() + width, getY() + height);\n\n boolean prevHovered = this.isHovered;\n this.isHovered = mouseX >= this.getX() && mouseY >= this.getY() && mouseX < this.getX() + this.width && mouseY < this.getY() + this.height;\n\n if (isHovered && !prevHovered) { // just started hovering\n if (this.animation != null) this.animation.abort();\n this.animation = AnimationSequence.of(\n Animation.of(5)\n .consumerF(f -> alpha = f, alpha, 0.1f)\n .easing(EasingFunction.EASE_OUT_SIN),\n AnimationGroup.of(\n Animation.of(10)\n .consumerI(f -> textXOffset = f, textXOffset, 0)\n .easing(EasingFunction.EASE_OUT_EXPO),\n Animation.of(5)\n .consumerI(f -> textYOffset = f, textYOffset, 0)\n .easing(EasingFunction.EASE_OUT_EXPO)\n )\n ).play();\n } else if (!isHovered && prevHovered) { // just stopped hovering\n if (this.animation != null) this.animation.abort();\n this.animation = AnimationSequence.of(\n Animation.of(5)\n .consumerF(f -> alpha = f, alpha, 0.9f)\n .easing(EasingFunction.EASE_IN_SIN),\n AnimationGroup.of(\n Animation.of(10)\n .consumerI(f -> textXOffset = f, textXOffset, 20)\n .easing(EasingFunction.EASE_OUT_EXPO),\n Animation.of(5)\n .consumerI(f -> textYOffset = f, textYOffset, 20)\n .easing(EasingFunction.EASE_OUT_EXPO)\n )\n ).play();\n }\n\n // Scale the image so that the image height is the same as the button height.\n float neededWidth = image.getFrameWidth() * ((float) this.height / image.getFrameHeight());\n\n // Scale the image to fit within the width and height of the button.\n graphics.pose().pushPose();\n // gl bilinear scaling.\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n this.contentHeight = image.render(graphics, getX(), getY(), (int) neededWidth, delta);\n graphics.pose().popPose();\n\n// context.drawTexture(image, getX(), getY(), this.width, this.height, 0, 0, 1920, 1080, 1920, 1080);\n\n int greyColor = FastColor.ARGB32.color((int) (alpha * 255), 0, 0, 0);\n graphics.fill(getX(), getY(), getX() + width, getY() + height, greyColor);\n\n // Draw text.\n var client = Minecraft.getInstance();\n\n float fontScaling = 1.24f;\n\n int unscaledTextX = this.getX() + 5 + textXOffset;\n int unscaledTextY = this.getY() + this.height - client.font.lineHeight - 5 + textYOffset;\n int textX = (int) (unscaledTextX / fontScaling);\n int textY = (int) (unscaledTextY / fontScaling);\n int endX = (int) ((this.getX() + this.width - 5) / fontScaling);\n int endY = (int) ((this.getY() + this.height - 5) / fontScaling);\n\n graphics.fill(unscaledTextX - 5, unscaledTextY - 5, unscaledTextX + this.width - 5, unscaledTextY + client.font.lineHeight + 5, 0xAF000000);\n\n graphics.pose().pushPose();\n graphics.pose().scale(fontScaling, fontScaling, 1.0f);\n\n// context.fill(textX, textY, endX, endY, 0xFFFF2F00);\n renderScrollingString(graphics, client.font, getMessage(), textX, textX, textY, endX, endY, 0xFFFFFF);\n\n graphics.pose().popPose();\n\n // Draw border.\n graphics.renderOutline(getX(), getY(), width, height, 0x0FFFFFFF);\n graphics.disableScissor();\n }\n\n @Override\n protected void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) {\n\n }\n\n @Override\n protected void updateWidgetNarration(NarrationElementOutput builder) {}\n}" } ]
import dev.isxander.yaul3.api.animation.Animation; import dev.isxander.yaul3.api.ui.*; import dev.isxander.yaul3.impl.ui.AbstractLayoutWidget; import dev.isxander.yaul3.impl.widgets.DynamicGridWidget; import dev.isxander.yaul3.impl.widgets.ImageButtonWidget; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation;
5,357
package dev.isxander.yaul3.test; public class TestScreen extends Screen implements UnitHelper { public TestScreen(Component title) { super(title); } @Override protected void init() { super.init(); DynamicGridWidget grid = new DynamicGridWidget(0, 0, this.width - 20, this.height - 20); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 4, 1); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 2, 2); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.setPadding(5); //grid.visitWidgets(this::addRenderableWidget); // var layout = FlexWidget.create() // .setWidth(percentW(100)).setHeight(percentH(100)) // .setJustification(FlexJustification.CENTER) // .setAlign(FlexAlign.CENTER) // .addWidgets( // LayoutWidget.of(Component.literal("Screen Title"), font) // ); // while (layout.justify()) {} // layout.addToScreen(this::addWidget, this::addRenderableOnly); IntState width = px(200);
package dev.isxander.yaul3.test; public class TestScreen extends Screen implements UnitHelper { public TestScreen(Component title) { super(title); } @Override protected void init() { super.init(); DynamicGridWidget grid = new DynamicGridWidget(0, 0, this.width - 20, this.height - 20); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 4, 1); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 2, 2); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.setPadding(5); //grid.visitWidgets(this::addRenderableWidget); // var layout = FlexWidget.create() // .setWidth(percentW(100)).setHeight(percentH(100)) // .setJustification(FlexJustification.CENTER) // .setAlign(FlexAlign.CENTER) // .addWidgets( // LayoutWidget.of(Component.literal("Screen Title"), font) // ); // while (layout.justify()) {} // layout.addToScreen(this::addWidget, this::addRenderableOnly); IntState width = px(200);
var animation = Animation.of(200)
0
2023-11-25 13:11:05+00:00
8k
DueWesternersProgramming/FRC-2023-Swerve-Offseason
src/main/java/frc/robot/OI/OperatorInterface.java
[ { "identifier": "EntechJoystick", "path": "src/main/java/entech/util/EntechJoystick.java", "snippet": "public class EntechJoystick extends CommandJoystick {\n private final Joystick hid;\n\n public EntechJoystick(int port) {\n super(port);\n hid = this.getHID();\n }\n\n public void WhilePressed(int button, EntechCommandBase command) {\n this.button(button).whileTrue(command);\n }\n\n public void WhenPressed(int button, EntechCommandBase command) {\n this.button(button).onTrue(command);\n }\n\n public void WhenReleased(int button, EntechCommandBase command) {\n this.button(button).onFalse(command);\n }\n\n public void WhileReleased(int button, EntechCommandBase command) {\n this.button(button).whileFalse(command);\n }\n\n public void whileSwitch(int button, EntechCommandBase commandOnTrue, EntechCommandBase commandOnFalse) {\n this.WhilePressed(button, commandOnTrue);\n this.WhileReleased(button, commandOnFalse);\n }\n\n public void whenSwitch(int button, EntechCommandBase commandOnTrue, EntechCommandBase commandOnFalse) {\n this.WhenPressed(button, commandOnTrue);\n this.WhenReleased(button, commandOnFalse);\n }\n\n public double getX() {\n return hid.getX();\n }\n\n public double getY() {\n return hid.getY();\n }\n\n public double getZ() {\n return hid.getZ();\n }\n}" }, { "identifier": "CommandFactory", "path": "src/main/java/frc/robot/CommandFactory.java", "snippet": "public class CommandFactory {\n private DriveSubsystem driveSubsystem;\n\n public CommandFactory(RobotContainer robotContainer) {\n this.driveSubsystem = robotContainer.getDriveSubsystem();\n }\n\n public EntechCommandBase gyroResetCommand() {\n return new GyroReset(driveSubsystem);\n }\n\n public Command getAutoCommand() {\n SequentialCommandGroup auto = new SequentialCommandGroup();\n //auto.addCommands(homeLimbCommand());\n auto.addCommands(new WaitCommand(3));\n //auto.addCommands(dialHighPosition());\n return auto;\n }\n}" }, { "identifier": "RobotConstants", "path": "src/main/java/frc/robot/RobotConstants.java", "snippet": "public final class RobotConstants {\n public static final class DrivetrainConstants {\n // Driving Parameters - Note that these are not the maximum capable speeds of\n // the robot, rather the allowed maximum speeds\n public static final double MAX_SPEED_METERS_PER_SECOND = 4.0; // 4.42; //4.8;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND = 2 * Math.PI; // radians per second\n\n public static final double DIRECTION_SLEW_RATE = 1.2; // radians per second\n public static final double MAGNITUDE_SLEW_RATE = 1.8; // 2.0; //1.8; // percent per second (1 = 100%)\n public static final double ROTATIONAL_SLEW_RATE = 2.0; // 20.0; //2.0; // percent per second (1 = 100%)\n\n // Chassis configuration\n public static final double TRACK_WIDTH_METERS = Units.inchesToMeters(21.75);\n\n // Distance between centers of right and left wheels on robot\n public static final double WHEEL_BASE_METERS = Units.inchesToMeters(21.75);\n\n // Distance between front and back wheels on robot\n public static final SwerveDriveKinematics DRIVE_KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(WHEEL_BASE_METERS / 2, TRACK_WIDTH_METERS / 2),\n new Translation2d(WHEEL_BASE_METERS / 2, -TRACK_WIDTH_METERS / 2),\n new Translation2d(-WHEEL_BASE_METERS / 2, TRACK_WIDTH_METERS / 2),\n new Translation2d(-WHEEL_BASE_METERS / 2, -TRACK_WIDTH_METERS / 2));\n\n public static final boolean kGyroReversed = false;\n }\n\n public static final class SwerveModuleConstants {\n public static final double FREE_SPEED_RPM = 5676;\n\n // The MAXSwerve module can be configured with one of three pinion gears: 12T,\n // 13T, or 14T.\n // This changes the drive speed of the module (a pinion gear with more teeth\n // will result in a\n // robot that drives faster).\n public static final int kDrivingMotorPinionTeeth = 14;\n\n // Invert the turning encoder, since the output shaft rotates in the opposite\n // direction of\n // the steering motor in the MAXSwerve Module.\n public static final boolean kTurningEncoderInverted = true;\n\n // Calculations required for driving motor conversion factors and feed forward\n public static final double DRIVING_MOTOR_FREE_SPEED_RPS = FREE_SPEED_RPM / 60;\n public static final double WHEEL_DIAMETER_METERS = 0.1016;\n public static final double WHEEL_CIRCUMFERENCE_METERS = WHEEL_DIAMETER_METERS * Math.PI;\n public static final double DRIVING_MOTOR_REDUCTION = (45.0 * 17 * 50) / (kDrivingMotorPinionTeeth * 15 * 27);\n public static final double DRIVE_WHEEL_FREE_SPEED_RPS = (DRIVING_MOTOR_FREE_SPEED_RPS\n * WHEEL_CIRCUMFERENCE_METERS) / DRIVING_MOTOR_REDUCTION;\n\n public static final double DRIVING_ENCODER_POSITION_FACTOR_METERS_PER_ROTATION = (WHEEL_DIAMETER_METERS\n * Math.PI) / DRIVING_MOTOR_REDUCTION; // meters, per rotation\n public static final double DRIVING_ENCODER_VELOCITY_FACTOR_METERS_PER_SECOND_PER_RPM = ((WHEEL_DIAMETER_METERS\n * Math.PI) / DRIVING_MOTOR_REDUCTION) / 60.0; // meters per second, per RPM\n\n public static final double TURNING_MOTOR_REDUCTION = 150.0 / 7.0; // ratio between internal relative encoder and\n // Through Bore (or Thrifty in our case)\n // absolute encoder - 150.0 / 7.0\n\n public static final double TURNING_ENCODER_POSITION_FACTOR_RADIANS_PER_ROTATION = (2 * Math.PI)\n / TURNING_MOTOR_REDUCTION; // radians, per rotation\n public static final double TURNING_ENCODER_VELOCITY_FACTOR_RADIANS_PER_SECOND_PER_RPM = (2 * Math.PI)\n / TURNING_MOTOR_REDUCTION / 60.0; // radians per second, per RPM\n\n public static final double TURNING_ENCODER_POSITION_PID_MIN_INPUT_RADIANS = 0; // radians\n public static final double TURNING_ENCODER_POSITION_PID_MAX_INPUT_RADIANS = (2 * Math.PI); // radians\n\n public static final double DRIVING_P = 0.04;\n public static final double DRIVING_I = 0;\n public static final double DRIVING_D = 0;\n public static final double DRIVING_FF = 1 / DRIVE_WHEEL_FREE_SPEED_RPS;\n public static final double DRIVING_MIN_OUTPUT_NORMALIZED = -1;\n public static final double DRIVING_MAX_OUTPUT_NORMALIZED = 1;\n\n public static final double TURNING_P = 1.0; // 1.0; // 1.0 might be a bit too much - reduce a bit if needed\n public static final double TURNING_I = 0;\n public static final double TURNING_D = 0;\n public static final double TURNING_FF = 0;\n public static final double TURNING_MIN_OUTPUT_NORMALIZED = -1;\n public static final double TURNING_MAX_OUTPUT_NORMALIZED = 1;\n\n public static final IdleMode DRIVING_MOTOR_IDLE_MODE = IdleMode.kBrake;\n public static final IdleMode TURNING_MOTOR_IDLE_MODE = IdleMode.kBrake;\n\n public static final int DRIVING_MOTOR_CURRENT_LIMIT_AMPS = 40; // 50; // amps\n public static final int TURNING_MOTOR_CURRENT_LIMIT_AMPS = 20; // amps\n }\n\n public static interface Ports {\n\n public static class CAN {\n public static final int FRONT_LEFT_DRIVING = 5;\n public static final int REAR_LEFT_DRIVING = 7;\n public static final int FRONT_RIGHT_DRIVING = 6;\n public static final int REAR_RIGHT_DRIVING = 8;\n\n public static final int FRONT_LEFT_TURNING = 9;\n public static final int REAR_LEFT_TURNING = 11;\n public static final int FRONT_RIGHT_TURNING = 10;\n public static final int REAR_RIGHT_TURNING = 12;\n\n public static final int FRONT_LEFT_STEERING = 1;\n public static final int FRONT_RIGHT_STEERING = 2;\n public static final int REAR_LEFT_STEERING = 3;\n public static final int REAR_RIGHT_STEERING = 4;\n }\n\n public static class CONTROLLER {\n public static final double JOYSTICK_AXIS_THRESHOLD = 0.2;\n public static final int JOYSTICK = 0;\n public static final int PANEL = 1;\n }\n }\n\n public static interface Offsets {\n public static final double FRONT_OFFSET_HEAVE_M = 0.0;\n public static final double FRONT_OFFSET_SWAY_M = 0.25;\n public static final double FRONT_OFFSET_SURGE_M = 0.0;\n public static final double FRONT_OFFSET_YAW_DEGREES = 45.0;\n public static final double FRONT_OFFSET_PITCH_DEGREES = 0.0;\n public static final double FRONT_OFFSET_ROLL_DEGREES = 0.0;\n }\n\n\n /**\n * TODO: Fix this disaster\n */\n public static interface AUTONOMOUS {\n public static final double MAX_SPEED_METERS_PER_SECOND = 3.0; // 4.42; //3.0;\n public static final double MAX_ACCELERATION_METERS_PER_SECOND_SQUARED = 3;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND = Math.PI;\n public static final double MAX_ANGULAR_ACCELERATION_RADIANS_PER_SECOND_SQUARED = Math.PI;\n\n public static final double X_CONTROLLER_P = 1;\n public static final double Y_CONTROLLER_P = 1;\n public static final double THETA_CONTROLLER_P = 1;\n\n // Constraint for the motion profiled robot angle controller\n public static final TrapezoidProfile.Constraints THETA_CONTROLLER_CONSTRAINTS = new TrapezoidProfile.Constraints(\n MAX_ANGULAR_SPEED_RADIANS_PER_SECOND, MAX_ANGULAR_ACCELERATION_RADIANS_PER_SECOND_SQUARED);\n }\n\n public interface INDICATOR_VALUES {\n public static final double POSITION_UNKNOWN = -1.0;\n public static final double POSITION_NOT_SET = -1.1;\n }\n\n}" }, { "identifier": "RobotContainer", "path": "src/main/java/frc/robot/RobotContainer.java", "snippet": "public class RobotContainer {\n\n public static final double GAMEPAD_AXIS_THRESHOLD = 0.2;\n\n public enum Autonomous {\n\n }\n\n private Autonomous auto = null;\n\n private final DriveSubsystem driveSubsystem = new DriveSubsystem();\n\n private final Field2d field = new Field2d(); // a representation of the field\n\n // The driver's controller\n // CommandXboxController driverGamepad = new\n // CommandXboxController(Ports.USB.GAMEPAD);\n Joystick driverGamepad = new Joystick(RobotConstants.Ports.CONTROLLER.JOYSTICK);\n\n /**\n * The container for the robot. Contains subsystems, OI devices, and commands.\n */\n public RobotContainer() {\n driveSubsystem.initialize();\n\n }\n\n public TrajectoryConfig createTrajectoryConfig() {\n TrajectoryConfig config = new TrajectoryConfig(\n RobotConstants.AUTONOMOUS.MAX_SPEED_METERS_PER_SECOND,\n RobotConstants.AUTONOMOUS.MAX_ACCELERATION_METERS_PER_SECOND_SQUARED)\n .setKinematics(DrivetrainConstants.DRIVE_KINEMATICS);\n\n return config;\n }\n\n public Trajectory createExampleTrajectory(TrajectoryConfig config) {\n Trajectory exampleTrajectory = TrajectoryGenerator.generateTrajectory(\n new Pose2d(0, 0, new Rotation2d(0)),\n List.of(new Translation2d(1, 1), new Translation2d(2, -1)),\n new Pose2d(3, 0, new Rotation2d(0)),\n config);\n\n return exampleTrajectory;\n }\n\n public Field2d getField() {\n return field;\n }\n\n public DriveSubsystem getDriveSubsystem() {\n return driveSubsystem;\n }\n}" }, { "identifier": "DriveCommand", "path": "src/main/java/frc/robot/commands/DriveCommand.java", "snippet": "public class DriveCommand extends EntechCommandBase {\n private static final double MAX_SPEED_PERCENT = 1;\n\n private final DriveSubsystem drive;\n private final EntechJoystick joystick;\n\n public DriveCommand(DriveSubsystem drive, EntechJoystick joystick) {\n super(drive);\n this.drive = drive;\n this.joystick = joystick;\n }\n\n @Override\n public void end(boolean interrupted) {\n drive.drive(0, 0, 0, false, true);\n }\n\n @Override\n public void execute() {\n double xRaw = joystick.getX() * -0.7;\n double yRaw = joystick.getY() * -0.7;\n double rotRaw = joystick.getZ() * 0.7;\n\n double xConstrained = MathUtil.applyDeadband(MathUtil.clamp(xRaw, -MAX_SPEED_PERCENT, MAX_SPEED_PERCENT),\n RobotConstants.Ports.CONTROLLER.JOYSTICK_AXIS_THRESHOLD);\n double yConstrained = MathUtil.applyDeadband(MathUtil.clamp(yRaw, -MAX_SPEED_PERCENT, MAX_SPEED_PERCENT),\n RobotConstants.Ports.CONTROLLER.JOYSTICK_AXIS_THRESHOLD);\n double rotConstrained = MathUtil.applyDeadband(\n MathUtil.clamp(rotRaw, -MAX_SPEED_PERCENT, MAX_SPEED_PERCENT),\n RobotConstants.Ports.CONTROLLER.JOYSTICK_AXIS_THRESHOLD);\n\n double xSquared = Math.copySign(xConstrained * xConstrained, xConstrained);\n double ySquared = Math.copySign(yConstrained * yConstrained, yConstrained);\n double rotSquared = Math.copySign(rotConstrained * rotConstrained, rotConstrained);\n\n if (UserPolicy.xLocked) {\n drive.setX();\n return;\n }\n\n if (UserPolicy.twistable) {\n drive.drive(-ySquared, -xSquared, -rotSquared, true, true);\n } else {\n drive.drive(-ySquared, -xSquared, 0, true, true);\n }\n }\n\n @Override\n public void initialize() {\n drive.drive(0, 0, 0, true, true);\n }\n\n @Override\n public boolean isFinished() {\n return false;\n }\n\n}" }, { "identifier": "TwistCommand", "path": "src/main/java/frc/robot/commands/TwistCommand.java", "snippet": "public class TwistCommand extends EntechCommandBase {\n public TwistCommand() {\n\n }\n\n @Override\n public void initialize() {\n UserPolicy.twistable = true;\n }\n\n @Override\n public void end(boolean interrupted) {\n UserPolicy.twistable = false;\n }\n}" }, { "identifier": "XCommand", "path": "src/main/java/frc/robot/commands/XCommand.java", "snippet": "public class XCommand extends EntechCommandBase {\n public XCommand() {\n\n }\n\n @Override\n public void initialize() {\n UserPolicy.xLocked = !UserPolicy.xLocked;\n }\n\n @Override\n public boolean isFinished() {\n return true;\n }\n}" } ]
import entech.util.EntechJoystick; import frc.robot.CommandFactory; import frc.robot.RobotConstants; import frc.robot.RobotContainer; import frc.robot.commands.DriveCommand; import frc.robot.commands.TwistCommand; import frc.robot.commands.XCommand;
3,923
package frc.robot.OI; public class OperatorInterface { private final EntechJoystick driveJoystick = new EntechJoystick(RobotConstants.Ports.CONTROLLER.JOYSTICK); //private final EntechJoystick operatorPanel = new EntechJoystick(RobotConstants.Ports.CONTROLLER.PANEL); public OperatorInterface(CommandFactory commandFactory, RobotContainer robotContainer) {
package frc.robot.OI; public class OperatorInterface { private final EntechJoystick driveJoystick = new EntechJoystick(RobotConstants.Ports.CONTROLLER.JOYSTICK); //private final EntechJoystick operatorPanel = new EntechJoystick(RobotConstants.Ports.CONTROLLER.PANEL); public OperatorInterface(CommandFactory commandFactory, RobotContainer robotContainer) {
driveJoystick.WhilePressed(1, new TwistCommand());
5
2023-11-21 01:49:41+00:00
8k
huangwei021230/memo
app/src/main/java/com/huawei/cloud/drive/MainActivity.java
[ { "identifier": "MemoAdapter", "path": "app/src/main/java/com/huawei/cloud/drive/adapter/MemoAdapter.java", "snippet": "public class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.ViewHolder> {\n private List<MemoInfo> memoList;\n private OnItemClickListener onItemClickListener;\n\n public MemoAdapter(List<MemoInfo> memoList) {\n this.memoList = memoList;\n }\n\n public void setOnItemClickListener(OnItemClickListener listener) {\n this.onItemClickListener = listener;\n }\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_memo, parent, false);\n return new ViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(ViewHolder holder, int position) {\n MemoInfo memo = memoList.get(position);\n holder.bind(memo);\n }\n\n @Override\n public int getItemCount() {\n return memoList.size();\n }\n\n public interface OnItemClickListener {\n void onItemClick(int position);\n }\n public void addMemos(List<MemoInfo> list) {\n for (MemoInfo newMemo : list) {\n boolean isExisting = false;\n for (int i = 0; i < memoList.size(); i++) {\n MemoInfo existingMemo = memoList.get(i);\n if (existingMemo.getId().equals(newMemo.getId())) {\n // 相同id的对象已存在,更新内容\n existingMemo.setTitle(newMemo.getTitle());\n existingMemo.setContent(newMemo.getContent());\n notifyItemChanged(i); // 通知适配器有数据更新\n isExisting = true;\n break;\n }\n }\n if (!isExisting) {\n // 相同id的对象不存在,添加到列表末尾\n memoList.add(newMemo);\n notifyItemInserted(memoList.size() - 1); // 通知适配器有新的数据插入\n }\n }\n }\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n private TextView titleTextView;\n private TextView contentTextView;\n\n public ViewHolder(View itemView) {\n super(itemView);\n titleTextView = itemView.findViewById(R.id.title_text_view);\n contentTextView = itemView.findViewById(R.id.content_text_view);\n itemView.setOnClickListener(this);\n }\n\n public void bind(MemoInfo memo) {\n titleTextView.setText(memo.getTitle());\n contentTextView.setText(memo.getContent());\n }\n\n @Override\n public void onClick(View v) {\n if (onItemClickListener != null) {\n onItemClickListener.onItemClick(getAdapterPosition());\n }\n }\n }\n}" }, { "identifier": "MemoInfo", "path": "app/src/main/java/com/huawei/cloud/drive/bean/MemoInfo.java", "snippet": "@PrimaryKeys({\"id\"})\npublic final class MemoInfo extends CloudDBZoneObject implements Serializable {\n private Long id;\n\n private String title;\n\n private String content;\n\n public MemoInfo() {\n super(MemoInfo.class);\n }\n public MemoInfo(Long id, String title, String content){\n super(MemoInfo.class);\n this.id = id;\n this.title = title;\n this.content = content;\n }\n public void setId(Long id) {\n this.id = id;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getContent() {\n return content;\n }\n public Bundle toBundle() {\n Bundle bundle = new Bundle();\n bundle.putLong(\"id\", id);\n bundle.putString(\"title\", title);\n bundle.putString(\"content\", content);\n return bundle;\n }\n // 从Bundle中提取属性值,并创建新的MemoInfo对象\n public static MemoInfo fromBundle(Bundle bundle) {\n Long id = bundle.getLong(\"id\");\n String title = bundle.getString(\"title\");\n String content = bundle.getString(\"content\");\n return new MemoInfo(id, title, content);\n }\n}" }, { "identifier": "CloudDBManager", "path": "app/src/main/java/com/huawei/cloud/drive/hms/CloudDBManager.java", "snippet": "public class CloudDBManager {\n private static final String TAG = \"CloudDBManager\";\n\n private AGConnectCloudDB mCloudDB;\n\n private CloudDBZone mCloudDBZone;\n\n private ListenerHandler mRegister;\n\n private CloudDBZoneConfig mConfig;\n\n private UiCallBack mUiCallBack = UiCallBack.DEFAULT;\n private CloudDBZoneOpenCallback mCloudDBZoneOpenCallback;\n public interface CloudDBZoneOpenCallback {\n void onCloudDBZoneOpened(CloudDBZone cloudDBZone);\n }\n public interface MemoCallback {\n void onSuccess(List<MemoInfo> memoInfoList);\n void onFailure(String errorMessage);\n }\n private int mMemoIndex = 0;\n\n private ReadWriteLock mReadWriteLock = new ReentrantReadWriteLock();\n\n /**\n * Monitor data change from database. Update memo info list if data have changed\n */\n private OnSnapshotListener<MemoInfo> mSnapshotListener = new OnSnapshotListener<MemoInfo>() {\n @Override\n public void onSnapshot(CloudDBZoneSnapshot<MemoInfo> cloudDBZoneSnapshot, AGConnectCloudDBException e) {\n if (e != null) {\n Log.w(TAG, \"onSnapshot: \" + e.getMessage());\n return;\n }\n CloudDBZoneObjectList<MemoInfo> snapshotObjects = cloudDBZoneSnapshot.getSnapshotObjects();\n List<MemoInfo> memoInfoList = new ArrayList<>();\n try {\n if (snapshotObjects != null) {\n while (snapshotObjects.hasNext()) {\n MemoInfo memoInfo = snapshotObjects.next();\n memoInfoList.add(memoInfo);\n updateMemoIndex(memoInfo);\n }\n }\n mUiCallBack.onSubscribe(memoInfoList);\n } catch (AGConnectCloudDBException snapshotException) {\n Log.w(TAG, \"onSnapshot:(getObject) \" + snapshotException.getMessage());\n } finally {\n cloudDBZoneSnapshot.release();\n }\n }\n };\n\n public CloudDBManager() {\n mCloudDB = AGConnectCloudDB.getInstance();\n }\n\n /**\n * Init AGConnectCloudDB in Application\n *\n * @param context application context\n */\n public static void initAGConnectCloudDB(Context context) {\n AGConnectCloudDB.initialize(context);\n }\n\n /**\n * Call AGConnectCloudDB.createObjectType to init schema\n */\n public void createObjectType() {\n try {\n mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());\n } catch (AGConnectCloudDBException e) {\n Log.w(TAG, \"createObjectType: \" + e.getMessage());\n }\n }\n\n /**\n * Call AGConnectCloudDB.openCloudDBZone to open a cloudDBZone.\n * We set it with cloud cache mode, and data can be store in local storage\n */\n public void openCloudDBZone() {\n mConfig = new CloudDBZoneConfig(\"quickStartMemoDemo\",\n CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,\n CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);\n mConfig.setPersistenceEnabled(true);\n try {\n mCloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);\n } catch (AGConnectCloudDBException e) {\n Log.w(TAG, \"openCloudDBZone: \" + e.getMessage());\n }\n }\n\n public void openCloudDBZoneV2(CloudDBZoneOpenCallback callback) {\n mCloudDBZoneOpenCallback = callback;\n mConfig = new CloudDBZoneConfig(\"quickStartMemoDemo\",\n CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,\n CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);\n mConfig.setPersistenceEnabled(true);\n Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);\n openDBZoneTask.addOnSuccessListener(new OnSuccessListener<CloudDBZone>() {\n @Override\n public void onSuccess(CloudDBZone cloudDBZone) {\n Log.i(TAG, \"Open cloudDBZone success\");\n mCloudDBZone = cloudDBZone;\n if (mCloudDBZoneOpenCallback != null) {\n mCloudDBZoneOpenCallback.onCloudDBZoneOpened(cloudDBZone);\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(Exception e) {\n Log.w(TAG, \"Open cloudDBZone failed for \" + e.getMessage());\n }\n });\n }\n\n /**\n * Call AGConnectCloudDB.closeCloudDBZone\n */\n public void closeCloudDBZone() {\n try {\n mRegister.remove();\n mCloudDB.closeCloudDBZone(mCloudDBZone);\n } catch (AGConnectCloudDBException e) {\n Log.w(TAG, \"closeCloudDBZone: \" + e.getMessage());\n }\n }\n\n /**\n * Call AGConnectCloudDB.deleteCloudDBZone\n */\n public void deleteCloudDBZone() {\n try {\n mCloudDB.deleteCloudDBZone(mConfig.getCloudDBZoneName());\n } catch (AGConnectCloudDBException e) {\n Log.w(TAG, \"deleteCloudDBZone: \" + e.getMessage());\n }\n }\n\n /**\n * Add a callback to update memo info list\n *\n * @param uiCallBack callback to update memo list\n */\n public void addCallBacks(UiCallBack uiCallBack) {\n mUiCallBack = uiCallBack;\n }\n\n /**\n * Add mSnapshotListener to monitor data changes from storage\n */\n /**\n * Query all memos in storage from cloud side with CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY\n */\n public void queryAllMemos() {\n if (mCloudDBZone == null) {\n Log.w(TAG, \"CloudDBZone is null, try re-open it\");\n return;\n }\n Task<CloudDBZoneSnapshot<MemoInfo>> queryTask = mCloudDBZone.executeQuery(\n CloudDBZoneQuery.where(MemoInfo.class),\n CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);\n queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<MemoInfo>>() {\n @Override\n public void onSuccess(CloudDBZoneSnapshot<MemoInfo> snapshot) {\n processQueryResult(snapshot);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(Exception e) {\n mUiCallBack.updateUiOnError(\"Query memo list from cloud failed\");\n }\n });\n }\n\n /**\n * Query memos with condition\n *\n * @param query query condition\n */\n public void queryMemos(CloudDBZoneQuery<MemoInfo> query) {\n if (mCloudDBZone == null) {\n Log.w(TAG, \"CloudDBZone is null, try re-open it\");\n return;\n }\n\n Task<CloudDBZoneSnapshot<MemoInfo>> queryTask = mCloudDBZone.executeQuery(query,\n CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);\n queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<MemoInfo>>() {\n @Override\n public void onSuccess(CloudDBZoneSnapshot<MemoInfo> snapshot) {\n processQueryResult(snapshot);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(Exception e) {\n mUiCallBack.updateUiOnError(\"Query failed\");\n }\n });\n }\n\n private void processQueryResult(CloudDBZoneSnapshot<MemoInfo> snapshot) {\n CloudDBZoneObjectList<MemoInfo> memoInfoCursor = snapshot.getSnapshotObjects();\n List<MemoInfo> memoInfoList = new ArrayList<>();\n try {\n while (memoInfoCursor.hasNext()) {\n MemoInfo memoInfo = memoInfoCursor.next();\n memoInfoList.add(memoInfo);\n }\n } catch (AGConnectCloudDBException e) {\n Log.w(TAG, \"processQueryResult: \" + e.getMessage());\n } finally {\n snapshot.release();\n }\n mUiCallBack.onAddOrQuery(memoInfoList);\n }\n\n\n public void upsertMemoInfos(MemoInfo memoInfo) {\n if (mCloudDBZone == null) {\n Log.w(TAG, \"CloudDBZone is null, try re-open it\");\n return;\n }\n\n Task<Integer> upsertTask = mCloudDBZone.executeUpsert(memoInfo);\n upsertTask.addOnSuccessListener(new OnSuccessListener<Integer>() {\n @Override\n public void onSuccess(Integer cloudDBZoneResult) {\n Log.i(TAG, \"Upsert \" + cloudDBZoneResult + \" records\");\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(Exception e) {\n mUiCallBack.updateUiOnError(\"Insert memo info failed\");\n }\n });\n }\n\n public void deleteMemoInfos(List<MemoInfo> memoInfoList) {\n if (mCloudDBZone == null) {\n Log.w(TAG, \"CloudDBZone is null, try re-open it\");\n return;\n }\n\n Task<Integer> deleteTask = mCloudDBZone.executeDelete(memoInfoList);\n if (deleteTask.getException() != null) {\n mUiCallBack.updateUiOnError(\"Delete memo info failed\");\n return;\n }\n mUiCallBack.onDelete(memoInfoList);\n }\n\n private void updateMemoIndex(MemoInfo memoInfo) {\n try {\n mReadWriteLock.writeLock().lock();\n if (mMemoIndex < memoInfo.getId()) {\n mMemoIndex = Math.toIntExact(memoInfo.getId());\n }\n } finally {\n mReadWriteLock.writeLock().unlock();\n }\n }\n\n /**\n * Get max id of memoinfos\n *\n * @return max memo info id\n */\n public int getMemoIndex() {\n try {\n mReadWriteLock.readLock().lock();\n return mMemoIndex;\n } finally {\n mReadWriteLock.readLock().unlock();\n }\n }\n\n public interface UiCallBack {\n UiCallBack DEFAULT = new UiCallBack() {\n @Override\n public void onAddOrQuery(List<MemoInfo> memoInfoList) {\n Log.i(TAG, \"Using default onAddOrQuery\");\n }\n\n @Override\n public void onSubscribe(List<MemoInfo> memoInfoList) {\n Log.i(TAG, \"Using default onSubscribe\");\n }\n\n @Override\n public void onDelete(List<MemoInfo> memoInfoList) {\n Log.i(TAG, \"Using default onDelete\");\n }\n\n @Override\n public void updateUiOnError(String errorMessage) {\n Log.i(TAG, \"Using default updateUiOnError\");\n }\n };\n\n void onAddOrQuery(List<MemoInfo> memoInfoList);\n\n void onSubscribe(List<MemoInfo> memoInfoList);\n\n void onDelete(List<MemoInfo> memoInfoList);\n\n void updateUiOnError(String errorMessage);\n }\n}" }, { "identifier": "UiCallBack", "path": "app/src/main/java/com/huawei/cloud/drive/hms/CloudDBManager.java", "snippet": "public interface UiCallBack {\n UiCallBack DEFAULT = new UiCallBack() {\n @Override\n public void onAddOrQuery(List<MemoInfo> memoInfoList) {\n Log.i(TAG, \"Using default onAddOrQuery\");\n }\n\n @Override\n public void onSubscribe(List<MemoInfo> memoInfoList) {\n Log.i(TAG, \"Using default onSubscribe\");\n }\n\n @Override\n public void onDelete(List<MemoInfo> memoInfoList) {\n Log.i(TAG, \"Using default onDelete\");\n }\n\n @Override\n public void updateUiOnError(String errorMessage) {\n Log.i(TAG, \"Using default updateUiOnError\");\n }\n };\n\n void onAddOrQuery(List<MemoInfo> memoInfoList);\n\n void onSubscribe(List<MemoInfo> memoInfoList);\n\n void onDelete(List<MemoInfo> memoInfoList);\n\n void updateUiOnError(String errorMessage);\n}" } ]
import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.huawei.agconnect.cloud.database.CloudDBZone; import com.huawei.cloud.drive.adapter.MemoAdapter; import com.huawei.cloud.drive.bean.MemoInfo; import com.huawei.cloud.drive.hms.CloudDBManager; import com.huawei.cloud.drive.hms.CloudDBManager.UiCallBack; import java.util.ArrayList; import java.util.List; import boogiepop.memo.R;
4,115
package com.huawei.cloud.drive; /** * Main Activity */ public class MainActivity extends AppCompatActivity implements UiCallBack { // 假设有一个 Memo 类来表示备忘录项 private CloudDBManager cloudDBManager;
package com.huawei.cloud.drive; /** * Main Activity */ public class MainActivity extends AppCompatActivity implements UiCallBack { // 假设有一个 Memo 类来表示备忘录项 private CloudDBManager cloudDBManager;
private List<MemoInfo> memoList;
1
2023-11-25 07:44:41+00:00
8k
kkyesyes/Multi-userCommunicationSystem-Client
src/com/kk/qqclient/view/QQView.java
[ { "identifier": "FileClientService", "path": "src/com/kk/qqclient/service/FileClientService.java", "snippet": "public class FileClientService {\n public void sendFileToOne(String src, String senderId, String getterId) {\n // 读取src文件 -> message\n Message message = new Message();\n message.setMesType(MessageType.MESSAGE_FILE_MES);\n message.setSender(senderId);\n message.setGetter(getterId);\n\n String regex = \"\\\\/([^\\\\/]+)$\";\n // 编译正则表达式\n Pattern pattern = Pattern.compile(regex);\n // 创建Matcher对象\n Matcher matcher = pattern.matcher(src);\n // 查找匹配\n if (matcher.find()) {\n // 获取捕获组中的文件名\n String fileName = matcher.group(1);\n message.setFileName(fileName);\n } else {\n message.setFileName(\"unknown.txt\");\n }\n\n FileInputStream fileInputStream = null;\n\n byte[] buff = new byte[(int)new File(src).length()];\n try {\n fileInputStream = new FileInputStream(src);\n fileInputStream.read(buff);\n message.setFileData(buff);\n// while (!((readLen = fileInputStream.read(buff)) != -1)) {\n// fileData.append(new String(buff, 0, readLen));\n// }\n// String content = new String(fileData);\n// message.setContent(content);\n } catch (IOException e) {\n throw new RuntimeException(e);\n } finally {\n try {\n if (fileInputStream != null) {\n fileInputStream.close();\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n try {\n ObjectOutputStream oos =\n new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(message.getSender()).getSocket().getOutputStream());\n oos.writeObject(message);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n System.out.println(\"文件发送成功\");\n }\n}" }, { "identifier": "UserClientService", "path": "src/com/kk/qqclient/service/UserClientService.java", "snippet": "public class UserClientService {\n private User u = new User();\n private Socket socket;\n\n /**\n * 验证用户是否合法\n * @param userId 用户ID\n * @param pwd 用户密码\n * @return 是否合法\n */\n public boolean checkUser(String userId, String pwd) {\n boolean b = false;\n\n u.setUserId(userId);\n u.setPasswd(pwd);\n\n try {\n socket = new Socket(\"115.236.153.174\", 48255);\n // 将用户信息发送至服务端验证登录\n ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());\n oos.writeObject(u);\n\n // 读取从服务器回复的Message对象\n ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());\n Message ms = (Message)ois.readObject();\n\n // 服务端返回登录是否成功\n if (ms.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) {\n // 成功\n // 开启线程ClientConnectServerThread\n ClientConnectServerThread clientConnectServerThread =\n new ClientConnectServerThread(socket);\n clientConnectServerThread.start();\n\n // 加入线程管理\n ManageClientConnectServerThread.addClientConnectServerThread(userId, clientConnectServerThread);\n b = true;\n } else {\n // 失败\n socket.close();\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n return b;\n }\n\n /**\n * 拉取在线用户\n */\n public void getOnlineFriends() {\n Message message = new Message();\n message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);\n message.setSender(u.getUserId());\n\n // 发送给服务器\n // 得到想要拉取列表的用户在客户端的线程的socket进行传输数据\n ClientConnectServerThread clientConnectServerThread =\n ManageClientConnectServerThread.getClientConnectServerThread(u.getUserId());\n Socket socket = clientConnectServerThread.getSocket();\n try {\n ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());\n\n oos.writeObject(message);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 群发\n */\n public void atAll(String content) {\n Message message = new Message();\n message.setMesType(MessageType.MESSAGE_COMM_MES);\n message.setSender(u.getUserId());\n message.setGetter(\"@all\");\n message.setContent(content);\n\n // 发送给服务器\n // 得到想要拉取列表的用户在客户端的线程的socket进行传输数据\n ClientConnectServerThread clientConnectServerThread =\n ManageClientConnectServerThread.getClientConnectServerThread(u.getUserId());\n Socket socket = clientConnectServerThread.getSocket();\n try {\n ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());\n\n oos.writeObject(message);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 私聊\n */\n public void talkTo(String userId, String content) {\n Message message = new Message();\n message.setMesType(MessageType.MESSAGE_COMM_MES);\n message.setSender(u.getUserId());\n message.setGetter(userId);\n message.setContent(content);\n\n // 发送给服务器\n // 得到想要拉取列表的用户在客户端的线程的socket进行传输数据\n ClientConnectServerThread clientConnectServerThread =\n ManageClientConnectServerThread.getClientConnectServerThread(u.getUserId());\n Socket socket = clientConnectServerThread.getSocket();\n try {\n ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());\n\n oos.writeObject(message);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 设置文件保存路径\n */\n public void setFileDownloadPath(String folderPath) {\n Settings.setDownloadPath(folderPath);\n }\n\n public void saveFile(String fileData) {\n String folderPath = Settings.getDownloadPath();\n\n }\n\n /**\n * 退出登录\n */\n public void logout() {\n Message message = new Message();\n message.setMesType(MessageType.MESSAGE_CLIENT_EXIT);\n message.setSender(u.getUserId());\n\n ClientConnectServerThread clientConnectServerThread =\n ManageClientConnectServerThread.getClientConnectServerThread(u.getUserId());\n Socket socket = clientConnectServerThread.getSocket();\n try {\n ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());\n\n oos.writeObject(message);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "Utility", "path": "src/com/kk/qqclient/utils/Utility.java", "snippet": "public class Utility {\n\t//静态属性。。。\n private static Scanner scanner = new Scanner(System.in);\n\n \n /**\n * 功能:读取键盘输入的一个菜单选项,值:1——5的范围\n * @return 1——5\n */\n\tpublic static char readMenuSelection() {\n char c;\n for (; ; ) {\n String str = readKeyBoard(1, false);//包含一个字符的字符串\n c = str.charAt(0);//将字符串转换成字符char类型\n if (c != '1' && c != '2' && \n c != '3' && c != '4' && c != '5') {\n System.out.print(\"选择错误,请重新输入:\");\n } else break;\n }\n return c;\n }\n\n\t/**\n\t * 功能:读取键盘输入的一个字符\n\t * @return 一个字符\n\t */\n public static char readChar() {\n String str = readKeyBoard(1, false);//就是一个字符\n return str.charAt(0);\n }\n /**\n * 功能:读取键盘输入的一个字符,如果直接按回车,则返回指定的默认值;否则返回输入的那个字符\n * @param defaultValue 指定的默认值\n * @return 默认值或输入的字符\n */\n \n public static char readChar(char defaultValue) {\n String str = readKeyBoard(1, true);//要么是空字符串,要么是一个字符\n return (str.length() == 0) ? defaultValue : str.charAt(0);\n }\n\t\n /**\n * 功能:读取键盘输入的整型,长度小于2位\n * @return 整数\n */\n public static int readInt() {\n int n;\n for (; ; ) {\n String str = readKeyBoard(10, false);//一个整数,长度<=10位\n try {\n n = Integer.parseInt(str);//将字符串转换成整数\n break;\n } catch (NumberFormatException e) {\n System.out.print(\"数字输入错误,请重新输入:\");\n }\n }\n return n;\n }\n /**\n * 功能:读取键盘输入的 整数或默认值,如果直接回车,则返回默认值,否则返回输入的整数\n * @param defaultValue 指定的默认值\n * @return 整数或默认值\n */\n public static int readInt(int defaultValue) {\n int n;\n for (; ; ) {\n String str = readKeyBoard(10, true);\n if (str.equals(\"\")) {\n return defaultValue;\n }\n\t\t\t\n\t\t\t//异常处理...\n try {\n n = Integer.parseInt(str);\n break;\n } catch (NumberFormatException e) {\n System.out.print(\"数字输入错误,请重新输入:\");\n }\n }\n return n;\n }\n\n /**\n * 功能:读取键盘输入的指定长度的字符串\n * @param limit 限制的长度\n * @return 指定长度的字符串\n */\n\n public static String readString(int limit) {\n return readKeyBoard(limit, false);\n }\n\n /**\n * 功能:读取键盘输入的指定长度的字符串或默认值,如果直接回车,返回默认值,否则返回字符串\n * @param limit 限制的长度\n * @param defaultValue 指定的默认值\n * @return 指定长度的字符串\n */\n\t\n public static String readString(int limit, String defaultValue) {\n String str = readKeyBoard(limit, true);\n return str.equals(\"\")? defaultValue : str;\n }\n\n\n\t/**\n\t * 功能:读取键盘输入的确认选项,Y或N\n\t * 将小的功能,封装到一个方法中.\n\t * @return Y或N\n\t */\n public static char readConfirmSelection() {\n System.out.println(\"请输入你的选择(Y/N): 请小心选择\");\n char c;\n for (; ; ) {//无限循环\n \t//在这里,将接受到字符,转成了大写字母\n \t//y => Y n=>N\n String str = readKeyBoard(1, false).toUpperCase();\n c = str.charAt(0);\n if (c == 'Y' || c == 'N') {\n break;\n } else {\n System.out.print(\"选择错误,请重新输入:\");\n }\n }\n return c;\n }\n\n /**\n * 功能: 读取一个字符串\n * @param limit 读取的长度\n * @param blankReturn 如果为true ,表示 可以读空字符串。 \n * \t\t\t\t\t 如果为false表示 不能读空字符串。\n * \t\t\t\n\t *\t如果输入为空,或者输入大于limit的长度,就会提示重新输入。\n * @return\n */\n private static String readKeyBoard(int limit, boolean blankReturn) {\n \n\t\t//定义了字符串\n\t\tString line = \"\";\n\n\t\t//scanner.hasNextLine() 判断有没有下一行\n while (scanner.hasNextLine()) {\n line = scanner.nextLine();//读取这一行\n \n\t\t\t//如果line.length=0, 即用户没有输入任何内容,直接回车\n\t\t\tif (line.length() == 0) {\n if (blankReturn) return line;//如果blankReturn=true,可以返回空串\n else continue; //如果blankReturn=false,不接受空串,必须输入内容\n }\n\n\t\t\t//如果用户输入的内容大于了 limit,就提示重写输入 \n\t\t\t//如果用户如的内容 >0 <= limit ,我就接受\n if (line.length() < 1 || line.length() > limit) {\n System.out.print(\"输入长度(不能大于\" + limit + \")错误,请重新输入:\");\n continue;\n }\n break;\n }\n\n return line;\n }\n}" }, { "identifier": "Settings", "path": "src/com/kk/qqcommon/Settings.java", "snippet": "public class Settings {\n private static String downloadPath = \"D:/\";\n\n public static String getDownloadPath() {\n return downloadPath;\n }\n\n public static void setDownloadPath(String downloadPath) {\n Settings.downloadPath = downloadPath;\n }\n\n\n}" } ]
import com.kk.qqclient.service.FileClientService; import com.kk.qqclient.service.UserClientService; import com.kk.qqclient.utils.Utility; import com.kk.qqcommon.Settings; import com.sun.xml.internal.ws.api.config.management.policy.ManagementAssertion;
4,126
package com.kk.qqclient.view; /** * 客户端菜单界面 * * @author KK * @version 1.0 */ public class QQView { // 循环控制 private boolean loop = true; // 接收用户键盘输入 private String key = ""; // 用户服务 private UserClientService userClientService = new UserClientService(); // 文件服务 private FileClientService fileClientService = new FileClientService(); public static void main(String[] args) { new QQView().mainMenu(); } // 显示主菜单 private void mainMenu() { while (loop) { System.out.println("==========欢迎登录网络通信系统=========="); System.out.println("\t\t1 登录系统"); System.out.println("\t\t9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": System.out.print("请输入用户号:"); String userId = Utility.readString(50); System.out.print("请输入密 码:"); String pwd = Utility.readString(50); // 验证用户是否合法 if (userClientService.checkUser(userId, pwd)) { System.out.println("==========欢迎用户(" + userId + ")登录成功=========="); // 二级菜单 while (loop) { System.out.println("\n==========网络通信系统二级菜单(用户" + userId + ")=========="); System.out.println("\t\t 1 显示在线用户列表"); System.out.println("\t\t 2 群发消息"); System.out.println("\t\t 3 私聊消息"); System.out.println("\t\t 4 发送文件"); System.out.println("\t\t 5 文件路径"); System.out.println("\t\t 9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": // System.out.println("显示在线用户列表"); userClientService.getOnlineFriends(); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } break; case "2": // System.out.println("群发消息"); while (true) { System.out.println("==========群发模式(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.atAll(data); } break; case "3": System.out.print("请输入私聊对方的用户号:"); String ID = Utility.readString(50); while (true) { System.out.println("==========与 " + ID + " 私聊消息中(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.talkTo(ID, data); } break; case "4": System.out.println("发送文件功能正在维护中"); // System.out.print("请输入文件接收方的用户号:"); // String getterId = Utility.readString(50); // System.out.println("即将向 " + getterId + " 发送文件"); // System.out.print("请输入本地文件绝对路径:"); // String filePath = Utility.readString(500); // fileClientService.sendFileToOne(filePath, userId, getterId); break; case "5":
package com.kk.qqclient.view; /** * 客户端菜单界面 * * @author KK * @version 1.0 */ public class QQView { // 循环控制 private boolean loop = true; // 接收用户键盘输入 private String key = ""; // 用户服务 private UserClientService userClientService = new UserClientService(); // 文件服务 private FileClientService fileClientService = new FileClientService(); public static void main(String[] args) { new QQView().mainMenu(); } // 显示主菜单 private void mainMenu() { while (loop) { System.out.println("==========欢迎登录网络通信系统=========="); System.out.println("\t\t1 登录系统"); System.out.println("\t\t9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": System.out.print("请输入用户号:"); String userId = Utility.readString(50); System.out.print("请输入密 码:"); String pwd = Utility.readString(50); // 验证用户是否合法 if (userClientService.checkUser(userId, pwd)) { System.out.println("==========欢迎用户(" + userId + ")登录成功=========="); // 二级菜单 while (loop) { System.out.println("\n==========网络通信系统二级菜单(用户" + userId + ")=========="); System.out.println("\t\t 1 显示在线用户列表"); System.out.println("\t\t 2 群发消息"); System.out.println("\t\t 3 私聊消息"); System.out.println("\t\t 4 发送文件"); System.out.println("\t\t 5 文件路径"); System.out.println("\t\t 9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": // System.out.println("显示在线用户列表"); userClientService.getOnlineFriends(); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } break; case "2": // System.out.println("群发消息"); while (true) { System.out.println("==========群发模式(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.atAll(data); } break; case "3": System.out.print("请输入私聊对方的用户号:"); String ID = Utility.readString(50); while (true) { System.out.println("==========与 " + ID + " 私聊消息中(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.talkTo(ID, data); } break; case "4": System.out.println("发送文件功能正在维护中"); // System.out.print("请输入文件接收方的用户号:"); // String getterId = Utility.readString(50); // System.out.println("即将向 " + getterId + " 发送文件"); // System.out.print("请输入本地文件绝对路径:"); // String filePath = Utility.readString(500); // fileClientService.sendFileToOne(filePath, userId, getterId); break; case "5":
System.out.println("默认文件保存路径为:" + Settings.getDownloadPath());
3
2023-11-22 16:29:22+00:00
8k
partypankes/ProgettoCalcolatrice2023
ProgrammableCalculator/src/test/java/group21/calculator/test/VariablesTest.java
[ { "identifier": "Variables", "path": "ProgrammableCalculator/src/main/java/group21/calculator/operation/Variables.java", "snippet": "public class Variables {\n\n private final Map<Character, ComplexNumber> variables;\n\n /**\n * Constructor for Variables.\n * Initializes a new HashMap to store the variables.\n */\n public Variables(){\n variables = new HashMap<>();\n }\n\n /**\n * Retrieves the map of variables.\n *\n * @return The map of variables with their associated ComplexNumber values.\n */\n public Map<Character, ComplexNumber> getVariables() {\n return variables;\n }\n\n /**\n * Searches for the variable in the map by its name.\n *\n * @param variableName The character name of the variable.\n * @return The ComplexNumber associated with the variable name, or null if not found.\n */\n public ComplexNumber searchVariable(char variableName){\n return variables.get(variableName);\n }\n\n /**\n * Performs operations on variables based on the specified string command.\n * Supports various operations such as assignment, addition, subtraction, multiplication,\n * division, square root, and sign inversion on variables using a stack for intermediate values.\n *\n * @param str The operation command string.\n * @param stack The stack used for holding intermediate values during computation.\n * @throws StackIsEmptyException If the stack is empty when an operation requires a value from it.\n * @throws NoValueInVariableException If a required variable has no assigned value.\n */\n public void perform(String str, StackNumber stack) throws StackIsEmptyException, NoValueInVariableException {\n char firstChar = str.charAt(0);\n char secondChar = str.charAt(1);\n\n if(firstChar == '<') {\n takeFromVariable (secondChar , stack);\n\n }else if(firstChar == '>') {\n pushInVariable(secondChar, stack.peekNumber(), stack.isEmpty());\n\n }else if(firstChar == '+') {\n addValueToVariable(secondChar, stack.peekNumber(), stack.isEmpty ());\n\n }else if(firstChar == '-') {\n subtractValueFromVariable(secondChar, stack.peekNumber(), stack.isEmpty ());\n\n }else if(firstChar == '*') {\n multiplyValueToValue(secondChar,stack.peekNumber(), stack.isEmpty());\n\n }else if(firstChar == '/') {\n divideValueFromValue(secondChar, stack.peekNumber(), stack.isEmpty ());\n\n }else if(firstChar == '√') {\n makeSqrtOfVariable(secondChar);\n\n }else if(firstChar == '±') {\n makeInvertSignOfVariable(secondChar);\n\n }\n\n }\n\n /**\n * Pushes a number into a variable. If the stack is empty, throws a StackIsEmptyException.\n *\n * @param varName The name of the variable.\n * @param number The complex number to be stored in the variable.\n * @param isStackEmpty Indicates whether the stack is empty.\n * @throws StackIsEmptyException If the stack is empty.\n */\n private void pushInVariable(char varName, ComplexNumber number, boolean isStackEmpty) throws StackIsEmptyException{\n if(isStackEmpty){\n throw new StackIsEmptyException ();\n }else{\n variables.put(varName, number);\n }\n }\n\n /**\n * Takes a value from a variable and pushes it onto the stack.\n *\n * @param varName The name of the variable.\n * @param stack The stack where the number will be pushed.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void takeFromVariable(char varName, StackNumber stack) throws NoValueInVariableException{\n if(hasNoValue(varName)){\n throw new NoValueInVariableException(varName);\n }else{\n stack.pushNumber(searchVariable(varName));\n }\n }\n\n /**\n * Adds a value from the stack to the specified variable.\n *\n * @param varName The name of the variable.\n * @param value The complex number to be added to the variable's value.\n * @param isStackEmpty Indicates whether the stack is empty.\n * @throws StackIsEmptyException If the stack is empty.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void addValueToVariable(char varName, ComplexNumber value, boolean isStackEmpty) {\n if(isStackEmpty){\n throw new StackIsEmptyException ();\n }else if(hasNoValue(varName)){\n throw new NoValueInVariableException (varName);\n }else{\n ComplexNumber currentNumber = searchVariable(varName);\n variables.put(varName, currentNumber.add(value));\n }\n }\n\n /**\n * Subtracts a value from the stack from the specified variable.\n *\n * @param varName The name of the variable.\n * @param value The complex number to be subtracted from the variable's value.\n * @param isStackEmpty Indicates whether the stack is empty.\n * @throws StackIsEmptyException If the stack is empty.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void subtractValueFromVariable(char varName, ComplexNumber value, boolean isStackEmpty){\n if(isStackEmpty){\n throw new StackIsEmptyException ();\n }else if(hasNoValue(varName)){\n throw new NoValueInVariableException (varName);\n }else{\n ComplexNumber currentNumber = searchVariable(varName);\n variables.put (varName , currentNumber.subtract(value));\n }\n }\n\n /**\n * Multiplies a value from the stack with the specified variable's value.\n *\n * @param varName The name of the variable.\n * @param value The complex number to multiply with the variable's value.\n * @param isStackEmpty Indicates whether the stack is empty.\n * @throws StackIsEmptyException If the stack is empty.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void multiplyValueToValue(char varName, ComplexNumber value, boolean isStackEmpty){\n if(isStackEmpty){\n throw new StackIsEmptyException ();\n }else if(hasNoValue(varName)){\n throw new NoValueInVariableException (varName);\n }else{\n ComplexNumber currentNumber = searchVariable(varName);\n variables.put (varName , currentNumber.multiply(value));\n }\n }\n\n /**\n * Divides a variable's value by a value from the stack.\n *\n * @param varName The name of the variable.\n * @param value The complex number to divide the variable's value by.\n * @param isStackEmpty Indicates whether the stack is empty.\n * @throws DivisionByZeroException If attempting to divide by zero.\n * @throws StackIsEmptyException If the stack is empty.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void divideValueFromValue(char varName, ComplexNumber value, boolean isStackEmpty){\n\n double sum = (value.getReal() * value.getReal()) + (value.getImaginary() * value.getImaginary());\n\n if(sum == 0) {\n throw new DivisionByZeroException();\n }else if(isStackEmpty){\n throw new StackIsEmptyException ();\n }else if(hasNoValue(varName)){\n throw new NoValueInVariableException (varName);\n }else{\n ComplexNumber currentNumber = searchVariable(varName);\n variables.put (varName , currentNumber.divide(value));\n }\n\n }\n\n /**\n * Calculates the square root of the specified variable's value.\n *\n * @param varName The name of the variable.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void makeSqrtOfVariable(char varName){\n if(hasNoValue(varName)){\n throw new NoValueInVariableException (varName);\n }else{\n ComplexNumber currentNumber = searchVariable(varName);\n variables.put (varName , currentNumber.squareRoot());\n }\n }\n\n /**\n * Inverts the sign of the specified variable's value.\n *\n * @param varName The name of the variable.\n * @throws NoValueInVariableException If the variable does not have a value.\n */\n private void makeInvertSignOfVariable(char varName){\n if(hasNoValue(varName)){\n throw new NoValueInVariableException (varName);\n }else{\n ComplexNumber currentNumber = searchVariable(varName);\n variables.put (varName , currentNumber.invertSign());\n }\n }\n\n /**\n * Checks if a variable has no value.\n *\n * @param varName The name of the variable.\n * @return True if the variable has no value, false otherwise.\n */\n private boolean hasNoValue(char varName){\n return searchVariable(varName) == (null);\n }\n\n}" }, { "identifier": "ComplexNumber", "path": "ProgrammableCalculator/src/main/java/group21/calculator/type/ComplexNumber.java", "snippet": "public class ComplexNumber {\n private final double real;\n private final double imaginary;\n\n /**\n * Constructor for creating a ComplexNumber object with specified real and imaginary parts.\n *\n * @param real The real part of the complex number.\n * @param imaginary The imaginary part of the complex number.\n */\n public ComplexNumber(double real, double imaginary) {\n this.real = real;\n this.imaginary = imaginary;\n }\n\n /**\n * Returns the real part of this complex number.\n *\n * @return The real part.\n */\n public double getReal() {\n return real;\n }\n\n /**\n * Returns the imaginary part of this complex number.\n *\n * @return The imaginary part.\n */\n public double getImaginary() {\n return imaginary;\n }\n\n /**\n * Adds this complex number to another complex number and returns the result.\n *\n * @param other The complex number to be added to this one.\n * @return The result of adding this complex number to the other complex number.\n */\n public ComplexNumber add(ComplexNumber other) {\n return new ComplexNumber(this.real + other.real, this.imaginary + other.imaginary);\n }\n\n /**\n * Subtracts another complex number from this complex number and returns the result.\n *\n * @param other The complex number to be subtracted from this one.\n * @return The result of subtracting the other complex number from this complex number.\n */\n public ComplexNumber subtract(ComplexNumber other) {\n return new ComplexNumber(this.real - other.real, this.imaginary - other.imaginary);\n }\n\n /**\n * Multiplies this complex number by another complex number and returns the result.\n *\n * @param other The complex number to multiply this one by.\n * @return The result of multiplying this complex number by the other complex number.\n */\n public ComplexNumber multiply(ComplexNumber other) {\n double newReal = this.real * other.real - this.imaginary * other.imaginary;\n double newImaginary = this.real * other.imaginary + this.imaginary * other.real;\n return new ComplexNumber(newReal, newImaginary);\n }\n\n /**\n * Divides this complex number by another complex number and returns the result.\n *\n * @param other The complex number to divide this one by.\n * @return The result of dividing this complex number by the other complex number.\n */\n public ComplexNumber divide(ComplexNumber other) {\n double denominator = other.real * other.real + other.imaginary * other.imaginary;\n\n double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;\n double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;\n\n return new ComplexNumber(newReal, newImaginary);\n }\n\n /**\n * Calculates the square root of this complex number and returns the result.\n *\n * @return The result of taking the square root of this complex number.\n */\n public ComplexNumber squareRoot() {\n double magnitude = Math.sqrt(this.real * this.real + this.imaginary * this.imaginary);\n double angle = Math.atan2(this.imaginary, this.real) / 2.0;\n\n double newReal = Math.sqrt(magnitude) * Math.cos(angle);\n double newImaginary = Math.sqrt(magnitude) * Math.sin(angle);\n\n return new ComplexNumber(newReal, newImaginary);\n }\n\n /**\n * Inverts the sign of this complex number and returns the result.\n *\n * @return The result of inverting the sign of this complex number.\n */\n public ComplexNumber invertSign() {\n if(this.real == 0) {\n return new ComplexNumber(this.real, -this.imaginary);\n }else if(this.imaginary == 0) {\n return new ComplexNumber(-this.real, this.imaginary);\n }else return new ComplexNumber(-this.real, -this.imaginary);\n }\n\n /**\n * Parses a string to create a ComplexNumber object.\n *\n * @param str The string representation of a complex number.\n * @return A ComplexNumber object represented by the string.\n */\n public static ComplexNumber complexParse(String str) {\n\n String regex = \"([-+]?(?:\\\\d*\\\\.?\\\\d+)?)?([-+]?(?:\\\\d*\\\\.?\\\\d+j)?)\";\n\n String realPart = str.replaceAll(regex, \"$1\"); //2j\n String imgPart = str.replaceAll(regex, \"$2\"); // j\n \n if(realPart.contains(\"j\")){\n if(realPart.matches(\"[-+]?j\")){\n realPart = realPart.replace(\"j\", \"1\");\n }\n imgPart = realPart;\n realPart = \"\";\n }\n\n double real = (realPart.isEmpty()) ? 0 : Double.parseDouble(realPart);\n double img = (imgPart.isEmpty()) ? 0 : Double.parseDouble(imgPart.replace(\"j\", \"\"));\n\n return new ComplexNumber(real, img);\n }\n\n /**\n * Returns a string representation of this complex number in the format \"a + bi\".\n *\n * @return The string representation of this complex number.\n */\n @Override\n public String toString() {\n\n if(imaginary == 0) {\n return String.format(\"%.2f\", real);\n }\n return String.format(\"%.2f%+.2fj\", real, imaginary);\n }\n\n /**\n * Checks if this complex number is equal to another object.\n * Equality is based on the comparison of the real and imaginary parts.\n *\n * @param o The object to compare with.\n * @return True if the objects are the same or if the real and imaginary parts are equal, false otherwise.\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 ComplexNumber that = (ComplexNumber) o;\n return Double.compare(real, that.real) == 0 && Double.compare(imaginary, that.imaginary) == 0;\n }\n\n\n}" }, { "identifier": "StackNumber", "path": "ProgrammableCalculator/src/main/java/group21/calculator/type/StackNumber.java", "snippet": "public class StackNumber {\n\n private final Stack<ComplexNumber> stack;\n\n /**\n * Constructor for the StackNumber class. Initializes a new Stack object to hold ComplexNumber instances.\n */\n public StackNumber() {\n stack = new Stack<>();\n }\n\n /**\n * Gets the current size of the stack.\n *\n * @return The size of the stack.\n */\n public int getStackSize() {\n return stack.size();\n }\n\n /**\n * Checks if the stack is empty.\n *\n * @return True if the stack is empty, false otherwise.\n */\n public boolean isEmpty() {\n return stack.isEmpty();\n }\n\n /**\n * Pushes a ComplexNumber onto the stack.\n *\n * @param number The ComplexNumber to be added to the stack.\n */\n public void pushNumber(ComplexNumber number){\n stack.push(number);\n }\n\n /**\n * Peeks at the top element of the stack without removing it.\n *\n * @return The ComplexNumber at the top of the stack.\n * @throws StackIsEmptyException If the stack is empty.\n */\n public ComplexNumber peekNumber() throws StackIsEmptyException{\n if (isEmpty()){\n throw new StackIsEmptyException();\n }else{\n return stack.peek ();\n }\n }\n\n /**\n * Removes and returns the top element of the stack.\n *\n * @return The ComplexNumber removed from the top of the stack.\n * @throws StackIsEmptyException If the stack is empty.\n */\n public ComplexNumber dropNumber() throws StackIsEmptyException{\n if(isEmpty()){\n throw new StackIsEmptyException();\n }else{\n return stack.pop();\n }\n }\n\n /**\n * Clears the stack of all elements.\n */\n public void clearNumber(){\n stack.clear();\n }\n\n /**\n * Duplicates the top element of the stack.\n *\n * @throws StackIsEmptyException If the stack is empty.\n */\n public void dupNumber() throws StackIsEmptyException{\n if (isEmpty()){\n throw new StackIsEmptyException();\n }else{\n pushNumber(peekNumber());\n }\n }\n\n /**\n * Swaps the top two elements of the stack.\n *\n * @throws StackIsEmptyException If the stack is empty.\n * @throws InsufficientOperandsException If there are less than two elements in the stack.\n */\n public void swapNumber() throws StackIsEmptyException, InsufficientOperandsException{\n if(stack.isEmpty()){\n throw new StackIsEmptyException ();\n }else if (getStackSize() < 2) {\n throw new InsufficientOperandsException();\n } else {\n ComplexNumber topNumber = dropNumber();\n ComplexNumber secondNumber = dropNumber();\n\n pushNumber(topNumber);\n pushNumber(secondNumber);\n }\n }\n\n /**\n * Pushes a copy of the second-to-top element of the stack onto the top.\n *\n * @throws StackIsEmptyException If the stack is empty.\n * @throws InsufficientOperandsException If there are less than two elements in the stack.\n */\n public void overNumber() throws StackIsEmptyException, InsufficientOperandsException{\n if (stack.isEmpty()){\n throw new StackIsEmptyException ();\n }else if (getStackSize() < 2) {\n throw new InsufficientOperandsException();\n }else {\n ComplexNumber topNumber = dropNumber();\n ComplexNumber secondNumber = peekNumber();\n\n pushNumber(topNumber);\n pushNumber(secondNumber);\n }\n }\n\n /**\n * Retrieves the string representation of the number at the specified index in the stack.\n *\n * @param i The index of the number in the stack.\n * @return The string representation of the ComplexNumber at the specified index.\n */\n public String getNumber(int i) {\n return stack.get(i).toString();\n }\n\n\n}" } ]
import group21.calculator.operation.Variables; import group21.calculator.type.ComplexNumber; import group21.calculator.type.StackNumber; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
4,706
package group21.calculator.test; class VariablesTest { Variables variables;
package group21.calculator.test; class VariablesTest { Variables variables;
StackNumber numbers;
2
2023-11-19 16:11:56+00:00
8k
Staffilon/KestraDataOrchestrator
IoT Simulator/src/main/java/net/acesinc/data/json/generator/RandomJsonGenerator.java
[ { "identifier": "WorkflowConfig", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/WorkflowConfig.java", "snippet": "public class WorkflowConfig {\n\t//nome per il flusso di lavoro\n private String workflowName;\n //nome del flie di configurazione del flusso di lavoro da eseguire\n private String workflowFilename;\n //numero di copie indentiche di istanze da eseguire\n private int instances = 1;\n //elenco di pacchetti in cui sono definiti gestori di tipi personalizzati \n private List<String> customTypeHandlers = new ArrayList<>();\n /**\n * @return the workflowName\n */\n public String getWorkflowName() {\n return workflowName;\n }\n\n /**\n * @param workflowName the workflowName to set\n */\n public void setWorkflowName(String workflowName) {\n this.workflowName = workflowName;\n }\n\n /**\n * @return the workflowFilename\n */\n public String getWorkflowFilename() {\n return workflowFilename;\n }\n\n /**\n * @param workflowFilename the workflowFilename to set\n */\n public void setWorkflowFilename(String workflowFilename) {\n this.workflowFilename = workflowFilename;\n }\n\n public int getInstances() {\n return instances;\n }\n\n public void setInstances(int instances) {\n this.instances = instances;\n }\n\n public List<String> getCustomTypeHandlers() {\n return customTypeHandlers;\n }\n\n public void setCustomTypeHandlers(List<String> customTypeHandlers) {\n this.customTypeHandlers = customTypeHandlers;\n }\n\n}" }, { "identifier": "TypeHandler", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/types/TypeHandler.java", "snippet": "public abstract class TypeHandler {\n private RandomDataGenerator rand;\n private String[] launchArguments;\n \n public TypeHandler() {\n rand = new RandomDataGenerator();\n }\n \n public abstract Object getNextRandomValue();\n public abstract String getName();\n \n /**\n * @return the rand\n */\n public RandomDataGenerator getRand() {\n return rand;\n }\n\n /**\n * @param rand the rand to set\n */\n public void setRand(RandomDataGenerator rand) {\n this.rand = rand;\n }\n\n /**\n * @return the launchArguments\n */\n public String[] getLaunchArguments() {\n return launchArguments;\n }\n\n /**\n * @param launchArguments the launchArguments to set\n */\n public void setLaunchArguments(String[] launchArguments) {\n this.launchArguments = launchArguments;\n }\n \n public static String stripQuotes(String s) {\n return s.replaceAll(\"'\", \"\").replaceAll(\"\\\"\", \"\").trim();\n }\n}" }, { "identifier": "TypeHandlerFactory", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/types/TypeHandlerFactory.java", "snippet": "public class TypeHandlerFactory {\n\n private static final Logger log = LogManager.getLogger(TypeHandlerFactory.class);\n private static final String TYPE_HANDLERS_DEFAULT_PATH = \"net.acesinc.data.json.generator.types\";\n\n private boolean configured = false;\n private static TypeHandlerFactory instance;\n private Map<String, Class> typeHandlerNameMap;\n private Map<String, TypeHandler> typeHandlerCache;\n\n private static final ThreadLocal<TypeHandlerFactory> localInstance = new ThreadLocal<TypeHandlerFactory>(){\n protected TypeHandlerFactory initialValue() {\n return new TypeHandlerFactory();\n }\n };\n\n private TypeHandlerFactory() {\n typeHandlerNameMap = new LinkedHashMap<>();\n typeHandlerCache = new LinkedHashMap<>();\n scanForTypeHandlers(TYPE_HANDLERS_DEFAULT_PATH);\n }\n\n public static TypeHandlerFactory getInstance() {\n return localInstance.get();\n }\n\n /**\n * Allows the type handler factory to be configured from the WorkflowConfig.\n * This will only configure itself once per thread. Any additional call\n * to config will be ignored.\n * @param workflowConfig\n */\n public void configure(WorkflowConfig workflowConfig) {\n if(!configured) {\n for(String packageName : workflowConfig.getCustomTypeHandlers()) {\n scanForTypeHandlers(packageName);\n }\n configured = true;\n }\n }\n\n private void scanForTypeHandlers(String packageName) {\n Reflections reflections = new Reflections(packageName);\n Set<Class<? extends TypeHandler>> subTypes = reflections.getSubTypesOf(TypeHandler.class);\n for (Class type : subTypes) {\n //first, make sure we aren't trying to create an abstract class\n if (Modifier.isAbstract(type.getModifiers())) {\n continue;\n }\n try {\n @SuppressWarnings(\"deprecation\")\n\t\t\t\tObject o = type.newInstance();\n Method nameMethod = o.getClass().getMethod(\"getName\");\n nameMethod.setAccessible(true);\n\n String typeHandlerName = (String) nameMethod.invoke(o);\n typeHandlerNameMap.put(typeHandlerName, type);\n log.debug(\"Discovered TypeHandler [ \" + typeHandlerName + \",\" + type.getName() + \" ]\");\n } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {\n log.warn(\"Error instantiating TypeHandler class [ \" + type.getName() + \" ]. It will not be available during processing.\", ex);\n }\n }\n }\n\n public TypeHandler getTypeHandler(String name, Map<String, Object> knownValues, String currentContext) throws IllegalArgumentException {\n if (name.contains(\"(\")) {\n String typeName = name.substring(0, name.indexOf(\"(\"));\n String args = name.substring(name.indexOf(\"(\") + 1, name.lastIndexOf(\")\"));\n String[] helperArgs = {};\n if (!args.isEmpty()) {\n helperArgs = args.split(\",\");\n helperArgs = prepareStrings(helperArgs);\n }\n\n List<String> resolvedArgs = new ArrayList<>();\n for (String arg : helperArgs) {\n if (arg.startsWith(\"this.\") || arg.startsWith(\"cur.\")) {\n String refPropName = null;\n if (arg.startsWith(\"this.\")) {\n refPropName = arg.substring(\"this.\".length(), arg.length());\n } else if (arg.startsWith(\"cur.\")) {\n refPropName = currentContext + arg.substring(\"cur.\".length(), arg.length());\n }\n Object refPropValue = knownValues.get(refPropName);\n if (refPropValue != null) {\n if (Date.class.isAssignableFrom(refPropValue.getClass())) {\n resolvedArgs.add(BaseDateType.INPUT_DATE_FORMAT.get().format((Date)refPropValue));\n } else {\n resolvedArgs.add(refPropValue.toString());\n }\n } else {\n log.warn(\"Sorry, unable to reference property [ \" + refPropName + \" ]. Maybe it hasn't been generated yet?\");\n }\n } else {\n resolvedArgs.add(arg);\n }\n }\n TypeHandler handler = typeHandlerCache.get(typeName);\n if (handler == null) {\n Class handlerClass = typeHandlerNameMap.get(typeName);\n if (handlerClass != null) {\n try {\n handler = (TypeHandler) handlerClass.newInstance();\n handler.setLaunchArguments(resolvedArgs.toArray(new String[]{}));\n\n typeHandlerCache.put(typeName, handler);\n } catch (InstantiationException | IllegalAccessException ex) {\n log.warn(\"Error instantiating TypeHandler class [ \" + handlerClass.getName() + \" ]\", ex);\n }\n\n }\n } else {\n handler.setLaunchArguments(resolvedArgs.toArray(new String[]{}));\n }\n\n return handler;\n } else {\n //not a type handler\n return null;\n }\n }\n\n public static String[] prepareStrings(String[] list) {\n List<String> newList = new ArrayList<>();\n for (String item : list) {\n newList.add(item.trim());\n }\n return newList.toArray(new String[]{});\n }\n\n public static void main(String[] args) {\n Map<String, Object> vals = new LinkedHashMap<>();\n TypeHandler random = TypeHandlerFactory.getInstance().getTypeHandler(\"random('one', 'two', 'three')\", vals, \"\");\n if (random == null) {\n log.error(\"error getting handler\");\n } else {\n log.info(\"success! random value: \" + random.getNextRandomValue());\n }\n }\n}" }, { "identifier": "JsonUtils", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/util/JsonUtils.java", "snippet": "public class JsonUtils {\n\n private ObjectMapper mapper;\n public JsonUtils() {\n mapper = new ObjectMapper();\n }\n\n public String flattenJson(String json) throws IOException {\n Map<String, Object> outputMap = new LinkedHashMap<>();\n flattenJsonIntoMap(\"\", mapper.readTree(json), outputMap);\n return mapper.writeValueAsString(outputMap);\n }\n \n public void flattenJsonIntoMap(String currentPath, JsonNode jsonNode, Map<String, Object> map) {\n if (jsonNode.isObject()) {\n ObjectNode objectNode = (ObjectNode) jsonNode;\n Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();\n String pathPrefix = currentPath.isEmpty() ? \"\" : currentPath + \".\";\n\n while (iter.hasNext()) {\n Map.Entry<String, JsonNode> entry = iter.next();\n flattenJsonIntoMap(pathPrefix + entry.getKey(), entry.getValue(), map);\n }\n } else if (jsonNode.isArray()) {\n ArrayNode arrayNode = (ArrayNode) jsonNode;\n for (int i = 0; i < arrayNode.size(); i++) {\n flattenJsonIntoMap(currentPath + \"[\" + i + \"]\", arrayNode.get(i), map);\n }\n } else if (jsonNode.isValueNode()) {\n ValueNode valueNode = (ValueNode) jsonNode;\n Object value = null;\n if (valueNode.isNumber()) {\n value = valueNode.numberValue();\n } else if (valueNode.isBoolean()) {\n value = valueNode.asBoolean();\n } else if (valueNode.isTextual()){\n value = valueNode.asText();\n }\n map.put(currentPath, value);\n }\n }\n}" } ]
import java.io.IOException; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.json.Json; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonGeneratorFactory; import org.apache.commons.math3.random.RandomDataGenerator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import net.acesinc.data.json.generator.config.WorkflowConfig; import net.acesinc.data.json.generator.types.TypeHandler; import net.acesinc.data.json.generator.types.TypeHandlerFactory; import net.acesinc.data.json.util.JsonUtils;
3,869
ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, List.class); } private javax.json.stream.JsonGenerator processProperties(javax.json.stream.JsonGenerator gen, Map<String, Object> props, String currentContext) { for (String propName : props.keySet()) { Object value = props.get(propName); if (value == null) { generatedValues.put(currentContext + propName, null); addValue(gen, propName, null); } else if (String.class.isAssignableFrom(value.getClass())) { String type = (String) value; handleStringGeneration(type, currentContext, gen, propName); } else if (Map.class.isAssignableFrom(value.getClass())) { //nested object Map<String, Object> nestedProps = (Map<String, Object>) value; if (propName == null) { gen.writeStartObject(); } else { gen.writeStartObject(propName); } String newContext = ""; if (propName != null) { if (currentContext.isEmpty()) { newContext = propName + "."; } else { newContext = currentContext + propName + "."; } } processProperties(gen, nestedProps, newContext); gen.writeEnd(); } else if (List.class.isAssignableFrom(value.getClass())) { //array List<Object> listOfItems = (List<Object>) value; String newContext = ""; if (propName != null) { gen.writeStartArray(propName); if (currentContext.isEmpty()) { newContext = propName; } else { newContext = currentContext + propName; } } else { gen.writeStartArray(); } if (!listOfItems.isEmpty()) { //Check if this is a special function at the start of the array boolean wasSpecialCase = false; if (String.class.isAssignableFrom(listOfItems.get(0).getClass()) && ((String) listOfItems.get(0)).contains("(")) { //special function in array String name = (String) listOfItems.get(0); String specialFunc = null; String[] specialFuncArgs = {}; specialFunc = name.substring(0, name.indexOf("(")); String args = name.substring(name.indexOf("(") + 1, name.indexOf(")")); if (!args.isEmpty()) { specialFuncArgs = args.split(","); } switch (specialFunc) { case "repeat": { int timesToRepeat = 1; if (specialFuncArgs.length == 1) { timesToRepeat = Integer.parseInt(specialFuncArgs[0]); } else { timesToRepeat = new RandomDataGenerator().nextInt(0, 10); } List<Object> subList = listOfItems.subList(1, listOfItems.size()); for (int i = 0; i < timesToRepeat; i++) { processList(subList, gen, newContext); } wasSpecialCase = true; break; } case "random": { //choose one of the items in the list at random List<Object> subList = listOfItems.subList(1, listOfItems.size()); Object item = subList.get(new RandomDataGenerator().nextInt(0, subList.size() - 1)); processItem(item, gen, newContext + "[0]"); wasSpecialCase = true; break; } } } if (!wasSpecialCase) { //it's not a special function, so process it like normal processList(listOfItems, gen, newContext); } } gen.writeEnd(); } else { //literals generatedValues.put(currentContext + propName, value); addValue(gen, propName, value); } } return gen; } protected void handleStringGeneration(String type, String currentContext, JsonGenerator gen, String propName) { if (type.startsWith("this.") || type.startsWith("cur.")) { String refPropName = null; if (type.startsWith("this.")) { refPropName = type.substring("this.".length(), type.length()); } else if (type.startsWith("cur.")) { refPropName = currentContext + type.substring("cur.".length(), type.length()); } Object refPropValue = generatedValues.get(refPropName); if (refPropValue != null) { addValue(gen, propName, refPropValue); } else { log.warn("Sorry, unable to reference property [ " + refPropName + " ]. Maybe it hasn't been generated yet?"); } } else { try {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ public class RandomJsonGenerator { private static final Logger log = LogManager.getLogger(RandomJsonGenerator.class); private SimpleDateFormat iso8601DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private Map<String, Object> config; private static JsonGeneratorFactory factory = Json.createGeneratorFactory(null); private Map<String, Object> generatedValues; private JsonUtils jsonUtils; private WorkflowConfig workflowConfig; public RandomJsonGenerator(Map<String, Object> config, WorkflowConfig workflowConfig) { this.config = config; this.workflowConfig = workflowConfig; jsonUtils = new JsonUtils(); TypeHandlerFactory.getInstance().configure(workflowConfig); } public String generateJson() { StringWriter w = new StringWriter(); javax.json.stream.JsonGenerator gen = factory.createGenerator(w); generatedValues = new LinkedHashMap<>(); processProperties(gen, config, ""); gen.flush(); return w.toString(); } public String generateFlattnedJson() throws IOException { String json = generateJson(); return jsonUtils.flattenJson(json); } @SuppressWarnings("unchecked") public Map<String, Object> generateJsonMap() throws IOException { String json = generateJson(); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, Map.class); } public List<Map<String, Object>> generateJsonList() throws IOException { String json = generateJson(); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, List.class); } private javax.json.stream.JsonGenerator processProperties(javax.json.stream.JsonGenerator gen, Map<String, Object> props, String currentContext) { for (String propName : props.keySet()) { Object value = props.get(propName); if (value == null) { generatedValues.put(currentContext + propName, null); addValue(gen, propName, null); } else if (String.class.isAssignableFrom(value.getClass())) { String type = (String) value; handleStringGeneration(type, currentContext, gen, propName); } else if (Map.class.isAssignableFrom(value.getClass())) { //nested object Map<String, Object> nestedProps = (Map<String, Object>) value; if (propName == null) { gen.writeStartObject(); } else { gen.writeStartObject(propName); } String newContext = ""; if (propName != null) { if (currentContext.isEmpty()) { newContext = propName + "."; } else { newContext = currentContext + propName + "."; } } processProperties(gen, nestedProps, newContext); gen.writeEnd(); } else if (List.class.isAssignableFrom(value.getClass())) { //array List<Object> listOfItems = (List<Object>) value; String newContext = ""; if (propName != null) { gen.writeStartArray(propName); if (currentContext.isEmpty()) { newContext = propName; } else { newContext = currentContext + propName; } } else { gen.writeStartArray(); } if (!listOfItems.isEmpty()) { //Check if this is a special function at the start of the array boolean wasSpecialCase = false; if (String.class.isAssignableFrom(listOfItems.get(0).getClass()) && ((String) listOfItems.get(0)).contains("(")) { //special function in array String name = (String) listOfItems.get(0); String specialFunc = null; String[] specialFuncArgs = {}; specialFunc = name.substring(0, name.indexOf("(")); String args = name.substring(name.indexOf("(") + 1, name.indexOf(")")); if (!args.isEmpty()) { specialFuncArgs = args.split(","); } switch (specialFunc) { case "repeat": { int timesToRepeat = 1; if (specialFuncArgs.length == 1) { timesToRepeat = Integer.parseInt(specialFuncArgs[0]); } else { timesToRepeat = new RandomDataGenerator().nextInt(0, 10); } List<Object> subList = listOfItems.subList(1, listOfItems.size()); for (int i = 0; i < timesToRepeat; i++) { processList(subList, gen, newContext); } wasSpecialCase = true; break; } case "random": { //choose one of the items in the list at random List<Object> subList = listOfItems.subList(1, listOfItems.size()); Object item = subList.get(new RandomDataGenerator().nextInt(0, subList.size() - 1)); processItem(item, gen, newContext + "[0]"); wasSpecialCase = true; break; } } } if (!wasSpecialCase) { //it's not a special function, so process it like normal processList(listOfItems, gen, newContext); } } gen.writeEnd(); } else { //literals generatedValues.put(currentContext + propName, value); addValue(gen, propName, value); } } return gen; } protected void handleStringGeneration(String type, String currentContext, JsonGenerator gen, String propName) { if (type.startsWith("this.") || type.startsWith("cur.")) { String refPropName = null; if (type.startsWith("this.")) { refPropName = type.substring("this.".length(), type.length()); } else if (type.startsWith("cur.")) { refPropName = currentContext + type.substring("cur.".length(), type.length()); } Object refPropValue = generatedValues.get(refPropName); if (refPropValue != null) { addValue(gen, propName, refPropValue); } else { log.warn("Sorry, unable to reference property [ " + refPropName + " ]. Maybe it hasn't been generated yet?"); } } else { try {
TypeHandler th = TypeHandlerFactory.getInstance().getTypeHandler(type, generatedValues, currentContext);
1
2023-11-26 10:57:17+00:00
8k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERGrimoireOfGaia.java
[ { "identifier": "JEMConfig", "path": "src/main/java/com/invadermonky/justenoughmagiculture/configs/JEMConfig.java", "snippet": "@LangKey(\"config.\" + JustEnoughMagiculture.MOD_ALIAS + \":\" + JustEnoughMagiculture.MOD_ALIAS)\n@Config(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustEnoughMagiculture.MOD_ID\n)\npublic class JEMConfig {\n private static final String LANG_KEY = \"config.\" + JustEnoughMagiculture.MOD_ALIAS + \":\";\n\n @RequiresMcRestart\n @LangKey(LANG_KEY + \"jeimodule\")\n @Comment(\"JEM Just Enough Items general settings.\")\n public static ModuleJEI MODULE_JEI = new ModuleJEI();\n public static class ModuleJEI {\n public boolean enableLootBagCategory = true;\n }\n\n @RequiresMcRestart\n @LangKey(LANG_KEY + \"jermodule\")\n @Comment(\"JEM Just Enough Resources general settings.\")\n public static ModuleJER MODULE_JER = new ModuleJER();\n public static class ModuleJER {\n @Comment(\"Enables the JER spawn biome integration. Setting this to false will cause all newly registered JER mobs to display \\\"Any\\\" for spawn biomes.\")\n public boolean enableJERSpawnBiomes = true;\n @Comment(\"Enables entity render overrides. Disabling this may cause certain entities to no longer render in JER.\")\n public boolean enableRenderOverrides = true;\n }\n\n\n @Comment(ConstantNames.ANIMANIA_EXTRA + \" JER integration configuration.\")\n public static final JEMConfigAnimaniaExtra ANIMANIA_EXTRA = new JEMConfigAnimaniaExtra();\n\n @Comment(ConstantNames.ANIMANIA_FARM + \" JER integration configuration.\")\n public static final JEMConfigAnimaniaFarm ANIMANIA_FARM = new JEMConfigAnimaniaFarm();\n\n @Comment(ConstantNames.ATUM + \" JER integration configuration.\")\n public static final JEMConfigAtum ATUM = new JEMConfigAtum();\n\n @Comment(ConstantNames.BEAR_WITH_ME + \" JER integration configuration.\")\n public static final JEMConfigBearWithMe BEAR_WITH_ME = new JEMConfigBearWithMe();\n\n @Comment(ConstantNames.BEAST_SLAYER + \" JER integration configuration.\")\n public static final JEMConfigBeastSlayer BEAST_SLAYER = new JEMConfigBeastSlayer();\n\n @Comment(ConstantNames.BEWITCHMENT + \" JER integration configuration.\")\n public static final JEMConfigBewitchment BEWITCHMENT = new JEMConfigBewitchment();\n\n @Comment(ConstantNames.BOTANIA + \" JER integration configuration.\")\n public static final JEMConfigBotania BOTANIA = new JEMConfigBotania();\n\n @Comment(ConstantNames.CHARM + \" JER integration configuration.\")\n public static final JEMConfigCharm CHARM = new JEMConfigCharm();\n\n @Comment(ConstantNames.CHOCOLATE_QUEST + \" JER integration configuration.\")\n public static final JEMConfigChocolateQuest CHOCOLATE_QUEST = new JEMConfigChocolateQuest();\n\n @Comment(ConstantNames.EB_WIZARDRY + \" JER integration configuration.\")\n public static final JEMConfigEBWizardry EB_WIZARDRY = new JEMConfigEBWizardry();\n\n @Comment(ConstantNames.EB_WIZARDRY_TF + \" JER integration configuration.\")\n public static final JEMConfigEBWizardryTF EB_WIZARDRY_TF = new JEMConfigEBWizardryTF();\n\n @Comment(ConstantNames.ENDER_IO + \" JER integration configuration.\")\n public static final JEMConfigEnderIO ENDER_IO = new JEMConfigEnderIO();\n\n @Comment(ConstantNames.EREBUS + \" JER integration configuration.\")\n public static final JEMConfigErebus EREBUS = new JEMConfigErebus();\n\n @Comment(ConstantNames.FAMILIAR_FAUNA + \" JER integration configuration.\")\n public static final JEMConfigFamiliarFauna FAMILIAR_FAUNA = new JEMConfigFamiliarFauna();\n\n @Comment(ConstantNames.FUTURE_MC + \" JER integration configuration.\")\n public static final JEMConfigFutureMC FUTURE_MC = new JEMConfigFutureMC();\n\n @Comment(ConstantNames.GRIMOIRE_OF_GAIA + \" JER integration configuration.\")\n public static final JEMConfigGrimoireOfGaia GRIMOIRE_OF_GAIA = new JEMConfigGrimoireOfGaia();\n\n @Comment(ConstantNames.HARVESTCRAFT + \" JER integration configuration.\")\n public static final JEMConfigHarvestcraft HARVESTCRAFT = new JEMConfigHarvestcraft();\n\n @Comment(ConstantNames.HARVESTERS_NIGHT + \" JER integration configuration.\")\n public static final JEMConfigHarvestersNight HARVESTERSNIGHT = new JEMConfigHarvestersNight();\n\n @Comment(ConstantNames.ICE_AND_FIRE + \" JER integration configuration.\")\n public static final JEMConfigIceAndFire ICE_AND_FIRE = new JEMConfigIceAndFire();\n\n @Comment(ConstantNames.INDUSTRIAL_FOREGOING + \" JER integration configuration.\")\n public static final JEMConfigIndustrialForegoing INDUSTRIAL_FOREGOING = new JEMConfigIndustrialForegoing();\n\n @Comment(\"Minecraft JER integration configuration.\")\n public static final JEMConfigMinecraft MINECRAFT = new JEMConfigMinecraft();\n\n @Comment(ConstantNames.MOWZIES_MOBS + \" JER integration configuration.\")\n public static final JEMConfigMowziesMobs MOWZIES_MOBS = new JEMConfigMowziesMobs();\n\n @Comment(ConstantNames.MUTANT_BEASTS + \" JER integration configuration.\")\n public static final JEMConfigMutantBeasts MUTANT_BEASTS = new JEMConfigMutantBeasts();\n\n @Comment(ConstantNames.NETHEREX + \" JER integration configuration.\")\n public static final JEMConfigNetherEx NETHEREX = new JEMConfigNetherEx();\n\n @Comment(ConstantNames.OCEANIC_EXPANSE + \" JER integration configuration.\")\n public static final JEMConfigOceanicExpanse OCEANIC_EXPANSE = new JEMConfigOceanicExpanse();\n\n @Comment(ConstantNames.PIZZACRAFT + \" JER integration configuration.\")\n public static final JEMConfigPizzacraft PIZZACRAFT = new JEMConfigPizzacraft();\n\n @Comment(ConstantNames.QUARK + \" JER integration configuration.\")\n public static final JEMConfigQuark QUARK = new JEMConfigQuark();\n\n @Comment(ConstantNames.RATS + \" JER integration configuration.\")\n public static final JEMConfigRats RATS = new JEMConfigRats();\n\n @Comment(ConstantNames.ROGUELIKE_DUNGEONS + \" JER integration configuration.\")\n public static final JEMConfigRoguelikeDungeons ROGUELIKE_DUNGEONS = new JEMConfigRoguelikeDungeons();\n\n @Comment(ConstantNames.RUSTIC + \" JER integration configuration.\")\n public static final JEMConfigRustic RUSTIC = new JEMConfigRustic();\n\n @Comment(ConstantNames.RUSTIC_THAUMATURGY + \" JER integration configuration.\")\n public static final JEMConfigRusticThaumaturgy RUSTIC_THAUMATURGY = new JEMConfigRusticThaumaturgy();\n\n @Comment(ConstantNames.THAUMCRAFT + \" JER integration configuration.\")\n public static final JEMConfigThaumcraft THAUMCRAFT = new JEMConfigThaumcraft();\n\n @Comment(ConstantNames.SPECIAL_MOBS + \" JER integration configuration.\")\n public static final JEMConfigSpecialMobs SPECIAL_MOBS = new JEMConfigSpecialMobs();\n\n @Comment(ConstantNames.THAUMIC_AUGMENTATION + \" JER integration configuration.\")\n public static final JEMConfigThaumicAugmentation THAUMIC_AUGMENTATION = new JEMConfigThaumicAugmentation();\n\n @Comment(ConstantNames.THERMAL_FOUNDATION + \" JER integration configuration.\")\n public static final JEMConfigThermalFoundation THERMAL_FOUNDATION = new JEMConfigThermalFoundation();\n\n @Comment(ConstantNames.TWILIGHT_FOREST + \" JER integration configuration.\")\n public static final JEMConfigTwilightForest TWILIGHT_FOREST = new JEMConfigTwilightForest();\n\n @Comment(ConstantNames.WADDLES + \" JER integration configuration.\")\n public static final JEMConfigWaddles WADDLES = new JEMConfigWaddles();\n\n\n\n\n @Mod.EventBusSubscriber(modid = JustEnoughMagiculture.MOD_ID)\n public static class ConfigChangeListener {\n @SubscribeEvent\n public static void onConfigChange(ConfigChangedEvent.OnConfigChangedEvent event) {\n if(event.getModID().equals(JustEnoughMagiculture.MOD_ID))\n ConfigManager.sync(JustEnoughMagiculture.MOD_ID, Type.INSTANCE);\n }\n }\n}" }, { "identifier": "JEMConfigGrimoireOfGaia", "path": "src/main/java/com/invadermonky/justenoughmagiculture/configs/mods/JEMConfigGrimoireOfGaia.java", "snippet": "public class JEMConfigGrimoireOfGaia {\n private static final String MOD_NAME = ConstantNames.GRIMOIRE_OF_GAIA;\n private static final String LANG_KEY = \"config.\" + JustEnoughMagiculture.MOD_ALIAS + \":\";\n public JEMConfigGrimoireOfGaia() {}\n\n @RequiresMcRestart\n @Comment(\"Enables JEM \" + MOD_NAME + \" JER mob integration.\")\n public boolean enableJERMobs = true;\n\n @RequiresMcRestart\n @Comment(\"JEM \" + MOD_NAME + \" Just Enough Items settings.\")\n public JEI JUST_ENOUGH_ITEMS = new JEI();\n public static class JEI {\n @Comment(\"Adds the Grimiore of Gaia loot boxes to the Loot Bag category. This is used to fix the otherwise \\n\" +\n \"hardcoded loot table for GoG's built-in category.\")\n public boolean enableJEILootBags = true;\n }\n\n @RequiresMcRestart\n @Comment(\"JEM \" + MOD_NAME + \" Just Enough Resources settings.\")\n public JER JUST_ENOUGH_RESOURCES = new JER();\n public static class JER {\n\n public boolean enableAntScavenger = true;\n public boolean enableAntWorker = true;\n public boolean enableAnubis = true;\n public boolean enableArachne = true;\n public boolean enableBanshee = true;\n public boolean enableBaphomet = true;\n public boolean enableBee = true;\n public boolean enableBeholder = true;\n public boolean enableBoneKnight = true;\n public boolean enableCecaelia = true;\n public boolean enableCentaur = true;\n public boolean enableCobbleGolem = true;\n public boolean enableCobblestoneGolem = true;\n public boolean enableCreep = true;\n public boolean enableCyclops = true;\n public boolean enableDeathword = true;\n public boolean enableDhampir = true;\n public boolean enableDryad = true;\n public boolean enableDullahan = true;\n public boolean enableDwarf = true;\n public boolean enableDwarfArcher = true;\n public boolean enableDwarfMiner = true;\n public boolean enableEnderDragonGirl = true;\n public boolean enableEnderEye = true;\n public boolean enableFleshLich = true;\n public boolean enableGelatinousSlime = true;\n public boolean enableGoblin = true;\n public boolean enableGoblinArcher = true;\n public boolean enableGravemite = true;\n public boolean enableGryphon = true;\n public boolean enableHarpy = true;\n public boolean enableHarpyWizard = true;\n public boolean enableHunter = true;\n public boolean enableKikimora = true;\n public boolean enableKobold = true;\n public boolean enableMandragora = true;\n public boolean enableMatango = true;\n public boolean enableMermaid = true;\n public boolean enableMimic = true;\n public boolean enableMinotaur = true;\n public boolean enableMinotaurus = true;\n public boolean enableMinotaurusArcher = true;\n public boolean enableMummy = true;\n public boolean enableNaga = true;\n public boolean enableNineTails = true;\n public boolean enableOni = true;\n public boolean enableOrc = true;\n public boolean enableOrcWizard = true;\n public boolean enableSatyress = true;\n public boolean enableSelkie = true;\n public boolean enableSHAMAN = true;\n public boolean enableSHARKO = true;\n public boolean enableSiren = true;\n public boolean enableSludgeGirl = true;\n public boolean enableSphinx = true;\n public boolean enableSporeling = true;\n public boolean enableSpriggan = true;\n public boolean enableSuccubus = true;\n public boolean enableToad = true;\n public boolean enableValkyrie = true;\n public boolean enableVampire = true;\n public boolean enableWerecat = true;\n public boolean enableWitch = true;\n public boolean enableWitherCow = true;\n public boolean enableYeti = true;\n public boolean enableYukiOnna = true;\n\n //No spawn mobs\n public MobJER FERAL_GOBLIN = new MobJER();\n public MobJER FERAL_GOBLIN_ARCHER = new MobJER();\n public MobJER FERAL_GOBLIN_BOMBER = new MobJER();\n public MobJER ILLAGER_BUTLER = new MobJER();\n public MobJER ILLAGER_INCINERATOR = new MobJER();\n public MobJER ILLAGER_INQUISITOR = new MobJER();\n\n }\n}" }, { "identifier": "LootBagEntry", "path": "src/main/java/com/invadermonky/justenoughmagiculture/integrations/jei/categories/lootbag/LootBagEntry.java", "snippet": "public class LootBagEntry {\n private final ItemStack lootBag;\n private final List<LootDrop> drops = new ArrayList<>();\n private final int minStacks;\n private final int maxStacks;\n\n public LootBagEntry(ItemStack lootBag, LootTable lootTable) {\n this.lootBag = lootBag;\n float[] minStacks = new float[] {0.0F};\n float[] maxStacks = new float[] {0.0F};\n LootTableManager manager = LootTableHelper.getManager();\n this.handleTable(lootTable, manager, minStacks, maxStacks);\n this.minStacks = MathHelper.floor(minStacks[0]);\n this.maxStacks = MathHelper.floor(maxStacks[0]);\n }\n\n private void handleTable(LootTable lootTable, LootTableManager manager, float[] tmpMinStacks, float[] tmpMaxStacks) {\n\n List<LootPool> pools = LootTableHelper.getPools(lootTable);\n for(LootPool pool : pools) {\n tmpMinStacks[0] += pool.getRolls().getMin();\n tmpMaxStacks[0] += pool.getRolls().getMax() + pool.getBonusRolls().getMax();\n final float totalWeight = LootTableHelper.getEntries(pool).stream().mapToInt(entry -> entry.getEffectiveWeight(0)).sum();\n\n List<LootEntry> entries = LootTableHelper.getEntries(pool);\n for(LootEntry entry : entries) {\n if(entry instanceof LootEntryItem) {\n LootEntryItem entryItem = (LootEntryItem) entry;\n drops.add(new LootDrop(LootTableHelper.getItem(entryItem), entryItem.getEffectiveWeight(0) / totalWeight, LootTableHelper.getFunctions(entryItem)));\n } else if(entry instanceof LootEntryTable) {\n LootEntryTable entryTable = (LootEntryTable) entry;\n LootTable table = manager.getLootTableFromLocation(entryTable.table);\n handleTable(table, manager, tmpMinStacks, tmpMaxStacks);\n }\n }\n }\n }\n\n public boolean containsItem(ItemStack itemStack) {\n return drops.stream().anyMatch(drop -> drop.item.isItemEqual(itemStack));\n }\n\n public ItemStack getLootBag() {\n return this.lootBag;\n }\n\n public List<ItemStack> getItemStacks(IFocus<ItemStack> focus) {\n return drops.stream().map(drop -> drop.item)\n .filter(stack -> focus == null || ItemStack.areItemStacksEqual(ItemHandlerHelper.copyStackWithSize(stack, focus.getValue().getCount()), focus.getValue()))\n .collect(Collectors.toList());\n }\n\n public int getMaxStacks() {\n return maxStacks;\n }\n\n public int getMinStacks() {\n return minStacks;\n }\n\n public LootDrop getBagDrop(ItemStack ingredient) {\n return drops.stream().filter(drop -> ItemStack.areItemsEqual(drop.item, ingredient)).findFirst().orElse(null);\n }}" }, { "identifier": "IJERIntegration", "path": "src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/IJERIntegration.java", "snippet": "public interface IJERIntegration {\n default void registerModDungeons() {}\n\n default void registerModEntities() {}\n\n default void registerModPlants() {}\n\n default void registerModVillagers() {}\n\n default void injectLoot() {}\n}" }, { "identifier": "JERBase", "path": "src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/JERBase.java", "snippet": "public abstract class JERBase {\n protected World world;\n protected LootTableManager manager;\n\n public JERBase() {\n this.world = InitIntegration.world;\n this.manager = InitIntegration.manager;\n }\n\n protected void registerDungeonLoot(String category, String unlocName, ResourceLocation drops) {\n if(!DungeonRegistry.categoryToLocalKeyMap.containsKey(category)) {\n InitIntegration.dungeonRegistry.registerCategory(category, unlocName);\n }\n InitIntegration.dungeonRegistry.registerChest(category, drops);\n }\n\n protected void registerDungeonLoot(String category, String unlocName, LootTable drops) {\n if(!DungeonRegistry.categoryToLocalKeyMap.containsKey(category)) {\n InitIntegration.dungeonRegistry.registerCategory(category, unlocName);\n }\n InitIntegration.dungeonRegistry.registerChest(category, drops);\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, int minExp, int maxExp, String[] biomes, LootDrop... lootDrops) {\n InitIntegration.mobRegistry.register(entity, level, minExp, maxExp, biomes, lootDrops);\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, String[] biomes, LootDrop... lootDrops) {\n int exp = entity instanceof EntityLiving ? ((EntityLiving) entity).experienceValue : 0;\n if(exp > 0)\n registerMob(entity, level, exp, exp, biomes, lootDrops);\n else if(entity instanceof EntityAnimal)\n registerMob(entity, level, 1, 3, biomes, lootDrops);\n else\n registerMob(entity, level, 0, 0, biomes, lootDrops);\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, String[] biomes, List<LootDrop> lootdrops) {\n registerMob(entity, level, biomes, lootdrops.toArray(new LootDrop[0]));\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, String[] biomes, ResourceLocation lootDrops) {\n registerMob(entity, level, biomes, LootTableHelper.toDrops(world, lootDrops).toArray(new LootDrop[0]));\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, ResourceLocation lootDrops) {\n registerMob(entity, level, new String[] {\"jer.any\"}, LootTableHelper.toDrops(world, lootDrops).toArray(new LootDrop[0]));\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, LootDrop... lootDrops) {\n registerMob(entity, level, new String[] {\"jer.any\"}, lootDrops);\n }\n\n protected void registerMob(EntityLivingBase entity, LightLevel level, int minExp, int maxExp, String[] biomes, ResourceLocation lootDrops) {\n registerMob(entity, level, minExp, maxExp, biomes, LootTableHelper.toDrops(world, lootDrops).toArray(new LootDrop[0]));\n }\n\n protected void registerRenderHook(Class<? extends EntityLivingBase> clazz, IMobRenderHook renderHook) {\n InitIntegration.mobRegistry.registerRenderHook(clazz, renderHook);\n }\n\n protected <T extends Item & IPlantable> void registerPlant(T plant, PlantDrop... drops) {\n InitIntegration.plantRegistry.register(plant, drops);\n }\n\n protected void registerPlant(ItemStack plant, PlantDrop... drops) {\n InitIntegration.plantRegistry.register(plant, drops);\n }\n\n protected void registerPlant(ItemStack stack, IPlantable plant, PlantDrop... drops) {\n InitIntegration.plantRegistry.register(stack, plant, drops);\n }\n\n protected <T extends Item & IPlantable> void registerPlant(T plant, IBlockState soil, PlantDrop... drops) {\n InitIntegration.plantRegistry.registerWithSoil(plant, soil, drops);\n }\n\n protected void registerPlant(ItemStack stack, IPlantable plant, IBlockState soil, PlantDrop... drops) {\n InitIntegration.plantRegistry.registerWithSoil(stack, plant, soil, drops);\n }\n\n protected <T extends Item & IPlantable> void registerCustomPlant(PlantEntry plantEntry) {\n CustomPlantRegistry.getInstance().registerPlant(plantEntry);\n }\n}" }, { "identifier": "JEMConditional", "path": "src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/conditionals/JEMConditional.java", "snippet": "public class JEMConditional {\n public static final Conditional affectedByAncient = new Conditional(\"jem.affectedByAncient.text\", TextModifier.purple);\n public static final Conditional affectedByResearch = new Conditional(\"jem.affectedByResearch\", TextModifier.purple);\n public static final Conditional dependsOnAge = new Conditional(\"jem.dependsOnAge.text\", TextModifier.orange);\n public static final Conditional dependsOnSize = new Conditional(\"jem.dependsOnSize.text\", TextModifier.lightGreen);\n public static final Conditional dependsOnVariant = new Conditional(\"jem.dependsOnVariant.text\", TextModifier.lightCyan);\n public static final Conditional isAdult = new Conditional(\"jem.adult.text\", TextModifier.orange);\n public static final Conditional isNotAdult = new Conditional(\"jem.notAdult.text\", isAdult);\n public static final Conditional killedWithAxe = new Conditional(\"jem.axeKill.text\", Conditional.belowLooting);\n public static final Conditional killedWithShovel = new Conditional(\"jem.shovelKill.text\", Conditional.belowLooting);\n public static final Conditional requiresBottle = new Conditional(\"jem.requiresBottle.text\", TextModifier.white);\n public static final Conditional isSquashed = new Conditional(\"jem.squashed.text\", TextModifier.darkGreen);\n public static final Conditional isNotSquashed = new Conditional(\"jem.notSquashed.text\", TextModifier.lightRed);\n}" }, { "identifier": "LootBagRegistry", "path": "src/main/java/com/invadermonky/justenoughmagiculture/registry/LootBagRegistry.java", "snippet": "public class LootBagRegistry {\n private Map<String, LootBagEntry> registry;\n private static LootBagRegistry instance;\n\n public static LootBagRegistry getInstance() {\n return instance != null ? instance : (instance = new LootBagRegistry());\n }\n\n public LootBagRegistry() {\n registry = new LinkedHashMap<>();\n }\n\n public boolean registerLootBag(LootBagEntry entry) {\n String key = MapKeys.getKey(entry.getLootBag());\n if(key == null || registry.containsKey(key))\n return false;\n registry.put(key, entry);\n return true;\n }\n\n public String getNumStacks(LootBagEntry entry) {\n int max = entry.getMaxStacks();\n int min = entry.getMinStacks();\n return min == max ? I18n.format(\"jer.stacks\", max) : I18n.format(\"jer.stacks\", min + \" - \" + max);\n }\n\n public List<LootBagEntry> getAllLootBags() {\n return new ArrayList<>(registry.values());\n }\n}" }, { "identifier": "BiomeHelper", "path": "src/main/java/com/invadermonky/justenoughmagiculture/util/BiomeHelper.java", "snippet": "public class BiomeHelper {\n public static String[] getBiomeNamesForBiomes(Biome... biomes) {\n List<String> biomeNames = new ArrayList<>();\n\n if(!JEMConfig.MODULE_JER.enableJERSpawnBiomes)\n return new String[] {\"jer.any\"};\n\n for(Biome biome : biomes) {\n biomeNames.add(WordUtils.capitalizeFully(biome.getBiomeName()));\n }\n\n return !biomeNames.isEmpty() ? biomeNames.toArray(new String[0]) : new String[] {\"jer.any\"};\n }\n\n public static String[] getBiomeNamesForBiomes(String... biomes) {\n List<String> biomeNames = new ArrayList<>();\n\n if(!JEMConfig.MODULE_JER.enableJERSpawnBiomes)\n return new String[] {\"jer.any\"};\n\n for(String biome : biomes) {\n if(biome != null && ForgeRegistries.BIOMES.containsKey(new ResourceLocation(biome))) {\n String validBiome = WordUtils.capitalizeFully(ForgeRegistries.BIOMES.getValue(new ResourceLocation(biome)).getBiomeName());\n biomeNames.add(validBiome);\n }\n }\n\n return !biomeNames.isEmpty() ? biomeNames.toArray(new String[0]) : new String[] {\"jer.any\"};\n }\n\n public static String[] getBiomeNamesForTypes(String... types) {\n ArrayList<Biome> biomeNames = new ArrayList<>();\n for(String typeStr : types) {\n Type type = Type.getType(typeStr);\n biomeNames.addAll(BiomeDictionary.getBiomes(type));\n }\n return getBiomeNamesForBiomes(biomeNames.toArray(new Biome[0]));\n }\n\n public static String[] getBiomeNamesForTypes(Type... types) {\n ArrayList<Biome> biomeNames = new ArrayList<>();\n for(Type type : types) {\n biomeNames.addAll(BiomeDictionary.getBiomes(type));\n }\n return getBiomeNamesForBiomes(biomeNames.toArray(new Biome[0]));\n }\n\n public static String[] getTypeNamesForTypes(Type... types) {\n List<String> typeNames = new ArrayList<>();\n\n if(!JEMConfig.MODULE_JER.enableJERSpawnBiomes)\n return new String[] {\"jer.any\"};\n\n for(Type type : types) {\n typeNames.add(WordUtils.capitalizeFully(type.getName()));\n }\n return !typeNames.isEmpty() ? typeNames.toArray(new String[0]) : new String[] {\"jer.any\"};\n }\n\n public static String[] getBiomeNames(String[] validBiomeTypes) {\n return getBiomeNames(validBiomeTypes, new String[0]);\n }\n\n public static String[] getBiomeNames(ConfigHelper.MobJER mobJER) {\n return getBiomeNames(mobJER.validBiomeTypes, mobJER.invalidBiomeTypes);\n }\n\n public static String[] getBiomeNames(String[] validBiomeTypes, String[] invalidBiomeTypes) {\n ArrayList<Biome> spawnBiomes = new ArrayList<>();\n\n for(String typeStr : validBiomeTypes) {\n Type type = Type.getType(typeStr);\n spawnBiomes.addAll(BiomeDictionary.getBiomes(type));\n }\n\n for(String typeStr : invalidBiomeTypes) {\n Type type = Type.getType(typeStr);\n spawnBiomes.removeAll(BiomeDictionary.getBiomes(type));\n }\n\n if(spawnBiomes.isEmpty())\n return new String[] {\"None\"};\n else if(spawnBiomes.size() > 30)\n return new String[] {\"jer.any\"};\n\n return BiomeHelper.getBiomeNamesForBiomes(spawnBiomes.toArray(new Biome[0]));\n }\n}" } ]
import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigGrimoireOfGaia; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag.LootBagEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.integrations.jer.conditionals.JEMConditional; import com.invadermonky.justenoughmagiculture.registry.LootBagRegistry; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import gaia.GaiaConfig; import gaia.entity.monster.*; import gaia.init.GaiaBlocks; import gaia.init.GaiaItems; import gaia.init.GaiaLootTables; import jeresources.api.conditionals.Conditional; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.util.LootTableHelper; import net.minecraft.block.Block; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.entity.EntityLiving; import net.minecraft.init.Blocks; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemEnchantedBook; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.*; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraft.world.storage.loot.functions.SetCount; import net.minecraft.world.storage.loot.functions.SetMetadata; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.List;
7,168
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERGrimoireOfGaia extends JERBase implements IJERIntegration { private static JERGrimoireOfGaia instance;
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERGrimoireOfGaia extends JERBase implements IJERIntegration { private static JERGrimoireOfGaia instance;
private final JEMConfigGrimoireOfGaia.JER jerConfig = JEMConfig.GRIMOIRE_OF_GAIA.JUST_ENOUGH_RESOURCES;
0
2023-11-19 23:09:14+00:00
8k
spring-cloud/spring-functions-catalog
supplier/spring-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumReactiveConsumerConfiguration.java
[ { "identifier": "DebeziumEngineBuilderAutoConfiguration", "path": "common/spring-debezium-autoconfigure/src/main/java/org/springframework/cloud/fn/common/debezium/DebeziumEngineBuilderAutoConfiguration.java", "snippet": "@AutoConfiguration\n@EnableConfigurationProperties(DebeziumProperties.class)\n@Conditional(DebeziumEngineBuilderAutoConfiguration.OnDebeziumConnectorCondition.class)\n@ConditionalOnProperty(prefix = \"debezium\", name = \"properties.connector.class\")\npublic class DebeziumEngineBuilderAutoConfiguration {\n\n\tprivate static final Log logger = LogFactory.getLog(DebeziumEngineBuilderAutoConfiguration.class);\n\n\t/**\n\t * The fully-qualified class name of the commit policy type. The default is a periodic\n\t * commit policy based upon time intervals.\n\t * @param properties the 'debezium.properties.offset.flush.interval.ms' configuration\n\t * is compulsory for the Periodic policy type. The ALWAYS and DEFAULT doesn't require\n\t * additional configuration.\n\t * @return {@link OffsetCommitPolicy} bean\n\t */\n\t@Bean\n\t@ConditionalOnMissingBean\n\tpublic OffsetCommitPolicy offsetCommitPolicy(DebeziumProperties properties) {\n\n\t\tswitch (properties.getOffsetCommitPolicy()) {\n\t\t\tcase PERIODIC:\n\t\t\t\treturn OffsetCommitPolicy.periodic(properties.getDebeziumNativeConfiguration());\n\t\t\tcase ALWAYS:\n\t\t\t\treturn OffsetCommitPolicy.always();\n\t\t\tcase DEFAULT:\n\t\t\tdefault:\n\t\t\t\treturn NULL_OFFSET_COMMIT_POLICY;\n\t\t}\n\t}\n\n\t/**\n\t * Use the specified clock when needing to determine the current time. Defaults to\n\t * {@link Clock#systemDefaultZone() system clock}, but you can override the Bean in\n\t * your configuration with you {@link Clock implementation}. Returns\n\t * @return {@link Clock} for the system default zone.\n\t */\n\t@Bean\n\t@ConditionalOnMissingBean\n\tpublic Clock debeziumClock() {\n\t\treturn Clock.systemDefaultZone();\n\t}\n\n\t/**\n\t * When the engine's {@link DebeziumEngine#run()} method completes, call the supplied\n\t * function with the results.\n\t * @return {@link CompletionCallback} that logs the completion status. The bean can be\n\t * overridden in custom implementation.\n\t */\n\t@Bean\n\t@ConditionalOnMissingBean\n\tpublic CompletionCallback completionCallback() {\n\t\treturn DEFAULT_COMPLETION_CALLBACK;\n\t}\n\n\t/**\n\t * During the engine run, provides feedback about the different stages according to\n\t * the completion state of each component running within the engine (connectors, tasks\n\t * etc.). The bean can be overridden in custom implementation.\n\t * @return {@link ConnectorCallback}\n\t */\n\t@Bean\n\t@ConditionalOnMissingBean\n\tpublic ConnectorCallback connectorCallback() {\n\t\treturn DEFAULT_CONNECTOR_CALLBACK;\n\t}\n\n\t@Bean\n\t@ConditionalOnMissingBean\n\tpublic DebeziumEngine.Builder<ChangeEvent<byte[], byte[]>> debeziumEngineBuilder(\n\t\t\tOffsetCommitPolicy offsetCommitPolicy, CompletionCallback completionCallback,\n\t\t\tConnectorCallback connectorCallback, DebeziumProperties properties, Clock debeziumClock) {\n\n\t\tClass<? extends SerializationFormat<byte[]>> payloadFormat = Objects.requireNonNull(\n\t\t\t\tserializationFormatClass(properties.getPayloadFormat()),\n\t\t\t\t\"Cannot find payload format for \" + properties.getProperties());\n\n\t\tClass<? extends SerializationFormat<byte[]>> headerFormat = Objects.requireNonNull(\n\t\t\t\tserializationFormatClass(properties.getHeaderFormat()),\n\t\t\t\t\"Cannot find header format for \" + properties.getProperties());\n\n\t\treturn DebeziumEngine.create(KeyValueHeaderChangeEventFormat.of(payloadFormat, payloadFormat, headerFormat))\n\t\t\t.using(properties.getDebeziumNativeConfiguration())\n\t\t\t.using(debeziumClock)\n\t\t\t.using(completionCallback)\n\t\t\t.using(connectorCallback)\n\t\t\t.using((offsetCommitPolicy != NULL_OFFSET_COMMIT_POLICY) ? offsetCommitPolicy : null);\n\t}\n\n\tprivate Class<? extends SerializationFormat<byte[]>> serializationFormatClass(DebeziumFormat debeziumFormat) {\n\t\treturn switch (debeziumFormat) {\n\t\t\tcase JSON -> io.debezium.engine.format.JsonByteArray.class;\n\t\t\tcase AVRO -> io.debezium.engine.format.Avro.class;\n\t\t\tcase PROTOBUF -> io.debezium.engine.format.Protobuf.class;\n\t\t};\n\t}\n\n\t/**\n\t * A callback function to be notified when the connector completes.\n\t */\n\tprivate static final CompletionCallback DEFAULT_COMPLETION_CALLBACK = (success, message, error) -> logger\n\t\t.info(String.format(\"Debezium Engine completed with success:%s, message:%s \", success, message), error);\n\n\t/**\n\t * Callback function which informs users about the various stages a connector goes\n\t * through during startup.\n\t */\n\tprivate static final ConnectorCallback DEFAULT_CONNECTOR_CALLBACK = new ConnectorCallback() {\n\n\t\t/**\n\t\t * Called after a connector has been successfully started by the engine.\n\t\t */\n\t\tpublic void connectorStarted() {\n\t\t\tlogger.info(\"Connector Started!\");\n\t\t};\n\n\t\t/**\n\t\t * Called after a connector has been successfully stopped by the engine.\n\t\t */\n\t\tpublic void connectorStopped() {\n\t\t\tlogger.info(\"Connector Stopped!\");\n\t\t}\n\n\t\t/**\n\t\t * Called after a connector task has been successfully started by the engine.\n\t\t */\n\t\tpublic void taskStarted() {\n\t\t\tlogger.info(\"Connector Task Started!\");\n\t\t}\n\n\t\t/**\n\t\t * Called after a connector task has been successfully stopped by the engine.\n\t\t */\n\t\tpublic void taskStopped() {\n\t\t\tlogger.info(\"Connector Task Stopped!\");\n\t\t}\n\n\t};\n\n\t/**\n\t * The policy that defines when the offsets should be committed to offset storage.\n\t */\n\tprivate static final OffsetCommitPolicy NULL_OFFSET_COMMIT_POLICY = (numberOfMessagesSinceLastCommit,\n\t\t\ttimeSinceLastCommit) -> {\n\t\tthrow new UnsupportedOperationException(\"Unimplemented method 'performCommit'\");\n\t};\n\n\t/**\n\t * Determine if Debezium connector is available. This either kicks in if any debezium\n\t * connector is available.\n\t */\n\t@Order\n\tstatic class OnDebeziumConnectorCondition extends AnyNestedCondition {\n\n\t\tOnDebeziumConnectorCondition() {\n\t\t\tsuper(ConfigurationPhase.REGISTER_BEAN);\n\t\t}\n\n\t\t@ConditionalOnClass(name = { \"io.debezium.connector.mysql.MySqlConnector\" })\n\t\tstatic class HasMySqlConnector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.postgresql.PostgresConnector\")\n\t\tstatic class HasPostgreSqlConnector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.db2.Db2Connector\")\n\t\tstatic class HasDb2Connector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.oracle.OracleConnector\")\n\t\tstatic class HasOracleConnector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.sqlserver.SqlServerConnector\")\n\t\tstatic class HasSqlServerConnector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.mongodb.MongoDbConnector\")\n\t\tstatic class HasMongoDbConnector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.vitess.VitessConnector\")\n\t\tstatic class HasVitessConnector {\n\n\t\t}\n\n\t\t@ConditionalOnClass(name = \"io.debezium.connector.spanner.SpannerConnector\")\n\t\tstatic class HasSpannerConnector {\n\n\t\t}\n\n\t}\n\n}" }, { "identifier": "DebeziumProperties", "path": "common/spring-debezium-autoconfigure/src/main/java/org/springframework/cloud/fn/common/debezium/DebeziumProperties.java", "snippet": "@ConfigurationProperties(\"debezium\")\npublic class DebeziumProperties {\n\n\tpublic enum DebeziumFormat {\n\n\t\t/**\n\t\t * JSON change event format.\n\t\t */\n\t\tJSON(\"application/json\"),\n\t\t/**\n\t\t * AVRO change event format.\n\t\t */\n\t\tAVRO(\"application/avro\"),\n\t\t/**\n\t\t * ProtoBuf change event format.\n\t\t */\n\t\tPROTOBUF(\"application/x-protobuf\"),;\n\n\t\tprivate final String contentType;\n\n\t\tDebeziumFormat(String contentType) {\n\t\t\tthis.contentType = contentType;\n\t\t}\n\n\t\tpublic final String contentType() {\n\t\t\treturn this.contentType;\n\t\t}\n\n\t};\n\n\t/**\n\t * Spring pass-trough wrapper for debezium configuration properties. All properties\n\t * with a 'debezium.properties.*' prefix are native Debezium properties.\n\t */\n\tprivate final Map<String, String> properties = new HashMap<>();\n\n\t/**\n\t * {@code io.debezium.engine.ChangeEvent} Key and Payload formats. Defaults to 'JSON'.\n\t */\n\tprivate DebeziumFormat payloadFormat = DebeziumFormat.JSON;\n\n\t/**\n\t * {@code io.debezium.engine.ChangeEvent} header format. Defaults to 'JSON'.\n\t */\n\tprivate DebeziumFormat headerFormat = DebeziumFormat.JSON;\n\n\t/**\n\t * The policy that defines when the offsets should be committed to offset storage.\n\t */\n\tprivate DebeziumOffsetCommitPolicy offsetCommitPolicy = DebeziumOffsetCommitPolicy.DEFAULT;\n\n\tpublic Map<String, String> getProperties() {\n\t\treturn this.properties;\n\t}\n\n\tpublic DebeziumFormat getPayloadFormat() {\n\t\treturn this.payloadFormat;\n\t}\n\n\tpublic void setPayloadFormat(DebeziumFormat format) {\n\t\tthis.payloadFormat = format;\n\t}\n\n\tpublic DebeziumFormat getHeaderFormat() {\n\t\treturn this.headerFormat;\n\t}\n\n\tpublic void setHeaderFormat(DebeziumFormat headerFormat) {\n\t\tthis.headerFormat = headerFormat;\n\t}\n\n\tpublic enum DebeziumOffsetCommitPolicy {\n\n\t\t/**\n\t\t * Commits offsets as frequently as possible. This may result in reduced\n\t\t * performance, but it has the least potential for seeing source records more than\n\t\t * once upon restart.\n\t\t */\n\t\tALWAYS,\n\t\t/**\n\t\t * Commits offsets no more than the specified time period. If the specified time\n\t\t * is less than {@code 0} then the policy will behave as ALWAYS policy. Requires\n\t\t * the 'debezium.properties.offset.flush.interval.ms' native property to be set.\n\t\t */\n\t\tPERIODIC,\n\t\t/**\n\t\t * Uses the default Debezium engine policy (PERIODIC).\n\t\t */\n\t\tDEFAULT;\n\n\t}\n\n\tpublic DebeziumOffsetCommitPolicy getOffsetCommitPolicy() {\n\t\treturn this.offsetCommitPolicy;\n\t}\n\n\tpublic void setOffsetCommitPolicy(DebeziumOffsetCommitPolicy offsetCommitPolicy) {\n\t\tthis.offsetCommitPolicy = offsetCommitPolicy;\n\t}\n\n\t/**\n\t * Convert the Spring Framework \"debezium.properties.*\" properties into native\n\t * Debezium configuration.\n\t * @return the properties for Debezium native configuration\n\t */\n\tpublic Properties getDebeziumNativeConfiguration() {\n\t\tProperties outProps = new java.util.Properties();\n\t\toutProps.putAll(getProperties());\n\t\treturn outProps;\n\t}\n\n}" } ]
import java.lang.reflect.Field; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.function.Supplier; import io.debezium.engine.ChangeEvent; import io.debezium.engine.DebeziumEngine; import io.debezium.engine.DebeziumEngine.Builder; import io.debezium.engine.Header; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Sinks; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.fn.common.debezium.DebeziumEngineBuilderAutoConfiguration; import org.springframework.cloud.fn.common.debezium.DebeziumProperties; import org.springframework.context.annotation.Bean; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.ClassUtils; import org.springframework.util.MimeTypeUtils;
3,679
/* * Copyright 2023-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.fn.supplier.debezium; /** * The Debezium supplier auto-configuration. * * @author Christian Tzolov * @author Artem Bilan */ @AutoConfiguration(after = DebeziumEngineBuilderAutoConfiguration.class) @EnableConfigurationProperties(DebeziumSupplierProperties.class) @ConditionalOnBean(DebeziumEngine.Builder.class) public class DebeziumReactiveConsumerConfiguration implements BeanClassLoaderAware { private static final Log LOGGER = LogFactory.getLog(DebeziumReactiveConsumerConfiguration.class); /** * ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL. */ public static final String ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL = "org.springframework.kafka.support.KafkaNull"; private Object kafkaNull = null; @Override public void setBeanClassLoader(ClassLoader classLoader) { try { Class<?> clazz = ClassUtils.forName(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, classLoader); Field field = clazz.getDeclaredField("INSTANCE"); this.kafkaNull = field.get(null); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) { } } /** * Reactive Streams, single subscriber, sink used to push down the change event * signals received from the Debezium Engine. */ private final Sinks.Many<Message<?>> eventSink = Sinks.many().unicast().onBackpressureError(); /** * Debezium Engine is designed to be submitted to an {@link ExecutorService} for * execution by a single thread, and a running connector can be stopped either by * calling {@code stop()} from another thread or by interrupting the running thread * (e.g., as is the case with {@link ExecutorService#shutdownNow()}). */ private final ExecutorService debeziumExecutor = Executors.newSingleThreadExecutor(); @Bean public DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine( Consumer<ChangeEvent<byte[], byte[]>> changeEventConsumer, Builder<ChangeEvent<byte[], byte[]>> debeziumEngineBuilder) { return debeziumEngineBuilder.notifying(changeEventConsumer).build(); } @Bean public Supplier<Flux<Message<?>>> debeziumSupplier(DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine) { return () -> this.eventSink.asFlux() .doOnRequest((r) -> this.debeziumExecutor.execute(debeziumEngine)) .doOnTerminate(this.debeziumExecutor::shutdownNow); } @Bean @ConditionalOnMissingBean
/* * Copyright 2023-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.fn.supplier.debezium; /** * The Debezium supplier auto-configuration. * * @author Christian Tzolov * @author Artem Bilan */ @AutoConfiguration(after = DebeziumEngineBuilderAutoConfiguration.class) @EnableConfigurationProperties(DebeziumSupplierProperties.class) @ConditionalOnBean(DebeziumEngine.Builder.class) public class DebeziumReactiveConsumerConfiguration implements BeanClassLoaderAware { private static final Log LOGGER = LogFactory.getLog(DebeziumReactiveConsumerConfiguration.class); /** * ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL. */ public static final String ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL = "org.springframework.kafka.support.KafkaNull"; private Object kafkaNull = null; @Override public void setBeanClassLoader(ClassLoader classLoader) { try { Class<?> clazz = ClassUtils.forName(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, classLoader); Field field = clazz.getDeclaredField("INSTANCE"); this.kafkaNull = field.get(null); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) { } } /** * Reactive Streams, single subscriber, sink used to push down the change event * signals received from the Debezium Engine. */ private final Sinks.Many<Message<?>> eventSink = Sinks.many().unicast().onBackpressureError(); /** * Debezium Engine is designed to be submitted to an {@link ExecutorService} for * execution by a single thread, and a running connector can be stopped either by * calling {@code stop()} from another thread or by interrupting the running thread * (e.g., as is the case with {@link ExecutorService#shutdownNow()}). */ private final ExecutorService debeziumExecutor = Executors.newSingleThreadExecutor(); @Bean public DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine( Consumer<ChangeEvent<byte[], byte[]>> changeEventConsumer, Builder<ChangeEvent<byte[], byte[]>> debeziumEngineBuilder) { return debeziumEngineBuilder.notifying(changeEventConsumer).build(); } @Bean public Supplier<Flux<Message<?>>> debeziumSupplier(DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine) { return () -> this.eventSink.asFlux() .doOnRequest((r) -> this.debeziumExecutor.execute(debeziumEngine)) .doOnTerminate(this.debeziumExecutor::shutdownNow); } @Bean @ConditionalOnMissingBean
public Consumer<ChangeEvent<byte[], byte[]>> changeEventConsumer(DebeziumProperties engineProperties,
1
2023-11-21 04:03:30+00:00
8k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/hud/BorderRegistry.java
[ { "identifier": "ProviHealthClient", "path": "src/main/java/com/provismet/provihealth/ProviHealthClient.java", "snippet": "public class ProviHealthClient implements ClientModInitializer {\n public static final String MODID = \"provihealth\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"Provi's Health Bars\");\n\n public static Identifier identifier (String path) {\n return Identifier.of(MODID, path);\n }\n\n @Override\n public void onInitializeClient () {\n HudRenderCallback.EVENT.register(new TargetHealthBar());\n\n FabricLoader.getInstance().getEntrypointContainers(MODID, ProviHealthApi.class).forEach(\n entrypoint -> {\n String otherModId = entrypoint.getProvider().getMetadata().getId();\n try {\n entrypoint.getEntrypoint().onInitialize();\n }\n catch (Exception e) {\n LOGGER.error(\"Mod \" + otherModId + \" caused an error during inter-mod initialisation: \", e);\n }\n }\n );\n\n Options.load();\n Particles.register();\n }\n \n}" }, { "identifier": "Options", "path": "src/main/java/com/provismet/provihealth/config/Options.java", "snippet": "public class Options {\n public static final Vector3f WHITE = Vec3d.unpackRgb(0xFFFFFF).toVector3f();\n\n public static int maxHealthBarTicks = 40;\n\n public static List<String> blacklist = Arrays.asList(\"minecraft:armor_stand\");\n public static List<String> blacklistHUD = Arrays.asList(\"minecraft:armor_stand\");\n\n public static VisibilityType bosses = VisibilityType.ALWAYS_HIDE;\n public static VisibilityType hostile = VisibilityType.ALWAYS_SHOW;\n public static VisibilityType players = VisibilityType.HIDE_IF_FULL;\n public static VisibilityType others = VisibilityType.HIDE_IF_FULL;\n\n public static boolean bossesVisibilityOverride = false;\n public static boolean hostileVisibilityOverride = true;\n public static boolean playersVisibilityOverride = true;\n public static boolean othersVisibilityOverride = true;\n\n public static HUDType bossHUD = HUDType.FULL;\n public static HUDType hostileHUD = HUDType.FULL;\n public static HUDType playerHUD = HUDType.FULL;\n public static HUDType otherHUD = HUDType.FULL;\n\n public static float hudGlide = 0.5f;\n public static float worldGlide = 0.5f;\n\n public static boolean showHudIcon = true;\n public static boolean useCustomHudPortraits = true;\n public static int hudOffsetPercent = 0;\n public static HUDPosition hudPosition = HUDPosition.LEFT;\n public static int hudStartColour = 0x00C100;\n public static int hudEndColour = 0xFF0000;\n public static Vector3f unpackedStartHud = Vec3d.unpackRgb(hudStartColour).toVector3f();\n public static Vector3f unpackedEndHud = Vec3d.unpackRgb(hudEndColour).toVector3f();\n public static boolean hudGradient = false;\n\n public static boolean showTextInWorld = true;\n public static float maxRenderDistance = 24f;\n public static float worldHealthBarScale = 1.5f;\n public static int worldStartColour = 0x00C100;\n public static int worldEndColour = 0xFF0000;\n public static Vector3f unpackedStartWorld = Vec3d.unpackRgb(worldStartColour).toVector3f();\n public static Vector3f unpackedEndWorld = Vec3d.unpackRgb(worldEndColour).toVector3f();\n public static boolean worldGradient = false;\n public static boolean overrideLabels = false;\n public static boolean worldShadows = true;\n public static float worldOffsetY = 0f;\n\n public static boolean spawnDamageParticles = true;\n public static boolean spawnHealingParticles = false;\n public static int damageColour = 0xFF0000;\n public static int healingColour = 0x00FF00;\n public static Vector3f unpackedDamage = Vec3d.unpackRgb(damageColour).toVector3f();\n public static Vector3f unpackedHealing = Vec3d.unpackRgb(healingColour).toVector3f();\n public static float particleScale = 0.25f;\n public static boolean particleTextShadow = true;\n public static int damageParticleTextColour = 0xFFFFFF;\n public static int healingParticleTextColour = 0xFFFFFF;\n public static DamageParticleType particleType = DamageParticleType.RISING;\n public static float maxParticleDistance = 16f;\n public static float damageAlpha = 1f;\n public static float healingAlpha = 1f;\n\n public static SeeThroughText seeThroughTextType = SeeThroughText.STANDARD;\n public static boolean compatInWorld = false;\n public static boolean compatInHUD = false;\n\n @SuppressWarnings(\"resource\")\n public static boolean shouldRenderHealthFor (LivingEntity livingEntity) {\n if (blacklist.contains(EntityType.getId(livingEntity.getType()).toString())) return false;\n if (livingEntity.distanceTo(MinecraftClient.getInstance().player) > Options.maxRenderDistance) return false;\n\n Entity target = MinecraftClient.getInstance().targetedEntity;\n if (livingEntity.getType().isIn(ConventionalEntityTypeTags.BOSSES)) {\n if (bossesVisibilityOverride && livingEntity == target) return true;\n return shouldRenderHealthFor(bosses, livingEntity);\n }\n else if (livingEntity instanceof HostileEntity) {\n if (hostileVisibilityOverride && livingEntity == target) return true;\n return shouldRenderHealthFor(hostile, livingEntity);\n }\n else if (livingEntity instanceof PlayerEntity) {\n if (playersVisibilityOverride && livingEntity == target) return true;\n return shouldRenderHealthFor(players, livingEntity);\n }\n else {\n if (othersVisibilityOverride && livingEntity == target) return true;\n return shouldRenderHealthFor(others, livingEntity);\n }\n }\n\n public static HUDType getHUDFor (LivingEntity livingEntity) {\n if (blacklistHUD.contains(EntityType.getId(livingEntity.getType()).toString())) return HUDType.NONE;\n else if (livingEntity.getType().isIn(ConventionalEntityTypeTags.BOSSES)) return bossHUD;\n else if (livingEntity instanceof HostileEntity) return hostileHUD;\n else if (livingEntity instanceof PlayerEntity) return playerHUD;\n else return otherHUD;\n }\n\n public static Vector3f getBarColour (float percentage, Vector3f start, Vector3f end, boolean shouldGradient) {\n if (shouldGradient) {\n Vector3f colour = new Vector3f();\n colour.x = MathHelper.lerp(percentage, end.x, start.x);\n colour.y = MathHelper.lerp(percentage, end.y, start.y);\n colour.z = MathHelper.lerp(percentage, end.z, start.z);\n return colour;\n }\n else return start;\n }\n\n public static void save () {\n JsonHelper json = new JsonHelper();\n String jsonData = json.start()\n .append(\"hudDuration\", maxHealthBarTicks).newLine()\n .append(\"hudIcon\", showHudIcon).newLine()\n .append(\"hudPortraits\", useCustomHudPortraits).newLine()\n .append(\"hudGlide\", hudGlide).newLine()\n .append(\"hudPosition\", hudPosition.name()).newLine()\n .append(\"hudOffsetY\", hudOffsetPercent).newLine()\n .append(\"hudGradient\", hudGradient).newLine()\n .append(\"hudStartColour\", hudStartColour).newLine()\n .append(\"hudEndColour\", hudEndColour).newLine()\n .append(\"replaceLabels\", overrideLabels).newLine()\n .append(\"worldGlide\", worldGlide).newLine()\n .append(\"worldHealthText\", showTextInWorld).newLine()\n .append(\"worldTextShadows\", worldShadows).newLine()\n .append(\"maxRenderDistance\", maxRenderDistance).newLine()\n .append(\"barScale\", worldHealthBarScale).newLine()\n .append(\"worldOffsetY\", worldOffsetY).newLine()\n .append(\"worldGradient\", worldGradient).newLine()\n .append(\"worldStartColour\", worldStartColour).newLine()\n .append(\"worldEndColour\", worldEndColour).newLine()\n .append(\"bossHealth\", bosses.name()).newLine()\n .append(\"bossTarget\", bossesVisibilityOverride).newLine()\n .append(\"hostileHealth\", hostile.name()).newLine()\n .append(\"hostileTarget\", hostileVisibilityOverride).newLine()\n .append(\"playerHealth\", players.name()).newLine()\n .append(\"playerTarget\", playersVisibilityOverride).newLine()\n .append(\"otherHealth\", others.name()).newLine()\n .append(\"otherTarget\", othersVisibilityOverride).newLine()\n .append(\"bossHUD\", bossHUD.name()).newLine()\n .append(\"hostileHUD\", hostileHUD.name()).newLine()\n .append(\"playerHUD\", playerHUD.name()).newLine()\n .append(\"otherHUD\", otherHUD.name()).newLine()\n .append(\"damageParticles\", spawnDamageParticles).newLine()\n .append(\"healingParticles\", spawnHealingParticles).newLine()\n .append(\"damageColour\", damageColour).newLine()\n .append(\"damageAlpha\", damageAlpha).newLine()\n .append(\"healingColour\", healingColour).newLine()\n .append(\"healingAlpha\", healingAlpha).newLine()\n .append(\"particleScale\", particleScale).newLine()\n .append(\"particleTextShadow\", particleTextShadow).newLine()\n .append(\"damageParticleTextColour\", damageParticleTextColour).newLine()\n .append(\"healingParticleTextColour\", healingParticleTextColour).newLine()\n .append(\"particleType\", particleType.name()).newLine()\n .append(\"maxParticleDistance\", maxParticleDistance).newLine()\n .append(\"topLayerTextType\", seeThroughTextType.name()).newLine()\n .append(\"compatWorldBar\", compatInWorld).newLine()\n .createArray(\"healthBlacklist\", blacklist).newLine()\n .createArray(\"hudBlacklist\", blacklistHUD).newLine(false)\n .closeObject()\n .toString();\n\n try {\n FileWriter writer = new FileWriter(\"config/provihealth.json\");\n writer.write(jsonData);\n writer.close();\n }\n catch (IOException e) {\n ProviHealthClient.LOGGER.error(\"Error whilst saving config: \", e);\n }\n }\n\n public static void load () {\n try {\n FileReader reader = new FileReader(\"config/provihealth.json\");\n JsonReader parser = new JsonReader(reader);\n\n parser.beginObject();\n while (parser.hasNext()) {\n final String label = parser.nextName();\n\n switch (label) {\n case \"hudDuration\":\n maxHealthBarTicks = parser.nextInt();\n break;\n \n case \"hudIcon\":\n showHudIcon = parser.nextBoolean();\n break;\n \n case \"hudPortraits\":\n useCustomHudPortraits = parser.nextBoolean();\n break;\n \n case \"hudGlide\":\n hudGlide = (float)parser.nextDouble();\n break;\n \n case \"hudPosition\":\n hudPosition = HUDPosition.valueOf(parser.nextString());\n break;\n\n case \"hudOffsetY\":\n hudOffsetPercent = parser.nextInt();\n break;\n\n case \"hudGradient\":\n hudGradient = parser.nextBoolean();\n break;\n \n case \"hudStartColour\":\n hudStartColour = parser.nextInt();\n unpackedStartHud = Vec3d.unpackRgb(hudStartColour).toVector3f();\n break;\n\n case \"hudEndColour\":\n hudEndColour = parser.nextInt();\n unpackedEndHud = Vec3d.unpackRgb(hudEndColour).toVector3f();\n break;\n\n case \"replaceLabels\":\n overrideLabels = parser.nextBoolean();\n break;\n \n case \"worldGlide\":\n worldGlide = (float)parser.nextDouble();\n break;\n\n case \"worldHealthText\":\n showTextInWorld = parser.nextBoolean();\n break;\n\n case \"worldTextShadows\":\n worldShadows = parser.nextBoolean();\n break;\n \n case \"maxRenderDistance\":\n maxRenderDistance = (float)parser.nextDouble();\n break;\n\n case \"barScale\":\n worldHealthBarScale = (float)parser.nextDouble();\n break;\n\n case \"worldOffsetY\":\n worldOffsetY = (float)parser.nextDouble();\n break;\n\n case \"worldGradient\":\n worldGradient = parser.nextBoolean();\n break;\n\n case \"worldStartColour\":\n worldStartColour = parser.nextInt();\n unpackedStartWorld = Vec3d.unpackRgb(worldStartColour).toVector3f();\n break;\n\n case \"worldEndColour\":\n worldEndColour = parser.nextInt();\n unpackedEndWorld = Vec3d.unpackRgb(worldEndColour).toVector3f();\n break;\n\n case \"bossHealth\":\n bosses = VisibilityType.valueOf(parser.nextString());\n break;\n \n case \"bossTarget\":\n bossesVisibilityOverride = parser.nextBoolean();\n break;\n\n case \"bossHUD\":\n bossHUD = HUDType.valueOf(parser.nextString());\n break;\n \n case \"hostileHealth\":\n hostile = VisibilityType.valueOf(parser.nextString());\n break;\n \n case \"hostileTarget\":\n hostileVisibilityOverride = parser.nextBoolean();\n break;\n \n case \"hostileHUD\":\n hostileHUD = HUDType.valueOf(parser.nextString());\n break;\n \n case \"playerHealth\":\n players = VisibilityType.valueOf(parser.nextString());\n break;\n \n case \"playerTarget\":\n playersVisibilityOverride = parser.nextBoolean();\n break;\n\n case \"playerHUD\":\n playerHUD = HUDType.valueOf(parser.nextString());\n break;\n \n case \"otherHealth\":\n others = VisibilityType.valueOf(parser.nextString());\n break;\n\n case \"otherTarget\":\n othersVisibilityOverride = parser.nextBoolean();\n break;\n\n case \"otherHUD\":\n otherHUD = HUDType.valueOf(parser.nextString());\n break;\n\n case \"damageParticles\":\n spawnDamageParticles = parser.nextBoolean();\n break;\n\n case \"healingParticles\":\n spawnHealingParticles = parser.nextBoolean();\n break;\n\n case \"damageColour\":\n damageColour = parser.nextInt();\n unpackedDamage = Vec3d.unpackRgb(damageColour).toVector3f();\n break;\n\n case \"damageAlpha\":\n damageAlpha = (float)parser.nextDouble();\n break;\n\n case \"healingColour\":\n healingColour = parser.nextInt();\n unpackedHealing = Vec3d.unpackRgb(healingColour).toVector3f();\n break;\n\n case \"healingAlpha\":\n healingAlpha = (float)parser.nextDouble();\n break;\n\n case \"particleScale\":\n particleScale = (float)parser.nextDouble();\n break;\n\n case \"particleTextShadow\":\n particleTextShadow = parser.nextBoolean();\n break;\n\n case \"damageParticleTextColour\":\n damageParticleTextColour = parser.nextInt();\n break;\n\n case \"healingParticleTextColour\":\n healingParticleTextColour = parser.nextInt();\n break;\n\n case \"particleType\":\n particleType = DamageParticleType.valueOf(parser.nextString());\n break;\n\n case \"maxParticleDistance\":\n maxParticleDistance = (float)parser.nextDouble();\n break;\n\n case \"topLayerTextType\":\n seeThroughTextType = SeeThroughText.valueOf(parser.nextString());\n break;\n\n case \"compatWorldBar\":\n compatInWorld = parser.nextBoolean();\n break;\n\n case \"healthBlacklist\":\n ArrayList<String> tempBlacklist = new ArrayList<>();\n parser.beginArray();\n while (parser.hasNext()) {\n tempBlacklist.add(parser.nextString());\n }\n parser.endArray();\n blacklist = tempBlacklist;\n break;\n\n case \"hudBlacklist\":\n ArrayList<String> tempHudBlacklist = new ArrayList<>();\n parser.beginArray();\n while (parser.hasNext()) {\n tempHudBlacklist.add(parser.nextString());\n }\n parser.endArray();\n blacklistHUD = tempHudBlacklist;\n break;\n \n default:\n ProviHealthClient.LOGGER.warn(\"Unknown label \\\"\" + label + \"\\\" found in config.\");\n parser.skipValue();\n break;\n }\n }\n parser.close();\n }\n catch (FileNotFoundException e) {\n ProviHealthClient.LOGGER.info(\"No config found, creating new one.\");\n save();\n }\n catch (IOException e2) {\n ProviHealthClient.LOGGER.error(\"Error whilst parsing config: \", e2);\n }\n }\n\n private static boolean shouldRenderHealthFor (VisibilityType type, LivingEntity livingEntity) {\n switch (type) {\n case ALWAYS_HIDE:\n return false;\n \n case HIDE_IF_FULL:\n if (livingEntity.getHealth() < livingEntity.getMaxHealth()) return true;\n else if (livingEntity.hasVehicle()) {\n Entity vehicle = livingEntity.getVehicle();\n while (vehicle != null) {\n if (vehicle instanceof LivingEntity livingVehicle) {\n if (livingVehicle.getHealth() < livingVehicle.getMaxHealth()) return true;\n }\n vehicle = vehicle.getVehicle();\n }\n }\n return false;\n \n case ALWAYS_SHOW:\n return true;\n \n default:\n return true;\n }\n }\n\n public static enum VisibilityType {\n ALWAYS_HIDE,\n HIDE_IF_FULL,\n ALWAYS_SHOW;\n\n @Override\n public String toString () {\n return \"enum.provihealth.\" + super.toString().toLowerCase();\n }\n }\n\n public static enum HUDType {\n NONE,\n PORTRAIT_ONLY,\n FULL;\n\n @Override\n public String toString () {\n return \"enum.provihealth.\" + super.toString().toLowerCase();\n }\n }\n\n public static enum DamageParticleType {\n RISING,\n GRAVITY,\n STATIC;\n\n @Override\n public String toString () {\n return \"enum.provihealth.\" + super.toString().toLowerCase();\n }\n }\n\n public static enum HUDPosition {\n LEFT(150f),\n RIGHT(210f);\n\n public final float portraitYAW;\n\n private HUDPosition (float portraitYAW) {\n this.portraitYAW = portraitYAW;\n }\n\n @Override\n public String toString () {\n return \"enum.provihealth.\" + super.toString().toLowerCase();\n }\n }\n\n public static enum SeeThroughText {\n STANDARD,\n NONE,\n FULL;\n\n @Override\n public String toString () {\n return \"enum.provihealth.seethroughtext.\" + super.toString().toLowerCase();\n }\n }\n}" } ]
import java.util.HashMap; import org.jetbrains.annotations.Nullable; import com.provismet.provihealth.ProviHealthClient; import com.provismet.provihealth.config.Options; import net.minecraft.entity.EntityGroup; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier;
5,117
package com.provismet.provihealth.hud; public class BorderRegistry { private static final HashMap<EntityGroup, Identifier> groupBorders = new HashMap<>(); private static final HashMap<EntityGroup, ItemStack> groupItems = new HashMap<>(); private static final HashMap<EntityType<?>, Identifier> overrideBorders = new HashMap<>(); private static final HashMap<EntityType<?>, ItemStack> overrideItems = new HashMap<>(); private static final Identifier DEFAULT = ProviHealthClient.identifier("textures/gui/healthbars/default.png"); public static boolean registerBorder (EntityGroup group, @Nullable Identifier border, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null object to the border registry."); return false; } else if (groupBorders.containsKey(group) && !force) { return false; } else { groupBorders.put(group, border); return false; } } public static boolean registerItem (EntityGroup group, @Nullable ItemStack item, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityGroup to the icon registry."); return false; } else if (groupItems.containsKey(group) && !force) { return false; } else { groupItems.put(group, item); return true; } } public static boolean registerBorder (EntityType<?> type, @Nullable Identifier border, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the border registry."); return false; } else if (overrideBorders.containsKey(type) && !force) { return false; } else { overrideBorders.put(type, border); return true; } } public static boolean registerItem (EntityType<?> type, @Nullable ItemStack item, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the icon registry."); return false; } else if (overrideItems.containsKey(type) && !force) { return false; } else { overrideItems.put(type, item); return true; } } public static Identifier getBorder (@Nullable LivingEntity entity) {
package com.provismet.provihealth.hud; public class BorderRegistry { private static final HashMap<EntityGroup, Identifier> groupBorders = new HashMap<>(); private static final HashMap<EntityGroup, ItemStack> groupItems = new HashMap<>(); private static final HashMap<EntityType<?>, Identifier> overrideBorders = new HashMap<>(); private static final HashMap<EntityType<?>, ItemStack> overrideItems = new HashMap<>(); private static final Identifier DEFAULT = ProviHealthClient.identifier("textures/gui/healthbars/default.png"); public static boolean registerBorder (EntityGroup group, @Nullable Identifier border, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null object to the border registry."); return false; } else if (groupBorders.containsKey(group) && !force) { return false; } else { groupBorders.put(group, border); return false; } } public static boolean registerItem (EntityGroup group, @Nullable ItemStack item, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityGroup to the icon registry."); return false; } else if (groupItems.containsKey(group) && !force) { return false; } else { groupItems.put(group, item); return true; } } public static boolean registerBorder (EntityType<?> type, @Nullable Identifier border, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the border registry."); return false; } else if (overrideBorders.containsKey(type) && !force) { return false; } else { overrideBorders.put(type, border); return true; } } public static boolean registerItem (EntityType<?> type, @Nullable ItemStack item, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the icon registry."); return false; } else if (overrideItems.containsKey(type) && !force) { return false; } else { overrideItems.put(type, item); return true; } } public static Identifier getBorder (@Nullable LivingEntity entity) {
if (entity == null || !Options.useCustomHudPortraits) return DEFAULT;
1
2023-11-26 02:46:37+00:00
8k
OysterRiverOverdrive/SwerveTemplate
src/main/java/frc/robot/subsystems/DrivetrainSubsystem.java
[ { "identifier": "DriveConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static class DriveConstants {\n // Controller Ports ---\n // Determined here but assigned in the driver station to determine and organize physical ports\n // the controllers are plug into\n public static final int kDrveControllerPort = 0;\n public static final int kOperControllerPort = 1;\n\n // Driver Controller Joystick ---\n public static final int kDriveX = 1;\n public static final int kDriveY = 0;\n public static final int kDriveRotate = 4;\n public static final double deadzoneDriver = 0.2;\n\n public enum joysticks {\n DRIVER,\n OPERATOR\n }\n\n // Driving Parameters - Note that these are not the maximum capable speeds of\n // the robot, rather the allowed maximum speeds\n\n public static final double kMaxSpeedMetersPerSecond = 4.8;\n public static final double kMaxAngularSpeed = 2 * Math.PI; // radians per second\n\n // Drive Mode Speeds\n // High\n public static final double kSpeedHighDrive = 6;\n public static final double kSpeedHighTurn = kMaxAngularSpeed;\n\n // Medium is Default Speeds\n\n // Slow\n public static final double kSpeedSlowDrive = 4.8;\n public static final double kSpeedSlowTurn = 1.8;\n\n public static final double kDirectionSlewRate = 1.2; // radians per second\n public static final double kMagnitudeSlewRate = 1.8; // percent per second (1 = 100%)\n public static final double kRotationalSlewRate = 2.0; // percent per second (1 = 100%)\n\n // Chassis configuration\n public static final double kTrackWidth = Units.inchesToMeters(26.5);\n // Distance between centers of right and left wheels on robot\n public static final double kWheelBase = Units.inchesToMeters(26.5);\n // Distance between front and back wheels on robot\n public static final SwerveDriveKinematics kDriveKinematics =\n new SwerveDriveKinematics(\n new Translation2d(kWheelBase / 2, kTrackWidth / 2),\n new Translation2d(kWheelBase / 2, -kTrackWidth / 2),\n new Translation2d(-kWheelBase / 2, kTrackWidth / 2),\n new Translation2d(-kWheelBase / 2, -kTrackWidth / 2));\n}" }, { "identifier": "RobotConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static final class RobotConstants {\n // SPARK MAX CAN IDs\n public static final int kFrontRightDrivingCanId = 1;\n public static final int kFrontRightTurningCanId = 2;\n\n public static final int kFrontLeftDrivingCanId = 3;\n public static final int kFrontLeftTurningCanId = 4;\n\n public static final int kRearRightDrivingCanId = 5;\n public static final int kRearRightTurningCanId = 6;\n\n public static final int kRearLeftDrivingCanId = 7;\n public static final int kRearLeftTurningCanId = 8;\n\n // Used to declare Navx as upside down\n public static final boolean kGyroReversed = false;\n\n // Angular offsets of the modules relative to the chassis in radians\n public static final double kFrontLeftChassisAngularOffset = -Math.PI / 2;\n public static final double kFrontRightChassisAngularOffset = 0;\n public static final double kBackLeftChassisAngularOffset = Math.PI;\n public static final double kBackRightChassisAngularOffset = Math.PI / 2;\n}" }, { "identifier": "SwerveModule", "path": "src/main/java/frc/utils/SwerveModule.java", "snippet": "public class SwerveModule {\n private final CANSparkMax m_drivingSparkMax;\n private final CANSparkMax m_turningSparkMax;\n\n private final RelativeEncoder m_drivingEncoder;\n private final AbsoluteEncoder m_turningEncoder;\n\n private final SparkPIDController m_drivingPIDController;\n private final SparkPIDController m_turningPIDController;\n\n private double m_chassisAngularOffset = 0;\n private SwerveModuleState m_desiredState = new SwerveModuleState(0.0, new Rotation2d());\n\n /**\n * Constructs a MAXSwerveModule and configures the driving and turning motor, encoder, and PID\n * controller. This configuration is specific to the REV MAXSwerve Module built with NEOs, SPARKS\n * MAX, and a Through Bore Encoder.\n */\n public SwerveModule(int drivingCANId, int turningCANId, double chassisAngularOffset) {\n // Creates one motor for driving the wheel and one for turning the wheel\n m_drivingSparkMax = new CANSparkMax(drivingCANId, MotorType.kBrushless);\n m_turningSparkMax = new CANSparkMax(turningCANId, MotorType.kBrushless);\n\n // Factory reset, so we get the SPARKS MAX to a known state before configuring\n // them. This is useful in case a SPARK MAX is swapped out.\n m_drivingSparkMax.restoreFactoryDefaults();\n m_turningSparkMax.restoreFactoryDefaults();\n\n // Setup encoders and PID controllers for the driving and turning SPARKS MAX.\n m_drivingEncoder = m_drivingSparkMax.getEncoder();\n m_turningEncoder = m_turningSparkMax.getAbsoluteEncoder(Type.kDutyCycle);\n m_drivingPIDController = m_drivingSparkMax.getPIDController();\n m_turningPIDController = m_turningSparkMax.getPIDController();\n m_drivingPIDController.setFeedbackDevice(m_drivingEncoder);\n m_turningPIDController.setFeedbackDevice(m_turningEncoder);\n\n // Apply position and velocity conversion factors for the driving encoder. The\n // native units for position and velocity are rotations and RPM, respectively,\n // but we want meters and meters per second to use with WPILib's swerve APIs.\n m_drivingEncoder.setPositionConversionFactor(ModuleConstants.kDrivingEncoderPositionFactor);\n m_drivingEncoder.setVelocityConversionFactor(ModuleConstants.kDrivingEncoderVelocityFactor);\n\n // Apply position and velocity conversion factors for the turning encoder. We\n // want these in radians and radians per second to use with WPILib's swerve\n // APIs.\n m_turningEncoder.setPositionConversionFactor(ModuleConstants.kTurningEncoderPositionFactor);\n m_turningEncoder.setVelocityConversionFactor(ModuleConstants.kTurningEncoderVelocityFactor);\n\n // Invert the turning encoder, since the output shaft rotates in the opposite direction of\n // the steering motor in the MAXSwerve Module.\n m_turningEncoder.setInverted(ModuleConstants.kTurningEncoderInverted);\n\n // Enable PID wrap around for the turning motor. This will allow the PID\n // controller to go through 0 to get to the setpoint i.e. going from 350 degrees\n // to 10 degrees will go through 0 rather than the other direction which is a\n // longer route.\n m_turningPIDController.setPositionPIDWrappingEnabled(true);\n m_turningPIDController.setPositionPIDWrappingMinInput(\n ModuleConstants.kTurningEncoderPositionPIDMinInput);\n m_turningPIDController.setPositionPIDWrappingMaxInput(\n ModuleConstants.kTurningEncoderPositionPIDMaxInput);\n\n // Set the PID gains for the driving motor. Note these are example gains, and you\n // may need to tune them for your own robot!\n m_drivingPIDController.setP(ModuleConstants.kDrivingP);\n m_drivingPIDController.setI(ModuleConstants.kDrivingI);\n m_drivingPIDController.setD(ModuleConstants.kDrivingD);\n m_drivingPIDController.setFF(ModuleConstants.kDrivingFF);\n m_drivingPIDController.setOutputRange(\n ModuleConstants.kDrivingMinOutput, ModuleConstants.kDrivingMaxOutput);\n\n // Set the PID gains for the turning motor. Note these are example gains, and you\n // may need to tune them for your own robot!\n m_turningPIDController.setP(ModuleConstants.kTurningP);\n m_turningPIDController.setI(ModuleConstants.kTurningI);\n m_turningPIDController.setD(ModuleConstants.kTurningD);\n m_turningPIDController.setFF(ModuleConstants.kTurningFF);\n m_turningPIDController.setOutputRange(\n ModuleConstants.kTurningMinOutput, ModuleConstants.kTurningMaxOutput);\n\n m_drivingSparkMax.setIdleMode(ModuleConstants.kDrivingMotorIdleMode);\n m_turningSparkMax.setIdleMode(ModuleConstants.kTurningMotorIdleMode);\n m_drivingSparkMax.setSmartCurrentLimit(ModuleConstants.kDrivingMotorCurrentLimit);\n m_turningSparkMax.setSmartCurrentLimit(ModuleConstants.kTurningMotorCurrentLimit);\n\n // Save the SPARK MAX configurations. If a SPARK MAX browns out during\n // operation, it will maintain the above configurations.\n m_drivingSparkMax.burnFlash();\n m_turningSparkMax.burnFlash();\n\n m_chassisAngularOffset = chassisAngularOffset;\n m_desiredState.angle = new Rotation2d(m_turningEncoder.getPosition());\n m_drivingEncoder.setPosition(0);\n }\n\n /**\n * Returns the current state of the module.\n *\n * @return The current state of the module.\n */\n public SwerveModuleState getState() {\n // Apply chassis angular offset to the encoder position to get the position\n // relative to the chassis.\n return new SwerveModuleState(\n m_drivingEncoder.getVelocity(),\n new Rotation2d(m_turningEncoder.getPosition() - m_chassisAngularOffset));\n }\n\n /**\n * Returns the current position of the module.\n *\n * @return The current position of the module.\n */\n public SwerveModulePosition getPosition() {\n // Apply chassis angular offset to the encoder position to get the position\n // relative to the chassis.\n return new SwerveModulePosition(\n m_drivingEncoder.getPosition(),\n new Rotation2d(m_turningEncoder.getPosition() - m_chassisAngularOffset));\n }\n\n /**\n * Sets the desired state for the module.\n *\n * @param desiredState Desired state with speed and angle.\n */\n public void setDesiredState(SwerveModuleState desiredState) {\n // Apply chassis angular offset to the desired state.\n SwerveModuleState correctedDesiredState = new SwerveModuleState();\n correctedDesiredState.speedMetersPerSecond = desiredState.speedMetersPerSecond;\n correctedDesiredState.angle =\n desiredState.angle.plus(Rotation2d.fromRadians(m_chassisAngularOffset));\n\n // Optimize the reference state to avoid spinning further than 90 degrees.\n SwerveModuleState optimizedDesiredState =\n SwerveModuleState.optimize(\n correctedDesiredState, new Rotation2d(m_turningEncoder.getPosition()));\n\n // Command driving and turning SPARKS MAX towards their respective setpoints.\n m_drivingPIDController.setReference(\n optimizedDesiredState.speedMetersPerSecond, CANSparkMax.ControlType.kVelocity);\n m_turningPIDController.setReference(\n optimizedDesiredState.angle.getRadians(), CANSparkMax.ControlType.kPosition);\n\n m_desiredState = desiredState;\n }\n\n /** Zeroes all the SwerveModule encoders. */\n public void resetEncoders() {\n m_drivingEncoder.setPosition(0);\n }\n}" }, { "identifier": "SwerveUtils", "path": "src/main/java/frc/utils/SwerveUtils.java", "snippet": "public class SwerveUtils {\n\n /**\n * Steps a value towards a target with a specified step size.\n *\n * @param _current The current or starting value. Can be positive or negative.\n * @param _target The target value the algorithm will step towards. Can be positive or negative.\n * @param _stepsize The maximum step size that can be taken.\n * @return The new value for {@code _current} after performing the specified step towards the\n * specified target.\n */\n public static double StepTowards(double _current, double _target, double _stepsize) {\n if (Math.abs(_current - _target) <= _stepsize) {\n return _target;\n } else if (_target < _current) {\n return _current - _stepsize;\n } else {\n return _current + _stepsize;\n }\n }\n\n /**\n * Steps a value (angle) towards a target (angle) taking the shortest path with a specified step\n * size.\n *\n * @param _current The current or starting angle (in radians). Can lie outside the 0 to 2*PI\n * range.\n * @param _target The target angle (in radians) the algorithm will step towards. Can lie outside\n * the 0 to 2*PI range.\n * @param _stepsize The maximum step size that can be taken (in radians).\n * @return The new angle (in radians) for {@code _current} after performing the specified step\n * towards the specified target. This value will always lie in the range 0 to 2*PI\n * (exclusive).\n */\n public static double StepTowardsCircular(double _current, double _target, double _stepsize) {\n _current = WrapAngle(_current);\n _target = WrapAngle(_target);\n\n double stepDirection = Math.signum(_target - _current);\n double difference = Math.abs(_current - _target);\n\n if (difference <= _stepsize) {\n return _target;\n } else if (difference > Math.PI) { // does the system need to wrap over eventually?\n // handle the special case where you can reach the target in one step while also wrapping\n if (_current + 2 * Math.PI - _target < _stepsize\n || _target + 2 * Math.PI - _current < _stepsize) {\n return _target;\n } else {\n return WrapAngle(\n _current - stepDirection * _stepsize); // this will handle wrapping gracefully\n }\n\n } else {\n return _current + stepDirection * _stepsize;\n }\n }\n\n /**\n * Finds the (unsigned) minimum difference between two angles including calculating across 0.\n *\n * @param _angleA An angle (in radians).\n * @param _angleB An angle (in radians).\n * @return The (unsigned) minimum difference between the two angles (in radians).\n */\n public static double AngleDifference(double _angleA, double _angleB) {\n double difference = Math.abs(_angleA - _angleB);\n return difference > Math.PI ? (2 * Math.PI) - difference : difference;\n }\n\n /**\n * Wraps an angle until it lies within the range from 0 to 2*PI (exclusive).\n *\n * @param _angle The angle (in radians) to wrap. Can be positive or negative and can lie multiple\n * wraps outside the output range.\n * @return An angle (in radians) from 0 and 2*PI (exclusive).\n */\n public static double WrapAngle(double _angle) {\n double twoPi = 2 * Math.PI;\n\n if (_angle\n == twoPi) { // Handle this case separately to avoid floating point errors with the floor\n // after the division in the case below\n return 0.0;\n } else if (_angle > twoPi) {\n return _angle - twoPi * Math.floor(_angle / twoPi);\n } else if (_angle < 0.0) {\n return _angle + twoPi * (Math.floor((-_angle) / twoPi) + 1);\n } else {\n return _angle;\n }\n }\n}" } ]
import edu.wpi.first.math.filter.SlewRateLimiter; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.util.WPIUtilJNI; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants.DriveConstants; import frc.robot.Constants.RobotConstants; import frc.utils.SwerveModule; import frc.utils.SwerveUtils;
5,076
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class DrivetrainSubsystem extends SubsystemBase { // Create SwerveModules private final SwerveModule m_frontLeft = new SwerveModule( RobotConstants.kFrontLeftDrivingCanId, RobotConstants.kFrontLeftTurningCanId, RobotConstants.kFrontLeftChassisAngularOffset); private final SwerveModule m_frontRight = new SwerveModule( RobotConstants.kFrontRightDrivingCanId, RobotConstants.kFrontRightTurningCanId, RobotConstants.kFrontRightChassisAngularOffset); private final SwerveModule m_rearLeft = new SwerveModule( RobotConstants.kRearLeftDrivingCanId, RobotConstants.kRearLeftTurningCanId, RobotConstants.kBackLeftChassisAngularOffset); private final SwerveModule m_rearRight = new SwerveModule( RobotConstants.kRearRightDrivingCanId, RobotConstants.kRearRightTurningCanId, RobotConstants.kBackRightChassisAngularOffset); // The gyro sensor // private AHRS m_gyro = new AHRS(SerialPort.Port.kUSB1); // Slew rate filter variables for controlling lateral acceleration private double m_currentRotation = 0.0; private double m_currentTranslationDir = 0.0; private double m_currentTranslationMag = 0.0; // Max Speeds private double maxSpeedDrive = DriveConstants.kMaxSpeedMetersPerSecond; private double maxSpeedTurn = DriveConstants.kMaxAngularSpeed; // Drop Down private final SendableChooser<String> m_drivemode = new SendableChooser<>(); private final String khigh = "High Speeds"; private final String kmedium = "Medium Speeds"; private final String kslow = "Low Speed"; private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DriveConstants.kMagnitudeSlewRate); private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DriveConstants.kRotationalSlewRate); private double m_prevTime = WPIUtilJNI.now() * 1e-6; // Odometry class for tracking robot pose // SwerveDriveOdometry m_odometry = // new SwerveDriveOdometry( // DriveConstants.kDriveKinematics, // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }); /** Creates a new DriveSubsystem. */ public DrivetrainSubsystem() { m_drivemode.setDefaultOption("Medium Speed", kmedium); m_drivemode.addOption("Slow Speeds (Demo Mode)", kslow); m_drivemode.addOption("High Speeds", khigh); SmartDashboard.putData("Driver Config", m_drivemode); } /** * Returns the currently-estimated pose of the robot. * * @return The pose. */ // public Pose2d getPose() { // return m_odometry.getPoseMeters(); // } /** * Resets the odometry to the specified pose. * * @param pose The pose to which to set the odometry. */ // public void resetOdometry(Pose2d pose) { // m_odometry.resetPosition( // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }, // pose); // } /** * Method to drive the robot using joystick info. * * @param xSpeed Speed of the robot in the x direction (forward). * @param ySpeed Speed of the robot in the y direction (sideways). * @param rot Angular rate of the robot. * @param fieldRelative Whether the provided x and y speeds are relative to the field. * @param rateLimit Whether to enable rate limiting for smoother control. */ public void drive( double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) { double xSpeedCommanded; double ySpeedCommanded; if (rateLimit) { // Convert XY to polar for rate limiting double inputTranslationDir = Math.atan2(ySpeed, xSpeed); double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2)); // Calculate the direction slew rate based on an estimate of the lateral acceleration double directionSlewRate; if (m_currentTranslationMag != 0.0) { directionSlewRate = Math.abs(DriveConstants.kDirectionSlewRate / m_currentTranslationMag); } else { directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous } double currentTime = WPIUtilJNI.now() * 1e-6; double elapsedTime = currentTime - m_prevTime;
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class DrivetrainSubsystem extends SubsystemBase { // Create SwerveModules private final SwerveModule m_frontLeft = new SwerveModule( RobotConstants.kFrontLeftDrivingCanId, RobotConstants.kFrontLeftTurningCanId, RobotConstants.kFrontLeftChassisAngularOffset); private final SwerveModule m_frontRight = new SwerveModule( RobotConstants.kFrontRightDrivingCanId, RobotConstants.kFrontRightTurningCanId, RobotConstants.kFrontRightChassisAngularOffset); private final SwerveModule m_rearLeft = new SwerveModule( RobotConstants.kRearLeftDrivingCanId, RobotConstants.kRearLeftTurningCanId, RobotConstants.kBackLeftChassisAngularOffset); private final SwerveModule m_rearRight = new SwerveModule( RobotConstants.kRearRightDrivingCanId, RobotConstants.kRearRightTurningCanId, RobotConstants.kBackRightChassisAngularOffset); // The gyro sensor // private AHRS m_gyro = new AHRS(SerialPort.Port.kUSB1); // Slew rate filter variables for controlling lateral acceleration private double m_currentRotation = 0.0; private double m_currentTranslationDir = 0.0; private double m_currentTranslationMag = 0.0; // Max Speeds private double maxSpeedDrive = DriveConstants.kMaxSpeedMetersPerSecond; private double maxSpeedTurn = DriveConstants.kMaxAngularSpeed; // Drop Down private final SendableChooser<String> m_drivemode = new SendableChooser<>(); private final String khigh = "High Speeds"; private final String kmedium = "Medium Speeds"; private final String kslow = "Low Speed"; private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DriveConstants.kMagnitudeSlewRate); private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DriveConstants.kRotationalSlewRate); private double m_prevTime = WPIUtilJNI.now() * 1e-6; // Odometry class for tracking robot pose // SwerveDriveOdometry m_odometry = // new SwerveDriveOdometry( // DriveConstants.kDriveKinematics, // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }); /** Creates a new DriveSubsystem. */ public DrivetrainSubsystem() { m_drivemode.setDefaultOption("Medium Speed", kmedium); m_drivemode.addOption("Slow Speeds (Demo Mode)", kslow); m_drivemode.addOption("High Speeds", khigh); SmartDashboard.putData("Driver Config", m_drivemode); } /** * Returns the currently-estimated pose of the robot. * * @return The pose. */ // public Pose2d getPose() { // return m_odometry.getPoseMeters(); // } /** * Resets the odometry to the specified pose. * * @param pose The pose to which to set the odometry. */ // public void resetOdometry(Pose2d pose) { // m_odometry.resetPosition( // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }, // pose); // } /** * Method to drive the robot using joystick info. * * @param xSpeed Speed of the robot in the x direction (forward). * @param ySpeed Speed of the robot in the y direction (sideways). * @param rot Angular rate of the robot. * @param fieldRelative Whether the provided x and y speeds are relative to the field. * @param rateLimit Whether to enable rate limiting for smoother control. */ public void drive( double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) { double xSpeedCommanded; double ySpeedCommanded; if (rateLimit) { // Convert XY to polar for rate limiting double inputTranslationDir = Math.atan2(ySpeed, xSpeed); double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2)); // Calculate the direction slew rate based on an estimate of the lateral acceleration double directionSlewRate; if (m_currentTranslationMag != 0.0) { directionSlewRate = Math.abs(DriveConstants.kDirectionSlewRate / m_currentTranslationMag); } else { directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous } double currentTime = WPIUtilJNI.now() * 1e-6; double elapsedTime = currentTime - m_prevTime;
double angleDif = SwerveUtils.AngleDifference(inputTranslationDir, m_currentTranslationDir);
3
2023-11-19 18:40:10+00:00
8k
gunnarmorling/1brc
src/main/java/dev/morling/onebrc/CreateMeasurements2.java
[ { "identifier": "CheaperCharBuffer", "path": "src/main/java/org/rschwietzke/CheaperCharBuffer.java", "snippet": "public class CheaperCharBuffer implements CharSequence {\n // our data, can grow - that is not safe and has be altered from the original code\n // to allow speed\n public char[] data_;\n\n // the current size of the string data\n public int length_;\n\n // the current size of the string data\n private final int growBy_;\n\n // how much do we grow if needed, half a cache line\n public static final int CAPACITY_GROWTH = 64 / 2;\n\n // what is our start size?\n // a cache line is 64 byte mostly, the overhead is mostly 24 bytes\n // a char is two bytes, let's use one cache lines\n public static final int INITIAL_CAPACITY = (64 - 24) / 2;\n\n // static empty version; DON'T MODIFY IT\n public static final CheaperCharBuffer EMPTY = new CheaperCharBuffer(0);\n\n // the � character\n private static final char REPLACEMENT_CHARACTER = '\\uFFFD';\n\n /**\n * Constructs an XMLCharBuffer with a default size.\n */\n public CheaperCharBuffer() {\n this.data_ = new char[INITIAL_CAPACITY];\n this.length_ = 0;\n this.growBy_ = CAPACITY_GROWTH;\n }\n\n /**\n * Constructs an XMLCharBuffer with a desired size.\n *\n * @param startSize the size of the buffer to start with\n */\n public CheaperCharBuffer(final int startSize) {\n this(startSize, CAPACITY_GROWTH);\n }\n\n /**\n * Constructs an XMLCharBuffer with a desired size.\n *\n * @param startSize the size of the buffer to start with\n * @param growBy by how much do we want to grow when needed\n */\n public CheaperCharBuffer(final int startSize, final int growBy) {\n this.data_ = new char[startSize];\n this.length_ = 0;\n this.growBy_ = Math.max(1, growBy);\n }\n\n /**\n * Constructs an XMLCharBuffer from another buffer. Copies the data\n * over. The new buffer capacity matches the length of the source.\n *\n * @param src the source buffer to copy from\n */\n public CheaperCharBuffer(final CheaperCharBuffer src) {\n this(src, 0);\n }\n\n /**\n * Constructs an XMLCharBuffer from another buffer. Copies the data\n * over. You can add more capacity on top of the source length. If\n * you specify 0, the capacity will match the src length.\n *\n * @param src the source buffer to copy from\n * @param addCapacity how much capacity to add to origin length\n */\n public CheaperCharBuffer(final CheaperCharBuffer src, final int addCapacity) {\n this.data_ = Arrays.copyOf(src.data_, src.length_ + Math.max(0, addCapacity));\n this.length_ = src.length();\n this.growBy_ = Math.max(1, CAPACITY_GROWTH);\n }\n\n /**\n * Constructs an XMLCharBuffer from a string. To avoid\n * too much allocation, we just take the string array as is and\n * don't allocate extra space in the first place.\n *\n * @param src the string to copy from\n */\n public CheaperCharBuffer(final String src) {\n this.data_ = src.toCharArray();\n this.length_ = src.length();\n this.growBy_ = CAPACITY_GROWTH;\n }\n\n /**\n * Constructs an XMLString structure preset with the specified values.\n * There will not be any room to grow, if you need that, construct an\n * empty one and append.\n *\n * <p>There are not range checks performed. Make sure your data is correct.\n *\n * @param ch The character array, must not be null\n * @param offset The offset into the character array.\n * @param length The length of characters from the offset.\n */\n public CheaperCharBuffer(final char[] ch, final int offset, final int length) {\n // just as big as we need it\n this(length);\n append(ch, offset, length);\n }\n\n /**\n * Check capacity and grow if needed automatically\n *\n * @param minimumCapacity how much space do we need at least\n */\n private void ensureCapacity(final int minimumCapacity) {\n if (minimumCapacity > this.data_.length) {\n final int newSize = Math.max(minimumCapacity + this.growBy_, (this.data_.length << 1) + 2);\n this.data_ = Arrays.copyOf(this.data_, newSize);\n }\n }\n\n /**\n * Returns the current max capacity without growth. Does not\n * indicate how much capacity is already in use. Use {@link #length()}\n * for that.\n *\n * @return the current capacity, not taken any usage into account\n */\n public int capacity() {\n return this.data_.length;\n }\n\n /**\n * Appends a single character to the buffer.\n *\n * @param c the character to append\n * @return this instance\n */\n public CheaperCharBuffer append(final char c) {\n final int oldLength = this.length_++;\n\n // ensureCapacity is not inlined by the compiler, so put that here for the most\n // called method of all appends. Duplicate code, but for a reason.\n if (oldLength == this.data_.length) {\n final int newSize = Math.max(oldLength + this.growBy_, (this.data_.length << 1) + 2);\n this.data_ = Arrays.copyOf(this.data_, newSize);\n }\n\n this.data_[oldLength] = c;\n\n return this;\n }\n\n /**\n * Append a string to this buffer without copying the string first.\n *\n * @param src the string to append\n * @return this instance\n */\n public CheaperCharBuffer append(final String src) {\n final int start = this.length_;\n this.length_ = this.length_ + src.length();\n ensureCapacity(this.length_);\n\n // copy char by char because we don't get a copy for free\n // from a string yet, this might change when immutable arrays\n // make it into Java, but that will not be very soon\n for (int i = 0; i < src.length(); i++) {\n this.data_[start + i] = src.charAt(i);\n }\n\n return this;\n }\n\n /**\n * Add another buffer to this one.\n *\n * @param src the buffer to append\n * @return this instance\n */\n public CheaperCharBuffer append(final CheaperCharBuffer src) {\n final int start = this.length_;\n this.length_ = this.length_ + src.length();\n ensureCapacity(this.length_);\n\n System.arraycopy(src.data_, 0, this.data_, start, src.length_);\n\n return this;\n }\n\n /**\n * Add data from a char array to this buffer with the ability to specify\n * a range to copy from\n *\n * @param src the source char array\n * @param offset the pos to start to copy from\n * @param length the length of the data to copy\n *\n * @return this instance\n */\n public CheaperCharBuffer append(final char[] src, final int offset, final int length) {\n final int start = this.length_;\n this.length_ = start + length;\n\n ensureCapacity(this.length_);\n\n System.arraycopy(src, offset, this.data_, start, length);\n\n return this;\n }\n\n /**\n * Returns the current length\n *\n * @return the length of the charbuffer data\n */\n public int length() {\n return length_;\n }\n\n /**\n * Tell us how much the capacity grows if needed\n *\n * @return the value that determines how much we grow the backing\n * array in case we have to\n */\n public int getGrowBy() {\n return this.growBy_;\n }\n\n /**\n * Resets the buffer to 0 length. It won't resize it to avoid memory\n * churn.\n *\n * @return this instance for fluid programming\n */\n public CheaperCharBuffer clear() {\n this.length_ = 0;\n\n return this;\n }\n\n /**\n * Resets the buffer to 0 length and sets the new data. This\n * is a little cheaper than clear().append(c) depending on\n * the where and the inlining decisions.\n *\n * @param c the char to set\n * @return this instance for fluid programming\n */\n public CheaperCharBuffer clearAndAppend(final char c) {\n this.length_ = 0;\n\n if (this.data_.length > 0) {\n this.data_[this.length_] = c;\n this.length_++;\n }\n else {\n // the rare case when we don't have any buffer at hand\n append(c);\n }\n\n return this;\n }\n\n /**\n * Does this buffer end with this string? If we check for\n * the empty string, we get true. If we would support JDK 11, we could\n * use Arrays.mismatch and be way faster.\n *\n * @param s the string to check the end against\n * @return true of the end matches the buffer, false otherwise\n */\n public boolean endsWith(final String s) {\n // length does not match, cannot be the end\n if (this.length_ < s.length()) {\n return false;\n }\n\n // check the string by each char, avoids a copy of the string\n final int start = this.length_ - s.length();\n\n // change this to Arrays.mismatch when going JDK 11 or higher\n for (int i = 0; i < s.length(); i++) {\n if (this.data_[i + start] != s.charAt(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Reduces the buffer to the content between start and end marker when\n * only whitespaces are found before the startMarker as well as after the end marker.\n * If both strings overlap due to identical characters such as \"foo\" and \"oof\"\n * and the buffer is \" foof \", we don't do anything.\n *\n * <p>If a marker is empty, it behaves like {@link java.lang.String#trim()} on that side.\n *\n * @param startMarker the start string to find, must not be null\n * @param endMarker the end string to find, must not be null\n * @return this instance\n *\n * @deprecated Use the new method {@link #trimToContent(String, String)} instead.\n */\n public CheaperCharBuffer reduceToContent(final String startMarker, final String endMarker) {\n return trimToContent(startMarker, endMarker);\n }\n\n /**\n * Reduces the buffer to the content between start and end marker when\n * only whitespaces are found before the startMarker as well as after the end marker.\n * If both strings overlap due to identical characters such as \"foo\" and \"oof\"\n * and the buffer is \" foof \", we don't do anything.\n *\n * <p>If a marker is empty, it behaves like {@link java.lang.String#trim()} on that side.\n *\n * @param startMarker the start string to find, must not be null\n * @param endMarker the end string to find, must not be null\n * @return this instance\n */\n public CheaperCharBuffer trimToContent(final String startMarker, final String endMarker) {\n // if both are longer or same length than content, don't do anything\n final int markerLength = startMarker.length() + endMarker.length();\n if (markerLength >= this.length_) {\n return this;\n }\n\n // run over starting whitespaces\n int sPos = 0;\n for (; sPos < this.length_ - markerLength; sPos++) {\n if (!Character.isWhitespace(this.data_[sPos])) {\n break;\n }\n }\n\n // run over ending whitespaces\n int ePos = this.length_ - 1;\n for (; ePos > sPos - markerLength; ePos--) {\n if (!Character.isWhitespace(this.data_[ePos])) {\n break;\n }\n }\n\n // if we have less content than marker length, give up\n // this also helps when markers overlap such as\n // <!-- and --> and the string is \" <!---> \"\n if (ePos - sPos + 1 < markerLength) {\n return this;\n }\n\n // check the start\n for (int i = 0; i < startMarker.length(); i++) {\n if (startMarker.charAt(i) != this.data_[i + sPos]) {\n // no start match, stop and don't do anything\n return this;\n }\n }\n\n // check the end, ePos is when the first good char\n // occurred\n final int endStartCheckPos = ePos - endMarker.length() + 1;\n for (int i = 0; i < endMarker.length(); i++) {\n if (endMarker.charAt(i) != this.data_[endStartCheckPos + i]) {\n // no start match, stop and don't do anything\n return this;\n }\n }\n\n // shift left and cut length\n final int newLength = ePos - sPos + 1 - markerLength;\n System.arraycopy(this.data_,\n sPos + startMarker.length(),\n this.data_,\n 0, newLength);\n this.length_ = newLength;\n\n return this;\n }\n\n /**\n * Check if we have only whitespaces\n *\n * @return true if we have only whitespace, false otherwise\n */\n public boolean isWhitespace() {\n for (int i = 0; i < this.length_; i++) {\n if (!Character.isWhitespace(this.data_[i])) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Trims the string similar to {@link java.lang.String#trim()}\n *\n * @return a string with removed whitespace at the beginning and the end\n */\n public CheaperCharBuffer trim() {\n // clean the end first, because it is cheap\n return trimTrailing().trimLeading();\n }\n\n /**\n * Removes all whitespace before the first non-whitespace char.\n * If all are whitespaces, we get an empty buffer\n *\n * @return this instance\n */\n public CheaperCharBuffer trimLeading() {\n // run over starting whitespace\n int sPos = 0;\n for (; sPos < this.length_; sPos++) {\n if (!Character.isWhitespace(this.data_[sPos])) {\n break;\n }\n }\n\n if (sPos == 0) {\n // nothing to do\n return this;\n }\n else if (sPos == this.length_) {\n // only whitespace\n this.length_ = 0;\n return this;\n }\n\n // shift left\n final int newLength = this.length_ - sPos;\n System.arraycopy(this.data_,\n sPos,\n this.data_,\n 0, newLength);\n this.length_ = newLength;\n\n return this;\n }\n\n /**\n * Removes all whitespace at the end.\n * If all are whitespace, we get an empty buffer\n *\n * @return this instance\n *\n * @deprecated Use {@link #trimTrailing()} instead.\n */\n public CheaperCharBuffer trimWhitespaceAtEnd() {\n return trimTrailing();\n }\n\n /**\n * Removes all whitespace at the end.\n * If all are whitespace, we get an empty buffer\n *\n * @return this instance\n */\n public CheaperCharBuffer trimTrailing() {\n // run over ending whitespaces\n int ePos = this.length_ - 1;\n for (; ePos >= 0; ePos--) {\n if (!Character.isWhitespace(this.data_[ePos])) {\n break;\n }\n }\n\n this.length_ = ePos + 1;\n\n return this;\n }\n\n /**\n * Shortens the buffer by that many positions. If the count is\n * larger than the length, we get just an empty buffer. If you pass in negative\n * values, we are failing, likely often silently. It is all about performance and\n * not a general all-purpose API.\n *\n * @param count a positive number, no runtime checks, if count is larger than\n * length, we get length = 0\n * @return this instance\n */\n public CheaperCharBuffer shortenBy(final int count) {\n final int newLength = this.length_ - count;\n this.length_ = newLength < 0 ? 0 : newLength;\n\n return this;\n }\n\n /**\n * Get the characters as char array, this will be a copy!\n *\n * @return a copy of the underlying char darta\n */\n public char[] getChars() {\n return Arrays.copyOf(this.data_, this.length_);\n }\n\n /**\n * Returns a string representation of this buffer. This will be a copy\n * operation. If the buffer is emoty, we get a constant empty String back\n * to avoid any overhead.\n *\n * @return a string of the content of this buffer\n */\n @Override\n public String toString() {\n if (this.length_ > 0) {\n return new String(this.data_, 0, this.length_);\n }\n else {\n return \"\";\n }\n }\n\n /**\n * Returns the char a the given position. Will complain if\n * we try to read outside the range. We do a range check here\n * because we might not notice when we are within the buffer\n * but outside the current length.\n *\n * @param index the position to read from\n * @return the char at the position\n * @throws IndexOutOfBoundsException\n * in case one tries to read outside of valid buffer range\n */\n @Override\n public char charAt(final int index) {\n if (index > this.length_ - 1 || index < 0) {\n throw new IndexOutOfBoundsException(\n \"Tried to read outside of the valid buffer data\");\n }\n\n return this.data_[index];\n }\n\n /**\n * Returns the char at the given position. No checks are\n * performed. It is up to the caller to make sure we\n * read correctly. Reading outside of the array will\n * cause an {@link IndexOutOfBoundsException} but using an\n * incorrect position in the array (such as beyond length)\n * might stay unnoticed! This is a performance method,\n * use at your own risk.\n *\n * @param index the position to read from\n * @return the char at the position\n */\n public char unsafeCharAt(final int index) {\n return this.data_[index];\n }\n\n /**\n * Returns a content copy of this buffer\n *\n * @return a copy of this buffer, the capacity might differ\n */\n @Override\n public CheaperCharBuffer clone() {\n return new CheaperCharBuffer(this);\n }\n\n /**\n * Returns a <code>CharSequence</code> that is a subsequence of this sequence.\n * The subsequence starts with the <code>char</code> value at the specified index and\n * ends with the <code>char</code> value at index <tt>end - 1</tt>. The length\n * (in <code>char</code>s) of the\n * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>\n * then an empty sequence is returned.\n *\n * @param start the start index, inclusive\n * @param end the end index, exclusive\n *\n * @return the specified subsequence\n *\n * @throws IndexOutOfBoundsException\n * if <tt>start</tt> or <tt>end</tt> are negative,\n * if <tt>end</tt> is greater than <tt>length()</tt>,\n * or if <tt>start</tt> is greater than <tt>end</tt>\n *\n * @return a charsequence of this buffer\n */\n @Override\n public CharSequence subSequence(final int start, final int end) {\n if (start < 0) {\n throw new StringIndexOutOfBoundsException(start);\n }\n if (end > this.length_) {\n throw new StringIndexOutOfBoundsException(end);\n }\n\n final int l = end - start;\n if (l < 0) {\n throw new StringIndexOutOfBoundsException(l);\n }\n\n return new String(this.data_, start, l);\n }\n\n /**\n * Two buffers are identical when the length and\n * the content of the backing array (only for the\n * data in view) are identical.\n *\n * @param o the object to compare with\n * @return true if length and array content match, false otherwise\n */\n @Override\n public boolean equals(final Object o) {\n if (o instanceof CharSequence) {\n final CharSequence ob = (CharSequence) o;\n\n if (ob.length() != this.length_) {\n return false;\n }\n\n // ok, in JDK 11 or up, we could use an\n // Arrays.mismatch, but we cannot do that\n // due to JDK 8 compatibility\n for (int i = 0; i < this.length_; i++) {\n if (ob.charAt(i) != this.data_[i]) {\n return false;\n }\n }\n\n // length and content match, be happy\n return true;\n }\n\n return false;\n }\n\n /**\n * We don't cache the hashcode because we mutate often. Don't use this in\n * hashmaps as key. But you can use that to look up in a hashmap against\n * a string using the CharSequence interface.\n *\n * @return the hashcode, similar to what a normal string would deliver\n */\n @Override\n public int hashCode() {\n int h = 0;\n\n for (int i = 0; i < this.length_; i++) {\n h = ((h << 5) - h) + this.data_[i];\n }\n\n return h;\n }\n\n /**\n * Append a character to an XMLCharBuffer. The character is an int value, and\n * can either be a single UTF-16 character or a supplementary character\n * represented by two UTF-16 code points.\n *\n * @param value The character value.\n * @return this instance for fluid programming\n *\n * @throws IllegalArgumentException if the specified\n * {@code codePoint} is not a valid Unicode code point.\n */\n public CheaperCharBuffer appendCodePoint(final int value) {\n if (value <= Character.MAX_VALUE) {\n return this.append((char) value);\n }\n else {\n try {\n final char[] chars = Character.toChars(value);\n return this.append(chars, 0, chars.length);\n }\n catch (final IllegalArgumentException e) {\n // when value is not valid as UTF-16\n this.append(REPLACEMENT_CHARACTER);\n throw e;\n }\n }\n }\n}" }, { "identifier": "FastRandom", "path": "src/main/java/org/rschwietzke/FastRandom.java", "snippet": "public class FastRandom {\n private long seed;\n\n public FastRandom() {\n this.seed = System.currentTimeMillis();\n }\n\n public FastRandom(long seed) {\n this.seed = seed;\n }\n\n protected int next(int nbits) {\n // N.B. Not thread-safe!\n long x = this.seed;\n x ^= (x << 21);\n x ^= (x >>> 35);\n x ^= (x << 4);\n this.seed = x;\n\n x &= ((1L << nbits) - 1);\n\n return (int) x;\n }\n\n /**\n * Borrowed from the JDK\n *\n * @param bound\n * @return\n */\n public int nextInt(int bound) {\n int r = next(31);\n int m = bound - 1;\n if ((bound & m) == 0) // i.e., bound is a power of 2\n r = (int) ((bound * (long) r) >> 31);\n else {\n for (int u = r; u - (r = u % bound) + m < 0; u = next(31))\n ;\n }\n return r;\n }\n\n /**\n * Borrowed from the JDK\n * @return\n */\n public int nextInt() {\n return next(32);\n }\n}" } ]
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.rschwietzke.CheaperCharBuffer; import org.rschwietzke.FastRandom;
6,554
/* * Copyright 2023 The original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.morling.onebrc; /** * Faster version with some data faking instead of a real Gaussian distribution * Good enough for our purppose I guess. */ public class CreateMeasurements2 { private static final String FILE = "./measurements2.txt"; static class WeatherStation { final static char[] NUMBERS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; final String id; final int meanTemperature; final char[] firstPart;
/* * Copyright 2023 The original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.morling.onebrc; /** * Faster version with some data faking instead of a real Gaussian distribution * Good enough for our purppose I guess. */ public class CreateMeasurements2 { private static final String FILE = "./measurements2.txt"; static class WeatherStation { final static char[] NUMBERS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; final String id; final int meanTemperature; final char[] firstPart;
final FastRandom r = new FastRandom(ThreadLocalRandom.current().nextLong());
1
2023-12-28 09:13:24+00:00
8k
EnigmaGuest/fnk-server
service-common/service-common-db/src/main/java/fun/isite/service/common/db/impl/BaseService.java
[ { "identifier": "LogicException", "path": "service-common/service-common-bean/src/main/java/fun/isite/service/common/bean/exception/LogicException.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class LogicException extends RuntimeException{\n private String message;\n\n private IResponseCode code;\n\n public LogicException(String message) {\n this.message = message;\n }\n\n public LogicException(IResponseCode code) {\n this.code = code;\n }\n\n public LogicException(String message, IResponseCode code) {\n this.message = message;\n this.code = code;\n }\n}" }, { "identifier": "SplitPageDTO", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/dto/SplitPageDTO.java", "snippet": "@Data\n@Schema(name = \"SplitPageDTO\", description = \"分页查询条件\")\npublic class SplitPageDTO implements Serializable {\n /**\n * 当前页码\n */\n @Schema(name = \"page\", description = \"当前页码\")\n private int page = 1;\n\n /**\n * 每页数量大小\n */\n @Schema(name = \"pageSize\", description = \"每页数量大小\")\n private int pageSize = 10;\n\n /**\n * 正序查询\n */\n @Schema(name = \"asc\", description = \"正序查询\")\n private boolean asc = false;\n\n /**\n * 查询条件-ID\n */\n @Schema(name = \"id\", description = \"查询条件-ID\")\n private Long id;\n\n /**\n * 查询条件-创建时间\n */\n @Schema(name = \"createTime\", description = \"查询条件-创建时间\")\n private String createTime;\n\n /**\n * 查询条件-更新时间\n */\n @Schema(name = \"updateTime\", description = \"查询条件-更新时间\")\n private String updateTime;\n}" }, { "identifier": "BaseEntity", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/entity/BaseEntity.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic abstract class BaseEntity<T extends Model<T>> extends Model<T> {\n\n @TableId\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n @Schema(name = \"id\", description = \"主键ID\")\n private String id;\n\n @TableField(fill = FieldFill.INSERT)\n @Schema(name = \"createTime\", description = \"创建时间\")\n private Date createTime;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n @Schema(name = \"updatedTime\", description = \"最后更新时间\")\n private Date updateTime;\n\n @TableLogic\n @Schema(name = \"deleted\",description = \"删除标记\")\n @JsonIgnore\n private short deleted;\n}" }, { "identifier": "CustomBasicPageQuery", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/interf/CustomBasicPageQuery.java", "snippet": "public interface CustomBasicPageQuery<T> {\n /**\n * 自定义查询\n *\n * @param wrapper 条件包装\n */\n void query(LambdaQueryWrapper<T> wrapper);\n}" }, { "identifier": "IBaseService", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/service/IBaseService.java", "snippet": "public interface IBaseService<T extends BaseEntity<T>> extends IService<T> {\n\n T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer);\n\n /**\n * 获取第一条记录\n *\n * @param queryWrapper 查询条件\n * @return 查询结果\n */\n T getFirst(LambdaQueryWrapper<T> queryWrapper);\n\n /**\n * 获取第一条记录\n *\n * @param queryWrapper 查询条件\n * @return 查询结果\n * @see IBaseService#getFirst(LambdaQueryWrapper)\n */\n T getFirst(QueryWrapper<T> queryWrapper);\n\n\n /**\n * 根据字段匹配获取第一条数据 <br>\n * 例如:用户名在全局是唯一的,则为getByField(User::getUsername, username)\n *\n * @param field 字段\n * @param value 字段值\n * @return 记录\n */\n T getByField(SFunction<T, ?> field, String value);\n\n /**\n * 基础分页查询方法\n *\n * @param dto 查询数据\n * @param orderByField 排序字段\n * @param customQuery 自定义查询条件组合\n * @return 分页查询数据\n */\n PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery);\n\n /**\n * 重置基础字段\n *\n * @param t 对象\n */\n void resetBaseField(T t);\n\n /**\n * 创建新的数据\n *\n * @param req 数据体\n * @return 数据\n */\n T create(T req);\n\n /**\n * 批量创建新的数据\n *\n * @param reqs 数据体\n * @return 数据\n */\n List<T> create(List<T> reqs);\n\n /**\n * 更新数据\n *\n * @param id ID\n * @param req 数据体\n * @return 数据\n */\n T update(String id, T req);\n\n\n /**\n * 更新数据\n *\n * @param id ID\n * @param req 数据体\n * @param query 附加查询条件\n * @return 数据\n */\n T update(String id, T req, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n /**\n * 删除数据\n *\n * @param id ID\n */\n void removeSingle(String id);\n\n /**\n * 删除数据\n *\n * @param query 附加查询条件\n * @param id ID\n */\n void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n /**\n * 批量删除数据\n *\n * @param idList ID列表\n */\n void remove(List<String> idList);\n\n /**\n * 批量删除数据\n *\n * @param idList ID列表\n * @param query 附加查询条件\n */\n void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n /**\n * 查询指定ID数据的详情\n *\n * @param id ID\n * @return 数据\n */\n T detail(String id);\n\n /**\n * 查询指定数据的详情\n *\n * @return 数据\n */\n T detail(Consumer<LambdaQueryWrapper<T>> consumer);\n\n /**\n * 查询指定ID数据的详情\n *\n * @param id ID\n * @param query 附加查询条件\n * @return 数据\n */\n T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n\n\n /**\n * 获取最后一条记录根据创建时间\n *\n * @param customQuery 自定义查询\n * @return 记录\n */\n T getLastByCreateTime(@Nullable CustomBasicPageQuery<T> customQuery);\n\n /**\n * 获取服务模型名称\n *\n * @return 模型名称\n */\n String getServiceModelName();\n\n /**\n * 获取服务模型的缓存ID\n *\n * @param t 模型\n * @return 缓存ID\n */\n String getServiceModelCacheId(T t);\n\n /**\n * 获取模型hash存储的缓存建值\n * 当此值不为null时,为开启缓存\n *\n * @return 是否开启\n */\n String getModelHashCacheKey();\n\n\n\n\n\n /**\n * 分页数据转换为VO分页数据\n *\n * @param page 分页数据结构\n * @param targetClass 目标类\n * @param <V> 类型\n * @return VO分页数据结构\n */\n <V> PageVO<V> pageToVO(PageVO<T> page, Class<V> targetClass);\n}" }, { "identifier": "PageVO", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/vo/PageVO.java", "snippet": "@Data\n@Schema(name = \"PageVO\", description = \"分页查询结果\")\n@NoArgsConstructor\npublic class PageVO<T> {\n @Schema(name = \"records\", description = \"分页查询结果\")\n private List<T> records;\n\n @Schema(name = \"total\", description = \"总记录数\")\n private long total;\n\n @Schema(name = \"size\", description = \"每页数量大小\")\n private long size;\n\n @Schema(name = \"current\", description = \"当前页码\")\n private long current;\n\n @Schema(name = \"orders\", description = \"正序查询\")\n private List<OrderItem> orders;\n\n @Schema(name = \"searchCount\", description = \"是否进行 count 查询\")\n private Boolean searchCount;\n\n @Schema(name = \"pages\", description = \"总页数\")\n private long pages;\n\n public PageVO(IPage<T> page) {\n this.records = page.getRecords();\n this.total = page.getTotal();\n this.size = page.getSize();\n this.current = page.getCurrent();\n this.orders = page.orders();\n this.searchCount = page.searchCount();\n this.pages = page.getPages();\n }\n\n public PageVO(IPage<?> page, List<T> records) {\n this.records = records;\n this.total = page.getTotal();\n this.size = page.getSize();\n this.current = page.getCurrent();\n this.orders = page.orders();\n this.searchCount = page.searchCount();\n this.pages = page.getPages();\n }\n}" }, { "identifier": "AssertUtils", "path": "service-common/service-common-tools/src/main/java/fun/isite/service/common/tools/lang/AssertUtils.java", "snippet": "public class AssertUtils {\n public static void isTrue(Boolean expression, String message) {\n if (expression) {\n throw new LogicException(message);\n }\n }\n\n public static void isFalse(Boolean expression, String message) {\n if (!expression) {\n throw new LogicException(message);\n }\n }\n\n public static void isLeZero(Integer expression, String message) {\n if (expression <= 0) {\n throw new LogicException(message);\n }\n }\n\n public static void isNull(Object obj, String message) {\n if (obj == null || BeanUtil.isEmpty(obj)) {\n throw new LogicException(message);\n }\n }\n\n public static void isNotNull(Object obj, String message) {\n if (BeanUtil.isNotEmpty(obj)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(String str, String message) {\n if (StrUtil.isEmpty(str)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Collection<?> collection, String message) {\n if (CollUtil.isEmpty(collection)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Iterable<?> iterable, String message) {\n if (CollUtil.isEmpty(iterable)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Map<?, ?> map, String message) {\n if (CollUtil.isEmpty(map)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(List<?> list, String message) {\n if (CollUtil.isEmpty(list)) {\n throw new LogicException(message);\n }\n }\n\n public static void isBlank(String str, String message) {\n if (StrUtil.isBlank(str)) {\n throw new LogicException(message);\n }\n }\n}" }, { "identifier": "RedisUtils", "path": "service-common/service-common-tools/src/main/java/fun/isite/service/common/tools/utils/RedisUtils.java", "snippet": "@Component\npublic class RedisUtils {\n /**\n * 唯一实例\n */\n @Getter\n private static RedisUtils INSTANCE;\n\n public RedisUtils(RedisTemplate<String, Object> redisTemplate) {\n this.redisTemplate = redisTemplate;\n }\n\n @PostConstruct\n public void init() {\n INSTANCE = this;\n }\n\n @Getter\n private final RedisTemplate<String, Object> redisTemplate;\n\n\n /**\n * 判断key是否存在\n *\n * @param key 键\n * @return true 存在 false不存在\n */\n public boolean hasKey(String key) {\n Boolean res = redisTemplate.hasKey(key);\n if (res == null) {\n return false;\n }\n return res;\n }\n\n\n /**\n * 删除缓存\n *\n * @param key 可以传一个值 或多个\n */\n public void del(String... key) {\n if (key != null && key.length > 0) {\n if (key.length == 1) {\n redisTemplate.delete(key[0]);\n } else {\n redisTemplate.delete(Arrays.asList(key));\n }\n }\n }\n public void del(String key) {\n if (key != null ) {\n redisTemplate.delete(key);\n }\n }\n public void del(Collection<String> keys) {\n redisTemplate.delete(keys);\n }\n\n\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public Object get(String key) {\n return key == null ? null : redisTemplate.opsForValue().get(key);\n }\n\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public <T> T get(String key, Class<T> clazz) {\n Object res = this.get(key);\n if (res != null && res.getClass().equals(clazz)) {\n return clazz.cast(res);\n }\n return null;\n }\n\n /**\n * 普通缓存获取\n *\n * @param keys 键\n * @return 值\n */\n public <T> List<T> multiGet(Class<T> clazz, Collection<String> keys) {\n List<Object> res = redisTemplate.opsForValue().multiGet(keys);\n if (res != null) {\n List<T> result = new ArrayList<>();\n for (Object item : res) {\n if (item.getClass().equals(clazz)) {\n result.add(clazz.cast(item));\n }\n }\n return result;\n }\n return null;\n }\n\n /**\n * @param key 键\n * @return 值\n */\n public <T extends Serializable> List<T> getList(String key, Class<T> clazz) {\n List<Object> res = this.redisTemplate.opsForList().range(key, 0, -1);\n if (CollUtil.isNotEmpty(res)) {\n List<T> finalRes = new ArrayList<>();\n for (Object re : res) {\n if (re.getClass().equals(clazz)) {\n finalRes.add(clazz.cast(re));\n }\n }\n return finalRes;\n }\n return null;\n }\n\n /**\n * 设置LIST集合\n *\n * @param key\n * @param list\n * @return\n */\n public <T extends Serializable> boolean setList(String key, Collection<T> list) {\n try {\n if (list == null) {\n return false;\n }\n for (T t : list) {\n redisTemplate.opsForList().leftPush(key, t);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public boolean lisAdd(String key, Object val) {\n try {\n redisTemplate.opsForList().leftPush(key, val);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 普通缓存放入\n *\n * @param key 键\n * @param value 值\n * @return true成功 false失败\n */\n public <T extends Serializable> boolean set(String key, T value) {\n try {\n redisTemplate.opsForValue().set(key, value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 普通缓存放入并设置时间\n *\n * @param key 键\n * @param hKey 值\n * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期\n * @return true成功 false 失败\n */\n public boolean set(String key, Serializable hKey, long time, TimeUnit timeUnit) {\n try {\n if (time > 0) {\n redisTemplate.opsForValue().set(key, hKey, time, timeUnit);\n } else {\n set(key, hKey);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n private <T> T objectToClass(Object object, Class<T> clazz) {\n if (object != null && object.getClass().equals(clazz)) {\n return clazz.cast(object);\n }\n return null;\n }\n\n /**\n * HashGet\n *\n * @param key 键 不能为null\n * @param hKey 项 不能为null\n * @return 值\n */\n public <T> T hGet(String key, Serializable hKey, Class<T> clazz) {\n return objectToClass(redisTemplate.opsForHash().get(key, String.valueOf(hKey)), clazz);\n }\n\n /**\n * 获取hashKey对应的所有键值\n *\n * @param key 键\n * @return 对应的多个键值\n */\n public <K, V> Map<K, V> hmGet(String key, Class<K> classK, Class<V> classV) {\n Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);\n Map<K, V> res = new HashMap<>();\n for (Object o : entries.keySet()) {\n K k = objectToClass(o, classK);\n if (k != null) {\n V val = objectToClass(entries.get(o), classV);\n if (val != null) {\n res.put(k, val);\n }\n }\n }\n return res;\n }\n\n /**\n * HashSet\n *\n * @param key 键\n * @param map 对应多个键值\n * @return true 成功 false 失败\n */\n public <K extends Serializable, V extends Serializable> boolean hmSet(String key, Map<K, V> map) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * HashSet 并设置时间\n *\n * @param key 键\n * @param map 对应多个键值\n * @param time 时间(秒)\n * @return true成功 false失败\n */\n public <T extends Serializable, E extends Serializable> boolean hmSet(String key, Map<T, E> map, long time, TimeUnit timeUnit) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n if (time > 0) {\n redisTemplate.expire(key, time, timeUnit);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param hKey 项\n * @param value 值\n * @return true 成功 false失败\n */\n public boolean hSet(String key, Serializable hKey, Object value) {\n try {\n redisTemplate.opsForHash().put(key, String.valueOf(hKey), value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param hKey 项\n * @param value 值\n * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间\n * @return true 成功 false失败\n */\n public boolean hSet(String key, Serializable hKey, Object value, long time, TimeUnit timeUnit) {\n try {\n redisTemplate.opsForHash().put(key, String.valueOf(hKey), value);\n if (time > 0) {\n redisTemplate.expire(key, time, timeUnit);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 删除hash表中的值\n *\n * @param key 键 不能为null\n * @param item 项 可以使多个 不能为null\n */\n public void hDel(String key, Object... item) {\n redisTemplate.opsForHash().delete(key, item);\n }\n\n /**\n * 判断hash表中是否有该项的值\n *\n * @param key 键 不能为null\n * @param item 项 不能为null\n * @return true 存在 false不存在\n */\n public boolean hHasKey(String key, Serializable item) {\n return redisTemplate.opsForHash().hasKey(key, item);\n }\n\n /**\n * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n *\n * @param key 键\n * @param item 项\n * @param by 要增加几(大于0)\n * @return\n */\n public double hIncr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, by);\n }\n\n /**\n * hash递减\n *\n * @param key 键\n * @param item 项\n * @param by 要减少记(小于0)\n * @return\n */\n public double hDecr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, -by);\n }\n\n\n /**\n * 模糊删除\n *\n * @param ex\n */\n public void likeDel(String ex) {\n Set<String> keys = redisTemplate.keys(ex);\n if (CollUtil.isNotEmpty(keys)) {\n redisTemplate.delete(keys);\n }\n }\n\n public Set<String> keys(String ex) {\n return redisTemplate.keys(ex);\n }\n\n\n /**\n * 向指定key的set集合中添加一个值\n *\n * @param key redis的key\n * @param val set集合的值\n * @return\n */\n public boolean setAdd(String key, Object val) {\n try {\n redisTemplate.opsForSet().add(key, val);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public <T extends Serializable> List<T> getSet(String key, Class<T> clazz) {\n if (Boolean.FALSE.equals(this.redisTemplate.hasKey(key))) {\n return null;\n }\n List<Object> res = this.redisTemplate.opsForSet().pop(key, -1);\n if (CollUtil.isNotEmpty(res)) {\n List<T> finalRes = new ArrayList<>();\n for (Object re : res) {\n if (re.getClass().equals(clazz)) {\n finalRes.add(clazz.cast(re));\n }\n }\n return finalRes;\n }\n return null;\n }\n\n /**\n * set集合中是否存在指定数据\n *\n * @param key\n * @param val\n * @return\n */\n public boolean setHas(String key, Object val) {\n if (hasKey(key)) {\n return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, val));\n } else {\n return false;\n }\n }\n\n public boolean streamAdd() {\n redisTemplate.opsForStream().add(null);\n return false;\n }\n}" } ]
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import fun.isite.service.common.bean.exception.LogicException; import fun.isite.service.common.db.dto.SplitPageDTO; import fun.isite.service.common.db.entity.BaseEntity; import fun.isite.service.common.db.interf.CustomBasicPageQuery; import fun.isite.service.common.db.service.IBaseService; import fun.isite.service.common.db.vo.PageVO; import fun.isite.service.common.tools.lang.AssertUtils; import fun.isite.service.common.tools.utils.RedisUtils; import jakarta.annotation.Nullable; import org.springframework.beans.BeanUtils; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer;
6,712
package fun.isite.service.common.db.impl; /** * @author Enigma */ public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> { public final static String[] BASE_ENTITY_FIELDS = {"id", "create_time", "update_time", "deleted"}; public final static String LIMIT_ONE = "limit 1"; @Override public T getFirst(QueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .eq(T::getId, id); if(wrapperConsumer!=null){ wrapperConsumer.accept(wrapper); } wrapper.last(LIMIT_ONE); return this.getOne(wrapper); } @Override public T getFirst(LambdaQueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getByField(SFunction<T, ?> field, String value) { return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value)); } @Override
package fun.isite.service.common.db.impl; /** * @author Enigma */ public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> { public final static String[] BASE_ENTITY_FIELDS = {"id", "create_time", "update_time", "deleted"}; public final static String LIMIT_ONE = "limit 1"; @Override public T getFirst(QueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .eq(T::getId, id); if(wrapperConsumer!=null){ wrapperConsumer.accept(wrapper); } wrapper.last(LIMIT_ONE); return this.getOne(wrapper); } @Override public T getFirst(LambdaQueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getByField(SFunction<T, ?> field, String value) { return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value)); } @Override
public PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery) {
1
2023-12-26 01:55:01+00:00
8k
codingmiao/hppt
cc/src/main/java/org/wowtools/hppt/cc/StartCc.java
[ { "identifier": "CcConfig", "path": "cc/src/main/java/org/wowtools/hppt/cc/pojo/CcConfig.java", "snippet": "public class CcConfig {\n /**\n * 客户端id,每个cc.jar用一个,不要重复\n */\n public String clientId;\n\n /**\n * 服务端http地址,可以填nginx转发过的地址\n */\n public String serverUrl;\n\n /**\n * 开始时闲置几毫秒发一次http请求,越短延迟越低但越耗性能\n */\n public long initSleepTime = 1_000;\n\n /**\n * 当收到空消息时,闲置毫秒数增加多少毫秒\n */\n public long addSleepTime = 1_000;\n\n /**\n * 当用户端输入字节时,唤醒发送线程,此后多少毫秒不睡眠\n */\n public long awakenTime = 10_000;\n\n /**\n * 闲置毫秒数最大到多少毫秒\n */\n public long maxSleepTime = 60_000;\n\n /**\n * 兜底策略,会话超过多少毫秒未确认后自行关闭\n */\n public long sessionTimeout = 60_000;\n\n /**\n * 向服务端发数据请求体的字节数最大值\n * 有时会出现413 Request Entity Too Large问题,没办法改nginx的话就用这个值限制\n */\n public int maxSendBodySize = Integer.MAX_VALUE;\n\n /**\n * 是否启用压缩,默认启用 需和服务端保持一致\n */\n public boolean enableCompress = true;\n\n /**\n * 是否启用内容加密,默认启用 需和服务端保持一致\n */\n public boolean enableEncrypt = true;\n\n /**\n * 缓冲区最大允许缓冲多少条消息\n */\n public int messageQueueSize = 10240;\n}" }, { "identifier": "ClientSessionService", "path": "cc/src/main/java/org/wowtools/hppt/cc/service/ClientSessionService.java", "snippet": "@Slf4j\npublic class ClientSessionService {\n\n private static final String talkUri = StartCc.config.serverUrl + \"/talk?c=\";\n private static long sleepTime = StartCc.config.initSleepTime - StartCc.config.addSleepTime;\n private static long noSleepLimitTime = 0;\n private static final AtomicBoolean sleeping = new AtomicBoolean(false);\n\n private static final Thread sendThread;\n\n\n static {\n sendThread = new Thread(() -> {\n while (true) {\n try {\n /* 发请求 */\n boolean isEmpty = sendToSs();\n\n /* 睡眠发送线程策略 */\n if (noSleepLimitTime > System.currentTimeMillis()) {\n //线程刚刚被唤醒,不睡眠\n sleepTime = StartCc.config.initSleepTime;\n log.debug(\"线程刚刚被唤醒 {}\", sleepTime);\n } else if (isEmpty) {\n //收发数据包都为空,逐步增加睡眠时间\n if (sleepTime < StartCc.config.maxSleepTime) {\n sleepTime += StartCc.config.addSleepTime;\n }\n log.debug(\"收发数据包都为空,逐步增加睡眠时间 {}\", sleepTime);\n } else {\n sleepTime = StartCc.config.initSleepTime;\n log.debug(\"正常包 {}\", sleepTime);\n }\n if (sleepTime > 0) {\n sleeping.set(true);\n try {\n log.debug(\"sleep {}\", sleepTime);\n Thread.sleep(sleepTime);\n } catch (InterruptedException e) {\n log.info(\"发送进程被唤醒\");\n } finally {\n sleeping.set(false);\n }\n }\n } catch (Exception e) {\n log.warn(\"发消息到服务端发生异常\", e);\n sleeping.set(true);\n try {\n Thread.sleep(StartCc.config.maxSleepTime);\n } catch (InterruptedException e1) {\n log.info(\"发送进程被唤醒\");\n } finally {\n sleeping.set(false);\n }\n StartCc.tryLogin();\n }\n }\n });\n }\n\n public static void start() {\n //启动轮询发送http请求线程\n sendThread.start();\n //起一个线程,定期检查超时session\n new Thread(() -> {\n while (true) {\n try {\n Thread.sleep(StartCc.config.sessionTimeout);\n log.debug(\"定期检查,当前session数 {}\", ClientSessionManager.clientSessionMap.size());\n for (Map.Entry<Integer, ClientSession> entry : ClientSessionManager.clientSessionMap.entrySet()) {\n ClientSession session = entry.getValue();\n if (session.isTimeOut()) {\n ClientSessionManager.disposeClientSession(session, \"超时不活跃\");\n }\n }\n\n } catch (Exception e) {\n log.warn(\"定期检查超时session异常\", e);\n }\n }\n }).start();\n }\n\n /**\n * 发请求\n *\n * @return 是否为空包 即发送和接收都是空\n * @throws Exception Exception\n */\n private static boolean sendToSs() throws Exception {\n boolean isEmpty = true;\n List<ProtoMessage.BytesPb> bytePbList = new LinkedList<>();\n //发字节\n ClientSessionManager.clientSessionMap.forEach((sessionId, clientSession) -> {\n byte[] bytes = clientSession.fetchSendSessionBytes();\n if (bytes != null) {\n bytePbList.add(ProtoMessage.BytesPb.newBuilder()\n .setSessionId(clientSession.getSessionId())\n .setBytes(ByteString.copyFrom(bytes))\n .build()\n );\n }\n });\n if (!bytePbList.isEmpty()) {\n isEmpty = false;\n }\n //发命令\n List<String> commands = new LinkedList<>();\n {\n StringBuilder closeSession = new StringBuilder().append(Constant.CsCommands.CloseSession);\n StringBuilder checkActiveSession = new StringBuilder().append(Constant.CsCommands.CheckSessionActive);\n\n ClientSessionManager.clientSessionMap.forEach((sessionId, session) -> {\n if (session.isNeedCheckActive()) {\n checkActiveSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n }\n });\n\n List<Integer> closedClientSessions = ClientSessionManager.fetchClosedClientSessions();\n if (null != closedClientSessions) {\n for (Integer sessionId : closedClientSessions) {\n closeSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n }\n }\n\n if (closeSession.length() > 1) {\n commands.add(closeSession.toString());\n }\n if (checkActiveSession.length() > 1) {\n commands.add(checkActiveSession.toString());\n }\n }\n cutSendToSs(bytePbList, commands);\n return isEmpty;\n }\n\n //如果请求体过大,会出现413 Request Entity Too Large,拆分一下发送\n private static boolean cutSendToSs(List<ProtoMessage.BytesPb> bytePbs, List<String> commands) throws Exception {\n List<ProtoMessage.BytesPb> bytesPbList = new LinkedList<>();\n List<String> commandList = new LinkedList<>();\n int requestBodyLength = 0;\n\n while (!bytePbs.isEmpty()) {\n if (bytePbs.getFirst().getBytes().size() > StartCc.config.maxSendBodySize) {\n //单个bytePb包含的字节数就超过限制了,那把bytes拆小\n ProtoMessage.BytesPb bytePb = bytePbs.removeFirst();\n byte[][] splitBytes = BytesUtil.splitBytes(bytePb.getBytes().toByteArray(), StartCc.config.maxSendBodySize);\n for (int i = splitBytes.length - 1; i >= 0; i--) {\n bytePbs.addFirst(ProtoMessage.BytesPb.newBuilder()\n .setBytes(ByteString.copyFrom(splitBytes[i]))\n .setSessionId(bytePb.getSessionId())\n .build());\n }\n } else {\n requestBodyLength += bytePbs.getFirst().getBytes().size();\n if (requestBodyLength > StartCc.config.maxSendBodySize) {\n break;\n }\n bytesPbList.add(bytePbs.removeFirst());\n }\n\n }\n\n while (!commands.isEmpty()) {\n if (commands.getFirst().length() > StartCc.config.maxSendBodySize) {\n throw new RuntimeException(\"maxSendBodySize 的值过小导致无法发送命令,请调整\");\n }\n requestBodyLength += commands.getFirst().length();//注意,这里限定了命令只能是ASCII字符\n if (requestBodyLength > StartCc.config.maxSendBodySize) {\n break;\n }\n commandList.add(commands.removeFirst());\n }\n log.debug(\"requestBodyLength {}\", requestBodyLength);\n boolean isEmpty = subSendToSs(bytesPbList, commandList);\n if (bytePbs.isEmpty() && commands.isEmpty()) {\n return isEmpty;\n } else {\n return cutSendToSs(bytePbs, commands);\n }\n }\n\n\n //发送和接收\n private static boolean subSendToSs(List<ProtoMessage.BytesPb> bytesPbList, List<String> commandList) throws Exception {\n boolean isEmpty = true;\n\n ProtoMessage.MessagePb.Builder messagePbBuilder = ProtoMessage.MessagePb.newBuilder();\n if (!bytesPbList.isEmpty()) {\n messagePbBuilder.addAllBytesPbList(bytesPbList);\n }\n if (!commandList.isEmpty()) {\n messagePbBuilder.addAllCommandList(commandList);\n }\n byte[] requestBody = messagePbBuilder.build().toByteArray();\n\n //压缩、加密\n if (StartCc.config.enableCompress) {\n requestBody = BytesUtil.compress(requestBody);\n }\n if (StartCc.config.enableEncrypt) {\n requestBody = StartCc.aesCipherUtil.encryptor.encrypt(requestBody);\n }\n\n log.debug(\"发送数据 bytesPbs {} commands {} 字节数 {}\", bytesPbList.size(), commandList.size(), requestBody.length);\n\n Response response;\n if (log.isDebugEnabled()) {\n long t = System.currentTimeMillis();\n response = HttpUtil.doPost(talkUri + StartCc.loginCode, requestBody);\n log.debug(\"发送http请求耗时 {}\", System.currentTimeMillis() - t);\n } else {\n response = HttpUtil.doPost(talkUri + StartCc.loginCode, requestBody);\n }\n\n\n byte[] responseBody;\n try {\n if (\"not_login\".equals(response.headers().get(\"err\"))) {\n //发现未登录标识,尝试重新登录\n StartCc.tryLogin();\n return true;\n }\n assert response.body() != null;\n responseBody = response.body().bytes();\n } finally {\n response.close();\n }\n\n ProtoMessage.MessagePb rMessagePb;\n byte[] responseBody0 = responseBody;\n try {\n //解密、解压\n if (StartCc.config.enableEncrypt) {\n responseBody = StartCc.aesCipherUtil.descriptor.decrypt(responseBody);\n }\n if (StartCc.config.enableCompress) {\n responseBody = BytesUtil.decompress(responseBody);\n }\n log.debug(\"收到服务端发回字节数 {}\", responseBody.length);\n rMessagePb = ProtoMessage.MessagePb.parseFrom(responseBody);\n } catch (Exception e) {\n log.warn(\"服务端响应错误 [{}]\", new String(responseBody0, StandardCharsets.UTF_8), e);\n StartCc.tryLogin();\n return true;\n }\n\n //收命令\n for (String command : rMessagePb.getCommandListList()) {\n log.debug(\"收到服务端命令 {} \", command);\n char type = command.charAt(0);\n switch (type) {\n case Constant.CcCommands.CloseSession -> {\n String[] strSessionIds = command.substring(1).split(Constant.sessionIdJoinFlag);\n for (String strSessionId : strSessionIds) {\n if (strSessionId.isEmpty()) {\n continue;\n }\n ClientSession clientSession = ClientSessionManager.clientSessionMap.get(Integer.parseInt(strSessionId));\n if (null != clientSession) {\n ClientSessionManager.disposeClientSession(clientSession, \"服务端发送关闭命令\");\n }\n }\n }\n case Constant.CcCommands.ActiveSession -> {\n String[] strSessionIds = command.substring(1).split(Constant.sessionIdJoinFlag);\n for (String strSessionId : strSessionIds) {\n ClientSession session = ClientSessionManager.getClientSession(Integer.parseInt(strSessionId));\n if (session != null) {\n session.activeSession();\n }\n }\n }\n case Constant.CcCommands.CreateSession -> {\n //2sessionId host port\n String[] strs = command.substring(1).split(\" \");\n int sessionId = Integer.parseInt(strs[0]);\n String host = strs[1];\n int port = Integer.parseInt(strs[2]);\n ClientSessionManager.createClientSession(host, port, sessionId);\n }\n }\n }\n\n //收字节\n List<ProtoMessage.BytesPb> rBytesPbListList = rMessagePb.getBytesPbListList();\n if (!rBytesPbListList.isEmpty()) {\n isEmpty = false;\n for (ProtoMessage.BytesPb bytesPb : rBytesPbListList) {\n ClientSession clientSession = ClientSessionManager.clientSessionMap.get(bytesPb.getSessionId());\n if (clientSession != null) {\n clientSession.putBytes(bytesPb.getBytes().toByteArray());\n }\n }\n noSleepLimitTime = System.currentTimeMillis() + StartCc.config.awakenTime;\n }\n\n return isEmpty;\n }\n\n /**\n * 唤醒发送线程\n */\n public static void awakenSendThread() {\n if (sleeping.get()) {\n try {\n sleepTime = StartCc.config.initSleepTime;\n sendThread.interrupt();\n log.info(\"唤醒发送线程\");\n } catch (Exception e) {\n log.warn(\"唤醒线程异常\", e);\n }\n }\n }\n\n}" }, { "identifier": "AesCipherUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/AesCipherUtil.java", "snippet": "@Slf4j\npublic class AesCipherUtil {\n\n public final Encryptor encryptor;\n\n public final Descriptor descriptor;\n\n\n public AesCipherUtil(String strKey, long ts) {\n strKey = strKey + (ts / (30 * 60 * 1000));\n SecretKey key = generateKey(strKey);\n this.encryptor = new Encryptor(key);\n this.descriptor = new Descriptor(key);\n }\n\n /**\n * 加密器\n */\n public static final class Encryptor {\n private final Cipher cipher;\n\n private Encryptor(SecretKey key) {\n try {\n cipher = Cipher.getInstance(\"AES\");\n cipher.init(Cipher.ENCRYPT_MODE, key);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public byte[] encrypt(byte[] bytes) {\n try {\n return cipher.doFinal(bytes);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n\n /**\n * 解密器\n */\n public static final class Descriptor {\n private final Cipher cipher;\n\n private Descriptor(SecretKey key) {\n try {\n cipher = Cipher.getInstance(\"AES\");\n cipher.init(Cipher.DECRYPT_MODE, key);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public byte[] decrypt(byte[] bytes) {\n try {\n return cipher.doFinal(bytes);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n\n private static final int n = 16;\n\n private static SecretKey generateKey(String input) {\n try {\n KeyGenerator kgen = KeyGenerator.getInstance(\"AES\");// 创建AES的Key生产者\n SecureRandom secureRandom = SecureRandom.getInstance(\"SHA1PRNG\");\n secureRandom.setSeed(input.getBytes());\n kgen.init(128, secureRandom);\n\n SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥\n return secretKey;\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n\n\n}" }, { "identifier": "BytesUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/BytesUtil.java", "snippet": "public class BytesUtil {\n /**\n * 按每个数组的最大长度限制,将一个数组拆分为多个\n *\n * @param originalArray 原数组\n * @param maxChunkSize 最大长度限制\n * @return 拆分结果\n */\n public static byte[][] splitBytes(byte[] originalArray, int maxChunkSize) {\n int length = originalArray.length;\n int numOfChunks = (int) Math.ceil((double) length / maxChunkSize);\n byte[][] splitArrays = new byte[numOfChunks][];\n\n for (int i = 0; i < numOfChunks; i++) {\n int start = i * maxChunkSize;\n int end = Math.min((i + 1) * maxChunkSize, length);\n int chunkSize = end - start;\n\n byte[] chunk = new byte[chunkSize];\n System.arraycopy(originalArray, start, chunk, 0, chunkSize);\n\n splitArrays[i] = chunk;\n }\n\n return splitArrays;\n }\n\n /**\n * 合并字节集合为一个byte[]\n *\n * @param collection 字节集合\n * @return byte[]\n */\n public static byte[] merge(Collection<byte[]> collection) {\n byte[] bytes;\n try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {\n for (byte[] byteArray : collection) {\n byteArrayOutputStream.write(byteArray);\n }\n bytes = byteArrayOutputStream.toByteArray();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return bytes;\n }\n\n /**\n * bytes转base64字符串\n *\n * @param bytes bytes\n * @return base64字符串\n */\n public static String bytes2base64(byte[] bytes) {\n return Base64.getEncoder().encodeToString(bytes);\n }\n\n /**\n * base64字符串转bytes\n *\n * @param base64 base64字符串\n * @return bytes\n */\n public static byte[] base642bytes(String base64) {\n return Base64.getDecoder().decode(base64);\n }\n\n // 使用GZIP压缩字节数组\n public static byte[] compress(byte[] input) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {\n gzipOutputStream.write(input);\n }\n return baos.toByteArray();\n }\n\n // 使用GZIP解压缩字节数组\n public static byte[] decompress(byte[] compressed) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ByteArrayInputStream bais = new ByteArrayInputStream(compressed);\n try (java.util.zip.GZIPInputStream gzipInputStream = new java.util.zip.GZIPInputStream(bais)) {\n byte[] buffer = new byte[1024];\n int len;\n while ((len = gzipInputStream.read(buffer)) > 0) {\n baos.write(buffer, 0, len);\n }\n }\n return baos.toByteArray();\n }\n\n public static ByteBuf bytes2byteBuf(ChannelHandlerContext ctx, byte[] bytes) {\n ByteBuf byteBuf = ctx.alloc().buffer(bytes.length, bytes.length);\n byteBuf.writeBytes(bytes);\n return byteBuf;\n }\n\n //把字节写入ChannelHandlerContext\n public static void writeToChannelHandlerContext(ChannelHandlerContext ctx, byte[] bytes) {\n ByteBuf byteBuf = bytes2byteBuf(ctx, bytes);\n ctx.writeAndFlush(byteBuf);\n }\n\n public static byte[] byteBuf2bytes(ByteBuf byteBuf) {\n byte[] bytes = new byte[byteBuf.readableBytes()];\n byteBuf.readBytes(bytes);\n return bytes;\n }\n\n\n\n}" }, { "identifier": "Constant", "path": "common/src/main/java/org/wowtools/hppt/common/util/Constant.java", "snippet": "public class Constant {\n public static final ObjectMapper jsonObjectMapper = new ObjectMapper();\n\n public static final ObjectMapper ymlMapper = new ObjectMapper(new YAMLFactory());\n\n public static final String sessionIdJoinFlag = \",\";\n\n //ss端执行的命令代码\n public static final class SsCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n }\n\n //Sc端执行的命令代码\n public static final class ScCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //Cs端执行的命令代码\n public static final class CsCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //cc端执行的命令代码\n public static final class CcCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n\n //新建会话 2sessionId host port\n public static final char CreateSession = '2';\n }\n\n}" }, { "identifier": "HttpUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/HttpUtil.java", "snippet": "@Slf4j\npublic class HttpUtil {\n\n private static final okhttp3.MediaType bytesMediaType = okhttp3.MediaType.parse(\"application/octet-stream\");\n\n private static final OkHttpClient okHttpClient;\n\n static {\n okHttpClient = new OkHttpClient.Builder()\n .sslSocketFactory(sslSocketFactory(), x509TrustManager())\n // 是否开启缓存\n .retryOnConnectionFailure(false)\n .connectionPool(pool())\n .connectTimeout(30L, TimeUnit.SECONDS)\n .readTimeout(30L, TimeUnit.SECONDS)\n .writeTimeout(30L, TimeUnit.SECONDS)\n .hostnameVerifier((hostname, session) -> true)\n // 设置代理\n// .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"127.0.0.1\", 8888)))\n // 拦截器\n// .addInterceptor()\n .build();\n\n }\n\n\n public static Response doGet(String url) {\n Request.Builder builder = new Request.Builder();\n Request request = builder.url(url).build();\n return execute(request);\n }\n\n public static Response doPost(String url) {\n RequestBody body = RequestBody.create(bytesMediaType, new byte[0]);\n Request request = new Request.Builder().url(url).post(body).build();\n return execute(request);\n }\n\n public static Response doPost(String url, byte[] bytes) {\n RequestBody body = RequestBody.create(bytesMediaType, bytes);\n Request request = new Request.Builder().url(url).post(body).build();\n return execute(request);\n }\n\n\n public static Response execute(Request request) {\n java.io.InterruptedIOException interruptedIOException = null;\n for (int i = 0; i < 5; i++) {\n try {\n return okHttpClient.newCall(request).execute();\n } catch (java.io.InterruptedIOException e) {\n interruptedIOException = e;\n try {\n Thread.sleep(10);\n } catch (Exception ex) {\n log.debug(\"发送请求sleep被打断\");\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n throw new RuntimeException(interruptedIOException);\n\n }\n\n\n private static X509TrustManager x509TrustManager() {\n return new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n }\n\n private static SSLSocketFactory sslSocketFactory() {\n try {\n // 信任任何链接\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());\n return sslContext.getSocketFactory();\n } catch (NoSuchAlgorithmException | KeyManagementException e) {\n throw new RuntimeException(e);\n }\n }\n\n private static ConnectionPool pool() {\n return new ConnectionPool(5, 1L, TimeUnit.MINUTES);\n }\n\n}" } ]
import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import org.apache.logging.log4j.core.config.Configurator; import org.wowtools.common.utils.ResourcesReader; import org.wowtools.hppt.cc.pojo.CcConfig; import org.wowtools.hppt.cc.service.ClientSessionService; import org.wowtools.hppt.common.util.AesCipherUtil; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.common.util.Constant; import org.wowtools.hppt.common.util.HttpUtil; import java.io.File; import java.net.URLEncoder; import java.nio.charset.StandardCharsets;
6,466
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc {
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc {
public static CcConfig config;
0
2023-12-22 14:14:27+00:00
8k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/AutoTrap.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final ExecutorService executorService;\n private final NavigationMeshManager navigationMeshManager;\n private final Pathfinder pathfinder;\n private final Minecraft minecraft;\n private final HoleManager holeManager;\n private final LagbackService lagbackService;\n private final LocalPlayerPositionService localPlayerPositionService;\n private final AttackService attackService;\n private final InvincibilityFrameService invincibilityFrameService;\n private final DamageService damageService;\n private final BlockPlacer blockPlacer;\n private final AntiCheat antiCheat;\n private final MotionUpdateService motionUpdateService;\n private final BlockUpdateService blockUpdateService;\n private final BlockDestructionService blockDestructionService;\n private final ServerService serverService;\n private final TotemPopService totemPopService;\n private final InventoryService inventoryService;\n private final ThreadSafeLevelService threadSafeLevelService;\n private final TaskService taskService;\n private final MovementService movementService;\n private final WorldVersionService worldVersionService;\n\n}" }, { "identifier": "BlockPlacingModule", "path": "src/main/java/me/earth/phobot/modules/BlockPlacingModule.java", "snippet": "@Getter\npublic abstract class BlockPlacingModule extends PhobotModule implements ChecksBlockPlacingValidity, BlockPlacer.PlacesBlocks {\n private final Setting<Integer> delay = number(\"Delay\", 30, 0, 500, \"Delay between placements.\");\n private final Setting<Boolean> noGlitchBlocks = bool(\"NoGlitchBlocks\", false, \"Does not place a block on the clientside.\");\n private final StopWatch.ForSingleThread timer = new StopWatch.ForSingleThread();\n private final BlockPlacer blockPlacer;\n private final int priority;\n\n public BlockPlacingModule(Phobot phobot, BlockPlacer blockPlacer, String name, Nameable category, String description, int priority) {\n super(phobot, name, category, description);\n this.blockPlacer = blockPlacer;\n this.priority = priority;\n // TODO: clear blockplacer when unregistered etc!\n blockPlacer.getModules().add(this);\n }\n\n @Override\n public boolean isActive() {\n return isEnabled();\n }\n\n @Override\n public void update(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n if (!timer.passed(delay.getValue())) {\n return;\n }\n\n updatePlacements(context, player, level, gameMode);\n }\n\n protected abstract void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode);\n\n public boolean isUsingSetCarriedItem() {\n return true;\n }\n\n @SuppressWarnings(\"UnusedReturnValue\")\n public boolean placePos(BlockPos pos, Block block, LocalPlayer player, ClientLevel level) {\n for (BlockPlacer.Action action : blockPlacer.getActions()) {\n if (action.getPos().equals(pos)) {\n return true;\n }\n }\n\n if (!level.getWorldBorder().isWithinBounds(pos)) {\n return false;\n }\n\n BlockState state = level.getBlockState(pos);\n if (!state.canBeReplaced()) {\n return false;\n }\n\n Set<BlockPlacer.Action> dependencies = new HashSet<>();\n Direction direction = getDirection(level, player, pos, dependencies);\n if (direction == null) {\n return false;\n }\n\n // TODO: not necessary for crystalpvp.cc, but trace the proper checks in BlockItem, they are much more accurate\n BlockPos placeOn = pos.relative(direction);\n BlockState futureState = block.defaultBlockState(); // TODO: use this!!! block.getStateForPlacement(blockPlaceContext) though for the simple blocks on cc this should be fine for now\n VoxelShape shape = futureState.getCollisionShape(level, pos, blockPlacer.getCollisionContext());\n if (!shape.isEmpty() && isBlockedByEntity(pos, shape, player, level, entity -> false)) {\n return false;\n }\n\n BlockPlacer.Action action = new BlockPlacer.Action(this, placeOn.immutable(), pos.immutable(), direction.getOpposite(), block.asItem(), !noGlitchBlocks.getValue(), isUsingSetCarriedItem(),\n isUsingPacketRotations(), getBlockPlacer(), requiresExactDirection());\n action.getDependencies().addAll(dependencies);\n addAction(blockPlacer, action);\n return true;\n }\n\n protected boolean isUsingPacketRotations() {\n return false;\n }\n\n protected boolean requiresExactDirection() { // for special stuff like piston aura, bedaura etc. where where we place matters.\n return false;\n }\n\n protected void addAction(BlockPlacer placer, BlockPlacer.Action action) {\n placer.addAction(action);\n timer.reset();\n }\n\n protected void updateOutsideOfTick(LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n phobot.getInventoryService().use(context -> {\n getBlockPlacer().startTick(player, level);\n update(context, player, level, gameMode);\n getBlockPlacer().endTick(context, player, level);\n });\n }\n\n public enum Rotate {\n None,\n Rotate,\n Packets\n }\n\n}" }, { "identifier": "BlockPathfinder", "path": "src/main/java/me/earth/phobot/pathfinder/blocks/BlockPathfinder.java", "snippet": "public class BlockPathfinder {\n private final BlockNode center;\n\n public BlockPathfinder() {\n BlockNodePoolBuilder builder = new BlockNodePoolBuilder();\n builder.build(10/* this is not radius but manhattan radius basically */, BlockNode::new);\n this.center = Objects.requireNonNull(builder.getCenter(), \"PoolBuilder center was null!\");\n }\n\n public @NotNull List<BlockPos> getShortestPath(BlockPos target, Block block, Player player, ClientLevel level, int maxCost, ChecksBlockPlacingValidity module, BlockPlacer blockPlacer) {\n BiPredicate<BlockPos, BlockPos> validityCheck = getDefaultValidityCheck(block, player, level, module, blockPlacer);\n BiPredicate<BlockPos, @Nullable BlockPos> goalCheck = getDefaultGoalCheck(player, block, level, module);\n return getShortestPath(target, maxCost, validityCheck, goalCheck);\n }\n\n public @NotNull List<BlockPos> getShortestPath(BlockPos target, int maxCost, BiPredicate<BlockPos, BlockPos> validityCheck, BiPredicate<BlockPos, @Nullable BlockPos> goalCheck) {\n center.setToOffsetFromCenter(target);\n BlockPathfinderAlgorithm firstSearchNoHeuristic = new BlockPathfinderAlgorithm(center, validityCheck, goalCheck, target, maxCost);\n List<BlockNode> result = firstSearchNoHeuristic.run(Cancellation.UNCANCELLABLE);\n if (result != null) {\n return result.stream().map(BlockNode::getCurrent).map(BlockPos::immutable).collect(Collectors.toList());\n }\n\n return Collections.emptyList();\n }\n\n public BiPredicate<BlockPos, @Nullable BlockPos> getDefaultGoalCheck(Player player, Block block, ClientLevel level, ChecksBlockPlacingValidity module) {\n BlockStateLevel.Delegating blockStateLevel = new BlockStateLevel.Delegating(level);\n return (testPos, from) -> {\n if (module.isOutsideRange(testPos, player) || from != null && !strictDirectionCheck(from, testPos, block, module, player, blockStateLevel)) {\n return false;\n }\n\n return module.isValidPlacePos(testPos, level, player) || module.hasActionCreatingPlacePos(testPos, null, player, level, null);\n };\n }\n\n public BiPredicate<BlockPos, BlockPos> getDefaultValidityCheck(Block block, Player player, ClientLevel level, ChecksBlockPlacingValidity module, BlockPlacer blockPlacer) {\n BlockStateLevel.Delegating blockStateLevel = new BlockStateLevel.Delegating(level);\n return (currentPos, testPos) -> {\n if (!level.getWorldBorder().isWithinBounds(testPos) || module.isOutsideRange(testPos, player)) {\n return false;\n }\n\n VoxelShape shape = block.defaultBlockState().getCollisionShape(level, testPos, blockPlacer.getCollisionContext());\n if (shape.isEmpty() || !module.isBlockedByEntity(testPos, shape, player, level, entity -> false, ((placer, endCrystal) -> {/*do not set crystal*/}))) {\n return strictDirectionCheck(currentPos, testPos, block, module, player, blockStateLevel);\n }\n\n return false;\n };\n }\n\n private boolean strictDirectionCheck(BlockPos currentPos, BlockPos testPos, Block block, ChecksBlockPlacingValidity module, Player player, BlockStateLevel.Delegating level) {\n if (module.getBlockPlacer().getAntiCheat().getStrictDirection().getValue() != StrictDirection.Type.Vanilla) {\n Direction direction = getDirectionBetweenAdjacent(currentPos, testPos);\n level.getMap().clear();\n BlockState state = level.getLevel().getBlockState(testPos);\n if (state.isAir()/* TODO: || isFluid || isGoingToBeReplaced by us?!?!?!*/) {\n state = block.defaultBlockState();\n }\n\n level.getMap().put(testPos, state); // do the other blocks we placed for the path also play a role during the check?\n return module.getBlockPlacer().getAntiCheat().getStrictDirectionCheck().strictDirectionCheck(testPos, direction, level, player);\n }\n\n return true;\n }\n\n private Direction getDirectionBetweenAdjacent(BlockPos pos, BlockPos placeOn) {\n if (pos.getY() > placeOn.getY()) {\n return Direction.UP;\n } else if (pos.getY() < placeOn.getY()) {\n return Direction.DOWN;\n } else if (pos.getX() > placeOn.getX()) {\n return Direction.EAST;\n } else if (pos.getX() < placeOn.getX()) {\n return Direction.WEST;\n } else if (pos.getZ() > placeOn.getZ()) {\n return Direction.SOUTH;\n }\n\n return Direction.NORTH;\n }\n\n}" }, { "identifier": "BlockPathfinderWithBlacklist", "path": "src/main/java/me/earth/phobot/pathfinder/blocks/BlockPathfinderWithBlacklist.java", "snippet": "@RequiredArgsConstructor\npublic class BlockPathfinderWithBlacklist extends BlockPathfinder {\n private final Map<BlockPos, Long> blacklist;\n\n @Override\n public BiPredicate<BlockPos, BlockPos> getDefaultValidityCheck(Block block, Player player, ClientLevel level, ChecksBlockPlacingValidity module, BlockPlacer blockPlacer) {\n BiPredicate<BlockPos, BlockPos> predicate = super.getDefaultValidityCheck(block, player, level, module, blockPlacer);\n return (currentPos, testPos) -> !blacklist.containsKey(testPos) && predicate.test(currentPos, testPos);\n }\n}" }, { "identifier": "SurroundService", "path": "src/main/java/me/earth/phobot/services/SurroundService.java", "snippet": "@Getter\npublic class SurroundService extends SubscriberImpl {\n private final StopWatch.ForMultipleThreads lastSafe = new StopWatch.ForMultipleThreads();\n private final Surround surround;\n private Set<BlockPos> positions = new HashSet<>();\n private volatile boolean surrounded;\n\n public SurroundService(Surround surround) {\n this.surround = surround;\n listen(new SafeListener<PostMotionPlayerUpdateEvent>(surround.getPingBypass().getMinecraft()) {\n @Override\n public void onEvent(PostMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n surrounded = isSurrounded(surround.getPhobot().getLocalPlayerPositionService().getPlayerOnLastPosition(player));\n if (surrounded) {\n lastSafe.reset();\n }\n }\n });\n }\n\n public boolean isSurrounded(Player player) {\n LocalPlayer localPlayer = surround.getPingBypass().getMinecraft().player;\n if (localPlayer == null) {\n return false;\n }\n\n var positions = surround.getAllSurroundingPositions(player, localPlayer, localPlayer.clientLevel, Blocks.OBSIDIAN, false);\n positions.removeIf(pos -> pos.getY() < player.getY() - 0.5);\n this.positions = positions;\n // TODO: make this better, ensure blocks that cant be blown up\n return positions.stream().noneMatch(pos -> localPlayer.clientLevel.getBlockState(pos).getShape(localPlayer.clientLevel, pos).isEmpty());\n }\n\n}" }, { "identifier": "InventoryContext", "path": "src/main/java/me/earth/phobot/services/inventory/InventoryContext.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PACKAGE)\npublic class InventoryContext {\n public static final int DEFAULT_SWAP_SWITCH = 0;\n public static final int PREFER_MAINHAND = 1;\n public static final int SWITCH_BACK = 2;\n public static final int SET_CARRIED_ITEM = 4;\n public static final int SKIP_OFFHAND = 8;\n\n private final List<Switch> switches = new ArrayList<>();\n private final InventoryService inventoryService;\n private final LocalPlayer player;\n private final MultiPlayerGameMode gameMode;\n private HotbarSwitch hotbarSwitch;\n\n public @Nullable SwitchResult switchTo(Item item, int flags) {\n if (!(player.containerMenu instanceof InventoryMenu)) {\n return null;\n }\n\n if (player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT).getItem().is(item)) {\n return SwitchResult.get(player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT));\n } else if (getSelectedSlot().getItem().is(item)) {\n return SwitchResult.get(getSelectedSlot());\n }\n\n Slot slot = find(s -> s.getItem().is(item) ? s : null);\n return switchTo(slot, flags);\n }\n\n public @Nullable SwitchResult switchTo(@Nullable Slot slot, int flags) {\n if (slot != null) {\n if ((flags & SKIP_OFFHAND) == 0 && slot.index == InventoryMenu.SHIELD_SLOT) {\n return SwitchResult.get(player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT));\n } else if (slot.getContainerSlot() == player.getInventory().selected) {\n return SwitchResult.get(getSelectedSlot());\n }\n\n Slot targetSlot = player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT);\n boolean slotIsHotbar = isHotbar(slot);\n if ((flags & PREFER_MAINHAND) != 0 || (flags & SET_CARRIED_ITEM) != 0 && slotIsHotbar) {\n targetSlot = getSelectedSlot();\n }\n\n // TODO: prefer SwapSwitch if we are mining!\n Switch action = (flags & SET_CARRIED_ITEM) != 0 && slotIsHotbar && isHotbar(targetSlot)\n ? new HotbarSwitch(targetSlot, slot, (flags & SWITCH_BACK) != 0)\n : new SwapSwitch(slot, targetSlot, (flags & SWITCH_BACK) != 0);\n\n action.execute(this);\n if (action instanceof HotbarSwitch hs) {\n if (this.hotbarSwitch == null) {\n this.hotbarSwitch = hs;\n }\n } else {\n switches.add(action);\n }\n\n /* TODO: if (isHotbar(slot) && (... || anticheat flagged too many swaps)) -> HotbarSwitch*/\n return SwitchResult.get(targetSlot, action);\n }\n\n return null;\n }\n\n public void moveWithTwoClicks(Slot from, Slot to) {\n if (player.containerMenu instanceof InventoryMenu) {\n gameMode.handleInventoryMouseClick(player.containerMenu.containerId, from.index, Keys.MOUSE_1, ClickType.PICKUP, player);\n gameMode.handleInventoryMouseClick(player.containerMenu.containerId, to.index, Keys.MOUSE_1, ClickType.PICKUP, player);\n closeScreen();\n }\n }\n\n public void click(Slot slot) {\n if (player.containerMenu instanceof InventoryMenu) {\n gameMode.handleInventoryMouseClick(player.containerMenu.containerId, slot.index, Keys.MOUSE_1, ClickType.PICKUP, player);\n closeScreen();\n }\n }\n\n public void drop(Slot slot) {\n gameMode.handleInventoryMouseClick(player.inventoryMenu.containerId, slot.index, 0, ClickType.THROW, player);\n closeScreen();\n }\n\n public Slot getOffhand() {\n return player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT);\n }\n\n public static InteractionHand getHand(Slot slot) {\n return slot.index == InventoryMenu.SHIELD_SLOT ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;\n }\n\n public boolean has(Item... items) {\n return find(items) != null;\n }\n\n @SuppressWarnings({\"unchecked\", \"RedundantCast\"})\n public Item find(Item... items) {\n return (Item) find(Arrays.stream(items).map(this::findItemFunction).toArray(Function[]::new));\n }\n\n @SuppressWarnings({\"unchecked\", \"RedundantCast\"})\n public Block findBlock(Block... blocks) {\n return (Block) find(Arrays.stream(blocks).map(this::findBlockFunction).toArray(Function[]::new));\n }\n\n @SafeVarargs\n public final <T> @Nullable T find(Function<Slot, @Nullable T>... functions) {\n for (var function : functions) {\n T result = function.apply(player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT));\n if (result != null) {\n return result;\n }\n\n result = function.apply(getSelectedSlot());\n if (result != null) {\n return result;\n }\n\n for (int i = InventoryMenu.USE_ROW_SLOT_START; i < InventoryMenu.USE_ROW_SLOT_END; i++) {\n result = function.apply(player.inventoryMenu.getSlot(i));\n if (result != null) {\n return result;\n }\n }\n\n for (int i = InventoryMenu.INV_SLOT_START; i < InventoryMenu.INV_SLOT_END; i++) {\n result = function.apply(player.inventoryMenu.getSlot(i));\n if (result != null) {\n return result;\n }\n }\n\n for (int i = InventoryMenu.CRAFT_SLOT_START; i < InventoryMenu.CRAFT_SLOT_END; i++) {\n result = function.apply(player.inventoryMenu.getSlot(i));\n if (result != null) {\n return result;\n }\n }\n\n // TODO: carried slot\n }\n\n return null;\n }\n\n public int getCount(Predicate<ItemStack> check) {\n int count = 0;\n for (Slot slot : player.inventoryMenu.slots) {\n if (check.test(slot.getItem())) {\n count += slot.getItem().getCount();\n }\n }\n\n return count;\n }\n\n private int toInventoryMenuSlot(int slot) {\n if (slot == Inventory.SLOT_OFFHAND) {\n return InventoryMenu.SHIELD_SLOT;\n }\n\n if (slot >= 0 && slot < Inventory.getSelectionSize()/*9*/) {\n return InventoryMenu.USE_ROW_SLOT_START + slot;\n }\n\n if (slot < 0 || slot > InventoryMenu.USE_ROW_SLOT_END) {\n return Inventory.NOT_FOUND_INDEX;\n }\n\n return slot;\n }\n\n public Slot getSelectedSlot() {\n int slotIndex = toInventoryMenuSlot(player.getInventory().selected);\n if (slotIndex < InventoryMenu.USE_ROW_SLOT_START || slotIndex >= InventoryMenu.USE_ROW_SLOT_END) {\n slotIndex = InventoryMenu.USE_ROW_SLOT_START;\n }\n\n return player.inventoryMenu.getSlot(slotIndex);\n }\n\n public boolean isSelected(Slot slot) {\n return slot.getContainerSlot() == getSelectedSlot().getContainerSlot();\n }\n\n public boolean isOffHand(Slot slot) {\n return slot.getContainerSlot() == Inventory.SLOT_OFFHAND;\n }\n\n void end() {\n if (inventoryService.getSwitchBack().get() /* or was eating!!!*/) {\n for (int i = switches.size() - 1; i >= 0; i--) {\n Switch action = switches.get(i);\n if (!action.switchBack || !action.revert(this)) {\n break;\n }\n }\n\n if (hotbarSwitch != null && hotbarSwitch.switchBack) {\n hotbarSwitch.revert(this);\n }\n }\n }\n\n private void closeScreen() {\n if (inventoryService.getAntiCheat().getCloseInv().getValue() && player.containerMenu == player.inventoryMenu) {\n player.connection.send(new ServerboundContainerClosePacket(player.containerMenu.containerId));\n }\n }\n\n private Function<Slot, Block> findBlockFunction(Block block) {\n return slot -> slot.getItem().is(block.asItem()) && slot.getItem().getCount() != 0 ? block : null;\n }\n\n private Function<Slot, Item> findItemFunction(Item item) {\n return slot -> slot.getItem().is(item) && slot.getItem().getCount() != 0 ? item : null;\n }\n\n private static boolean isHotbar(Slot slot) {\n return slot.getContainerSlot() >= 0 && slot.getContainerSlot() < Inventory.getSelectionSize()/*9*/;\n }\n\n public record SwitchResult(Slot slot, InteractionHand hand, @Nullable Block block, @Nullable Switch action) {\n public static SwitchResult get(Slot slot) {\n return get(slot, null);\n }\n\n public static SwitchResult get(Slot slot, @Nullable Switch action) {\n return new SwitchResult(slot, getHand(slot), slot.getItem().getItem() instanceof BlockItem block ? block.getBlock() : null, action);\n }\n }\n\n @RequiredArgsConstructor\n public abstract static class Switch {\n protected final Slot from;\n protected final Slot to;\n protected final boolean switchBack;\n\n public abstract boolean execute(InventoryContext context, Slot from, Slot to);\n\n public boolean execute(InventoryContext context) {\n return execute(context, from, to);\n }\n\n public boolean revert(InventoryContext context) {\n return execute(context, to, from);\n }\n }\n\n public static class SwapSwitch extends Switch {\n public SwapSwitch(Slot from, Slot to, boolean silent) {\n super(from, to, silent);\n }\n\n @Override\n public boolean execute(InventoryContext context, Slot from, Slot to) {\n if (context.player.containerMenu instanceof InventoryMenu && (isHotbar(to) || to.getContainerSlot() == Inventory.SLOT_OFFHAND)) {\n context.gameMode.handleInventoryMouseClick(context.player.containerMenu.containerId, from.index, to.getContainerSlot(), ClickType.SWAP, context.player);\n context.closeScreen();\n return true;\n }\n\n return false;\n }\n\n @Override\n public boolean revert(InventoryContext context) {\n return execute(context, from, to);\n }\n }\n\n public static class HotbarSwitch extends Switch {\n public HotbarSwitch(Slot from, Slot to, boolean silent) {\n super(from, to, silent);\n }\n\n @Override\n public boolean execute(InventoryContext context, Slot from, Slot to) {\n if (isHotbar(to)) {\n context.player.getInventory().selected = to.getContainerSlot();\n // TODO: via reflection we could actually register an ASM transformer to make GameMode.carriedIndex volatile?!\n ((IMultiPlayerGameMode) context.gameMode).invokeEnsureHasSentCarriedItem();\n return true;\n }\n\n return false;\n }\n }\n\n}" }, { "identifier": "ResetUtil", "path": "src/main/java/me/earth/phobot/util/ResetUtil.java", "snippet": "@UtilityClass\npublic class ResetUtil {\n public static void disableOnRespawnAndWorldChange(Module module, Minecraft mc) {\n onRespawnOrWorldChange(module, mc, module::disable);\n }\n\n public static void onRespawnOrWorldChange(Subscriber module, Minecraft mc, Runnable runnable) {\n module.getListeners().add(new Listener<ChangeWorldEvent>() {\n @Override\n public void onEvent(ChangeWorldEvent event) {\n runnable.run();\n }\n });\n\n module.getListeners().add(new Listener<PacketEvent.Receive<ClientboundRespawnPacket>>() {\n @Override\n public void onEvent(PacketEvent.Receive<ClientboundRespawnPacket> event) {\n mc.submit(runnable);\n }\n });\n }\n\n}" }, { "identifier": "EntityUtil", "path": "src/main/java/me/earth/phobot/util/entity/EntityUtil.java", "snippet": "@UtilityClass\npublic class EntityUtil {\n public static final double RANGE = 6.0;\n public static final double RANGE_SQ = ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE;\n\n public static boolean isDead(LivingEntity entity) {\n return !entity.isAlive() || entity.isDeadOrDying();\n }\n\n public static float getHealth(LivingEntity entity) {\n return entity.getHealth() + entity.getAbsorptionAmount();\n }\n\n public static boolean isEnemyInRange(PingBypass pingBypass, Player self, Player player, double range) {\n return isEnemy(pingBypass, self, player) && self.distanceToSqr(player) <= range * range;\n }\n\n public static boolean isEnemy(PingBypass pingBypass, Player self, Player player) {\n return player != null && !isDead(player) && !self.equals(player) && !pingBypass.getFriendManager().contains(player.getUUID());\n }\n\n public static Iterable<EndCrystal> getCrystalsInRange(Player player, ClientLevel level) {\n return level.getEntities(EntityType.END_CRYSTAL, PositionUtil.getAABBOfRadius(player, 8.0),\n endCrystal -> endCrystal.isAlive()\n && isInAttackRange(player, endCrystal)\n && level.getWorldBorder().isWithinBounds(endCrystal.blockPosition()));\n }\n\n public static boolean isInAttackRange(Player player, Entity entity) {\n return entity.getBoundingBox().distanceToSqr(player.getEyePosition()) < RANGE_SQ;\n }\n\n}" } ]
import lombok.Getter; import me.earth.phobot.Phobot; import me.earth.phobot.modules.BlockPlacingModule; import me.earth.phobot.pathfinder.blocks.BlockPathfinder; import me.earth.phobot.pathfinder.blocks.BlockPathfinderWithBlacklist; import me.earth.phobot.services.SurroundService; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.entity.EntityUtil; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.api.setting.Setting; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap;
6,701
package me.earth.phobot.modules.combat; @Getter public class AutoTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<PacketRotationMode> packetRotations = constant("PacketRotations", PacketRotationMode.None, "Sends additional packets to rotate, might lag back," + "but allows you to place more blocks in one tick. With Mode Surrounded this will only happen when you are surrounded, so that you do not have to worry about lagbacks."); private final Setting<Integer> maxHelping = number("Helping", 3, 1, 10, "Amount of helping blocks to use."); private final Map<BlockPos, Long> blackList = new ConcurrentHashMap<>(); private final BlockPathfinder blockPathfinder = new BlockPathfinderWithBlacklist(blackList); private final SurroundService surroundService; public AutoTrap(Phobot phobot, SurroundService surroundService) { super(phobot, phobot.getBlockPlacer(), "AutoTrap", Categories.COMBAT, "Traps other players.", 5); this.surroundService = surroundService; listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { Block block = context.findBlock(Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN); if (block == null) { return; } Set<BlockPos> allCurrentPositions = new HashSet<>(); for (Player enemy : level.players()) {
package me.earth.phobot.modules.combat; @Getter public class AutoTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<PacketRotationMode> packetRotations = constant("PacketRotations", PacketRotationMode.None, "Sends additional packets to rotate, might lag back," + "but allows you to place more blocks in one tick. With Mode Surrounded this will only happen when you are surrounded, so that you do not have to worry about lagbacks."); private final Setting<Integer> maxHelping = number("Helping", 3, 1, 10, "Amount of helping blocks to use."); private final Map<BlockPos, Long> blackList = new ConcurrentHashMap<>(); private final BlockPathfinder blockPathfinder = new BlockPathfinderWithBlacklist(blackList); private final SurroundService surroundService; public AutoTrap(Phobot phobot, SurroundService surroundService) { super(phobot, phobot.getBlockPlacer(), "AutoTrap", Categories.COMBAT, "Traps other players.", 5); this.surroundService = surroundService; listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { Block block = context.findBlock(Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN); if (block == null) { return; } Set<BlockPos> allCurrentPositions = new HashSet<>(); for (Player enemy : level.players()) {
if (EntityUtil.isEnemyInRange(getPingBypass(), player, enemy, 7.0)) {
7
2023-12-22 14:32:16+00:00
8k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/handlers/OpenLink.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"2.0\";\n\n Minecraft mc = Minecraft.getMinecraft();\n public static Logger logger;\n\n public static JsonObject roomsJson;\n public static JsonObject waypointsJson;\n static boolean updateChecked = false;\n public static boolean usingSBPSecrets = false;\n public static String guiToOpen = null;\n public static KeyBinding[] keyBindings = new KeyBinding[2];\n public static String hotkeyOpen = \"gui\";\n static int tickAmount = 1;\n public static List<String> motd = null;\n\n @EventHandler\n public void preInit(final FMLPreInitializationEvent event) {\n ClientCommandHandler.instance.registerCommand(new DungeonRoomCommand());\n logger = LogManager.getLogger(\"DungeonRooms\");\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(new AutoRoom());\n MinecraftForge.EVENT_BUS.register(new Waypoints());\n\n ConfigHandler.reloadConfig();\n\n try {\n ResourceLocation roomsLoc = new ResourceLocation( \"dungeonrooms\",\"dungeonrooms.json\");\n InputStream roomsIn = Minecraft.getMinecraft().getResourceManager().getResource(roomsLoc).getInputStream();\n BufferedReader roomsReader = new BufferedReader(new InputStreamReader(roomsIn));\n\n ResourceLocation waypointsLoc = new ResourceLocation( \"dungeonrooms\",\"secretlocations.json\");\n InputStream waypointsIn = Minecraft.getMinecraft().getResourceManager().getResource(waypointsLoc).getInputStream();\n BufferedReader waypointsReader = new BufferedReader(new InputStreamReader(waypointsIn));\n\n Gson gson = new Gson();\n roomsJson = gson.fromJson(roomsReader, JsonObject.class);\n logger.info(\"DungeonRooms: Loaded dungeonrooms.json\");\n\n waypointsJson = gson.fromJson(waypointsReader, JsonObject.class);\n logger.info(\"DungeonRooms: Loaded secretlocations.json\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n keyBindings[0] = new KeyBinding(\"Open Room Images in DSG/SBP\", Keyboard.KEY_O, \"FakepixelDungeonHelper Mod\");\n keyBindings[1] = new KeyBinding(\"Open Waypoint Menu\", Keyboard.KEY_P, \"FakepixelDungeonHelper Mod\");\n for (KeyBinding keyBinding : keyBindings) {\n ClientRegistry.registerKeyBinding(keyBinding);\n }\n }\n\n @EventHandler\n public void postInit(final FMLPostInitializationEvent event) {\n usingSBPSecrets = Loader.isModLoaded(\"sbp\");\n DungeonRooms.logger.info(\"FDH: SBP Dungeon Secrets detection: \" + usingSBPSecrets);\n }\n\n /*\n Update Checker taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/).\n This code was released under GNU General Public License v3.0 and remains under said license.\n Modified by Quantizr (_risk) in Feb. 2021.\n */\n @SubscribeEvent\n public void onJoin(EntityJoinWorldEvent event) {\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n\n if (!updateChecked) {\n updateChecked = true;\n\n // MULTI THREAD DRIFTING\n new Thread(() -> {\n try {\n DungeonRooms.logger.info(\"FDH: Checking for updates...\");\n\n URL url = new URL(\"https://discord.com/fakepixel\");\n URLConnection request = url.openConnection();\n request.connect();\n JsonParser json = new JsonParser();\n JsonObject latestRelease = json.parse(new InputStreamReader((InputStream) request.getContent())).getAsJsonObject();\n\n String latestTag = latestRelease.get(\"tag_name\").getAsString();\n DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(VERSION);\n DefaultArtifactVersion latestVersion = new DefaultArtifactVersion(latestTag.substring(1));\n\n if (currentVersion.compareTo(latestVersion) < 0) {\n String releaseURL = \"https://discord.gg/Fakepixel\";\n ChatComponentText update = new ChatComponentText(EnumChatFormatting.GREEN + \"\" + EnumChatFormatting.BOLD + \" [UPDATE] \");\n update.setChatStyle(update.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, releaseURL)));\n\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"FakepixelDungeonHelper Mod is outdated. Please update to \" + latestTag + \".\\n\").appendSibling(update));\n }\n } catch (IOException e) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"An error has occured. See logs for more details.\"));\n e.printStackTrace();\n }\n\n try {\n URL url = new URL(\"https://gist.githubusercontent.com/Quantizr/0af2afd91cd8b1aa22e42bc2d65cfa75/raw/\");\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n String line;\n motd = new ArrayList<>();\n while ((line = in.readLine()) != null) {\n motd.add(line);\n }\n in.close();\n } catch (IOException e) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"An error has occured. See logs for more details.\"));\n e.printStackTrace();\n }\n }).start();\n }\n }\n\n @SubscribeEvent\n public void renderPlayerInfo(final RenderGameOverlayEvent.Post event) {\n if (event.type != RenderGameOverlayEvent.ElementType.ALL) return;\n if (Utils.inDungeons) {\n if (AutoRoom.guiToggled) {\n AutoRoom.renderText();\n }\n if (AutoRoom.coordToggled) {\n AutoRoom.renderCoord();\n }\n }\n }\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (event.phase != TickEvent.Phase.START) return;\n World world = mc.theWorld;\n EntityPlayerSP player = mc.thePlayer;\n\n tickAmount++;\n\n // Checks every second\n if (tickAmount % 20 == 0) {\n if (player != null) {\n Utils.checkForSkyblock();\n Utils.checkForDungeons();\n tickAmount = 0;\n }\n }\n }\n\n @SubscribeEvent\n public void onKey(InputEvent.KeyInputEvent event) {\n EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;\n if (keyBindings[0].isPressed()) {\n if (!Utils.inDungeons) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: Use this hotkey in dungeons\"));\n return;\n }\n switch (hotkeyOpen) {\n case \"gui\":\n OpenLink.checkForLink(\"gui\");\n break;\n case \"dsg\":\n OpenLink.checkForLink(\"dsg\");\n break;\n case \"sbp\":\n OpenLink.checkForLink(\"sbp\");\n break;\n default:\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: hotkeyOpen config value improperly set, do \\\"/room set <gui | dsg | sbp>\\\" to change the value\"));\n break;\n }\n }\n if (keyBindings[1].isPressed()) {\n DungeonRooms.guiToOpen = \"waypoints\";\n }\n }\n\n // Delay GUI by 1 tick\n @SubscribeEvent\n public void onRenderTick(TickEvent.RenderTickEvent event) {\n if (guiToOpen != null) {\n switch (guiToOpen) {\n case \"link\":\n mc.displayGuiScreen(new LinkGUI());\n break;\n case \"waypoints\":\n mc.displayGuiScreen(new WaypointsGUI());\n break;\n }\n guiToOpen = null;\n }\n }\n}" }, { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatToggled = false;\n public static boolean guiToggled = true;\n public static boolean coordToggled = false;\n public static String lastRoomHash = null;\n public static JsonObject lastRoomJson;\n public static String lastRoomName = null;\n private static boolean newRoom = false;\n public static int worldLoad = 0;\n\n public static int scaleX = 50;\n public static int scaleY = 5;\n\n private final Executor executor = Executors.newFixedThreadPool(5);\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (event.phase != TickEvent.Phase.START) return;\n World world = mc.theWorld;\n EntityPlayerSP player = mc.thePlayer;\n\n tickAmount++;\n if (worldLoad < 200) { //10 seconds\n worldLoad++;\n }\n\n // Checks every 1.5 seconds\n if (tickAmount % 30 == 0 && Utils.inDungeons && worldLoad == 200) {\n executor.execute(() -> {\n if (AutoRoom.chatToggled || AutoRoom.guiToggled || Waypoints.enabled){\n List<String> autoText = autoText();\n if (autoText != null) {\n autoTextOutput = autoText;\n }\n }\n if (AutoRoom.chatToggled) {\n toggledChat();\n }\n });\n tickAmount = 0;\n }\n }\n\n @SubscribeEvent\n public void onWorldChange(WorldEvent.Load event) {\n Utils.inDungeons = false;\n Utils.originBlock = null;\n Utils.originCorner = null;\n worldLoad = 0;\n Waypoints.allSecretsMap.clear();\n\n Random random = new Random();\n List<String> output = new ArrayList<>();\n\n if (random.nextBoolean()) {\n if (DungeonRooms.motd != null) {\n if (!DungeonRooms.motd.isEmpty()) {\n output.addAll(DungeonRooms.motd);\n }\n }\n }\n if (output.isEmpty()) {\n output.add(\"FDH: \" + EnumChatFormatting.GREEN+ \"Press the hotkey \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[1].getKeyCode()) +\"\\\" to configure\");\n output.add(EnumChatFormatting.GREEN + \"Secret Waypoints settings.\");\n output.add(EnumChatFormatting.WHITE + \"(You can change the keybinds in Minecraft controls menu)\");\n }\n autoTextOutput = output;\n\n }\n\n @SubscribeEvent\n public void onWorldUnload(WorldEvent.Unload event) {\n Utils.inDungeons = false;\n }\n\n public static List<String> autoText() {\n List<String> output = new ArrayList<>();\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n int x = (int) Math.floor(player.posX);\n int y = (int) Math.floor(player.posY);\n int z = (int) Math.floor(player.posZ);\n\n int top = Utils.dungeonTop(x, y, z);\n String blockFrequencies = Utils.blockFrequency(x, top, z, true);\n if (blockFrequencies == null) return output; //if not in room (under hallway or render distance too low)\n String MD5 = Utils.getMD5(blockFrequencies);\n String floorFrequencies = Utils.floorFrequency(x, top, z);\n String floorHash = Utils.getMD5(floorFrequencies);\n String text = \"FDH: You are in \" + EnumChatFormatting.GREEN;\n\n if (MD5.equals(\"16370f79b2cad049096f881d5294aee6\") && !floorHash.equals(\"94fb12c91c4b46bd0c254edadaa49a3d\")) {\n floorHash = \"e617eff1d7b77faf0f8dd53ec93a220f\"; //exception for box room because floorhash changes when you walk on it\n }\n\n if (MD5.equals(lastRoomHash) && lastRoomJson != null && floorHash != null) {\n if (lastRoomJson.get(\"floorhash\") != null) {\n if (floorHash.equals(lastRoomJson.get(\"floorhash\").getAsString())) {\n newRoom = false;\n return null;\n }\n } else {\n newRoom = false;\n return null;\n }\n }\n\n newRoom = true;\n lastRoomHash = MD5;\n //Setting this to true may prevent waypoint flicker, but may cause waypoints to break if Hypixel bugs out\n Waypoints.allFound = false;\n\n if (DungeonRooms.roomsJson.get(MD5) == null && Utils.getSize(x,top,z).equals(\"1x1\")) {\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"FDH: If you see this message in game (and did not create ghost blocks), send a\");\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"screenshot and the room name to #bug-report channel in the Discord\");\n output.add(EnumChatFormatting.AQUA + MD5);\n output.add(EnumChatFormatting.AQUA + floorHash);\n output.add(\"FDH: You are probably in: \");\n output.add(EnumChatFormatting.GREEN + \"Literally no idea, all the rooms should have been found\");\n lastRoomJson = null;\n return output;\n } else if (DungeonRooms.roomsJson.get(MD5) == null) {\n lastRoomJson = null;\n return output;\n }\n\n JsonArray MD5Array = DungeonRooms.roomsJson.get(MD5).getAsJsonArray();\n int arraySize = MD5Array.size();\n\n if (arraySize >= 2) {\n boolean floorHashFound = false;\n List<String> chatMessages = new ArrayList<>();\n\n for(int i = 0; i < arraySize; i++){\n JsonObject roomObject = MD5Array.get(i).getAsJsonObject();\n JsonElement jsonFloorHash = roomObject.get(\"floorhash\");\n if (floorHash != null && jsonFloorHash != null){\n if (floorHash.equals(jsonFloorHash.getAsString())){\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n output.add(text + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n output.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n lastRoomJson = roomObject;\n floorHashFound = true;\n }\n } else {\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n chatMessages.add(EnumChatFormatting.GREEN + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n chatMessages.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n }\n }\n if (!floorHashFound) {\n output.add(\"FDH: You are probably in one of the following: \");\n output.add(EnumChatFormatting.AQUA + \"(check # of secrets to narrow down rooms)\");\n output.addAll(chatMessages);\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"FDH: If you see this message in game (and did not create ghost blocks), send a\");\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"screenshot and the room name to #bug-report channel in the Discord\");\n output.add(EnumChatFormatting.AQUA + MD5);\n output.add(EnumChatFormatting.AQUA + floorHash);\n lastRoomJson = null;\n }\n } else {\n JsonObject roomObject = MD5Array.get(0).getAsJsonObject();\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n output.add(text + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n output.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n lastRoomJson = roomObject;\n }\n\n //Store/Retrieve which waypoints to enable\n if (lastRoomJson != null && lastRoomJson.get(\"name\") != null) {\n lastRoomName = lastRoomJson.get(\"name\").getAsString();\n Waypoints.allSecretsMap.putIfAbsent(lastRoomName, new ArrayList<>(Collections.nCopies(9, true)));\n Waypoints.secretsList = Waypoints.allSecretsMap.get(lastRoomName);\n } else {\n lastRoomName = null;\n }\n\n return output;\n }\n\n public static void toggledChat() {\n if (!newRoom) return;\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n if (autoTextOutput == null) return;\n if (autoTextOutput.isEmpty()) return;\n for (String message:autoTextOutput) {\n player.addChatMessage(new ChatComponentText(message));\n }\n }\n\n public static void renderText() {\n if (autoTextOutput == null) return;\n if (autoTextOutput.isEmpty()) return;\n Minecraft mc = Minecraft.getMinecraft();\n ScaledResolution scaledResolution = new ScaledResolution(mc);\n int y = 0;\n for (String message:autoTextOutput) {\n int roomStringWidth = mc.fontRendererObj.getStringWidth(message);\n TextRenderer.drawText(mc, message, ((scaledResolution.getScaledWidth() * scaleX) / 100) - (roomStringWidth / 2),\n ((scaledResolution.getScaledHeight() * scaleY) / 100) + y, 1D, true);\n y += mc.fontRendererObj.FONT_HEIGHT;\n }\n }\n\n public static void renderCoord() {\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayerSP player = mc.thePlayer;\n ScaledResolution scaledResolution = new ScaledResolution(mc);\n\n BlockPos relativeCoord = Utils.actualToRelative(new BlockPos(player.posX,player.posY,player.posZ));\n if (relativeCoord == null) return;\n\n List<String> coordDisplay = new ArrayList<>();\n coordDisplay.add(\"Direction: \" + Utils.originCorner);\n coordDisplay.add(\"Origin: \" + Utils.originBlock.getX() + \",\" + Utils.originBlock.getY() + \",\" + Utils.originBlock.getZ());\n coordDisplay.add(\"Relative Pos.: \"+ relativeCoord.getX() + \",\" + relativeCoord.getY() + \",\" + relativeCoord.getZ());\n int yPos = 0;\n for (String message:coordDisplay) {\n int roomStringWidth = mc.fontRendererObj.getStringWidth(message);\n TextRenderer.drawText(mc, message, ((scaledResolution.getScaledWidth() * 95) / 100) - (roomStringWidth),\n ((scaledResolution.getScaledHeight() * 5) / 100) + yPos, 1D, true);\n yPos += mc.fontRendererObj.FONT_HEIGHT;\n }\n }\n}" } ]
import io.github.quantizr.DungeonRooms; import io.github.quantizr.core.AutoRoom; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.event.ClickEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.client.ClientCommandHandler; import net.minecraftforge.fml.client.FMLClientHandler; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List;
5,523
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM 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. DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.handlers; public class OpenLink { public static void checkForLink(String type){ Minecraft mc = Minecraft.getMinecraft(); EntityPlayerSP player = mc.thePlayer; if (!AutoRoom.chatToggled && !AutoRoom.guiToggled){ List<String> autoText = AutoRoom.autoText(); if (autoText != null) { AutoRoom.autoTextOutput = autoText; } } if (AutoRoom.lastRoomHash == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: You do not appear to be in a detected Dungeon room right now.")); return; } if (AutoRoom.lastRoomJson == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: This command does not work when the current room is detected as one of multiple.")); return; } if (AutoRoom.lastRoomJson.get("dsg").getAsString().equals("null") && AutoRoom.lastRoomJson.get("sbp") == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: There are no channels/images for this room.")); return; } switch (type) { case "gui":
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM 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. DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.handlers; public class OpenLink { public static void checkForLink(String type){ Minecraft mc = Minecraft.getMinecraft(); EntityPlayerSP player = mc.thePlayer; if (!AutoRoom.chatToggled && !AutoRoom.guiToggled){ List<String> autoText = AutoRoom.autoText(); if (autoText != null) { AutoRoom.autoTextOutput = autoText; } } if (AutoRoom.lastRoomHash == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: You do not appear to be in a detected Dungeon room right now.")); return; } if (AutoRoom.lastRoomJson == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: This command does not work when the current room is detected as one of multiple.")); return; } if (AutoRoom.lastRoomJson.get("dsg").getAsString().equals("null") && AutoRoom.lastRoomJson.get("sbp") == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: There are no channels/images for this room.")); return; } switch (type) { case "gui":
DungeonRooms.guiToOpen = "link";
0
2023-12-22 04:44:39+00:00
8k
R2turnTrue/chzzk4j
src/test/java/ChannelApiTest.java
[ { "identifier": "Chzzk", "path": "src/main/java/xyz/r2turntrue/chzzk4j/Chzzk.java", "snippet": "public class Chzzk {\n public static String API_URL = \"https://api.chzzk.naver.com\";\n public static String GAME_API_URL = \"https://comm-api.game.naver.com/nng_main\";\n\n public boolean isDebug = false;\n\n private String nidAuth;\n private String nidSession;\n private boolean isAnonymous;\n\n private OkHttpClient httpClient;\n private Gson gson;\n\n Chzzk(ChzzkBuilder chzzkBuilder) {\n this.nidAuth = chzzkBuilder.nidAuth;\n this.nidSession = chzzkBuilder.nidSession;\n this.isAnonymous = chzzkBuilder.isAnonymous;\n this.gson = new Gson();\n\n OkHttpClient.Builder httpBuilder = new OkHttpClient().newBuilder();\n\n if (!chzzkBuilder.isAnonymous) {\n httpBuilder.addInterceptor(chain -> {\n Request original = chain.request();\n Request authorized = original.newBuilder()\n .addHeader(\"Cookie\",\n \"NID_AUT=\" + chzzkBuilder.nidAuth + \"; \" +\n \"NID_SES=\" + chzzkBuilder.nidSession)\n .build();\n\n return chain.proceed(authorized);\n });\n }\n\n httpClient = httpBuilder.build();\n }\n\n /**\n * Get this {@link Chzzk} logged in.\n */\n public boolean isLoggedIn() {\n return !isAnonymous;\n }\n\n /**\n * Get new an instance of {@link ChzzkChat} with this {@link Chzzk}.\n */\n public ChzzkChat chat() {\n return new ChzzkChat(this);\n }\n\n public OkHttpClient getHttpClient() {\n return httpClient;\n }\n\n /**\n * Get {@link ChzzkChannel} by the channel id.\n *\n * @param channelId ID of {@link ChzzkChannel} that to get.\n * @return {@link ChzzkChannel} to get\n * @throws IOException if the request to API failed\n * @throws ChannelNotExistsException if the channel doesn't exists\n */\n public ChzzkChannel getChannel(String channelId) throws IOException, ChannelNotExistsException {\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(API_URL + \"/service/v1/channels/\" + channelId).build());\n\n ChzzkChannel channel = gson.fromJson(\n contentJson,\n ChzzkChannel.class);\n\n if (channel.getChannelId() == null) {\n throw new ChannelNotExistsException(\"The channel does not exists!\");\n }\n\n return channel;\n }\n\n /**\n * Get channel's {@link ChzzkChannelRules} by the channel id.\n *\n * @param channelId ID of {@link ChzzkChannel}\n * @return {@link ChzzkChannelRules} of the channel\n * @throws IOException if the request to API failed\n * @throws NotExistsException if the channel doesn't exists or the rules of the channel doesn't available\n */\n public ChzzkChannelRules getChannelChatRules(String channelId) throws IOException, NotExistsException {\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(API_URL + \"/service/v1/channels/\" + channelId + \"/chat-rules\").build());\n\n ChzzkChannelRules rules = gson.fromJson(\n contentJson,\n ChzzkChannelRules.class);\n\n if (rules.getUpdatedDate() == null) {\n throw new NotExistsException(\"The channel or rules of the channel does not exists!\");\n }\n\n return rules;\n }\n\n /**\n * Get following status about channel.\n *\n * @param channelId ID of {@link ChzzkChannel} to get following status\n * @return user's {@link ChzzkChannelFollowingData} of the channel\n * @throws IOException if the request to API failed\n * @throws NotLoggedInException if this {@link Chzzk} didn't log in\n * @throws ChannelNotExistsException if the channel doesn't exists\n */\n public ChzzkChannelFollowingData getFollowingStatus(String channelId) throws IOException, NotLoggedInException, ChannelNotExistsException {\n if (isAnonymous) {\n throw new NotLoggedInException(\"Can't get following status without logging in!\");\n }\n\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(API_URL + \"/service/v1/channels/\" + channelId + \"/follow\").build());\n\n ChzzkFollowingStatusResponse followingDataResponse = gson.fromJson(\n contentJson,\n ChzzkFollowingStatusResponse.class);\n\n if (followingDataResponse.channel.getChannelId() == null) {\n throw new NotExistsException(\"The channel does not exists!\");\n }\n\n return followingDataResponse.channel.getPersonalData().getFollowing();\n }\n\n /**\n * Get {@link ChzzkUser} that the {@link Chzzk} logged in.\n *\n * @return {@link ChzzkUser} that current logged in\n * @throws IOException if the request to API failed\n * @throws NotLoggedInException if this {@link Chzzk} didn't log in\n */\n public ChzzkUser getLoggedUser() throws IOException, NotLoggedInException {\n if (isAnonymous) {\n throw new NotLoggedInException(\"Can't get information of logged user without logging in!\");\n }\n\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(GAME_API_URL + \"/v1/user/getUserStatus\").build());\n\n ChzzkUser user = gson.fromJson(\n contentJson,\n ChzzkUser.class);\n\n return user;\n }\n}" }, { "identifier": "ChzzkBuilder", "path": "src/main/java/xyz/r2turntrue/chzzk4j/ChzzkBuilder.java", "snippet": "public class ChzzkBuilder {\n boolean isAnonymous = false;\n String nidAuth;\n String nidSession;\n\n /**\n * Creates a new {@link ChzzkBuilder} that not logged in.\n */\n public ChzzkBuilder() {\n this.isAnonymous = true;\n }\n\n /**\n * Creates a new {@link ChzzkBuilder} that logged in.\n * To build an instance of {@link Chzzk} that logged in, we must have\n * the values of NID_AUT and NID_SES cookies.<br>\n *\n * You can get that values from developer tools of your browser.<br>\n * In Chrome, you can see the values from\n * {@code Application > Cookies > https://chzzk.naver.com}\n *\n * @param nidAuth The value of NID_AUT cookie\n * @param nidSession The value of NID_SES cookie\n */\n public ChzzkBuilder(String nidAuth, String nidSession) {\n this.nidAuth = nidAuth;\n this.nidSession = nidSession;\n }\n\n public Chzzk build() {\n return new Chzzk(this);\n }\n}" }, { "identifier": "ChannelNotExistsException", "path": "src/main/java/xyz/r2turntrue/chzzk4j/exception/ChannelNotExistsException.java", "snippet": "public class ChannelNotExistsException extends NotExistsException {\n /**\n * Constructs an {@code ChannelNotExistsException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n */\n public ChannelNotExistsException(String reason) {\n super(reason);\n }\n}" }, { "identifier": "NotExistsException", "path": "src/main/java/xyz/r2turntrue/chzzk4j/exception/NotExistsException.java", "snippet": "public class NotExistsException extends InvalidObjectException {\n /**\n * Constructs an {@code NotExistsException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n */\n public NotExistsException(String reason) {\n super(reason);\n }\n}" }, { "identifier": "NotLoggedInException", "path": "src/main/java/xyz/r2turntrue/chzzk4j/exception/NotLoggedInException.java", "snippet": "public class NotLoggedInException extends Exception {\n public NotLoggedInException(String reason) {\n super(reason);\n }\n}" }, { "identifier": "ChzzkUser", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/ChzzkUser.java", "snippet": "public class ChzzkUser {\n private boolean hasProfile;\n private String userIdHash;\n private String nickname;\n private String profileImageUrl;\n private Object[] penalties; // unknown\n private boolean officialNotiAgree;\n private String officialNotiAgreeUpdatedDate;\n private boolean verifiedMark;\n private boolean loggedIn;\n\n private ChzzkUser() {}\n\n /**\n * Get the user has profile.\n */\n public boolean isHasProfile() {\n return hasProfile;\n }\n\n /**\n * Get the user's id.\n */\n public String getUserId() {\n return userIdHash;\n }\n\n /**\n * Get the nickname of the user.\n */\n public String getNickname() {\n return nickname;\n }\n\n /**\n * Get url of the user's profile image.\n */\n public String getProfileImageUrl() {\n return profileImageUrl;\n }\n\n /**\n * Get user agreed to official notification.\n */\n public boolean isOfficialNotiAgree() {\n return officialNotiAgree;\n }\n\n /**\n * Get when user agreed to official notification in ISO-8601 format.\n */\n @Nullable\n public String getOfficialNotiAgreeUpdatedDate() {\n return officialNotiAgreeUpdatedDate;\n }\n\n /**\n * Get user has verified mark.\n */\n public boolean isVerifiedMark() {\n return verifiedMark;\n }\n\n @Override\n public String toString() {\n return \"ChzzkUser{\" +\n \"hasProfile=\" + hasProfile +\n \", userIdHash='\" + userIdHash + '\\'' +\n \", nickname='\" + nickname + '\\'' +\n \", profileImageUrl='\" + profileImageUrl + '\\'' +\n \", penalties=\" + Arrays.toString(penalties) +\n \", officialNotiAgree=\" + officialNotiAgree +\n \", officialNotiAgreeUpdatedDate='\" + officialNotiAgreeUpdatedDate + '\\'' +\n \", verifiedMark=\" + verifiedMark +\n \", loggedIn=\" + loggedIn +\n '}';\n }\n}" }, { "identifier": "ChzzkChannel", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/channel/ChzzkChannel.java", "snippet": "public class ChzzkChannel extends ChzzkPartialChannel {\n private String channelDescription;\n private int followerCount;\n private boolean openLive;\n\n private ChzzkChannel() {\n super();\n }\n\n /**\n * Get description of the channel.\n */\n public String getChannelDescription() {\n return channelDescription;\n }\n\n /**\n * Get the count of the channel's followers.\n */\n public int getFollowerCount() {\n return followerCount;\n }\n\n /**\n * Get is the channel broadcasting.\n */\n public boolean isBroadcasting() {\n return openLive;\n }\n\n @Override\n public String toString() {\n return \"ChzzkChannel{\" +\n \"parent=\" + super.toString() +\n \", channelDescription='\" + channelDescription + '\\'' +\n \", followerCount=\" + followerCount +\n \", openLive=\" + openLive +\n '}';\n }\n}" }, { "identifier": "ChzzkChannelFollowingData", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/channel/ChzzkChannelFollowingData.java", "snippet": "public class ChzzkChannelFollowingData {\n private boolean following;\n private boolean notification;\n private String followDate;\n\n private ChzzkChannelFollowingData() {}\n\n /**\n * Get is me following the channel.\n */\n public boolean isFollowing() {\n return following;\n }\n\n /**\n * Get is me enabled the channel notification.\n */\n public boolean isEnabledNotification() {\n return notification;\n }\n\n /**\n * Get when me followed the channel in yyyy-mm-dd HH:mm:ss format.\n */\n public String getFollowDate() {\n return followDate;\n }\n\n @Override\n public String toString() {\n return \"ChzzkChannelFollowingData{\" +\n \"following=\" + following +\n \", notification=\" + notification +\n \", followDate='\" + followDate + '\\'' +\n '}';\n }\n}" }, { "identifier": "ChzzkChannelRules", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/channel/ChzzkChannelRules.java", "snippet": "public class ChzzkChannelRules {\n private boolean agree;\n private String channelId;\n private String rule;\n private String updatedDate;\n private boolean serviceAgree;\n\n private ChzzkChannelRules() {}\n\n /**\n * Get the user is agreed to the rules of channel.\n */\n public boolean isAgree() {\n return agree;\n }\n\n /**\n * Get the id of channel.\n */\n public String getChannelId() {\n return channelId;\n }\n\n /**\n * Get the rule string of channel.\n */\n public String getRule() {\n return rule;\n }\n\n /**\n * Get when the rule updated in yyyy-mm-dd HH:mm:ss format.\n */\n public String getUpdatedDate() {\n return updatedDate;\n }\n\n /**\n * Get the user is agreed to the rules of channel.\n */\n public boolean isServiceAgree() {\n return serviceAgree;\n }\n\n @Override\n public String toString() {\n return \"ChzzkChannelRules{\" +\n \"agree=\" + agree +\n \", channelId='\" + channelId + '\\'' +\n \", rule='\" + rule + '\\'' +\n \", updatedDate='\" + updatedDate + '\\'' +\n \", serviceAgree=\" + serviceAgree +\n '}';\n }\n}" } ]
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import xyz.r2turntrue.chzzk4j.Chzzk; import xyz.r2turntrue.chzzk4j.ChzzkBuilder; import xyz.r2turntrue.chzzk4j.exception.ChannelNotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotLoggedInException; import xyz.r2turntrue.chzzk4j.types.ChzzkUser; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelFollowingData; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelRules;
4,234
// 8e7a6f0a0b1f0612afee1a673e94027d - 레고칠칠 // c2186ca6edb3a663f137b15ed7346fac - 리얼진짜우왁굳 // 두 채널 모두 팔로우한 뒤 테스트 진행해주세요. // // 22bd842599735ae19e454983280f611e - ENCHANT // 위 채널은 팔로우 해제 후 테스트 진행해주세요. public class ChannelApiTest extends ChzzkTestBase { public final String FOLLOWED_CHANNEL_1 = "8e7a6f0a0b1f0612afee1a673e94027d"; // 레고칠칠 public final String FOLLOWED_CHANNEL_2 = "c2186ca6edb3a663f137b15ed7346fac"; // 리얼진짜우왁굳 public final String UNFOLLOWED_CHANNEL = "22bd842599735ae19e454983280f611e"; // ENCHANT @Test void gettingNormalChannelInfo() throws IOException { AtomicReference<ChzzkChannel> channel = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> channel.set(chzzk.getChannel(FOLLOWED_CHANNEL_2))); System.out.println(channel); } @Test void gettingInvalidChannelInfo() throws IOException { Assertions.assertThrowsExactly(ChannelNotExistsException.class, () -> { chzzk.getChannel("invalidchannelid"); }); } @Test void gettingNormalChannelRules() throws IOException { AtomicReference<ChzzkChannelRules> rule = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> rule.set(chzzk.getChannelChatRules(FOLLOWED_CHANNEL_1))); System.out.println(rule); } @Test void gettingInvalidChannelRules() throws IOException { Assertions.assertThrowsExactly(NotExistsException.class, () -> { chzzk.getChannelChatRules("invalidchannel or no rule channel"); }); } @Test void gettingFollowStatusAnonymous() throws IOException { Assertions.assertThrowsExactly(NotLoggedInException.class, () -> chzzk.getFollowingStatus("FOLLOWED_CHANNEL_1")); } @Test void gettingFollowStatus() throws IOException { AtomicReference<ChzzkChannelFollowingData> followingStatus = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(FOLLOWED_CHANNEL_1))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), true); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(UNFOLLOWED_CHANNEL))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), false); } @Test void gettingUserInfo() throws IOException, NotLoggedInException {
// 8e7a6f0a0b1f0612afee1a673e94027d - 레고칠칠 // c2186ca6edb3a663f137b15ed7346fac - 리얼진짜우왁굳 // 두 채널 모두 팔로우한 뒤 테스트 진행해주세요. // // 22bd842599735ae19e454983280f611e - ENCHANT // 위 채널은 팔로우 해제 후 테스트 진행해주세요. public class ChannelApiTest extends ChzzkTestBase { public final String FOLLOWED_CHANNEL_1 = "8e7a6f0a0b1f0612afee1a673e94027d"; // 레고칠칠 public final String FOLLOWED_CHANNEL_2 = "c2186ca6edb3a663f137b15ed7346fac"; // 리얼진짜우왁굳 public final String UNFOLLOWED_CHANNEL = "22bd842599735ae19e454983280f611e"; // ENCHANT @Test void gettingNormalChannelInfo() throws IOException { AtomicReference<ChzzkChannel> channel = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> channel.set(chzzk.getChannel(FOLLOWED_CHANNEL_2))); System.out.println(channel); } @Test void gettingInvalidChannelInfo() throws IOException { Assertions.assertThrowsExactly(ChannelNotExistsException.class, () -> { chzzk.getChannel("invalidchannelid"); }); } @Test void gettingNormalChannelRules() throws IOException { AtomicReference<ChzzkChannelRules> rule = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> rule.set(chzzk.getChannelChatRules(FOLLOWED_CHANNEL_1))); System.out.println(rule); } @Test void gettingInvalidChannelRules() throws IOException { Assertions.assertThrowsExactly(NotExistsException.class, () -> { chzzk.getChannelChatRules("invalidchannel or no rule channel"); }); } @Test void gettingFollowStatusAnonymous() throws IOException { Assertions.assertThrowsExactly(NotLoggedInException.class, () -> chzzk.getFollowingStatus("FOLLOWED_CHANNEL_1")); } @Test void gettingFollowStatus() throws IOException { AtomicReference<ChzzkChannelFollowingData> followingStatus = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(FOLLOWED_CHANNEL_1))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), true); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(UNFOLLOWED_CHANNEL))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), false); } @Test void gettingUserInfo() throws IOException, NotLoggedInException {
ChzzkUser currentUser = loginChzzk.getLoggedUser();
5
2023-12-30 20:01:23+00:00
8k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/LauncherBar.java
[ { "identifier": "MovieRepo", "path": "app/src/main/java/net/lonelytransistor/launcher/repos/MovieRepo.java", "snippet": "public class MovieRepo implements Serializable {\n private static final String TAG = \"MovieRepo\";\n private static final String PREFERENCE_KEY = \"MOVIE_REPO\";\n private static final String MOVIES_MAP = \"MOVIES\";\n private static final String ALIAS_MAP = \"ALIASES\";\n\n private static Preferences prefs = null;\n private static final Map<String,MovieTitle> movieRepoID = new HashMap<>();\n private static final Map<String,String> movieAliases = new HashMap<>();\n static final ReentrantLock mutex = new ReentrantLock();\n private static final List<MovieTitle> watchNext = new ArrayList<>();\n private static long watchNextTimestamp = 0;\n private static final Map<JustWatch.Type, List<MovieTitle>> recommended = new HashMap<>();\n private static long recommendedTimestamp = 0;\n\n public static class ID {\n JustWatch.Type type = JustWatch.Type.ERROR;\n int id = 0;\n private String get() {\n return type.name() + \"_\" + id;\n }\n ID(JustWatch.Type type, int id) {\n this.type = type;\n this.id = id;\n }\n ID(String id) {\n if (id == null)\n return;\n String[] id_ = id.split(\"_\", 2);\n this.type = JustWatch.Type.valueOf(id_[0]);\n this.id = Integer.parseInt(id_[1]);\n }\n }\n static MovieTitle put(ID id, MovieTitle title) {\n mutex.lock();\n MovieTitle ret = movieRepoID.put(id.get(), title);\n mutex.unlock();\n return ret;\n }\n public static MovieTitle get(ID id) {\n mutex.lock();\n MovieTitle ret = movieRepoID.get(id.get());\n mutex.unlock();\n return ret;\n }\n public static MovieTitle get(JustWatch.Type type, int id) {\n return get(new ID(type, id));\n }\n\n public static ID INVALID_ID = new ID(JustWatch.Type.ERROR, 0);\n public static MovieTitle INVALID_TITLE = new MovieTitle(0);\n static void putAlias(String title, ID id) {\n mutex.lock();\n movieAliases.put(title, id != null ? id.get() : INVALID_ID.get());\n mutex.unlock();\n }\n static MovieTitle getAlias(String title) {\n mutex.lock();\n String id = movieAliases.get(title);\n MovieTitle ret = null;\n if (Objects.equals(id, INVALID_ID.get())) {\n ret = INVALID_TITLE;\n } else if (id != null) {\n ret = get(new ID(id));\n }\n mutex.unlock();\n return ret;\n }\n\n public static void save() {\n mutex.lock();\n prefs.setMap(MOVIES_MAP, movieRepoID);\n prefs.setMap(ALIAS_MAP, movieAliases);\n mutex.unlock();\n }\n static void init(Context ctx) {\n if (prefs == null) {\n prefs = new Preferences(ctx, PREFERENCE_KEY);\n }\n }\n static void postInit(Context ctx) {\n load(ctx);\n }\n public static void load(Context ctx) {\n mutex.lock();\n movieRepoID.clear();\n movieRepoID.putAll((Map<String, MovieTitle>) prefs.getMap(MOVIES_MAP));\n movieAliases.clear();\n movieAliases.putAll((Map<String, String>) prefs.getMap(ALIAS_MAP));\n createWatchNext(ctx);\n createRecommended();\n mutex.unlock();\n }\n public static List<MovieTitle> getWatchNext() {\n return watchNext;\n }\n public static long getWatchNextTimestamp() {\n return watchNextTimestamp;\n }\n public static List<MovieTitle> getRecommended(JustWatch.Type type) {\n return recommended.getOrDefault(type, new ArrayList<>());\n }\n public static long getRecommendedTimestamp() {\n return recommendedTimestamp;\n }\n\n @SuppressLint(\"RestrictedApi\") private static void createWatchNext(Context ctx) {\n Cursor cursor = ctx.getContentResolver().query(\n TvContract.WatchNextPrograms.CONTENT_URI,\n WatchNextProgram.PROJECTION,\n null, new String[]{}, null);\n assert cursor != null;\n AtomicInteger requests = new AtomicInteger(0);\n if (cursor.moveToFirst()) do {\n WatchNextProgram prog = WatchNextProgram.fromCursor(cursor);\n String title = prog.getTitle();\n int index = cursor.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_LAST_PLAYBACK_POSITION_MILLIS);\n long timeNow = Math.max(0, index > 0 ? cursor.getLong(index) : 0);\n index = cursor.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_DURATION_MILLIS);\n long timeTotal = Math.max(1, index > 0 ? cursor.getLong(index) : 1);\n\n requests.incrementAndGet();\n JustWatch.findMovieTitle(title, new JustWatch.Callback() {\n @Override\n public void onFailure(String error) {\n mutex.lock();\n if (requests.decrementAndGet() == 0) {\n watchNextTimestamp = System.currentTimeMillis();\n }\n mutex.unlock();\n }\n @Override\n public void onSuccess(List<MovieTitle> titles_) {\n MovieTitle movie = titles_.get(0);\n movie.system.pkgName = prog.getPackageName();\n movie.system.lastWatched = prog.getLastEngagementTimeUtcMillis();\n movie.system.timeWatched = timeNow;\n movie.system.runtime = timeTotal;\n switch (prog.getWatchNextType()) {\n case TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE:\n movie.system.state = (100*timeNow/timeTotal) > 95 ?\n MovieTitle.System.State.WATCHED : MovieTitle.System.State.WATCHING;\n break;\n case TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT:\n movie.system.state = MovieTitle.System.State.NEXT;\n break;\n case TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEW:\n case TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_WATCHLIST:\n movie.system.state = MovieTitle.System.State.NEW;\n break;\n default:\n break;\n }\n MovieTitle title = titles_.get(0);\n try {\n Intent intent = prog.getIntent();\n ApkRepo.Platform platform = ApkRepo.getPlatform(intent);\n if (ApkRepo.getPlatformApp(platform) != null) {\n title.offers.put(platform, intent.getDataString());\n }\n } catch (URISyntaxException ignored) {}\n\n mutex.lock();\n if (!watchNext.contains(title)) {\n watchNext.add(title);\n }\n if (requests.decrementAndGet() == 0) {\n watchNextTimestamp = System.currentTimeMillis();\n }\n mutex.unlock();\n }\n });\n } while (cursor.moveToNext());\n cursor.close();\n }\n private static void createRecommended() {\n ReentrantLock mutexLocal = new ReentrantLock();\n for (JustWatch.Type type : JustWatch.Type.values()) {\n if (type == JustWatch.Type.ERROR) {\n continue;\n }\n if (!recommended.containsKey(type)) {\n recommended.put(type, new ArrayList<>());\n }\n JustWatch.Config cfg = new JustWatch.Config();\n cfg.count = 40;\n cfg.type = new JustWatch.Type[]{type};\n cfg.sortOrder = JustWatch.SortOrder.POPULAR;\n cfg.sortPostOrder = JustWatch.SortOrder.IMDB_SCORE;\n JustWatch.getPopularTitles(cfg, new JustWatch.Callback() {\n @Override\n public void onFailure(String error) {\n Log.e(TAG, error);\n }\n @Override\n public void onSuccess(List<MovieTitle> titles) {\n mutexLocal.lock();\n recommended.get(type).addAll(titles);\n recommendedTimestamp = System.currentTimeMillis();\n mutexLocal.unlock();\n }\n });\n }\n }\n}" }, { "identifier": "MovieTitle", "path": "app/src/main/java/net/lonelytransistor/launcher/repos/MovieTitle.java", "snippet": "public class MovieTitle implements Serializable {\n final public int id;\n final public JustWatch.Type type;\n\n final public String title;\n final public String originalTitle;\n final public String description;\n final public String imagePath;\n final public String imageUrl;\n final public int runtime;\n final public JustWatch.AgeRating ageRating;\n final public JustWatch.Genre[] genres;\n\n final public String[] productionCountries;\n final public Map<String,String> actors;\n final public double imdbScore;\n final public int popularity;\n final public int popularityDelta;\n final public int year;\n\n final public Map<ApkRepo.Platform, String> offers;\n\n public static class System implements Serializable {\n public String pkgName = \"\";\n public long lastWatched = 0; //in milliseconds\n public long timeWatched = 0;\n public long runtime = 0;\n public enum State {\n NONE,\n NEW,\n NEXT,\n WATCHING,\n WATCHED\n }\n public State state = State.NONE;\n\n @Override\n public String toString() {\n return \"System{\" +\n \"pkgName='\" + pkgName + '\\'' +\n \", lastWatched=\" + lastWatched +\n \", timeWatched=\" + timeWatched +\n \", runtime=\" + runtime +\n \", state=\" + state +\n '}';\n }\n }\n final public System system = new System();\n\n private static Drawable POPULARITY_UP = null;\n private static Drawable POPULARITY_SAME = null;\n private static Drawable POPULARITY_DOWN = null;\n static void init(Context ctx) {\n if (POPULARITY_UP == null) {\n POPULARITY_UP = ctx.getDrawable(R.drawable.popularity_up);\n }\n if (POPULARITY_SAME == null) {\n POPULARITY_SAME = ctx.getDrawable(R.drawable.popularity_same);\n }\n if (POPULARITY_DOWN == null) {\n POPULARITY_DOWN = ctx.getDrawable(R.drawable.popularity_down);\n }\n }\n public Drawable getPopularityDeltaImage() {\n return popularityDelta > 0 ? POPULARITY_UP : (popularityDelta < 0 ? POPULARITY_DOWN : POPULARITY_SAME);\n }\n public Drawable getImage() {\n return Drawable.createFromPath(imagePath);\n }\n public int getTimeWatched() {\n return 0;\n }\n\n public MovieTitle(MovieTitle priv) {\n id = priv.id;\n type = priv.type;\n title = priv.title;\n originalTitle = priv.originalTitle;\n description = priv.description;\n imagePath = priv.imagePath;\n imageUrl = priv.imageUrl;\n runtime = priv.runtime;\n ageRating = priv.ageRating;\n genres = priv.genres != null ? priv.genres.clone() : new JustWatch.Genre[]{};\n productionCountries = priv.productionCountries != null ? priv.productionCountries.clone() : new String[]{};\n actors = priv.actors;\n imdbScore = priv.imdbScore;\n popularity = priv.popularity;\n popularityDelta = priv.popularityDelta;\n year = priv.year;\n offers = priv.offers;\n }\n public MovieTitle(MovieTitlePriv priv) {\n id = priv.id;\n type = priv.type;\n title = priv.title;\n originalTitle = priv.originalTitle;\n description = priv.description;\n imagePath = priv.imagePath;\n imageUrl = priv.imageUrl;\n runtime = priv.runtime;\n ageRating = priv.ageRating;\n genres = priv.genres;\n productionCountries = priv.productionCountries;\n actors = priv.actors;\n imdbScore = priv.imdbScore;\n popularity = priv.popularity;\n popularityDelta = priv.popularityDelta;\n year = priv.year;\n offers = priv.offers;\n }\n\n @Override\n public String toString() {\n return \"MovieTitle{\" +\n \"id=\" + id +\n \", type=\" + type +\n \", title='\" + title + '\\'' +\n \", originalTitle='\" + originalTitle + '\\'' +\n \", description='\" + description + '\\'' +\n \", imagePath='\" + imagePath + '\\'' +\n \", imageUrl='\" + imageUrl + '\\'' +\n \", runtime=\" + runtime +\n \", ageRating=\" + ageRating +\n \", genres=\" + Arrays.toString(genres) +\n \", productionCountries=\" + Arrays.toString(productionCountries) +\n \", actors=\" + actors +\n \", imdbScore=\" + imdbScore +\n \", popularity=\" + popularity +\n \", popularityDelta=\" + popularityDelta +\n \", year=\" + year +\n \", offers=\" + offers +\n \", system=\" + system +\n '}';\n }\n\n public MovieTitle(int id) {\n this.id = id;\n type = JustWatch.Type.ERROR;\n title = \"title\" + id;\n originalTitle = \"originalTitle\" + id;\n description = \"description\" + id;\n imagePath = \"\";\n imageUrl = \"\" + id;\n runtime = 3600;\n ageRating = JustWatch.AgeRating.values()[id % JustWatch.AgeRating.values().length];\n genres = new JustWatch.Genre[]{};\n productionCountries = new String[]{};\n actors = new HashMap<>();\n imdbScore = 0;\n popularity = 0;\n popularityDelta = 0;\n year = 1900;\n offers = new HashMap<>();\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 MovieTitle that = (MovieTitle) o;\n return id == that.id && type == that.type && Objects.equals(title, that.title) && Objects.equals(originalTitle, that.originalTitle) && Objects.equals(description, that.description);\n }\n @Override\n public int hashCode() {\n return Objects.hash(id, type, title, originalTitle, description);\n }\n}" } ]
import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import net.lonelytransistor.commonlib.OutlinedTextView; import net.lonelytransistor.commonlib.ProgressDrawable; import net.lonelytransistor.launcher.repos.MovieRepo; import net.lonelytransistor.launcher.repos.MovieTitle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit;
5,385
} else { currentlyVisible = v; ScheduledFuture<?> sch = delayedSchedule.put(v, delayedExecutor.schedule(new FutureTask<>( () -> { uiExecutor.execute(() -> animateFocus(v, true)); return null; }), DELAY, TimeUnit.MILLISECONDS)); if (sch != null) sch.cancel(true); } }; protected boolean onKey(View v, int keyCode, KeyEvent event) { return keyListenerRoot.onKey(v, keyCode, event); } private final Map<Integer, BarViewHolder> positionToViewHolder = new HashMap<>(); public boolean requestSelection(int position) { for (RecyclerView v : rootViews) { v.setDescendantFocusability(v == rootView ? FOCUS_AFTER_DESCENDANTS : FOCUS_BLOCK_DESCENDANTS); } rootView.smoothScrollToPosition(position); BarViewHolder vh = positionToViewHolder.get(Math.min(position, getItemCount()-1)); if (vh != null) { vh.itemView.requestFocus(); return vh.itemView.hasFocus(); } else { return false; } } @Override final public void onBindViewHolder(@NonNull BarViewHolder vh, int position) { positionToViewHolder.put(position, vh); vh.itemView.setScaleX(1.0f); vh.itemView.setScaleY(1.0f); onBindView(vh, position); } abstract public void onBindView(@NonNull BarViewHolder holder, int position); @NonNull @Override final public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { BarViewHolder vh = onCreateViewHolder(parent); vh.itemView.setOnFocusChangeListener(focusListener); return vh; } @NonNull abstract public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent); } private static class TopBarViewHolder extends BarViewHolder { final ConstraintLayout parent; final ImageView mainImage; final ImageView statusIcon; final OutlinedTextView scoreText; final ImageView scoreIcon; final OutlinedTextView popularityText; final ImageView popularityIcon; final TextView primaryText; final TextView secondaryText; TopBarViewHolder(@NonNull View itemView) { super(itemView); mainImage = itemView.findViewById(R.id.main_image); statusIcon = itemView.findViewById(R.id.status_icon); scoreText = itemView.findViewById(R.id.score); scoreIcon = itemView.findViewById(R.id.score_icon); popularityText = itemView.findViewById(R.id.popularity); popularityIcon = itemView.findViewById(R.id.popularity_icon); primaryText = itemView.findViewById(R.id.primary_text); secondaryText = itemView.findViewById(R.id.secondary_text); parent = (ConstraintLayout) mainImage.getParent(); } } private class TopBarAdapter extends BarAdapter { private final int foldedCardHeight; private final int unfoldedCardHeight; private final Map<Integer, List<MovieCard>> rows = new HashMap<>(); private List<MovieCard> currentRow; private int currentRowIx = 0; private int globalCount = 0; private int lastActiveIx = 0; TopBarAdapter() { super(LauncherBar.this.getContext(), topBar); ConstraintLayout.LayoutParams lp; View card = LayoutInflater.from(LauncherBar.this.getContext()) .inflate(R.layout.top_card_view, null, false); lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.main_image).getLayoutParams(); int mainImageHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.primary_text).getLayoutParams(); int primaryTextHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.secondary_text).getLayoutParams(); int secondaryTextHeight = lp.height; foldedCardHeight = mainImageHeight + primaryTextHeight + card.getPaddingTop() + card.getPaddingBottom(); unfoldedCardHeight = foldedCardHeight + secondaryTextHeight; lp = (ConstraintLayout.LayoutParams) topBar.getLayoutParams(); lp.height = (int) ((foldedCardHeight + secondaryTextHeight) * 1.1f); topBar.setLayoutParams(lp); } private final OnKeyListener keyListenerInternal = (v, keyCode, event) -> { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_DOWN_LEFT: case KeyEvent.KEYCODE_DPAD_DOWN_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN: case KeyEvent.KEYCODE_CHANNEL_DOWN: bottomBarAdapter.restoreFocus(); case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_UP_LEFT: case KeyEvent.KEYCODE_DPAD_UP_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP: case KeyEvent.KEYCODE_CHANNEL_UP: return true; } return onKey(v, keyCode, event); }; private final OnClickListener clickListenerInternal = v -> { MovieCard card = currentRow.get(lastActiveIx); if (card.clickIntent != null && card.clickIntent.getAction() != null && !card.clickIntent.getAction().isEmpty()) { Log.i(TAG, "intent: " + card.clickIntent + card.clickIntent.getDataString());
package net.lonelytransistor.launcher; public class LauncherBar extends FrameLayout { private static final String TAG = "LauncherActivity"; private static final int DELAY = 200; private static final int ANIMATION_DURATION = 200; public LauncherBar(Context context) { super(context); constructor(); } public LauncherBar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); constructor(); } public LauncherBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); constructor(); } public LauncherBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); constructor(); } private OnKeyListener keyListenerRoot = (v, keyCode, event) -> false; @Override public void setOnKeyListener(OnKeyListener l) { super.setOnKeyListener(l); keyListenerRoot = l; } private OnClickListener clickListenerRoot = (v) -> {}; @Override public void setOnClickListener(@Nullable OnClickListener l) { super.setOnClickListener(l); clickListenerRoot = l; } private static abstract class BarViewHolder extends RecyclerView.ViewHolder { BarViewHolder(@NonNull View itemView) { super(itemView); } } private abstract class BarAdapter extends RecyclerView.Adapter<BarViewHolder> { BarAdapter(Context ctx, RecyclerView v) { super(); uiExecutor = ctx.getMainExecutor(); rootView = v; rootViews.add(v); } private Executor uiExecutor; private final RecyclerView rootView; private static final List<RecyclerView> rootViews = new ArrayList<>(); View currentlyVisible = null; final ScheduledExecutorService delayedExecutor = Executors.newScheduledThreadPool(4); Map<View, ScheduledFuture<?>> delayedSchedule = new HashMap<>(); public void onFocused(BarViewHolder vh, boolean hasFocus) {} private void animateFocus(View v, boolean hasFocus) { animatedViews.add(v); v.animate() .scaleY(hasFocus ? 1.1f : 1.0f) .scaleX(hasFocus ? 1.1f : 1.0f) .setDuration(ANIMATION_DURATION) .setListener(new AnimatorListenerAdapter() { void reset() { v.setScaleX(hasFocus ? 1.1f : 1.0f); v.setScaleY(hasFocus ? 1.1f : 1.0f); animatedViews.remove(v); if (hasFocus && !v.hasFocus()) { animateFocus(v, false); } } @Override public void onAnimationCancel(Animator animation) { reset(); } @Override public void onAnimationEnd(Animator animation) { reset(); } @Override public void onAnimationPause(Animator animation) { reset(); } }) .start(); if ((hasFocus && v.getScaleY() == 1.0f) || (!hasFocus && v.getScaleY() == 1.1f)) { BarViewHolder vh; try { vh = (BarViewHolder) rootView.getChildViewHolder(v); } catch (Exception e) { Log.w(TAG, "Hover out of bounds."); return; } onFocused(vh, hasFocus); } } private final List<View> animatedViews = new ArrayList<>(); private final View.OnFocusChangeListener focusListener = (v, hasFocus) -> { int padding = v.getPaddingBottom(); v.setBackgroundResource(hasFocus ? R.drawable.border_hover: R.drawable.border_normal); v.setPadding(padding,padding,padding,padding); if (!hasFocus) { ScheduledFuture<?> sch = delayedSchedule.get(v); if (sch != null) sch.cancel(true); v.clearAnimation(); if (!animatedViews.contains(v)) { animateFocus(v, false); } } else { currentlyVisible = v; ScheduledFuture<?> sch = delayedSchedule.put(v, delayedExecutor.schedule(new FutureTask<>( () -> { uiExecutor.execute(() -> animateFocus(v, true)); return null; }), DELAY, TimeUnit.MILLISECONDS)); if (sch != null) sch.cancel(true); } }; protected boolean onKey(View v, int keyCode, KeyEvent event) { return keyListenerRoot.onKey(v, keyCode, event); } private final Map<Integer, BarViewHolder> positionToViewHolder = new HashMap<>(); public boolean requestSelection(int position) { for (RecyclerView v : rootViews) { v.setDescendantFocusability(v == rootView ? FOCUS_AFTER_DESCENDANTS : FOCUS_BLOCK_DESCENDANTS); } rootView.smoothScrollToPosition(position); BarViewHolder vh = positionToViewHolder.get(Math.min(position, getItemCount()-1)); if (vh != null) { vh.itemView.requestFocus(); return vh.itemView.hasFocus(); } else { return false; } } @Override final public void onBindViewHolder(@NonNull BarViewHolder vh, int position) { positionToViewHolder.put(position, vh); vh.itemView.setScaleX(1.0f); vh.itemView.setScaleY(1.0f); onBindView(vh, position); } abstract public void onBindView(@NonNull BarViewHolder holder, int position); @NonNull @Override final public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { BarViewHolder vh = onCreateViewHolder(parent); vh.itemView.setOnFocusChangeListener(focusListener); return vh; } @NonNull abstract public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent); } private static class TopBarViewHolder extends BarViewHolder { final ConstraintLayout parent; final ImageView mainImage; final ImageView statusIcon; final OutlinedTextView scoreText; final ImageView scoreIcon; final OutlinedTextView popularityText; final ImageView popularityIcon; final TextView primaryText; final TextView secondaryText; TopBarViewHolder(@NonNull View itemView) { super(itemView); mainImage = itemView.findViewById(R.id.main_image); statusIcon = itemView.findViewById(R.id.status_icon); scoreText = itemView.findViewById(R.id.score); scoreIcon = itemView.findViewById(R.id.score_icon); popularityText = itemView.findViewById(R.id.popularity); popularityIcon = itemView.findViewById(R.id.popularity_icon); primaryText = itemView.findViewById(R.id.primary_text); secondaryText = itemView.findViewById(R.id.secondary_text); parent = (ConstraintLayout) mainImage.getParent(); } } private class TopBarAdapter extends BarAdapter { private final int foldedCardHeight; private final int unfoldedCardHeight; private final Map<Integer, List<MovieCard>> rows = new HashMap<>(); private List<MovieCard> currentRow; private int currentRowIx = 0; private int globalCount = 0; private int lastActiveIx = 0; TopBarAdapter() { super(LauncherBar.this.getContext(), topBar); ConstraintLayout.LayoutParams lp; View card = LayoutInflater.from(LauncherBar.this.getContext()) .inflate(R.layout.top_card_view, null, false); lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.main_image).getLayoutParams(); int mainImageHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.primary_text).getLayoutParams(); int primaryTextHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.secondary_text).getLayoutParams(); int secondaryTextHeight = lp.height; foldedCardHeight = mainImageHeight + primaryTextHeight + card.getPaddingTop() + card.getPaddingBottom(); unfoldedCardHeight = foldedCardHeight + secondaryTextHeight; lp = (ConstraintLayout.LayoutParams) topBar.getLayoutParams(); lp.height = (int) ((foldedCardHeight + secondaryTextHeight) * 1.1f); topBar.setLayoutParams(lp); } private final OnKeyListener keyListenerInternal = (v, keyCode, event) -> { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_DOWN_LEFT: case KeyEvent.KEYCODE_DPAD_DOWN_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN: case KeyEvent.KEYCODE_CHANNEL_DOWN: bottomBarAdapter.restoreFocus(); case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_UP_LEFT: case KeyEvent.KEYCODE_DPAD_UP_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP: case KeyEvent.KEYCODE_CHANNEL_UP: return true; } return onKey(v, keyCode, event); }; private final OnClickListener clickListenerInternal = v -> { MovieCard card = currentRow.get(lastActiveIx); if (card.clickIntent != null && card.clickIntent.getAction() != null && !card.clickIntent.getAction().isEmpty()) { Log.i(TAG, "intent: " + card.clickIntent + card.clickIntent.getDataString());
for (MovieTitle t : MovieRepo.getWatchNext()) {
1
2023-12-28 18:24:12+00:00
8k
Patbox/GlideAway
src/main/java/eu/pb4/glideaway/item/WindInABottleItem.java
[ { "identifier": "GliderEntity", "path": "src/main/java/eu/pb4/glideaway/entity/GliderEntity.java", "snippet": "public class GliderEntity extends Entity implements PolymerEntity {\n private static final TrackedData<Float> ROLL = DataTracker.registerData(GliderEntity.class, TrackedDataHandlerRegistry.FLOAT);\n private ItemStack itemStack = GlideItems.HANG_GLIDER.getDefaultStack();\n private ItemStack modelStack = GlideItems.HANG_GLIDER.getDefaultStack();\n private int damageTimer;\n private int lastAttack = -999;\n\n private final ElementHolder holder = new ElementHolder();\n private int soundTimer;\n private int attacks;\n\n public static boolean create(World world, LivingEntity rider, ItemStack stack, Hand hand) {\n if (rider.hasVehicle() || (rider.isSneaking() && !world.getGameRules().getBoolean(GlideGamerules.ALLOW_SNEAK_RELEASE))) {\n return false;\n }\n stack.damage((int) Math.max(0, -rider.getVelocity().y\n * world.getGameRules().get(GlideGamerules.INITIAL_VELOCITY_GLIDER_DAMAGE).get()\n * (90 - Math.abs(MathHelper.clamp(rider.getPitch(), -30, 80))) / 90),\n rider, player -> player.sendEquipmentBreakStatus(hand == Hand.MAIN_HAND ? EquipmentSlot.MAINHAND : EquipmentSlot.OFFHAND));\n\n if (stack.isEmpty()) {\n return false;\n }\n\n var entity = new GliderEntity(GlideEntities.GLIDER, world);\n var sitting = rider.getDimensions(EntityPose.SITTING);\n var currentDim = rider.getDimensions(rider.getPose());\n entity.setItemStack(stack);\n entity.setPosition(rider.getPos().add(0, currentDim.height - sitting.height - rider.getRidingOffset(entity), 0));\n entity.setYaw(rider.getYaw());\n entity.setPitch(rider.getPitch());\n entity.setVelocity(rider.getVelocity().add(rider.getRotationVector().multiply(0.2, 0.02, 0.2).multiply(rider.isSneaking() ? 2 : 1)));\n\n world.spawnEntity(entity);\n entity.playSound(GlideSoundEvents.HANG_GLIDER_OPENS, 0.8f, entity.random.nextFloat() * 0.2f + 1.2f);\n\n if (!rider.isSneaking()) {\n rider.startRiding(entity);\n }\n return true;\n }\n\n public static ItemStack createDispenser(BlockPointer pointer, ItemStack stack) {\n Direction direction = pointer.state().get(DispenserBlock.FACING);\n ServerWorld serverWorld = pointer.world();\n Vec3d vec3d = pointer.centerPos();\n\n var entity = new GliderEntity(GlideEntities.GLIDER, serverWorld);\n entity.setItemStack(stack.copyWithCount(1));\n entity.setPosition(vec3d.x, vec3d.y - 0.5f, vec3d.z);\n entity.setYaw(direction.getAxis() == Direction.Axis.Y ? 0 : direction.asRotation());\n entity.setPitch(direction.getAxis() != Direction.Axis.Y ? 0 : (direction == Direction.UP ? -90 : 90));\n entity.setVelocity(Vec3d.of(direction.getVector()).multiply(0.6));\n\n serverWorld.spawnEntity(entity);\n entity.playSound(GlideSoundEvents.HANG_GLIDER_OPENS, 0.8f, entity.random.nextFloat() * 0.2f + 1.2f);\n stack.decrement(1);\n return stack;\n }\n\n public void setItemStack(ItemStack stack) {\n this.itemStack = stack;\n this.modelStack = stack.getItem().getDefaultStack();\n if (stack.hasNbt() && stack.getItem() instanceof DyeableItem dyeableItem) {\n dyeableItem.setColor(this.modelStack, dyeableItem.getColor(stack));\n }\n }\n\n public GliderEntity(EntityType<?> type, World world) {\n super(type, world);\n this.setInvisible(true);\n var interaction = InteractionElement.redirect(this);\n interaction.setSize(0.8f, 1.2f);\n this.holder.addElement(interaction);\n }\n\n @Override\n public boolean damage(DamageSource source, float amount) {\n if (source.isIn(DamageTypeTags.CAN_BREAK_ARMOR_STAND)) {\n if (this.age - this.lastAttack > 30) {\n this.attacks = 0;\n } else if (this.attacks == 2) {\n this.giveOrDrop(this.getFirstPassenger());\n this.discard();\n }\n\n this.attacks++;\n this.lastAttack = this.age;\n var sign = Math.signum(this.dataTracker.get(ROLL));\n if (sign == 0) {\n sign = 1;\n }\n\n this.dataTracker.set(ROLL, -sign * Math.min(Math.abs(this.dataTracker.get(ROLL) + 0.2f), 1) );\n return true;\n } else if (source.isIn(DamageTypeTags.ALWAYS_KILLS_ARMOR_STANDS)) {\n this.giveOrDrop(this.getFirstPassenger());\n this.discard();\n return true;\n } else if (source.isIn(DamageTypeTags.IGNITES_ARMOR_STANDS)) {\n this.damageStack((int) (amount * 2));\n return true;\n }\n\n return super.damage(source, amount);\n }\n\n private boolean damageStack(int i) {\n var serverWorld = (ServerWorld) this.getWorld();\n if (itemStack.damage(i, this.random, null)) {\n var old = this.itemStack;\n this.setItemStack(ItemStack.EMPTY);\n if (this.getFirstPassenger() != null) {\n this.getFirstPassenger().stopRiding();\n }\n serverWorld.spawnParticles(new ItemStackParticleEffect(ParticleTypes.ITEM, old), this.getX(), this.getY() + 0.5, this.getZ(), 80, 1, 1, 1, 0.1);\n this.discard();\n return true;\n }\n return false;\n }\n\n @Override\n public boolean handleAttack(Entity attacker) {\n return false;\n }\n\n @Override\n protected Vector3f getPassengerAttachmentPos(Entity passenger, EntityDimensions dimensions, float scaleFactor) {\n return new Vector3f();\n }\n\n @Override\n public boolean canBeHitByProjectile() {\n return false;\n }\n\n @Override\n public boolean canHit() {\n return false;\n }\n\n public void giveOrDrop(@Nullable Entity entity) {\n if (this.isRemoved()) {\n return;\n }\n\n if (entity instanceof LivingEntity livingEntity && entity.isAlive()) {\n if (livingEntity.getStackInHand(Hand.MAIN_HAND).isEmpty()) {\n livingEntity.setStackInHand(Hand.MAIN_HAND, this.getItemStack());\n } else if (livingEntity.getStackInHand(Hand.OFF_HAND).isEmpty()) {\n livingEntity.setStackInHand(Hand.OFF_HAND, this.getItemStack());\n } else if (!(entity instanceof PlayerEntity player && player.giveItemStack(this.getItemStack()))) {\n this.dropStack(this.getItemStack());\n }\n } else {\n this.dropStack(this.getItemStack());\n }\n this.setItemStack(ItemStack.EMPTY);\n this.discard();\n }\n\n @Override\n public void tick() {\n if (!(this.getWorld() instanceof ServerWorld serverWorld)) {\n return;\n }\n\n super.tick();\n var passenger = this.getFirstPassenger();\n\n if (passenger != null && !passenger.isAlive()) {\n passenger.stopRiding();\n passenger = null;\n }\n\n if (passenger == null && this.holder.getAttachment() == null) {\n EntityAttachment.of(this.holder, this);\n VirtualEntityUtils.addVirtualPassenger(this, this.holder.getEntityIds().getInt(0));\n } else if (passenger != null && this.holder.getAttachment() != null) {\n VirtualEntityUtils.removeVirtualPassenger(this, this.holder.getEntityIds().getInt(0));\n this.holder.destroy();\n }\n\n if ((this.isOnGround() || (passenger != null && passenger.isOnGround())) && this.age > 10) {\n this.giveOrDrop(passenger);\n return;\n }\n\n if (passenger != null) {\n this.setYaw(MathHelper.lerpAngleDegrees(0.175f, this.getYaw(), passenger.getYaw()));\n this.setPitch(MathHelper.lerpAngleDegrees(0.175f, this.getPitch(), MathHelper.clamp(passenger.getPitch(), -30, 80)));\n var roll = MathHelper.clamp((-MathHelper.subtractAngles(passenger.getYaw(), this.getYaw())) * MathHelper.RADIANS_PER_DEGREE * 0.5f, -1f, 1f);\n\n if (Math.abs(roll - this.getDataTracker().get(ROLL)) > MathHelper.RADIANS_PER_DEGREE / 2) {\n this.getDataTracker().set(ROLL, roll);\n }\n } else {\n var roll = this.getDataTracker().get(ROLL) * 0.98f;\n\n if (Math.abs(roll - this.getDataTracker().get(ROLL)) > MathHelper.RADIANS_PER_DEGREE / 2 || Math.abs(roll) > MathHelper.RADIANS_PER_DEGREE / 2) {\n this.getDataTracker().set(ROLL, roll);\n }\n }\n\n int dmgTimeout = serverWorld.getRegistryKey() == World.NETHER ? 6 : 10;\n int dmgFrequency = 2;\n int dmg = 1;\n\n var mut = this.getBlockPos().mutableCopy();\n for (int i = 0; i < 32; i++) {\n var state = serverWorld.getBlockState(mut);\n if (state.isOf(Blocks.FIRE) || state.isOf(Blocks.CAMPFIRE) && i < 24) {\n this.addVelocity(0, ((32 - i) / 32f) * this.getWorld().getGameRules().get(GlideGamerules.FIRE_BOOST).get(), 0);\n dmgFrequency = 1;\n } else if (state.isOf(Blocks.LAVA) && i < 6) {\n this.addVelocity(0, ((6 - i) / 6f) * this.getWorld().getGameRules().get(GlideGamerules.LAVA_BOOST).get(), 0);\n dmgTimeout = 2;\n dmgFrequency = 1;\n dmg = 2;\n } else if (state.isSideSolidFullSquare(serverWorld, mut, Direction.UP)) {\n break;\n }\n\n mut.move(0, -1, 0);\n }\n\n\n double gravity = 0.07;\n if (serverWorld.hasRain(this.getBlockPos())) {\n gravity = 0.1;\n } else if (GlideDimensionTypeTags.isIn(serverWorld, GlideDimensionTypeTags.HIGH_GRAVITY)) {\n gravity = 0.084;\n } else if (GlideDimensionTypeTags.isIn(serverWorld, GlideDimensionTypeTags.LOW_GRAVITY)) {\n gravity = 0.056;\n }\n\n this.limitFallDistance();\n if (passenger != null) {\n passenger.limitFallDistance();\n }\n Vec3d velocity = this.getVelocity();\n Vec3d rotationVector = this.getRotationVector();\n float pitch = this.getPitch() * (float) (Math.PI / 180.0);\n double rotationLength = Math.sqrt(rotationVector.x * rotationVector.x + rotationVector.z * rotationVector.z);\n double horizontalVelocity = velocity.horizontalLength();\n double rotationVectorLength = rotationVector.length();\n double cosPitch = Math.cos((double)pitch);\n cosPitch = cosPitch * cosPitch * Math.min(1.0, rotationVectorLength / 0.4);\n velocity = this.getVelocity().add(0.0, gravity * (-1.0 + cosPitch * 0.75), 0.0);\n if (velocity.y < 0.0 && rotationLength > 0.0) {\n double m = velocity.y * -0.1 * cosPitch;\n velocity = velocity.add(rotationVector.x * m / rotationLength, m, rotationVector.z * m / rotationLength);\n }\n\n if (pitch < 0.0F && rotationLength > 0.0) {\n double m = horizontalVelocity * (double)(-MathHelper.sin(pitch)) * 0.04;\n velocity = velocity.add(-rotationVector.x * m / rotationLength, m * 3.2, -rotationVector.z * m / rotationLength);\n }\n\n if (rotationLength > 0.0) {\n velocity = velocity.add((rotationVector.x / rotationLength * horizontalVelocity - velocity.x) * 0.1, 0.0, (rotationVector.z / rotationLength * horizontalVelocity - velocity.z) * 0.1);\n }\n\n if (this.isInFluid()) {\n this.setVelocity(velocity.multiply(0.8F, 0.8F, 0.8F));\n\n if (this.getVelocity().horizontalLength() < 0.04) {\n if (passenger != null) {\n passenger.stopRiding();\n }\n this.giveOrDrop(passenger);\n return;\n }\n } else {\n this.setVelocity(velocity.multiply(0.985F, 0.96F, 0.985F));\n }\n\n if (passenger instanceof ServerPlayerEntity player && this.age > 20 * 5 && this.soundTimer++ % 20 * 4 == 0) {\n var l = this.getVelocity().length();\n\n if (l > 0.05 && serverWorld.getGameRules().getBoolean(GlideGamerules.WIND_SOUND)) {\n player.networkHandler.sendPacket(new PlaySoundFromEntityS2CPacket(GlideSoundEvents.WIND, SoundCategory.AMBIENT, player, (float) MathHelper.clamp(l, 0.05, 0.8), this.random.nextFloat() * 0.2f + 0.9f, this.random.nextLong()));\n }\n }\n\n if (this.itemStack.getItem() instanceof HangGliderItem gliderItem) {\n gliderItem.tickGlider(serverWorld, this, passenger, this.itemStack);\n }\n\n this.move(MovementType.SELF, this.getVelocity());\n if (this.horizontalCollision && passenger != null) {\n double m = this.getVelocity().horizontalLength();\n double n = horizontalVelocity - m;\n float o = (float)(n * 10.0 - 3.0);\n if (o > 0.0F) {\n //this.playSound(passenger.getFallSound((int)o), 1.0F, 1.0F);\n passenger.damage(this.getDamageSources().flyIntoWall(), o);\n }\n }\n\n int i = ++this.damageTimer;\n if ((i % dmgTimeout == 0 && (i / dmgFrequency) % dmgTimeout == 0) || this.isOnFire()) {\n this.damageStack(dmg);\n this.emitGameEvent(GameEvent.ELYTRA_GLIDE);\n }\n }\n\n @Override\n public ActionResult interact(PlayerEntity player, Hand hand) {\n if (this.getFirstPassenger() != null) {\n return ActionResult.FAIL;\n }\n\n player.startRiding(this);\n\n return ActionResult.SUCCESS;\n }\n\n @Override\n protected void tickInVoid() {\n if (GlideDimensionTypeTags.isIn(this.getWorld(), GlideDimensionTypeTags.VOID_PICKUP)) {\n this.giveOrDrop(this.getFirstPassenger());\n } else {\n super.tickInVoid();\n }\n }\n\n @Override\n public EntityType<?> getPolymerEntityType(ServerPlayerEntity player) {\n return EntityType.ITEM_DISPLAY;\n }\n\n @Override\n public void modifyRawTrackedData(List<DataTracker.SerializedEntry<?>> data, ServerPlayerEntity player, boolean initial) {\n if (initial) {\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.TELEPORTATION_DURATION, 2));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.INTERPOLATION_DURATION, 2));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.Item.ITEM, this.modelStack));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.TRANSLATION, new Vector3f(0, 1.2f, -0.05f)));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.SCALE, new Vector3f(1.5f)));\n }\n\n for (var entry : data.toArray(new DataTracker.SerializedEntry<?>[0])) {\n if (entry.id() == ROLL.getId()) {\n data.remove(entry);\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.LEFT_ROTATION, new Quaternionf().rotateZ((Float) entry.value())));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.START_INTERPOLATION, 0));\n }\n }\n }\n\n @Override\n protected void initDataTracker() {\n this.dataTracker.startTracking(ROLL, 0f);\n }\n\n @Override\n protected void readCustomDataFromNbt(NbtCompound nbt) {\n setItemStack(ItemStack.fromNbt(nbt.getCompound(\"stack\")));\n }\n\n @Override\n protected void writeCustomDataToNbt(NbtCompound nbt) {\n nbt.put(\"stack\", this.itemStack.writeNbt(new NbtCompound()));\n }\n\n public ItemStack getItemStack() {\n return this.itemStack;\n }\n}" }, { "identifier": "ServerPlayNetworkHandlerAccessor", "path": "src/main/java/eu/pb4/glideaway/mixin/ServerPlayNetworkHandlerAccessor.java", "snippet": "@Mixin(ServerPlayNetworkHandler.class)\npublic interface ServerPlayNetworkHandlerAccessor {\n @Accessor\n void setFloatingTicks(int floatingTicks);\n}" } ]
import eu.pb4.factorytools.api.item.ModeledItem; import eu.pb4.glideaway.entity.GliderEntity; import eu.pb4.glideaway.mixin.ServerPlayNetworkHandlerAccessor; import net.fabricmc.fabric.api.event.player.UseEntityCallback; import net.minecraft.advancement.criterion.Criteria; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.SmallFireballEntity; import net.minecraft.entity.projectile.WindChargeEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.particle.ParticleTypes; import net.minecraft.potion.PotionUtil; import net.minecraft.potion.Potions; import net.minecraft.resource.featuretoggle.FeatureFlags; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.stat.Stats; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraft.world.event.GameEvent;
5,011
package eu.pb4.glideaway.item; public class WindInABottleItem extends ModeledItem { private final boolean consume; public WindInABottleItem(Settings settings, boolean consume) { super(settings); this.consume = consume; } public ActionResult useOnEntityEvent(PlayerEntity user, World world, Hand hand, Entity entity, EntityHitResult result) { var stack = user.getStackInHand(hand); var hasWindCharge = world.getEnabledFeatures().contains(FeatureFlags.UPDATE_1_21); if (!world.isClient && hasWindCharge && entity instanceof WindChargeEntity windChargeEntity && stack.isOf(Items.GLASS_BOTTLE)) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, windChargeEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); windChargeEntity.discard(); return ActionResult.SUCCESS; } else if (!world.isClient && !hasWindCharge && entity instanceof SmallFireballEntity fireballEntity && stack.isOf(Items.POTION) && PotionUtil.getPotion(stack) == Potions.EMPTY) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, fireballEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); fireballEntity.discard(); return ActionResult.SUCCESS; } return ActionResult.PASS; } @Override public boolean hasGlint(ItemStack stack) { return !this.consume; } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
package eu.pb4.glideaway.item; public class WindInABottleItem extends ModeledItem { private final boolean consume; public WindInABottleItem(Settings settings, boolean consume) { super(settings); this.consume = consume; } public ActionResult useOnEntityEvent(PlayerEntity user, World world, Hand hand, Entity entity, EntityHitResult result) { var stack = user.getStackInHand(hand); var hasWindCharge = world.getEnabledFeatures().contains(FeatureFlags.UPDATE_1_21); if (!world.isClient && hasWindCharge && entity instanceof WindChargeEntity windChargeEntity && stack.isOf(Items.GLASS_BOTTLE)) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, windChargeEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); windChargeEntity.discard(); return ActionResult.SUCCESS; } else if (!world.isClient && !hasWindCharge && entity instanceof SmallFireballEntity fireballEntity && stack.isOf(Items.POTION) && PotionUtil.getPotion(stack) == Potions.EMPTY) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, fireballEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); fireballEntity.discard(); return ActionResult.SUCCESS; } return ActionResult.PASS; } @Override public boolean hasGlint(ItemStack stack) { return !this.consume; } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
if (user.getRootVehicle() instanceof GliderEntity glider) {
0
2023-12-22 11:00:52+00:00
8k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/web/interceptors/AutoLoginInterceptor.java
[ { "identifier": "User", "path": "src/main/java/es/storeapp/business/entities/User.java", "snippet": "@Entity(name = Constants.USER_ENTITY)\n@Table(name = Constants.USERS_TABLE)\npublic class User implements Serializable {\n\n private static final long serialVersionUID = 570528466125178223L;\n\n public User() {\n }\n\n public User(String name, String email, String password, String address, String image) {\n this.name = name;\n this.email = email;\n this.password = password;\n this.address = address;\n this.image = image;\n }\n \n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long userId;\n \n @NotBlank(message = \"Name cannot be null\")\n @Column(name = \"name\", nullable = false, unique = false)\n private String name;\n \n @Email(message = \"Email should be valid\")\n @NotBlank(message = \"Email cannot be null\")\n @Column(name = \"email\", nullable = false, unique = true)\n private String email;\n \n @Column(name = \"password\", nullable = false)\n private String password;\n\n @NotBlank(message = \"address cannot be null\")\n @Column(name = \"address\", nullable = false)\n private String address;\n\n @Column(name = \"resetPasswordToken\")\n private String resetPasswordToken;\n \n @Embedded\n @AttributeOverrides(value = {\n @AttributeOverride(name = \"card\", column = @Column(name = \"card\")),\n @AttributeOverride(name = \"cvv\", column = @Column(name = \"CVV\")),\n @AttributeOverride(name = \"expirationMonth\", column = @Column(name = \"expirationMonth\")),\n @AttributeOverride(name = \"expirationYear\", column = @Column(name = \"expirationYear\"))\n })\n private CreditCard card;\n \n @Column(name = \"image\")\n private String image;\n \n @OneToMany(mappedBy = \"user\")\n private List<Comment> comments = new ArrayList<>();\n \n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public CreditCard getCard() {\n return card;\n }\n\n public void setCard(CreditCard card) {\n this.card = card;\n }\n\n public List<Comment> getComments() {\n return comments;\n }\n\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n\n public String getResetPasswordToken() {\n return resetPasswordToken;\n }\n\n public void setResetPasswordToken(String resetPasswordToken) {\n this.resetPasswordToken = resetPasswordToken;\n }\n\n @Override\n public String toString() {\n return String.format(\"User{userId=%s, name=%s, email=%s, password=%s, address=%s, resetPasswordToken=%s, card=%s, image=%s}\", \n userId, name, email, password, address, resetPasswordToken, card, image);\n }\n\n}" }, { "identifier": "UserService", "path": "src/main/java/es/storeapp/business/services/UserService.java", "snippet": "@Service\npublic class UserService {\n\n private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(UserService.class);\n\n @Autowired\n ConfigurationParameters configurationParameters;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private MessageSource messageSource;\n\n @Autowired\n ExceptionGenerationUtils exceptionGenerationUtils;\n\n private File resourcesDir;\n\n @PostConstruct\n public void init() {\n resourcesDir = new File(configurationParameters.getResources());\n }\n\n @Transactional(readOnly = true)\n public User findByEmail(String email) {\n return userRepository.findByEmail(email);\n }\n\n @Transactional(readOnly = true)\n public User login(String email, String clearPassword) throws AuthenticationException {\n if (!userRepository.existsUser(email)) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_USER_MESSAGE, email);\n }\n User user = userRepository.findByEmail(email);\n if (!BCrypt.checkpw(clearPassword, user.getPassword())) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_PASSWORD_MESSAGE, email);\n }\n return user;\n }\n\n @Transactional()\n public void sendResetPasswordEmail(String email, String url, Locale locale)\n throws AuthenticationException, ServiceException {\n User user = userRepository.findByEmail(email);\n if (user == null) {\n return;\n }\n String token = UUID.randomUUID().toString();\n\n try {\n\n System.setProperty(\"mail.smtp.ssl.protocols\", \"TLSv1.2\");\n\n HtmlEmail htmlEmail = new HtmlEmail();\n htmlEmail.setHostName(configurationParameters.getMailHost());\n htmlEmail.setSmtpPort(configurationParameters.getMailPort());\n htmlEmail.setSslSmtpPort(Integer.toString(configurationParameters.getMailPort()));\n htmlEmail.setAuthentication(configurationParameters.getMailUserName(),\n configurationParameters.getMailPassword());\n htmlEmail.setSSLOnConnect(configurationParameters.getMailSslEnable() != null\n && configurationParameters.getMailSslEnable());\n if (configurationParameters.getMailStartTlsEnable()) {\n htmlEmail.setStartTLSEnabled(true);\n htmlEmail.setStartTLSRequired(true);\n }\n htmlEmail.addTo(email, user.getName());\n htmlEmail.setFrom(configurationParameters.getMailFrom());\n htmlEmail.setSubject(messageSource.getMessage(Constants.MAIL_SUBJECT_MESSAGE,\n new Object[]{user.getName()}, locale));\n\n String link = url + Constants.PARAMS\n + Constants.TOKEN_PARAM + Constants.PARAM_VALUE + token + Constants.NEW_PARAM_VALUE\n + Constants.EMAIL_PARAM + Constants.PARAM_VALUE + email;\n\n htmlEmail.setHtmlMsg(messageSource.getMessage(Constants.MAIL_TEMPLATE_MESSAGE,\n new Object[]{user.getName(), link}, locale));\n\n htmlEmail.setTextMsg(messageSource.getMessage(Constants.MAIL_HTML_NOT_SUPPORTED_MESSAGE,\n new Object[0], locale));\n\n htmlEmail.send();\n } catch (Exception ex) {\n logger.error(ex.getMessage(), ex);\n throw new ServiceException(ex.getMessage());\n }\n\n user.setResetPasswordToken(token);\n userRepository.update(user);\n }\n\n @Transactional\n public User create(String name, String email, String password, String address,\n String image, byte[] imageContents) throws DuplicatedResourceException {\n if (userRepository.findByEmail(email) != null) {\n throw exceptionGenerationUtils.toDuplicatedResourceException(Constants.EMAIL_FIELD, email,\n Constants.DUPLICATED_INSTANCE_MESSAGE);\n }\n User user = userRepository.create(new User(name, email, BCrypt.hashpw(password, BCrypt.gensalt()), address, image));\n saveProfileImage(user.getUserId(), image, imageContents);\n return user;\n }\n\n @Transactional\n public User update(Long id, String name, String email, String address, String image, byte[] imageContents)\n throws DuplicatedResourceException, InstanceNotFoundException, ServiceException {\n User user = userRepository.findById(id);\n User emailUser = userRepository.findByEmail(email);\n if (emailUser != null && !Objects.equals(emailUser.getUserId(), user.getUserId())) {\n throw exceptionGenerationUtils.toDuplicatedResourceException(Constants.EMAIL_FIELD, email,\n Constants.DUPLICATED_INSTANCE_MESSAGE);\n }\n user.setName(name);\n user.setEmail(email);\n user.setAddress(address);\n if (image != null && image.trim().length() > 0 && imageContents != null) {\n try {\n deleteProfileImage(id, user.getImage());\n } catch (Exception ex) {\n logger.error(ex.getMessage(), ex);\n }\n saveProfileImage(id, image, imageContents);\n user.setImage(image);\n }\n return userRepository.update(user);\n }\n\n @Transactional\n public User changePassword(Long id, String oldPassword, String password)\n throws InstanceNotFoundException, AuthenticationException {\n User user = userRepository.findById(id);\n if (user == null) {\n throw exceptionGenerationUtils.toAuthenticationException(\n Constants.AUTH_INVALID_USER_MESSAGE, id.toString());\n }\n if (userRepository.findByEmailAndPassword(user.getEmail(), BCrypt.hashpw(oldPassword, BCrypt.gensalt())) == null) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_PASSWORD_MESSAGE,\n id.toString());\n }\n user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));\n return userRepository.update(user);\n }\n\n @Transactional\n public User changePassword(String email, String password, String token) throws AuthenticationException {\n User user = userRepository.findByEmail(email);\n if (user == null) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_USER_MESSAGE, email);\n }\n if (user.getResetPasswordToken() == null || !user.getResetPasswordToken().equals(token)) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_TOKEN_MESSAGE, email);\n }\n user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));\n user.setResetPasswordToken(null);\n return userRepository.update(user);\n }\n\n @Transactional\n public User removeImage(Long id) throws InstanceNotFoundException, ServiceException {\n User user = userRepository.findById(id);\n try {\n deleteProfileImage(id, user.getImage());\n } catch (IOException ex) {\n logger.error(ex.getMessage(), ex);\n throw new ServiceException(ex.getMessage());\n }\n user.setImage(null);\n return userRepository.update(user);\n }\n\n @Transactional\n public byte[] getImage(Long id) throws InstanceNotFoundException {\n User user = userRepository.findById(id);\n try {\n return getProfileImage(id, user.getImage());\n } catch (IOException ex) {\n logger.error(ex.getMessage(), ex);\n return null;\n }\n }\n\n private void saveProfileImage(Long id, String image, byte[] imageContents) {\n if (image != null && image.trim().length() > 0 && imageContents != null) {\n File userDir = new File(resourcesDir, id.toString());\n userDir.mkdirs();\n File profilePicture = new File(userDir, image);\n try (FileOutputStream outputStream = new FileOutputStream(profilePicture);) {\n IOUtils.copy(new ByteArrayInputStream(imageContents), outputStream);\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n }\n }\n }\n\n private void deleteProfileImage(Long id, String image) throws IOException {\n if (image != null && image.trim().length() > 0) {\n File userDir = new File(resourcesDir, id.toString());\n File profilePicture = new File(userDir, image);\n Files.delete(profilePicture.toPath());\n }\n }\n\n private byte[] getProfileImage(Long id, String image) throws IOException {\n if (image != null && image.trim().length() > 0) {\n File userDir = new File(resourcesDir, id.toString());\n File profilePicture = new File(userDir, image);\n try (FileInputStream input = new FileInputStream(profilePicture)) {\n return IOUtils.toByteArray(input);\n }\n }\n return null;\n }\n\n}" }, { "identifier": "Constants", "path": "src/main/java/es/storeapp/common/Constants.java", "snippet": "public class Constants {\n\n private Constants() {\n }\n \n /* Messages */\n \n public static final String AUTH_INVALID_USER_MESSAGE = \"auth.invalid.user\";\n public static final String AUTH_INVALID_PASSWORD_MESSAGE = \"auth.invalid.password\";\n public static final String AUTH_INVALID_TOKEN_MESSAGE = \"auth.invalid.token\";\n public static final String REGISTRATION_INVALID_PARAMS_MESSAGE = \"registration.invalid.parameters\";\n public static final String UPDATE_PROFILE_INVALID_PARAMS_MESSAGE = \"update.profile.invalid.parameters\";\n public static final String CHANGE_PASSWORD_INVALID_PARAMS_MESSAGE = \"change.password.invalid.parameters\";\n public static final String RESET_PASSWORD_INVALID_PARAMS_MESSAGE = \"reset.password.invalid.parameters\";\n public static final String LOGIN_INVALID_PARAMS_MESSAGE = \"login.invalid.parameters\";\n public static final String INSTANCE_NOT_FOUND_MESSAGE = \"instance.not.found.exception\";\n public static final String DUPLICATED_INSTANCE_MESSAGE = \"duplicated.instance.exception\";\n public static final String DUPLICATED_COMMENT_MESSAGE = \"duplicated.comment.exception\";\n public static final String INVALID_PROFILE_IMAGE_MESSAGE = \"invalid.profile.image\";\n public static final String INVALID_STATE_EXCEPTION_MESSAGE = \"invalid.state\";\n public static final String INVALID_EMAIL_MESSAGE = \"invalid.email\";\n \n public static final String PRODUCT_ADDED_TO_THE_SHOPPING_CART = \"product.added.to.the.cart\";\n public static final String PRODUCT_REMOVED_FROM_THE_SHOPPING_CART = \"product.removed.from.the.cart\";\n public static final String PRODUCT_ALREADY_IN_SHOPPING_CART = \"product.already.in.cart\";\n public static final String PRODUCT_NOT_IN_SHOPPING_CART = \"product.not.in.cart\";\n public static final String EMPTY_SHOPPING_CART = \"shopping.cart.empty\";\n public static final String PRODUCT_COMMENT_CREATED = \"product.comment.created\";\n \n public static final String ORDER_AUTOGENERATED_NAME = \"order.name.autogenerated\";\n public static final String ORDER_SINGLE_PRODUCT_AUTOGENERATED_NAME_MESSAGE = \"order.name.single.product.autogenerated\";\n public static final String CREATE_ORDER_INVALID_PARAMS_MESSAGE = \"create.order.invalid.parameters\";\n public static final String PAY_ORDER_INVALID_PARAMS_MESSAGE = \"pay.order.invalid.parameters\";\n public static final String CANCEL_ORDER_INVALID_PARAMS_MESSAGE = \"cancel.order.invalid.parameters\";\n \n public static final String ORDER_CREATED_MESSAGE = \"order.created\";\n public static final String ORDER_PAYMENT_COMPLETE_MESSAGE = \"order.payment.completed\";\n public static final String ORDER_CANCEL_COMPLETE_MESSAGE = \"order.cancellation.completed\";\n \n public static final String REGISTRATION_SUCCESS_MESSAGE = \"registration.success\";\n public static final String PROFILE_UPDATE_SUCCESS = \"profile.updated.success\";\n public static final String CHANGE_PASSWORD_SUCCESS = \"change.password.success\";\n \n public static final String MAIL_SUBJECT_MESSAGE = \"mail.subject\";\n public static final String MAIL_TEMPLATE_MESSAGE = \"mail.template\";\n public static final String MAIL_HTML_NOT_SUPPORTED_MESSAGE = \"mail.html.not.supported\";\n public static final String MAIL_SUCCESS_MESSAGE = \"mail.sent.success\";\n public static final String MAIL_NOT_CONFIGURED_MESSAGE = \"mail.not.configured\";\n \n /* Web Endpoints */\n \n public static final String ROOT_ENDPOINT = \"/\";\n public static final String ALL_ENDPOINTS = \"/**\";\n public static final String LOGIN_ENDPOINT = \"/login\";\n public static final String LOGOUT_ENDPOINT = \"/logout\";\n public static final String USER_PROFILE_ALL_ENDPOINTS = \"/profile/**\";\n public static final String USER_PROFILE_ENDPOINT = \"/profile\";\n public static final String USER_PROFILE_IMAGE_ENDPOINT = \"/profile/image\";\n public static final String USER_PROFILE_IMAGE_REMOVE_ENDPOINT = \"/profile/image/remove\";\n public static final String REGISTRATION_ENDPOINT = \"/registration\";\n public static final String ORDERS_ALL_ENDPOINTS = \"/orders/**\";\n public static final String ORDERS_ENDPOINT = \"/orders\";\n public static final String ORDER_ENDPOINT = \"/orders/{id}\";\n public static final String ORDER_ENDPOINT_TEMPLATE = \"/orders/{0}\";\n public static final String ORDER_CONFIRM_ENDPOINT = \"/orders/complete\";\n public static final String ORDER_PAYMENT_ENDPOINT = \"/orders/{id}/pay\";\n public static final String ORDER_PAYMENT_ENDPOINT_TEMPLATE = \"/orders/{0}/pay\";\n public static final String ORDER_CANCEL_ENDPOINT = \"/orders/{id}/cancel\";\n public static final String PRODUCTS_ENDPOINT = \"/products\";\n public static final String PRODUCT_ENDPOINT = \"/products/{id}\";\n public static final String PRODUCT_TEMPLATE = \"/products/{0}\";\n public static final String CHANGE_PASSWORD_ENDPOINT = \"/changePassword\";\n public static final String RESET_PASSWORD_ENDPOINT = \"/resetPassword\";\n public static final String SEND_EMAIL_ENDPOINT = \"/sendEmail\";\n public static final String CART_ADD_PRODUCT_ENDPOINT = \"/products/{id}/addToCart\";\n public static final String CART_REMOVE_PRODUCT_ENDPOINT = \"/products/{id}/removeFromCart\";\n public static final String CART_ENDPOINT = \"/cart\";\n public static final String COMMENT_PRODUCT_ENDPOINT = \"/products/{id}/rate\";\n public static final String EXTERNAL_RESOURCES = \"/resources/**\";\n public static final String LIBS_RESOURCES = \"/webjars/**\";\n public static final String SEND_REDIRECT = \"redirect:\";\n \n /* Web Pages */\n \n public static final String LOGIN_PAGE = \"Login\";\n public static final String HOME_PAGE = \"Index\";\n public static final String ERROR_PAGE = \"error\";\n public static final String PASSWORD_PAGE = \"ChangePassword\";\n public static final String SEND_EMAIL_PAGE = \"SendEmail\";\n public static final String RESET_PASSWORD_PAGE = \"ResetPassword\";\n public static final String USER_PROFILE_PAGE = \"Profile\";\n public static final String PRODUCTS_PAGE = \"Products\";\n public static final String PRODUCT_PAGE = \"Product\";\n public static final String SHOPPING_CART_PAGE = \"Cart\";\n public static final String ORDER_COMPLETE_PAGE = \"OrderConfirm\";\n public static final String ORDER_PAGE = \"Order\";\n public static final String ORDER_PAYMENT_PAGE = \"Payment\";\n public static final String ORDERS_PAGE = \"Orders\";\n public static final String PAYMENTS_PAGE = \"Orders\";\n public static final String COMMENT_PAGE = \"Comment\";\n \n /* Request/session/model Attributes */\n \n public static final String PARAMS = \"?\";\n public static final String PARAM_VALUE = \"=\";\n public static final String NEW_PARAM_VALUE = \"&\";\n public static final String USER_SESSION = \"user\";\n public static final String SHOPPING_CART_SESSION = \"shoppingCart\";\n public static final String ERROR_MESSAGE = \"errorMessage\";\n public static final String EXCEPTION = \"exception\";\n public static final String WARNING_MESSAGE = \"warningMessage\";\n public static final String SUCCESS_MESSAGE = \"successMessage\";\n public static final String MESSAGE = \"message\"; /* predefined */\n public static final String LOGIN_FORM = \"loginForm\";\n public static final String USER_PROFILE_FORM = \"userProfileForm\";\n public static final String PASSWORD_FORM = \"passwordForm\";\n public static final String RESET_PASSWORD_FORM = \"resetPasswordForm\";\n public static final String COMMENT_FORM = \"commentForm\";\n public static final String PAYMENT_FORM = \"paymentForm\";\n public static final String NEXT_PAGE = \"next\";\n public static final String CATEGORIES = \"categories\";\n public static final String PRODUCTS = \"products\";\n public static final String PRODUCTS_ARRAY = \"products[]\";\n public static final String PRODUCT = \"product\";\n public static final String ORDER_FORM = \"orderForm\";\n public static final String ORDERS = \"orders\";\n public static final String ORDER = \"order\";\n public static final String PAY_NOW = \"pay\";\n public static final String BUY_BY_USER = \"buyByUser\";\n public static final String EMAIL_PARAM = \"email\";\n public static final String TOKEN_PARAM = \"token\";\n \n /* Entities, attributes and tables */\n \n public static final String USER_ENTITY = \"User\";\n public static final String PRODUCT_ENTITY = \"Product\";\n public static final String CATEGORY_ENTITY = \"Category\";\n public static final String COMMENT_ENTITY = \"Comment\";\n public static final String ORDER_ENTITY = \"Order\";\n public static final String ORDER_LINE_ENTITY = \"OrderLine\";\n \n public static final String USERS_TABLE = \"Users\";\n public static final String PRODUCTS_TABLE = \"Products\";\n public static final String CATEGORIES_TABLE = \"Categories\";\n public static final String COMMENTS_TABLE = \"Comments\";\n public static final String ORDERS_TABLE = \"Orders\";\n public static final String ORDER_LINES_TABLE = \"OrderLines\";\n \n public static final String PRICE_FIELD = \"price\";\n public static final String NAME_FIELD = \"name\";\n public static final String EMAIL_FIELD = \"email\";\n \n /* Other */\n \n public static final String CONTENT_TYPE_HEADER = \"Content-Type\";\n public static final String CONTENT_DISPOSITION_HEADER = \"Content-Disposition\";\n public static final String CONTENT_DISPOSITION_HEADER_VALUE = \"attachment; filename={0}-{1}\";\n public static final String PERSISTENT_USER_COOKIE = \"user-info\";\n public static final String URL_FORMAT = \"{0}://{1}:{2}{3}{4}\";\n \n}" }, { "identifier": "UserInfo", "path": "src/main/java/es/storeapp/web/cookies/UserInfo.java", "snippet": "@XmlRootElement(name=\"UserInfo\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class UserInfo {\n\n @XmlElement\n private String email;\n @XmlElement\n private String password;\n\n public UserInfo() {\n }\n\n public UserInfo(String email, String password) {\n this.email = email;\n this.password = password;\n }\n \n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n \n}" } ]
import es.storeapp.business.entities.User; import es.storeapp.business.services.UserService; import es.storeapp.common.Constants; import es.storeapp.web.cookies.UserInfo; import java.io.ByteArrayInputStream; import java.util.Base64; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor;
5,229
package es.storeapp.web.interceptors; public class AutoLoginInterceptor implements HandlerInterceptor { private final UserService userService; public AutoLoginInterceptor(UserService userService) { this.userService = userService; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(true); if (session.getAttribute(Constants.USER_SESSION) != null || request.getCookies() == null) { return true; } for (Cookie c : request.getCookies()) { if (Constants.PERSISTENT_USER_COOKIE.equals(c.getName())) { String cookieValue = c.getValue(); if (cookieValue == null) { continue; } Base64.Decoder decoder = Base64.getDecoder();
package es.storeapp.web.interceptors; public class AutoLoginInterceptor implements HandlerInterceptor { private final UserService userService; public AutoLoginInterceptor(UserService userService) { this.userService = userService; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(true); if (session.getAttribute(Constants.USER_SESSION) != null || request.getCookies() == null) { return true; } for (Cookie c : request.getCookies()) { if (Constants.PERSISTENT_USER_COOKIE.equals(c.getName())) { String cookieValue = c.getValue(); if (cookieValue == null) { continue; } Base64.Decoder decoder = Base64.getDecoder();
JAXBContext context = JAXBContext.newInstance(UserInfo.class);
3
2023-12-24 19:24:49+00:00
8k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/view/RankFrame.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素\", currentUser = \"\";\r\n public static final String[] themeList = {\"典雅\", \"激情\", \"像素\"};\r\n\r\n private static RankFrame rankFrame = null;\r\n public static boolean hasLogon = false;\r\n public static int currentUserId = 0, mode = 0;\r\n public static Map<String, JsonElement> data;\r\n public static ArrayList<String> userList = new ArrayList<>();\r\n public static ArrayList<Integer> scoresList = new ArrayList<>();\r\n\r\n public static void main(String[] args) {\r\n Gson gson = new Gson();\r\n\r\n FlatLightLaf.setup();\r\n\r\n String raw = FileUtils.getDataFromFile(\"data\");\r\n if (raw == null) raw = \"{}\";\r\n try {\r\n data = JsonParser.parseString(raw).getAsJsonObject().asMap();\r\n } catch (Exception e) {\r\n System.out.println(e.getMessage());\r\n data = new HashMap<>();\r\n }\r\n if (gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType()) == null)\r\n userList.add(\"test\");\r\n else\r\n userList = gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType());\r\n if (gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType()) == null)\r\n scoresList.add(0);\r\n else\r\n scoresList = gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType());\r\n theme = gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType()) == null ? \"像素\" : gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType());\r\n\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/FZShiGKSJW.TTF\");\r\n titleFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n titleFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SweiSpringCJKtc-Medium.ttf\");\r\n serifFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n serifFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SourceHanSansCN-Regular.otf\");\r\n sansFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n sansFont = Font.getFont(Font.SANS_SERIF);\r\n }\r\n\r\n SwingUtilities.invokeLater(Main::backStart);\r\n\r\n playBGMusic();\r\n }\r\n\r\n public static void startGame(int mode) {\r\n Main.mode = mode;\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n if (startFrame != null) startFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n playNotifyMusic(\"gamestart\");\r\n }\r\n\r\n public static void goRank() {\r\n rankFrame = new RankFrame(480, 720);\r\n rankFrame.setVisible(true);\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (startFrame != null) startFrame.dispose();\r\n }\r\n\r\n public static void refreshGame() {\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n }\r\n\r\n public static void backStart() {\r\n startFrame = new StartFrame(480, 720);\r\n startFrame.setVisible(true);\r\n if (rankFrame != null) rankFrame.dispose();\r\n if (gameFrame != null) gameFrame.dispose();\r\n }\r\n\r\n\r\n public static String getThemeResource(String type) {\r\n switch (type) {\r\n case \"bg\":\r\n if (theme.equals(themeList[0])) return \"Resources/background1.jpg\";\r\n if (theme.equals(themeList[1])) return \"Resources/background2.jpg\";\r\n else return \"Resources/background3.jpg\";\r\n case \"startbtn\":\r\n if (theme.equals(themeList[0])) return \"Resources/button2.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/button1.png\";\r\n else return \"Resources/button3.png\";\r\n case \"btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"md-btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn-md.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"board\":\r\n if (theme.equals(themeList[0])) return \"Resources/board1.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/board2.png\";\r\n else return \"Resources/board3.png\";\r\n case \"chess-pixel\":\r\n return \"Resources/pixel-chess.png\";\r\n case \"chess-pixel-sel\":\r\n return \"Resources/pixel-chess-sel.png\";\r\n case \"chess-pixel-opq\":\r\n return \"Resources/pixel-chess-opq.png\";\r\n case \"chessfill\":\r\n if (theme.equals(themeList[0])) return \"#f6b731\";\r\n else return \"#E28B24\";\r\n case \"chessfillopaque\":\r\n if (theme.equals(themeList[0])) return \"#f2deb2\";\r\n else return \"#dca35f\";\r\n case \"chessborder\":\r\n if (theme.equals(themeList[0])) return \"#e3914a\";\r\n else return \"#B3391F\";\r\n }\r\n return \"\";\r\n }\r\n\r\n public static Color getThemeColor(String type) {\r\n switch (type) {\r\n case \"indicatorBlack\":\r\n if (theme.equals(themeList[0]) || theme.equals(themeList[2]))\r\n return ChessColor.BLACK.getColor();\r\n else return Color.WHITE;\r\n case \"indicatorRed\":\r\n return ChessColor.RED.getColor();\r\n case \"title\":\r\n if (theme.equals(themeList[0])) return Color.WHITE;\r\n else return Color.BLACK;\r\n case \"black\":\r\n return Color.BLACK;\r\n }\r\n return Color.BLACK;\r\n }\r\n\r\n public static void playBGMusic() {\r\n playMusic(\"Resources/bgm1.wav\", 0f, true);\r\n }\r\n\r\n public static void playNotifyMusic(String id) {\r\n playMusic(\"Resources/\" + id + \".wav\", (id.equals(\"click\") ? 5f : 0f), false);\r\n }\r\n\r\n private static void playMusic(String filePath, float volume, boolean shouldLoop) {\r\n try {\r\n if (Main.class.getResourceAsStream(filePath) != null) {\r\n BufferedInputStream musicPath =\r\n new BufferedInputStream(Objects.requireNonNull(Main.class.getResourceAsStream(filePath)));\r\n Clip clip1;\r\n AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);\r\n clip1 = AudioSystem.getClip();\r\n clip1.open(audioInput);\r\n FloatControl gainControl = (FloatControl) clip1.getControl(FloatControl.Type.MASTER_GAIN);\r\n gainControl.setValue(volume); //设置音量,范围为 -60.0f 到 6.0f\r\n clip1.start();\r\n clip1.loop(shouldLoop ? Clip.LOOP_CONTINUOUSLY : 0);\r\n } else {\r\n log(\"Cannot find music\");\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n}\r" }, { "identifier": "ImageUtils", "path": "CS109_2022_Fall/Chess/utils/ImageUtils.java", "snippet": "public class ImageUtils {\r\n public static ImageIcon changeImageSize(ImageIcon image, float i) {\r\n int width = (int) (image.getIconWidth() * i);\r\n int height = (int) (image.getIconHeight() * i);\r\n Image img = image.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);\r\n return new ImageIcon(img);\r\n }\r\n\r\n public static ImageIcon changeToOriginalSize(ImageIcon image, int width, int height) {\r\n Image img = image.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);\r\n return new ImageIcon(img);\r\n }\r\n}\r" }, { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素\", currentUser = \"\";\r\n public static final String[] themeList = {\"典雅\", \"激情\", \"像素\"};\r\n\r\n private static RankFrame rankFrame = null;\r\n public static boolean hasLogon = false;\r\n public static int currentUserId = 0, mode = 0;\r\n public static Map<String, JsonElement> data;\r\n public static ArrayList<String> userList = new ArrayList<>();\r\n public static ArrayList<Integer> scoresList = new ArrayList<>();\r\n\r\n public static void main(String[] args) {\r\n Gson gson = new Gson();\r\n\r\n FlatLightLaf.setup();\r\n\r\n String raw = FileUtils.getDataFromFile(\"data\");\r\n if (raw == null) raw = \"{}\";\r\n try {\r\n data = JsonParser.parseString(raw).getAsJsonObject().asMap();\r\n } catch (Exception e) {\r\n System.out.println(e.getMessage());\r\n data = new HashMap<>();\r\n }\r\n if (gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType()) == null)\r\n userList.add(\"test\");\r\n else\r\n userList = gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType());\r\n if (gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType()) == null)\r\n scoresList.add(0);\r\n else\r\n scoresList = gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType());\r\n theme = gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType()) == null ? \"像素\" : gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType());\r\n\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/FZShiGKSJW.TTF\");\r\n titleFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n titleFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SweiSpringCJKtc-Medium.ttf\");\r\n serifFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n serifFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SourceHanSansCN-Regular.otf\");\r\n sansFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n sansFont = Font.getFont(Font.SANS_SERIF);\r\n }\r\n\r\n SwingUtilities.invokeLater(Main::backStart);\r\n\r\n playBGMusic();\r\n }\r\n\r\n public static void startGame(int mode) {\r\n Main.mode = mode;\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n if (startFrame != null) startFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n playNotifyMusic(\"gamestart\");\r\n }\r\n\r\n public static void goRank() {\r\n rankFrame = new RankFrame(480, 720);\r\n rankFrame.setVisible(true);\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (startFrame != null) startFrame.dispose();\r\n }\r\n\r\n public static void refreshGame() {\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n }\r\n\r\n public static void backStart() {\r\n startFrame = new StartFrame(480, 720);\r\n startFrame.setVisible(true);\r\n if (rankFrame != null) rankFrame.dispose();\r\n if (gameFrame != null) gameFrame.dispose();\r\n }\r\n\r\n\r\n public static String getThemeResource(String type) {\r\n switch (type) {\r\n case \"bg\":\r\n if (theme.equals(themeList[0])) return \"Resources/background1.jpg\";\r\n if (theme.equals(themeList[1])) return \"Resources/background2.jpg\";\r\n else return \"Resources/background3.jpg\";\r\n case \"startbtn\":\r\n if (theme.equals(themeList[0])) return \"Resources/button2.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/button1.png\";\r\n else return \"Resources/button3.png\";\r\n case \"btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"md-btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn-md.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"board\":\r\n if (theme.equals(themeList[0])) return \"Resources/board1.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/board2.png\";\r\n else return \"Resources/board3.png\";\r\n case \"chess-pixel\":\r\n return \"Resources/pixel-chess.png\";\r\n case \"chess-pixel-sel\":\r\n return \"Resources/pixel-chess-sel.png\";\r\n case \"chess-pixel-opq\":\r\n return \"Resources/pixel-chess-opq.png\";\r\n case \"chessfill\":\r\n if (theme.equals(themeList[0])) return \"#f6b731\";\r\n else return \"#E28B24\";\r\n case \"chessfillopaque\":\r\n if (theme.equals(themeList[0])) return \"#f2deb2\";\r\n else return \"#dca35f\";\r\n case \"chessborder\":\r\n if (theme.equals(themeList[0])) return \"#e3914a\";\r\n else return \"#B3391F\";\r\n }\r\n return \"\";\r\n }\r\n\r\n public static Color getThemeColor(String type) {\r\n switch (type) {\r\n case \"indicatorBlack\":\r\n if (theme.equals(themeList[0]) || theme.equals(themeList[2]))\r\n return ChessColor.BLACK.getColor();\r\n else return Color.WHITE;\r\n case \"indicatorRed\":\r\n return ChessColor.RED.getColor();\r\n case \"title\":\r\n if (theme.equals(themeList[0])) return Color.WHITE;\r\n else return Color.BLACK;\r\n case \"black\":\r\n return Color.BLACK;\r\n }\r\n return Color.BLACK;\r\n }\r\n\r\n public static void playBGMusic() {\r\n playMusic(\"Resources/bgm1.wav\", 0f, true);\r\n }\r\n\r\n public static void playNotifyMusic(String id) {\r\n playMusic(\"Resources/\" + id + \".wav\", (id.equals(\"click\") ? 5f : 0f), false);\r\n }\r\n\r\n private static void playMusic(String filePath, float volume, boolean shouldLoop) {\r\n try {\r\n if (Main.class.getResourceAsStream(filePath) != null) {\r\n BufferedInputStream musicPath =\r\n new BufferedInputStream(Objects.requireNonNull(Main.class.getResourceAsStream(filePath)));\r\n Clip clip1;\r\n AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);\r\n clip1 = AudioSystem.getClip();\r\n clip1.open(audioInput);\r\n FloatControl gainControl = (FloatControl) clip1.getControl(FloatControl.Type.MASTER_GAIN);\r\n gainControl.setValue(volume); //设置音量,范围为 -60.0f 到 6.0f\r\n clip1.start();\r\n clip1.loop(shouldLoop ? Clip.LOOP_CONTINUOUSLY : 0);\r\n } else {\r\n log(\"Cannot find music\");\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n}\r" } ]
import Chess.Main; import Chess.utils.ImageUtils; import com.google.gson.Gson; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import static Chess.Main.*; import static javax.swing.ListSelectionModel.SINGLE_SELECTION;
4,204
package Chess.view; public class RankFrame extends JFrame { private final int WIDTH; private final int HEIGHT; private Gson gson = new Gson(); public RankFrame(int width, int height) { setTitle("本地玩家排行"); this.WIDTH = width; this.HEIGHT = height; setSize(WIDTH, HEIGHT); setResizable(false); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addBackButton(); addList(); addBg(); } private void addList() { ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < scoresList.size(); i++) { arr.add(" " + userList.get(i) + " " + scoresList.get(i)); } arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(" ")[2]), Integer.parseInt(o1.split(" ")[2]))); for (int i = 0; i < arr.size(); i++) { arr.set(i, " " + arr.get(i)); } JList<String> list = new JList<>(arr.toArray(new String[0])); list.setBackground(new Color(0, 0, 0, 0)); list.setOpaque(false);//workaround keep opaque after repainted list.setFont(sansFont.deriveFont(Font.PLAIN, 18)); list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5); add(list); // chess board as bg workaround
package Chess.view; public class RankFrame extends JFrame { private final int WIDTH; private final int HEIGHT; private Gson gson = new Gson(); public RankFrame(int width, int height) { setTitle("本地玩家排行"); this.WIDTH = width; this.HEIGHT = height; setSize(WIDTH, HEIGHT); setResizable(false); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addBackButton(); addList(); addBg(); } private void addList() { ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < scoresList.size(); i++) { arr.add(" " + userList.get(i) + " " + scoresList.get(i)); } arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(" ")[2]), Integer.parseInt(o1.split(" ")[2]))); for (int i = 0; i < arr.size(); i++) { arr.set(i, " " + arr.get(i)); } JList<String> list = new JList<>(arr.toArray(new String[0])); list.setBackground(new Color(0, 0, 0, 0)); list.setOpaque(false);//workaround keep opaque after repainted list.setFont(sansFont.deriveFont(Font.PLAIN, 18)); list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5); add(list); // chess board as bg workaround
InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("board"));
2
2023-12-31 05:50:13+00:00
8k
Patbox/serveruifix
src/main/java/eu/pb4/serveruifix/ModInit.java
[ { "identifier": "PolydexCompat", "path": "src/main/java/eu/pb4/serveruifix/polydex/PolydexCompat.java", "snippet": "public class PolydexCompat {\n private static final boolean IS_PRESENT = FabricLoader.getInstance().isModLoaded(\"polydex2\");\n\n\n public static void register() {\n if (IS_PRESENT) {\n PolydexCompatImpl.register();\n } else {\n //LOGGER.warn(\"[PolyDecorations] Polydex not found! It's highly suggested to install it!\");\n }\n }\n\n\n public static GuiElement getButton(RecipeType<?> type) {\n if (IS_PRESENT) {\n return PolydexCompatImpl.getButton(type);\n }\n return GuiElement.EMPTY;\n }\n}" }, { "identifier": "GuiTextures", "path": "src/main/java/eu/pb4/serveruifix/util/GuiTextures.java", "snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> STONECUTTER = background(\"stonecutter\");\n\n public static final Supplier<GuiElementBuilder> POLYDEX_BUTTON = icon32(\"polydex\");\n public static final Supplier<GuiElementBuilder> LEFT_BUTTON = icon16(\"left\");\n public static final Supplier<GuiElementBuilder> RIGHT_BUTTON = icon16(\"right\");\n\n public static void register() {\n }\n\n\n public record Progress(GuiElement[] elements) {\n\n public GuiElement get(float progress) {\n return elements[Math.min((int) (progress * elements.length), elements.length - 1)];\n }\n\n public static Progress createVertical(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n public static Progress createVertical32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n }\n\n}" }, { "identifier": "UiResourceCreator", "path": "src/main/java/eu/pb4/serveruifix/util/UiResourceCreator.java", "snippet": "public class UiResourceCreator {\n public static final String BASE_MODEL = \"minecraft:item/generated\";\n public static final String X32_MODEL = \"serveruifix:sgui/button_32\";\n public static final String X32_RIGHT_MODEL = \"serveruifix:sgui/button_32_right\";\n\n private static final Style STYLE = Style.EMPTY.withColor(0xFFFFFF).withFont(id(\"gui\"));\n private static final String ITEM_TEMPLATE = \"\"\"\n {\n \"parent\": \"|BASE|\",\n \"textures\": {\n \"layer0\": \"|ID|\"\n }\n }\n \"\"\".replace(\" \", \"\").replace(\"\\n\", \"\");\n\n private static final List<SlicedTexture> VERTICAL_PROGRESS = new ArrayList<>();\n private static final List<SlicedTexture> HORIZONTAL_PROGRESS = new ArrayList<>();\n private static final List<Pair<PolymerModelData, String>> SIMPLE_MODEL = new ArrayList<>();\n private static final Char2IntMap SPACES = new Char2IntOpenHashMap();\n private static final Char2ObjectMap<Identifier> TEXTURES = new Char2ObjectOpenHashMap<>();\n private static final Object2ObjectMap<Pair<Character, Character>, Identifier> TEXTURES_POLYDEX = new Object2ObjectOpenHashMap<>();\n private static final List<String> TEXTURES_NUMBERS = new ArrayList<>();\n private static char character = 'a';\n\n private static final char CHEST_SPACE0 = character++;\n private static final char CHEST_SPACE1 = character++;\n\n public static Supplier<GuiElementBuilder> icon16(String path) {\n var model = genericIconRaw(Items.ALLIUM, path, BASE_MODEL);\n return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());\n }\n\n public static Supplier<GuiElementBuilder> icon32(String path) {\n var model = genericIconRaw(Items.ALLIUM, path, X32_MODEL);\n return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());\n }\n\n public static IntFunction<GuiElementBuilder> icon32Color(String path) {\n var model = genericIconRaw(Items.LEATHER_LEGGINGS, path, X32_MODEL);\n return (i) -> {\n var b = new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());\n var display = new NbtCompound();\n display.putInt(\"color\", i);\n b.getOrCreateNbt().put(\"display\", display);\n return b;\n };\n }\n\n public static IntFunction<GuiElementBuilder> icon16(String path, int size) {\n var models = new PolymerModelData[size];\n\n for (var i = 0; i < size; i++) {\n models[i] = genericIconRaw(Items.ALLIUM, path + \"_\" + i, BASE_MODEL);\n }\n return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());\n }\n\n public static IntFunction<GuiElementBuilder> horizontalProgress16(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, BASE_MODEL, HORIZONTAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> horizontalProgress32(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_MODEL, HORIZONTAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> horizontalProgress32Right(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, HORIZONTAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> verticalProgress32(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_MODEL, VERTICAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> verticalProgress32Right(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, VERTICAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> verticalProgress16(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, BASE_MODEL, VERTICAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> genericProgress(String path, int start, int stop, boolean reverse, String base, List<SlicedTexture> progressType) {\n\n var models = new PolymerModelData[stop - start];\n\n progressType.add(new SlicedTexture(path, start, stop, reverse));\n\n for (var i = start; i < stop; i++) {\n models[i - start] = genericIconRaw(Items.ALLIUM, \"gen/\" + path + \"_\" + i, base);\n }\n return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());\n }\n\n public static PolymerModelData genericIconRaw(Item item, String path, String base) {\n var model = PolymerResourcePackUtils.requestModel(item, elementPath(path));\n SIMPLE_MODEL.add(new Pair<>(model, base));\n return model;\n }\n\n private static Identifier elementPath(String path) {\n return id(\"sgui/elements/\" + path);\n }\n\n public static Function<Text, Text> background(String path) {\n var builder = new StringBuilder().append(CHEST_SPACE0);\n var c = (character++);\n builder.append(c);\n builder.append(CHEST_SPACE1);\n TEXTURES.put(c, id(\"sgui/\" + path));\n\n return new TextBuilders(Text.literal(builder.toString()).setStyle(STYLE));\n }\n\n public static Pair<Text, Text> polydexBackground(String path) {\n var c = (character++);\n var d = (character++);\n TEXTURES_POLYDEX.put(new Pair<>(c, d), id(\"sgui/polydex/\" + path));\n\n return new Pair<>(\n Text.literal(Character.toString(c)).setStyle(STYLE),\n Text.literal(Character.toString(d)).setStyle(STYLE)\n );\n }\n\n public static void setup() {\n SPACES.put(CHEST_SPACE0, -8);\n SPACES.put(CHEST_SPACE1, -168);\n\n if (ModInit.DYNAMIC_ASSETS) {\n PolymerResourcePackUtils.RESOURCE_PACK_CREATION_EVENT.register((b) -> UiResourceCreator.generateAssets(b::addData));\n }\n }\n\n /*private static void generateProgress(BiConsumer<String, byte[]> assetWriter, List<SlicedTexture> list, boolean horizontal) {\n for (var pair : list) {\n var sourceImage = ResourceUtils.getTexture(elementPath(pair.path()));\n\n var image = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\n var xw = horizontal ? image.getHeight() : image.getWidth();\n\n var mult = pair.reverse ? -1 : 1;\n var offset = pair.reverse ? pair.stop + pair.start - 1 : 0;\n\n for (var y = pair.start; y < pair.stop; y++) {\n var path = elementPath(\"gen/\" + pair.path + \"_\" + y);\n var pos = offset + y * mult;\n\n for (var x = 0; x < xw; x++) {\n if (horizontal) {\n image.setRGB(pos, x, sourceImage.getRGB(pos, x));\n } else {\n image.setRGB(x, pos, sourceImage.getRGB(x, pos));\n }\n }\n\n var out = new ByteArrayOutputStream();\n try {\n ImageIO.write(image, \"png\", out);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n assetWriter.accept(AssetPaths.texture(path.getNamespace(), path.getPath() + \".png\"), out.toByteArray());\n }\n }\n }*/\n\n public static void generateAssets(BiConsumer<String, byte[]> assetWriter) {\n for (var texture : SIMPLE_MODEL) {\n assetWriter.accept(\"assets/\" + texture.getLeft().modelPath().getNamespace() + \"/models/\" + texture.getLeft().modelPath().getPath() + \".json\",\n ITEM_TEMPLATE.replace(\"|ID|\", texture.getLeft().modelPath().toString()).replace(\"|BASE|\", texture.getRight()).getBytes(StandardCharsets.UTF_8));\n }\n\n //generateProgress(assetWriter, VERTICAL_PROGRESS, false);\n //generateProgress(assetWriter, HORIZONTAL_PROGRESS, true);\n\n var fontBase = new JsonObject();\n var providers = new JsonArray();\n\n {\n var spaces = new JsonObject();\n spaces.addProperty(\"type\", \"space\");\n var advances = new JsonObject();\n SPACES.char2IntEntrySet().stream().sorted(Comparator.comparing(Char2IntMap.Entry::getCharKey)).forEach((c) -> advances.addProperty(Character.toString(c.getCharKey()), c.getIntValue()));\n spaces.add(\"advances\", advances);\n providers.add(spaces);\n }\n\n\n TEXTURES.char2ObjectEntrySet().stream().sorted(Comparator.comparing(Char2ObjectMap.Entry::getCharKey)).forEach((entry) -> {\n var bitmap = new JsonObject();\n bitmap.addProperty(\"type\", \"bitmap\");\n bitmap.addProperty(\"file\", entry.getValue().toString() + \".png\");\n bitmap.addProperty(\"ascent\", 13);\n bitmap.addProperty(\"height\", 256);\n var chars = new JsonArray();\n chars.add(Character.toString(entry.getCharKey()));\n bitmap.add(\"chars\", chars);\n providers.add(bitmap);\n });\n\n TEXTURES_POLYDEX.entrySet().stream().sorted(Comparator.comparing(x -> x.getKey().getLeft())).forEach((entry) -> {\n var bitmap = new JsonObject();\n bitmap.addProperty(\"type\", \"bitmap\");\n bitmap.addProperty(\"file\", entry.getValue().toString() + \".png\");\n bitmap.addProperty(\"ascent\", -4);\n bitmap.addProperty(\"height\", 128);\n var chars = new JsonArray();\n chars.add(Character.toString(entry.getKey().getLeft()));\n chars.add(Character.toString(entry.getKey().getRight()));\n bitmap.add(\"chars\", chars);\n providers.add(bitmap);\n });\n\n fontBase.add(\"providers\", providers);\n\n assetWriter.accept(\"assets/serveruifix/font/gui.json\", fontBase.toString().getBytes(StandardCharsets.UTF_8));\n }\n\n private record TextBuilders(Text base) implements Function<Text, Text> {\n @Override\n public Text apply(Text text) {\n return Text.empty().append(base).append(text);\n }\n }\n\n public record SlicedTexture(String path, int start, int stop, boolean reverse) {};\n}" } ]
import eu.pb4.serveruifix.polydex.PolydexCompat; import eu.pb4.serveruifix.util.GuiTextures; import eu.pb4.serveruifix.util.UiResourceCreator; import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
3,815
package eu.pb4.serveruifix; public class ModInit implements ModInitializer { public static final String ID = "serveruifix"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("Server Ui Fix"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of ServerUiFix!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); } UiResourceCreator.setup();
package eu.pb4.serveruifix; public class ModInit implements ModInitializer { public static final String ID = "serveruifix"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("Server Ui Fix"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of ServerUiFix!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); } UiResourceCreator.setup();
GuiTextures.register();
1
2023-12-28 23:01:30+00:00
8k
psobiech/opengr8on
lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetIpCommand.java
[ { "identifier": "Command", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/Command.java", "snippet": "public interface Command {\n int INITIAL_BUFFER_SIZE = 256;\n\n int MIN_IP_SIZE = 7;\n\n int IV_SIZE = 16;\n\n int KEY_SIZE = 16;\n\n int MAC_SIZE = 12;\n\n int MIN_SERIAL_NUMBER_SIZE = 4;\n\n int MAX_SERIAL_NUMBER_SIZE = 8;\n\n int MIN_SESSION_SIZE = 6;\n\n int RANDOM_SIZE = 30;\n\n int RANDOM_ENCRYPTED_SIZE = 32;\n\n static boolean equals(String value1, byte[] buffer, int offset) {\n if (value1 == null) {\n return false;\n }\n\n return value1.equals(asString(buffer, offset, value1.length()));\n }\n\n static String asString(byte[] buffer) {\n return asString(buffer, 0);\n }\n\n static String asString(byte[] buffer, int offset) {\n return asStringOfRange(buffer, offset, buffer.length);\n }\n\n static String asString(byte[] buffer, int offset, int limit) {\n return asStringOfRange(buffer, offset, offset + limit);\n }\n\n private static String asStringOfRange(byte[] buffer, int from, int to) {\n return new String(Arrays.copyOfRange(buffer, from, to)).trim();\n }\n\n default String uuid(UUID uuid) {\n return Client.uuid(uuid, this);\n }\n\n static byte[] serialize(Object... objects) {\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(INITIAL_BUFFER_SIZE)) {\n for (Object object : objects) {\n outputStream.write(serializeObject(object));\n }\n\n return outputStream.toByteArray();\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n private static byte[] serializeObject(Object object) {\n if (object instanceof byte[]) {\n return (byte[]) object;\n }\n\n if (object instanceof String) {\n return ((String) object).getBytes(StandardCharsets.UTF_8);\n }\n\n if (object instanceof Long || object instanceof Integer) {\n return serializeObject(String.valueOf(object));\n }\n\n if (object instanceof Inet4Address) {\n return serializeObject(((Inet4Address) object).getHostAddress());\n }\n\n throw new UnexpectedException(\"Unsupported object type: \" + object);\n }\n\n byte[] asByteArray();\n}" }, { "identifier": "HexUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/HexUtil.java", "snippet": "public final class HexUtil {\n static final int HEX_BASE = 16;\n\n static final String HEX_PREFIX = \"0x\";\n\n private HexUtil() {\n // NOP\n }\n\n public static long asLong(String hexAsString) {\n try {\n return Long.parseUnsignedLong(\n stripPrefix(hexAsString),\n HEX_BASE\n );\n } catch (NumberFormatException e) {\n throw new UnexpectedException(String.format(\"Value %s is not in the correct HEX format\", hexAsString), e);\n }\n }\n\n public static int asInt(String hexAsString) {\n try {\n return Integer.parseUnsignedInt(\n stripPrefix(hexAsString),\n HEX_BASE\n );\n } catch (NumberFormatException e) {\n throw new UnexpectedException(String.format(\"Value %s is not in the correct HEX format\", hexAsString), e);\n }\n }\n\n public static byte[] asBytes(String hexAsString) {\n try {\n return Hex.decodeHex(\n stripPrefix(hexAsString)\n );\n } catch (DecoderException e) {\n throw new UnexpectedException(String.format(\"Value %s is not in the correct HEX format\", hexAsString), e);\n }\n }\n\n private static String stripPrefix(String hexAsString) {\n if (hexAsString.startsWith(HEX_PREFIX)) {\n return hexAsString.substring(HEX_PREFIX.length());\n }\n\n return hexAsString;\n }\n\n public static String asString(BigInteger value) {\n if (value == null) {\n return null;\n }\n\n return format(value.toString(HEX_BASE));\n }\n\n public static String asString(byte value) {\n return asString(value & 0xFF);\n }\n\n public static String asString(byte[] array) {\n return format(Hex.encodeHexString(array));\n }\n\n public static String asString(Integer value) {\n if (value == null) {\n return null;\n }\n\n return format(Integer.toHexString(value));\n }\n\n public static String asString(Long value) {\n if (value == null) {\n return null;\n }\n\n return format(Long.toHexString(value));\n }\n\n private static String format(String valueAsString) {\n return evenZeroLeftPad(\n upperCase(valueAsString)\n );\n }\n\n private static String evenZeroLeftPad(String valueAsString) {\n if (valueAsString.length() % 2 == 0) {\n return valueAsString;\n }\n\n return '0' + valueAsString;\n }\n}" }, { "identifier": "IPv4AddressUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/IPv4AddressUtil.java", "snippet": "public final class IPv4AddressUtil {\n private static final Logger LOGGER = LoggerFactory.getLogger(IPv4AddressUtil.class);\n\n private static final int PING_TIMEOUT = 2000;\n\n public static final Inet4Address BROADCAST_ADDRESS = parseIPv4(\"255.255.255.255\");\n\n public static final Set<Inet4Address> DEFAULT_BROADCAST_ADDRESSES = Set.of(\n BROADCAST_ADDRESS,\n parseIPv4(\"255.255.0.0\"),\n parseIPv4(\"255.0.0.0\")\n );\n\n public static final Set<String> HARDWARE_ADDRESS_PREFIX_BLACKLIST = Set.of(\n HexUtil.asString(0x000569), // VMware, Inc.\n HexUtil.asString(0x001c14), // VMware, Inc.\n HexUtil.asString(0x000c29), // VMware, Inc.\n HexUtil.asString(0x005056) // VMware, Inc.\n );\n\n public static final Set<String> NETWORK_INTERFACE_NAME_PREFIX_BLACKLIST = Set.of(\n \"vmnet\", \"vboxnet\"\n );\n\n private IPv4AddressUtil() {\n // NOP\n }\n\n public static Optional<NetworkInterfaceDto> getLocalIPv4NetworkInterfaceByNameOrAddress(String nameOrAddress) {\n final List<NetworkInterfaceDto> networkInterfaces = getLocalIPv4NetworkInterfaces();\n for (NetworkInterfaceDto networkInterface : networkInterfaces) {\n if (Objects.equals(networkInterface.getNetworkInterface().getName(), nameOrAddress)) {\n return Optional.of(networkInterface);\n }\n\n if (Objects.equals(networkInterface.getAddress().getHostAddress(), nameOrAddress)) {\n return Optional.of(networkInterface);\n }\n }\n\n return Optional.empty();\n }\n\n public static Optional<NetworkInterfaceDto> getLocalIPv4NetworkInterfaceByName(String name) {\n final List<NetworkInterfaceDto> networkInterfaces = getLocalIPv4NetworkInterfaces();\n for (NetworkInterfaceDto networkInterface : networkInterfaces) {\n if (Objects.equals(networkInterface.getNetworkInterface().getName(), name)) {\n return Optional.of(networkInterface);\n }\n }\n\n return Optional.empty();\n }\n\n public static Optional<NetworkInterfaceDto> getLocalIPv4NetworkInterfaceByIpAddress(String ipAddress) {\n final List<NetworkInterfaceDto> networkInterfaces = getLocalIPv4NetworkInterfaces();\n for (NetworkInterfaceDto networkInterface : networkInterfaces) {\n if (Objects.equals(networkInterface.getAddress().getHostAddress(), ipAddress)) {\n return Optional.of(networkInterface);\n }\n }\n\n return Optional.empty();\n }\n\n public static List<NetworkInterfaceDto> getLocalIPv4NetworkInterfaces() {\n final List<NetworkInterface> validNetworkInterfaces = allValidNetworkInterfaces();\n final List<NetworkInterfaceDto> networkInterfaces = new ArrayList<>(validNetworkInterfaces.size());\n for (NetworkInterface networkInterface : validNetworkInterfaces) {\n for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {\n final InetAddress address = interfaceAddress.getAddress();\n if (!(address instanceof Inet4Address)) {\n continue;\n }\n\n final InetAddress broadcastAddress = interfaceAddress.getBroadcast();\n if (!(broadcastAddress instanceof Inet4Address)) {\n continue;\n }\n\n if (!address.isSiteLocalAddress()) {\n continue;\n }\n\n final int networkMask = getNetworkMaskFromPrefix(interfaceAddress.getNetworkPrefixLength());\n\n networkInterfaces.add(new NetworkInterfaceDto(\n (Inet4Address) address, (Inet4Address) broadcastAddress,\n networkMask,\n networkInterface\n ));\n }\n }\n\n return networkInterfaces;\n }\n\n private static int getNetworkMaskFromPrefix(short networkPrefixLength) {\n int networkMask = 0x00;\n for (int i = 0; i < Integer.SIZE - networkPrefixLength; i++) {\n networkMask += (1 << i);\n }\n\n networkMask ^= 0xFFFFFFFF;\n\n return networkMask;\n }\n\n private static List<NetworkInterface> allValidNetworkInterfaces() {\n final List<NetworkInterface> networkInterfaces;\n try {\n networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());\n } catch (SocketException e) {\n throw new UnexpectedException(e);\n }\n\n final List<NetworkInterface> validNetworkInterfaces = new ArrayList<>(networkInterfaces.size());\n for (NetworkInterface networkInterface : networkInterfaces) {\n try {\n if (!networkInterface.isUp()\n || networkInterface.isLoopback()\n || networkInterface.isPointToPoint()\n || isBlacklisted(networkInterface)\n ) {\n continue;\n }\n } catch (SocketException e) {\n LOGGER.warn(e.getMessage(), e);\n\n continue;\n }\n\n validNetworkInterfaces.add(networkInterface);\n }\n\n return validNetworkInterfaces;\n }\n\n private static boolean isBlacklisted(NetworkInterface networkInterface) throws SocketException {\n final String networkInterfaceName = networkInterface.getName();\n for (String blacklistedNetworkInterfaceNamePrefix : NETWORK_INTERFACE_NAME_PREFIX_BLACKLIST) {\n if (networkInterfaceName.startsWith(blacklistedNetworkInterfaceNamePrefix)) {\n return true;\n }\n }\n\n final byte[] hardwareAddress = networkInterface.getHardwareAddress();\n if (hardwareAddress == null) {\n return true;\n }\n\n return isHardwareAddressBlacklisted(hardwareAddress);\n }\n\n private static boolean isHardwareAddressBlacklisted(byte[] macAddress) {\n if (macAddress == null) {\n return true;\n }\n\n final String hardwareAddressPrefix = HexUtil.asString(Arrays.copyOf(macAddress, 3));\n\n return HARDWARE_ADDRESS_PREFIX_BLACKLIST.contains(hardwareAddressPrefix);\n }\n\n public static Inet4Address parseIPv4(String ipv4AddressAsString) {\n try {\n return (Inet4Address) InetAddress.getByAddress(\n getIPv4AsBytes(ipv4AddressAsString)\n );\n } catch (UnknownHostException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static Inet4Address parseIPv4(int ipv4AddressAsNumber) {\n try {\n final byte[] buffer = asBytes(ipv4AddressAsNumber);\n\n return (Inet4Address) InetAddress.getByAddress(buffer);\n } catch (UnknownHostException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static String getIPv4FromNumber(int ipv4AsNumber) {\n final byte[] buffer = asBytes(ipv4AsNumber);\n\n return IntStream.range(0, Integer.BYTES)\n .mapToObj(i -> String.valueOf(buffer[i] & 0xFF))\n .collect(Collectors.joining(\".\"));\n }\n\n private static byte[] asBytes(int ipv4AsNumber) {\n final ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.BYTES);\n\n byteBuffer.putInt(ipv4AsNumber);\n byteBuffer.flip();\n\n return byteBuffer.array();\n }\n\n public static int getIPv4AsNumber(Inet4Address inetAddress) {\n return getIPv4AsNumber(inetAddress.getAddress());\n }\n\n public static int getIPv4AsNumber(String ipv4AddressAsString) {\n return getIPv4AsNumber(getIPv4AsBytes(ipv4AddressAsString));\n }\n\n public static int getIPv4AsNumber(byte[] ipv4AddressAsBytes) {\n if (ipv4AddressAsBytes.length != Integer.BYTES) {\n throw new UnexpectedException(\"Invalid IPv4 address: \" + Arrays.toString(ipv4AddressAsBytes));\n }\n\n return ByteBuffer.wrap(ipv4AddressAsBytes)\n .getInt();\n }\n\n private static byte[] getIPv4AsBytes(String ipv4AddressAsString) {\n final String[] ipAddressParts = Util.splitAtLeast(ipv4AddressAsString, \"\\\\.\", Integer.BYTES)\n .orElseThrow(() -> new UnexpectedException(\"Invalid IPv4 address: \" + ipv4AddressAsString));\n\n final byte[] addressAsBytes = new byte[Integer.BYTES];\n for (int i = 0; i < addressAsBytes.length; i++) {\n addressAsBytes[i] = (byte) Integer.parseInt(ipAddressParts[i]);\n }\n\n return addressAsBytes;\n }\n\n public static boolean ping(InetAddress inetAddress) {\n try {\n return inetAddress.isReachable(PING_TIMEOUT);\n } catch (IOException e) {\n LOGGER.warn(e.getMessage(), e);\n\n return false;\n }\n }\n\n public static final class NetworkInterfaceDto {\n private final Inet4Address address;\n\n private final Inet4Address broadcastAddress;\n\n private final int networkAddress;\n\n private final int networkMask;\n\n private final NetworkInterface networkInterface;\n\n public NetworkInterfaceDto(\n Inet4Address address, Inet4Address broadcastAddress,\n int networkMask,\n NetworkInterface networkInterface\n ) {\n this.address = address;\n\n final int addressAsNumber = IPv4AddressUtil.getIPv4AsNumber(address.getAddress());\n this.networkAddress = addressAsNumber & networkMask;\n\n assert IPv4AddressUtil.getIPv4AsNumber(broadcastAddress) == (networkAddress | (~networkMask));\n this.broadcastAddress = broadcastAddress;\n this.networkMask = networkMask;\n\n this.networkInterface = networkInterface;\n }\n\n public Inet4Address getAddress() {\n return address;\n }\n\n public Inet4Address getNetworkAddress() {\n return parseIPv4(networkAddress);\n }\n\n public Inet4Address getBroadcastAddress() {\n return broadcastAddress;\n }\n\n public int getNetworkMask() {\n return networkMask;\n }\n\n public NetworkInterface getNetworkInterface() {\n return networkInterface;\n }\n\n public boolean valid(Inet4Address address) {\n final int ipAsNumber = getIPv4AsNumber(address);\n\n return ipAsNumber > networkAddress && ipAsNumber < IPv4AddressUtil.getIPv4AsNumber(broadcastAddress);\n }\n\n public Optional<Inet4Address> nextAvailable(\n Inet4Address startingAddress,\n Duration timeout,\n Inet4Address currentAddress,\n Collection<Inet4Address> exclusionList\n ) {\n final List<Inet4Address> addresses = nextAvailableExcluding(startingAddress, timeout, 1, currentAddress, exclusionList);\n if (addresses.isEmpty()) {\n return Optional.empty();\n }\n\n return Optional.of(addresses.getFirst());\n }\n\n public List<Inet4Address> nextAvailableExcluding(\n Inet4Address startingAddress,\n Duration timeout,\n int limit,\n Inet4Address currentAddress,\n Collection<Inet4Address> exclusionList\n ) {\n final Set<Integer> excludedIpAddressNumbers = exclusionList.stream()\n .map(IPv4AddressUtil::getIPv4AsNumber)\n .collect(Collectors.toSet());\n\n final int currentIpAsNumber = getIPv4AsNumber(currentAddress);\n int ipAsNumber = getIPv4AsNumber(startingAddress);\n\n final List<Inet4Address> addresses = new ArrayList<>(limit);\n do {\n final long startedAt = System.nanoTime();\n\n final int addressAsNumber = ipAsNumber++;\n if (currentIpAsNumber == addressAsNumber) {\n addresses.add(currentAddress);\n continue;\n }\n\n if (excludedIpAddressNumbers.contains(addressAsNumber)) {\n continue;\n }\n\n final Inet4Address address = parseIPv4(addressAsNumber);\n if (!ping(address)) {\n addresses.add(address);\n }\n\n timeout = timeout.minusNanos(System.nanoTime() - startedAt);\n } while (timeout.isPositive() && addresses.size() < limit && !Thread.interrupted());\n\n return addresses;\n }\n\n @Override\n public String toString() {\n return \"NetworkInterfaceDto{\" +\n \"networkInterface=\" + ToStringUtil.toString(networkInterface) +\n \", address=\" + ToStringUtil.toString(address) +\n \", broadcastAddress=\" + ToStringUtil.toString(broadcastAddress) +\n \", networkAddress=\" + ToStringUtil.toString(parseIPv4(networkAddress)) +\n \", networkMask=\" + ToStringUtil.toString(parseIPv4(networkMask)) +\n '}';\n }\n }\n}" }, { "identifier": "Util", "path": "common/src/main/java/pl/psobiech/opengr8on/util/Util.java", "snippet": "public final class Util {\n public static final int ONE_HUNDRED_PERCENT = 100;\n\n private static final double ONE_HUNDRED_PERCENT_DOUBLE = ONE_HUNDRED_PERCENT;\n\n private Util() {\n // NOP\n }\n\n public static Optional<Boolean> repeatUntilTrueOrTimeout(Duration timeout, Function<Duration, Optional<Boolean>> fn) {\n Optional<Boolean> optionalBoolean;\n do {\n final long startedAt = System.nanoTime();\n\n optionalBoolean = fn.apply(timeout);\n if (optionalBoolean.isPresent() && optionalBoolean.get()) {\n return optionalBoolean;\n }\n\n timeout = timeout.minusNanos(System.nanoTime() - startedAt);\n } while (timeout.isPositive() && !Thread.interrupted());\n\n return optionalBoolean;\n }\n\n public static <T> Optional<T> repeatUntilTimeout(Duration timeout, Function<Duration, Optional<T>> fn) {\n return repeatUntilTimeoutOrLimit(timeout, 1, fn).stream().findAny();\n }\n\n public static <T> List<T> repeatUntilTimeoutOrLimit(Duration timeout, int limit, Function<Duration, Optional<T>> fn) {\n final ArrayList<T> results = new ArrayList<>(Math.max(limit == Integer.MAX_VALUE ? -1 : limit, 0));\n do {\n final long startedAt = System.nanoTime();\n\n fn.apply(timeout)\n .ifPresent(results::add);\n\n timeout = timeout.minusNanos(System.nanoTime() - startedAt);\n } while (timeout.isPositive() && results.size() < limit && !Thread.interrupted());\n\n return results;\n }\n\n public static Optional<String[]> splitExact(String value, String pattern, int exactlyParts) {\n final String[] split = value.split(pattern, exactlyParts + 1);\n if (split.length != exactlyParts) {\n return Optional.empty();\n }\n\n return Optional.of(split);\n }\n\n public static Optional<String[]> splitAtLeast(String value, String pattern, int atLeastParts) {\n final String[] split = value.split(pattern, atLeastParts + 1);\n if (split.length < atLeastParts) {\n return Optional.empty();\n }\n\n return Optional.of(split);\n }\n\n public static int percentage(long elementCount, long totalElementCount) {\n return (int) max(0, min(ONE_HUNDRED_PERCENT_DOUBLE, round((elementCount * ONE_HUNDRED_PERCENT_DOUBLE) / (double) totalElementCount)));\n }\n\n /**\n * @return tries to convert a Serializable to Number formatted as string (with 2 decimal places), defaults to {@link String#valueOf(Object)}\n */\n public static String formatNumber(Number value) {\n if (value == null) {\n return null;\n }\n\n final DecimalFormat scoreDecimalFormat = new DecimalFormat(\"0.##\");\n\n return scoreDecimalFormat.format(((Number) value).doubleValue());\n }\n\n public static <E> List<E> nullAsEmpty(List<E> list) {\n if (list == null) {\n return Collections.emptyList();\n }\n\n return list;\n }\n\n public static <K, V> Map<K, V> nullAsEmpty(Map<K, V> map) {\n if (map == null) {\n return Collections.emptyMap();\n }\n\n return map;\n }\n\n public static <E> Set<E> nullAsEmpty(Set<E> list) {\n if (list == null) {\n return Collections.emptySet();\n }\n\n return list;\n }\n\n public static <E> Collection<E> nullAsEmpty(Collection<E> list) {\n if (list == null) {\n return Collections.emptyList();\n }\n\n return list;\n }\n\n public static <F, T> T mapNullSafe(F from, Function<F, T> mapper) {\n return mapNullSafeWithDefault(from, mapper, null);\n }\n\n public static <F, T> T mapNullSafeWithDefault(F from, Function<F, T> mapper, T nullValue) {\n if (from != null) {\n final T value = mapper.apply(from);\n if (value != null) {\n return value;\n }\n }\n\n return nullValue;\n }\n\n public static <F, T> List<T> mapNullSafe(List<F> from, Function<F, T> mapper) {\n return mapNullSafeListWithDefault(from, mapper, Collections.emptyList());\n }\n\n public static <F, T> List<T> mapNullSafeListWithDefault(List<F> from, Function<F, T> mapper, List<T> nullValue) {\n return Optional.ofNullable(from)\n .map(f ->\n f.stream()\n .map(mapper)\n .collect(Collectors.toList())\n )\n .orElse(nullValue);\n }\n\n public static <T> T nullAsDefault(T value, T defaultValue) {\n return Objects.requireNonNullElse(value, defaultValue);\n }\n\n public static <T> T nullAsDefaultGet(T value, Supplier<? extends T> defaultValueSupplier) {\n return Objects.requireNonNullElseGet(value, defaultValueSupplier);\n }\n\n public static <E extends Enum<E>> EnumSet<E> asEnum(List<String> valueList, Class<E> enumClass) {\n if (valueList == null) {\n return null;\n }\n\n return valueList.stream()\n .map(valueAsString -> Enum.valueOf(enumClass, valueAsString))\n .collect(Collectors.toCollection(() -> EnumSet.noneOf(enumClass)));\n }\n\n /**\n * @return lazy initiated singleton (thread safe)\n */\n public static <T> Supplier<T> lazy(Supplier<T> supplier) {\n return cache(supplier);\n }\n\n /**\n * @return lazy initiated singleton (thread safe)\n */\n public static <T> Supplier<T> cache(Supplier<T> constructor) {\n final AtomicReference<T> reference = new AtomicReference<>();\n\n return () -> {\n final T currentValue = reference.get();\n if (currentValue != null) {\n return currentValue;\n }\n\n return reference.updateAndGet(value -> {\n if (value != null) {\n // new value was already allocated by some other thread between notnull check and here, we preserve the other thread value\n return value;\n }\n\n return constructor.get();\n });\n };\n }\n}" } ]
import java.net.Inet4Address; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import pl.psobiech.opengr8on.client.Command; import pl.psobiech.opengr8on.util.HexUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.Util;
6,250
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client.commands; public class SetIpCommand { private static final int SERIAL_NUMBER_PART = 1; private static final int IP_ADDRESS_PART = 2; private static final int GATEWAY_IP_ADDRESS_PART = 3; private SetIpCommand() { // NOP } public static Request request(Long serialNumber, Inet4Address ipAddress, Inet4Address gatewayIpAddress) { return new Request(serialNumber, ipAddress, gatewayIpAddress); } public static Optional<Request> requestFromByteArray(byte[] buffer) { if (!requestMatches(buffer)) { return Optional.empty(); } final Optional<String[]> requestPartsOptional = Util.splitExact(Command.asString(buffer), ":", 4); if (requestPartsOptional.isEmpty()) { return Optional.empty(); } final String[] requestParts = requestPartsOptional.get(); final Long serialNumber = HexUtil.asLong(requestParts[SERIAL_NUMBER_PART]);
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client.commands; public class SetIpCommand { private static final int SERIAL_NUMBER_PART = 1; private static final int IP_ADDRESS_PART = 2; private static final int GATEWAY_IP_ADDRESS_PART = 3; private SetIpCommand() { // NOP } public static Request request(Long serialNumber, Inet4Address ipAddress, Inet4Address gatewayIpAddress) { return new Request(serialNumber, ipAddress, gatewayIpAddress); } public static Optional<Request> requestFromByteArray(byte[] buffer) { if (!requestMatches(buffer)) { return Optional.empty(); } final Optional<String[]> requestPartsOptional = Util.splitExact(Command.asString(buffer), ":", 4); if (requestPartsOptional.isEmpty()) { return Optional.empty(); } final String[] requestParts = requestPartsOptional.get(); final Long serialNumber = HexUtil.asLong(requestParts[SERIAL_NUMBER_PART]);
final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(requestParts[IP_ADDRESS_PART]);
2
2023-12-23 09:56:14+00:00
8k
Pigmice2733/frc-2024
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "DrivetrainConfig", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final static class DrivetrainConfig {\n public static final double MAX_DRIVE_SPEED = 4.5; // max meters / second\n public static final double MAX_TURN_SPEED = 5; // max radians / second\n public static final double SLOWMODE_MULTIPLIER = 0.5;\n\n // distance from the center of one wheel to another\n public static final double TRACK_WIDTH_METERS = 0.5842;\n\n private final static SwerveDriveKinematics KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(TRACK_WIDTH_METERS / 2,\n TRACK_WIDTH_METERS / 2), // Front left\n new Translation2d(TRACK_WIDTH_METERS / 2,\n -TRACK_WIDTH_METERS / 2), // Front right\n new Translation2d(-TRACK_WIDTH_METERS / 2,\n TRACK_WIDTH_METERS / 2), // Back left\n new Translation2d(-TRACK_WIDTH_METERS / 2,\n -TRACK_WIDTH_METERS / 2) // Back right\n );\n\n // Constants found in Sysid (volts)\n private static final SimpleMotorFeedforward DRIVE_FEED_FORWARD = new SimpleMotorFeedforward(\n 0.35493, 2.3014, 0.12872);\n\n // From what I have seen, it is common to only use a P value in path following\n private static final PathConstraints PATH_CONSTRAINTS = new PathConstraints(2, 2); // 3, 2.5\n private static final PIDController PATH_DRIVE_PID = new PIDController(0.3, 0, 0);\n private static final PIDController PATH_TURN_PID = new PIDController(0.31, 0, 0);\n\n // Offset from chassis center that the robot will rotate about\n private static final Translation2d ROTATION_CENTER_OFFSET = new Translation2d(0, 0);\n\n private static final MkSwerveModuleBuilder FRONT_LEFT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Front Left\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(0, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.FRONT_LEFT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.FRONT_LEFT_STEER)\n .withSteerEncoderPort(CANConfig.FRONT_LEFT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(73));\n\n private static final MkSwerveModuleBuilder FRONT_RIGHT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Front Right\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(1, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.FRONT_RIGHT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.FRONT_RIGHT_STEER)\n .withSteerEncoderPort(CANConfig.FRONT_RIGHT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(-99));\n\n private static final MkSwerveModuleBuilder BACK_LEFT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Back Left\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(2, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.BACK_LEFT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.BACK_LEFT_STEER)\n .withSteerEncoderPort(CANConfig.BACK_LEFT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(219));\n\n private static final MkSwerveModuleBuilder BACK_RIGHT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Back Right\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(3, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.BACK_RIGHT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.BACK_RIGHT_STEER)\n .withSteerEncoderPort(CANConfig.BACK_RIGHT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(-285));\n\n public static final SwerveConfig SWERVE_CONFIG = new SwerveConfig(\n FRONT_LEFT_MODULE, FRONT_RIGHT_MODULE, BACK_LEFT_MODULE,\n BACK_RIGHT_MODULE,\n PATH_CONSTRAINTS, PATH_DRIVE_PID, PATH_TURN_PID,\n MAX_DRIVE_SPEED, MAX_TURN_SPEED,\n SLOWMODE_MULTIPLIER, KINEMATICS, DRIVE_FEED_FORWARD, SWERVE_TAB,\n ROTATION_CENTER_OFFSET);\n}" }, { "identifier": "ArmState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum ArmState {\n HIGH(90),\n MIDDLE(45),\n DOWN(0);\n\n private double position;\n\n ArmState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "ClimberState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum ClimberState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n ClimberState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "IntakeState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum IntakeState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n IntakeState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "FireShooter", "path": "src/main/java/frc/robot/commands/actions/FireShooter.java", "snippet": "public class FireShooter extends SequentialCommandGroup {\n public FireShooter(Arm arm, Shooter shooter, ArmState armAngle) {\n addCommands(Commands.sequence(arm.setTargetState(armAngle), shooter.spinFlywheelsForward(),\n Commands.waitSeconds(AutoConfig.FLYWHEEL_SPINUP_TIME), shooter.spinFeederForward()));\n addRequirements(arm, shooter);\n }\n\n}" }, { "identifier": "HandoffToShooter", "path": "src/main/java/frc/robot/commands/actions/HandoffToShooter.java", "snippet": "public class HandoffToShooter extends SequentialCommandGroup {\n public HandoffToShooter(Intake intake, Shooter shooter) {\n addCommands(intake.setTargetState(IntakeState.UP),\n Commands.waitSeconds(AutoConfig.INTAKE_MOVE_TIME), intake.runWheelsBackward(),\n shooter.spinFeederForward(), Commands.waitSeconds(AutoConfig.INTAKE_FEED_TIME),\n Commands.runOnce(() -> ControllerRumbler.rumblerOperator(RumbleType.kBothRumble, 0.25, 0.3)));\n addRequirements(intake, shooter);\n }\n}" }, { "identifier": "Arm", "path": "src/main/java/frc/robot/subsystems/Arm.java", "snippet": "public class Arm extends PIDSubsystemBase {\n\n public Arm() {\n super(new CANSparkMax(CANConfig.ARM, MotorType.kBrushless), ArmConfig.P, ArmConfig.i, ArmConfig.D,\n new Constraints(ArmConfig.MAX_VELOCITY, ArmConfig.MAX_ACCELERATION), false,\n ArmConfig.MOTOR_POSITION_CONVERSION, 50, Constants.ARM_TAB, true);\n }\n\n /** Sets the rotation state of the arm */\n public Command setTargetState(ArmState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "ClimberExtension", "path": "src/main/java/frc/robot/subsystems/ClimberExtension.java", "snippet": "public class ClimberExtension extends PIDSubsystemBase {\n public ClimberExtension() {\n super(new CANSparkMax(CANConfig.CLIMBER_EXTENSION, MotorType.kBrushless), ClimberConfig.P, ClimberConfig.I,\n ClimberConfig.D, new Constraints(ClimberConfig.MAX_VELOCITY, ClimberConfig.MAX_ACCELERATION), false,\n ClimberConfig.MOTOR_POSITION_CONVERSION, 50, Constants.CLIMBER_TAB, true);\n }\n\n @Override\n public void periodic() {\n }\n\n /** Sets the height state of the climber */\n public Command setTargetState(ClimberState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "Intake", "path": "src/main/java/frc/robot/subsystems/Intake.java", "snippet": "public class Intake extends PIDSubsystemBase {\n private final CANSparkMax wheelsMotor = new CANSparkMax(CANConfig.INTAKE_WHEELS, MotorType.kBrushless);\n\n public Intake() {\n super(new CANSparkMax(CANConfig.INTAKE_PIVOT, MotorType.kBrushless), IntakeConfig.P, IntakeConfig.I,\n IntakeConfig.D, new Constraints(IntakeConfig.MAX_VELOCITY, IntakeConfig.MAX_ACCELERATION), false,\n IntakeConfig.MOTOR_POSITION_CONVERSION, 50, Constants.INTAKE_TAB, true);\n\n wheelsMotor.restoreFactoryDefaults();\n wheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.INTAKE_TAB, () -> wheelsMotor.get());\n }\n\n /** Sets the intake motor to a percent output (0.0 - 1.0) */\n public void outputToMotor(double percent) {\n wheelsMotor.set(percent);\n }\n\n /** Spins intake wheels to intake balls. */\n public Command runWheelsForward() {\n return Commands.runOnce(() -> outputToMotor(IntakeConfig.WHEELS_SPEED));\n }\n\n /** Spins intake wheels to eject balls. */\n public Command runWheelsBackward() {\n return Commands.runOnce(() -> outputToMotor(-IntakeConfig.WHEELS_SPEED));\n }\n\n /** Sets intake wheels to zero output. */\n public Command stopWheels() {\n return Commands.runOnce(() -> outputToMotor(0));\n }\n\n /** Sets the rotation state of the intake */\n public Command setTargetState(IntakeState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "Shooter", "path": "src/main/java/frc/robot/subsystems/Shooter.java", "snippet": "public class Shooter extends SubsystemBase {\n private final CANSparkMax flywheelsMotor = new CANSparkMax(CANConfig.SHOOTER_MOTOR, MotorType.kBrushless);\n private final CANSparkMax feederMotor = new CANSparkMax(CANConfig.FEEDER_MOTOR, MotorType.kBrushless);\n\n public Shooter() {\n flywheelsMotor.restoreFactoryDefaults();\n flywheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.SHOOTER_TAB, () -> flywheelsMotor.get());\n }\n\n private void outputToFlywheels(double output) {\n flywheelsMotor.set(output);\n }\n\n public Command spinFlywheelsForward() {\n return Commands.runOnce(() -> outputToFlywheels(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFlywheelsBackward() {\n return Commands.runOnce(() -> outputToFlywheels(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFlywheels() {\n return Commands.runOnce(() -> outputToFlywheels(0));\n }\n\n private void outputToFeeder(double output) {\n feederMotor.set(output);\n }\n\n public Command spinFeederForward() {\n return Commands.runOnce(() -> outputToFeeder(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFeederBackward() {\n return Commands.runOnce(() -> outputToFeeder(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFeeder() {\n return Commands.runOnce(() -> outputToFeeder(0));\n }\n}" }, { "identifier": "Vision", "path": "src/main/java/frc/robot/subsystems/Vision.java", "snippet": "public class Vision extends SubsystemBase {\n private static String camName = VisionConfig.CAM_NAME;\n\n private Results targetingResults;\n private LimelightTarget_Fiducial bestTarget;\n private boolean hasTarget;\n\n public Vision() {\n ShuffleboardHelper.addOutput(\"Target X\", Constants.VISION_TAB,\n () -> bestTarget == null ? 0 : bestTarget.tx);\n ShuffleboardHelper.addOutput(\"Target Y\", Constants.VISION_TAB,\n () -> bestTarget == null ? 0 : bestTarget.ty);\n\n ShuffleboardHelper.addOutput(\"Bot Pose X\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getEstimatedRobotPose().getX());\n ShuffleboardHelper.addOutput(\"Bot Pose Y\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getEstimatedRobotPose().getY());\n\n ShuffleboardHelper.addOutput(\"Pose to tag X\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getTranslationToBestTarget().getX());\n ShuffleboardHelper.addOutput(\"Pose to tag Y\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getTranslationToBestTarget().getY());\n }\n\n @Override\n public void periodic() {\n LimelightResults results = LimelightHelpers.getLatestResults(camName);\n hasTarget = results != null;\n\n if (hasTarget) {\n bestTarget = null;\n return;\n }\n\n targetingResults = results.targetingResults;\n\n var allTargets = results.targetingResults.targets_Fiducials;\n bestTarget = allTargets[0];\n }\n\n /** Returns the best target's id or -1 if no target is seen */\n public int getBestTargetID() {\n return (int) (!hasTarget ? -1 : bestTarget.fiducialID);\n }\n\n /** Returns the robot's estimated 2d pose or null if no target is seen */\n public Pose2d getEstimatedRobotPose() {\n return !hasTarget ? null : targetingResults.getBotPose2d();\n }\n\n /** Returns the estimated 2d translation to the best target */\n public Pose2d getTranslationToBestTarget() {\n return !hasTarget ? null : bestTarget.getRobotPose_TargetSpace2D();\n }\n}" } ]
import com.pigmice.frc.lib.controller_rumbler.ControllerRumbler; import com.pigmice.frc.lib.drivetrain.swerve.SwerveDrivetrain; import com.pigmice.frc.lib.drivetrain.swerve.commands.DriveWithJoysticksSwerve; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.XboxController.Button; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.DrivetrainConfig; import frc.robot.Constants.ArmConfig.ArmState; import frc.robot.Constants.ClimberConfig.ClimberState; import frc.robot.Constants.IntakeConfig.IntakeState; import frc.robot.commands.actions.FireShooter; import frc.robot.commands.actions.HandoffToShooter; import frc.robot.subsystems.Arm; import frc.robot.subsystems.ClimberExtension; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter; import frc.robot.subsystems.Vision;
3,917
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since * Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in * the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of * the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final SwerveDrivetrain drivetrain = new SwerveDrivetrain(DrivetrainConfig.SWERVE_CONFIG); private final Arm arm = new Arm(); private final ClimberExtension climberExtension = new ClimberExtension();
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since * Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in * the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of * the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final SwerveDrivetrain drivetrain = new SwerveDrivetrain(DrivetrainConfig.SWERVE_CONFIG); private final Arm arm = new Arm(); private final ClimberExtension climberExtension = new ClimberExtension();
private final Intake intake = new Intake();
8
2023-12-30 06:06:45+00:00
8k
fatorius/DUCO-Android-Miner
DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/services/MinerBackgroundService.java
[ { "identifier": "MiningActivity", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/activities/MiningActivity.java", "snippet": "public class MiningActivity extends AppCompatActivity { //implements UIThreadMethods {\n RequestQueue requestQueue;\n JsonObjectRequest getMiningPoolRequester;\n\n TextView miningNodeDisplay;\n TextView acceptedSharesTextDisplay;\n TextView hashrateDisplay;\n TextView miningLogsTextDisplay;\n TextView performancePerThread;\n\n Button stopMining;\n\n ProgressBar gettingPoolProgress;\n\n String poolName;\n String poolIp;\n int poolPort;\n String poolServerName;\n\n String ducoUsername;\n float efficiency;\n int numberOfMiningThreads;\n\n int sentShares;\n int acceptedShares;\n\n float acceptedPercetage;\n\n List<String> minerLogLines;\n List<Integer> threadsHashrate;\n\n SharedPreferences sharedPreferences;\n\n private BroadcastReceiver broadcastReceiver;\n\n boolean isAppOnFocus;\n\n public static final String COMMUNICATION_ACTION = \"com.fatorius.duinocoinminer.COMMUNICATION_ACTION\";\n static final String GET_MINING_POOL_URL = \"https://server.duinocoin.com/getPool\";\n\n public MiningActivity(){\n MiningActivity miningActivity = this;\n\n sentShares = 0;\n acceptedShares = 0;\n acceptedPercetage = 100.0f;\n\n minerLogLines = new ArrayList<>();\n threadsHashrate = new ArrayList<>();\n\n getMiningPoolRequester = new JsonObjectRequest(\n Request.Method.GET, GET_MINING_POOL_URL, null,\n\n response -> {\n gettingPoolProgress.setVisibility(View.GONE);\n\n try {\n poolName = response.getString(\"name\");\n poolIp = response.getString(\"ip\");\n poolPort = response.getInt(\"port\");\n poolServerName = response.getString(\"server\");\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n\n String newMiningText = \"Mining node: \" + poolName;\n miningNodeDisplay.setText(newMiningText);\n\n Intent miningServiceIntent = new Intent(miningActivity, MinerBackgroundService.class);\n\n miningServiceIntent.putExtra(\"poolIp\", poolIp);\n miningServiceIntent.putExtra(\"numberOfThreads\", numberOfMiningThreads);\n miningServiceIntent.putExtra(\"poolPort\", poolPort);\n miningServiceIntent.putExtra(\"ducoUsername\", ducoUsername);\n miningServiceIntent.putExtra(\"efficiency\", efficiency);\n\n miningActivity.startForegroundService(miningServiceIntent);\n\n stopMining.setOnClickListener(view -> {\n stopService(miningServiceIntent);\n\n Intent intent = new Intent(miningActivity, MinerBackgroundService.class);\n intent.setAction(MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING);\n startService(intent);\n\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.clear();\n editor.apply();\n\n finish();\n });\n },\n\n error -> {\n gettingPoolProgress.setVisibility(View.GONE);\n\n String errorMsg = \"Fail getting mining node\";\n\n String errorType = error.toString();\n\n switch (errorType){\n case \"com.android.volley.TimeoutError\":\n errorMsg = \"Error: Timeout connecting to server.duinocoin.com\";\n break;\n case \"com.android.volley.NoConnectionError: java.net.UnknownHostException: Unable to resolve host \\\"server.duinocoin.com\\\": No address associated with hostname\":\n errorMsg = \"Error: no internet connection\";\n break;\n case \"com.android.volley.ServerError\":\n errorMsg = \"Error: server.duinocoin.com internal error\";\n break;\n }\n\n Log.i(\"Resquest error\", error.toString());\n\n miningNodeDisplay.setText(errorMsg);\n\n String stopMiningNewText = \"Back\";\n\n stopMining.setText(stopMiningNewText);\n\n stopMining.setOnClickListener(view -> {\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.clear();\n editor.apply();\n\n finish();\n });\n }\n );\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_mining);\n\n miningNodeDisplay = findViewById(R.id.miningNodeDisplay);\n acceptedSharesTextDisplay = findViewById(R.id.acceptedSharesDisplay);\n hashrateDisplay = findViewById(R.id.hashrateDisplayText);\n miningLogsTextDisplay = findViewById(R.id.minerlogsMultiline);\n performancePerThread = findViewById(R.id.threadPerformanceView);\n\n stopMining = findViewById(R.id.stopMiningButton);\n\n gettingPoolProgress = findViewById(R.id.gettingPoolLoading);\n\n sharedPreferences = getSharedPreferences(\"com.fatorius.duinocoinminer\", MODE_PRIVATE);\n ducoUsername = sharedPreferences.getString(\"username_value\", \"---------------------\");\n numberOfMiningThreads = sharedPreferences.getInt(\"threads_value\", 1);\n\n for (int t = 0; t < numberOfMiningThreads; t++){\n threadsHashrate.add(t, 0);\n }\n\n int miningIntensity = sharedPreferences.getInt(\"mining_intensity_value\", 0);\n\n efficiency = calculateEfficiency(miningIntensity);\n\n requestQueue = Volley.newRequestQueue(this);\n requestQueue.add(getMiningPoolRequester);\n\n broadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n if (intent.getAction() != null && intent.getAction().equals(COMMUNICATION_ACTION) && isAppOnFocus) {\n int threadNo = intent.getIntExtra(\"threadNo\", 0);\n int hr = intent.getIntExtra(\"hashrate\", 0);\n int nonceFound = intent.getIntExtra(\"nonce\", 0);\n float timeElapsed = intent.getFloatExtra(\"timeElapsed\", 0.0f);\n\n sentShares = intent.getIntExtra(\"sharesSent\", 0);\n acceptedShares = intent.getIntExtra(\"sharesAccepted\", 0);\n\n updatePercentage();\n\n String minerNewLine = \"Thread \" + threadNo + \" | Nonce found: \" + nonceFound + \" | Time elapsed: \" + timeElapsed + \"s | Hashrate: \" + hr;\n addNewLineFromMiner(minerNewLine);\n\n threadsHashrate.add(threadNo, hr);\n\n int totalHashrate = 0;\n StringBuilder displayHashratePerThread = new StringBuilder();\n\n int threadHs;\n\n for (int th = 0; th < numberOfMiningThreads; th++){\n threadHs = threadsHashrate.get(th);\n totalHashrate += threadHs;\n displayHashratePerThread.append(\"Thread \").append(th).append(\": \").append(threadHs).append(\"h/s \\n\");\n }\n\n hashrateDisplay.setText(convertHashrate(totalHashrate));\n performancePerThread.setText(displayHashratePerThread.toString());\n }\n }\n };\n }\n\n @Override\n public void onResume(){\n super.onResume();\n\n isAppOnFocus = true;\n\n IntentFilter filter = new IntentFilter(COMMUNICATION_ACTION);\n registerReceiver(broadcastReceiver, filter);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n\n isAppOnFocus = false;\n\n unregisterReceiver(broadcastReceiver);\n }\n\n public void addNewLineFromMiner(String line) {\n long currentTimeMillis = System.currentTimeMillis();\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());\n Date currentDate = new Date(currentTimeMillis);\n String formattedDate = sdf.format(currentDate);\n\n String newLine = formattedDate + \" | \" + line;\n minerLogLines.add(0, newLine);\n\n if (minerLogLines.size() > 8){\n minerLogLines.remove(8);\n }\n\n StringBuilder newMultiLineText = new StringBuilder();\n\n for (int i = 0; i < minerLogLines.size(); i++){\n newMultiLineText.append(minerLogLines.get(i)).append(\"\\n\");\n }\n\n miningLogsTextDisplay.setText(newMultiLineText.toString());\n }\n\n private void updatePercentage(){\n acceptedPercetage = (((float) acceptedShares / (float) sentShares)) * 10000;\n acceptedPercetage = Math.round(acceptedPercetage) / 100.0f;\n\n String newText = \"Accepted shares: \" + acceptedShares + \"/\" + sentShares + \" (\" + acceptedPercetage + \"%)\";\n\n acceptedSharesTextDisplay.setText(newText);\n }\n\n static float calculateEfficiency(int eff){\n if (eff >= 90){\n return 0.005f;\n }\n else if (eff >= 70){\n return 0.1f;\n }\n else if (eff >= 50){\n return 0.8f;\n }\n else if (eff >= 30) {\n return 1.8f;\n }\n\n return 3.0f;\n }\n\n static String convertHashrate(int hr){\n float roundedHashrate;\n\n if (hr >= 1_000_000){\n hr /= 1_000;\n roundedHashrate = hr / 1_000.0f;\n\n return roundedHashrate + \"M\";\n }\n else if (hr >= 1_000){\n hr /= 100;\n roundedHashrate = hr / 10.0f;\n return roundedHashrate + \"k\";\n }\n\n return String.valueOf(hr);\n }\n}" }, { "identifier": "ServiceNotificationActivity", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/activities/ServiceNotificationActivity.java", "snippet": "public class ServiceNotificationActivity extends AppCompatActivity {\n @Override\n public void onCreate(Bundle savedInstanceState){\n super.onCreate(savedInstanceState);\n\n Intent intent = new Intent(this, MinerBackgroundService.class);\n intent.setAction(MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING);\n startService(intent);\n\n finish();\n }\n}" }, { "identifier": "MiningThread", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/MiningThread.java", "snippet": "public class MiningThread implements Runnable{\n static{\n System.loadLibrary(\"ducohasher\");\n }\n\n public final static String MINING_THREAD_NAME_ID = \"duinocoin_mining_thread\";\n\n String ip;\n int port;\n\n int threadNo;\n\n Client tcpClient;\n\n String username;\n\n DUCOS1Hasher hasher;\n\n float miningEfficiency;\n\n ServiceCommunicationMethods service;\n\n public MiningThread(String ip, int port, String username, float miningEfficiency, int threadNo, ServiceCommunicationMethods service) throws IOException {\n this.ip = ip;\n this.port = port;\n this.username = username;\n this.miningEfficiency = miningEfficiency;\n this.service = service;\n this.threadNo = threadNo;\n\n hasher = new DUCOS1Hasher();\n\n Log.d(\"Mining thread\" + threadNo, threadNo + \" created\");\n }\n\n @Override\n public void run() {\n Log.d(\"Mining thread\" + threadNo, threadNo + \" started\");\n\n try {\n String responseData;\n\n try {\n tcpClient = new Client(ip, port);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n while (!Thread.currentThread().isInterrupted()) {\n tcpClient.send(\"JOB,\" + username + \",LOW\");\n\n try {\n responseData = tcpClient.readLine();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n Log.d(\"Thread \" + threadNo + \" | JOB received\", responseData);\n\n String[] values = responseData.split(\",\");\n\n String lastBlockHash = values[0];\n String expectedHash = values[1];\n\n int difficulty = Integer.parseInt(values[2]);\n\n int nonce = hasher.mine(lastBlockHash, expectedHash, difficulty, miningEfficiency);\n\n float timeElapsed = hasher.getTimeElapsed();\n float hashrate = hasher.getHashrate();\n\n Log.d(\"Thread \" + threadNo + \" | Nonce found\", nonce + \" Time elapsed: \" + timeElapsed + \"s Hashrate: \" + (int) hashrate);\n\n service.newShareSent();\n\n tcpClient.send(nonce + \",\" + (int) hashrate + \",\" + MinerInfo.MINER_NAME + \",\" + Build.MODEL);\n\n String shareResult;\n try {\n shareResult = tcpClient.readLine();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n if (shareResult.contains(\"GOOD\")) {\n service.newShareAccepted(threadNo, (int) hashrate, timeElapsed, nonce);\n }\n\n Log.d(\"Share accepted\", shareResult);\n }\n }\n catch (RuntimeException e){\n e.printStackTrace();\n }\n finally {\n try {\n tcpClient.closeConnection();\n Log.d(\"Mining thread \" + threadNo, \"Thread \" + threadNo + \" interrupted\");\n } catch (IOException e) {\n Log.w(\"Miner thread\", \"Couldn't properly end socket connection\");\n }\n }\n }\n}" }, { "identifier": "ServiceCommunicationMethods", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/ServiceCommunicationMethods.java", "snippet": "public interface ServiceCommunicationMethods {\n void newShareSent();\n void newShareAccepted(int threadNo, int hashrate, float timeElapsed, int nonce);\n}" } ]
import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.ServiceInfo; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.fatorius.duinocoinminer.R; import com.fatorius.duinocoinminer.activities.MiningActivity; import com.fatorius.duinocoinminer.activities.ServiceNotificationActivity; import com.fatorius.duinocoinminer.threads.MiningThread; import com.fatorius.duinocoinminer.threads.ServiceCommunicationMethods; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
3,873
package com.fatorius.duinocoinminer.services; public class MinerBackgroundService extends Service implements ServiceCommunicationMethods { public static final String ACTION_STOP_BACKGROUND_MINING = "com.fatorius.duinocoinminer.STOP_BACKGROUND_MINING"; private static final int NOTIFICATION_INTERVAL = 30_000; private PowerManager.WakeLock wakeLock; List<Thread> miningThreads; List<Integer> threadsHashrate; int numberOfMiningThreads; int sentShares = 0; int acceptedShares = 0; float acceptedPercetage = 0.0f; long lastNotificationSent = 0; NotificationChannel channel; PendingIntent pendingIntent; private static final int NOTIFICATION_ID = 1; @Override public void onCreate(){ super.onCreate(); channel = new NotificationChannel( "duinoCoinAndroidMinerChannel", "MinerServicesNotification", NotificationManager.IMPORTANCE_MIN ); getSystemService(NotificationManager.class).createNotificationChannel(channel); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { assert intent != null; String action = intent.getAction(); if (MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING.equals(action)) { Log.d("Miner Service", "Finishing"); stopForegroundService(); stopForeground(true); stopSelf(); return START_STICKY; } PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DuinoCoinMiner::MinerServiceWaveLock"); wakeLock.acquire(); String poolIp = intent.getStringExtra("poolIp"); String ducoUsername = intent.getStringExtra("ducoUsername"); numberOfMiningThreads = intent.getIntExtra("numberOfThreads", 0); int poolPort = intent.getIntExtra("poolPort", 0); float efficiency = intent.getFloatExtra("efficiency", 0); Log.d("Mining service", "Mining service started");
package com.fatorius.duinocoinminer.services; public class MinerBackgroundService extends Service implements ServiceCommunicationMethods { public static final String ACTION_STOP_BACKGROUND_MINING = "com.fatorius.duinocoinminer.STOP_BACKGROUND_MINING"; private static final int NOTIFICATION_INTERVAL = 30_000; private PowerManager.WakeLock wakeLock; List<Thread> miningThreads; List<Integer> threadsHashrate; int numberOfMiningThreads; int sentShares = 0; int acceptedShares = 0; float acceptedPercetage = 0.0f; long lastNotificationSent = 0; NotificationChannel channel; PendingIntent pendingIntent; private static final int NOTIFICATION_ID = 1; @Override public void onCreate(){ super.onCreate(); channel = new NotificationChannel( "duinoCoinAndroidMinerChannel", "MinerServicesNotification", NotificationManager.IMPORTANCE_MIN ); getSystemService(NotificationManager.class).createNotificationChannel(channel); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { assert intent != null; String action = intent.getAction(); if (MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING.equals(action)) { Log.d("Miner Service", "Finishing"); stopForegroundService(); stopForeground(true); stopSelf(); return START_STICKY; } PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DuinoCoinMiner::MinerServiceWaveLock"); wakeLock.acquire(); String poolIp = intent.getStringExtra("poolIp"); String ducoUsername = intent.getStringExtra("ducoUsername"); numberOfMiningThreads = intent.getIntExtra("numberOfThreads", 0); int poolPort = intent.getIntExtra("poolPort", 0); float efficiency = intent.getFloatExtra("efficiency", 0); Log.d("Mining service", "Mining service started");
Intent notificationIntent = new Intent(this, ServiceNotificationActivity.class);
1
2023-12-27 06:00:05+00:00
8k
fanxiaoning/framifykit
framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/KD100Executor.java
[ { "identifier": "ServiceException", "path": "framifykit-starter/framifykit-common/src/main/java/com/famifykit/starter/common/exception/ServiceException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic final class ServiceException extends RuntimeException {\n\n /**\n * 错误码\n * {@link ServiceErrorCodeRange}\n */\n private Integer code;\n\n /**\n * 错误信息\n */\n private String msg;\n\n /**\n * 空构造方法,避免反序列化问题\n */\n public ServiceException() {\n }\n\n public ServiceException(AbstractCode exception) {\n this.code = exception.getCode();\n this.msg = exception.getMsg();\n }\n\n public ServiceException(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n}" }, { "identifier": "FramifyResult", "path": "framifykit-starter/framifykit-common/src/main/java/com/famifykit/starter/common/result/FramifyResult.java", "snippet": "@Data\npublic class FramifyResult<T> implements Serializable {\n\n /**\n * 响应码\n * {@link ErrorCode#getCode()}\n * {@link SuccessCode#getCode()}\n */\n private Integer code;\n\n /**\n * 响应信息\n * {@link ErrorCode#getCode()}\n * {@link SuccessCode#getCode()}\n */\n private String msg;\n\n\n /**\n * 返回数据\n */\n private T data;\n\n\n /**\n * 将传入的 result 对象,转换成另外一个泛型结果的对象\n * <p>\n * 因为 A 方法返回的 FramifyResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。\n * </p>\n *\n * @param result 传入的 result 对象\n * @param <T> 返回的泛型\n * @return 新的 FramifyResult 对象\n */\n public static <T> FramifyResult<T> error(FramifyResult<?> result) {\n return error(result.getCode(), result.getMsg());\n }\n\n public static <T> FramifyResult<T> error(Integer code, String message) {\n FramifyResult<T> result = new FramifyResult<>();\n result.code = code;\n result.msg = message;\n return result;\n }\n\n public static <T> FramifyResult<T> error(AbstractCode errorCode) {\n return error(errorCode.getCode(), errorCode.getMsg());\n }\n\n public static <T> FramifyResult<T> success(T data) {\n FramifyResult<T> result = new FramifyResult<>();\n result.code = GlobalCodeConstants.SUCCESS.getCode();\n result.data = data;\n result.msg = \"\";\n return result;\n }\n\n public static boolean isSuccess(Integer code) {\n return Objects.equals(code, GlobalCodeConstants.SUCCESS.getCode());\n }\n\n @JsonIgnore\n public boolean isSuccess() {\n return isSuccess(code);\n }\n\n @JsonIgnore\n public boolean isError() {\n return !isSuccess();\n }\n\n\n /**\n * 异常体系集成\n */\n /**\n * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常\n */\n public void checkError() throws ServiceException {\n if (isSuccess()) {\n return;\n }\n // 业务异常\n throw new ServiceException(code, msg);\n }\n\n /**\n * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常\n * 如果没有,则返回 {@link #data} 数据\n */\n @JsonIgnore\n public T getCheckedData() {\n checkError();\n return data;\n }\n\n public static <T> FramifyResult<T> error(ServiceException serviceException) {\n return error(serviceException.getCode(), serviceException.getMessage());\n }\n}" }, { "identifier": "LogisticsTypeEnum", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/constant/LogisticsTypeEnum.java", "snippet": "public enum LogisticsTypeEnum {\n\n\n /**\n * 京东物流\n */\n JD(\"1000\", \"京东物流\"),\n\n /**\n * 快递100\n */\n KD_100(\"1001\", \"快递100\"),\n\n /**\n * 顺丰\n */\n SF(\"1002\", \"顺丰快递\"),\n\n /**\n * 其他\n */\n OTHER(\"1003\", \"其他物流\");\n\n\n private String code;\n private String name;\n\n LogisticsTypeEnum(String code, String name) {\n this.code = code;\n this.name = name;\n }\n\n public static LogisticsTypeEnum getType(String code) {\n for (LogisticsTypeEnum type : values()) {\n if (type.getCode().equals(code)) {\n return type;\n }\n }\n return OTHER;\n }\n\n public String getCode() {\n return code;\n }\n\n\n public String getName() {\n return name;\n }\n\n\n}" }, { "identifier": "ILogisticsGetConfig", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/config/ILogisticsGetConfig.java", "snippet": "public interface ILogisticsGetConfig<CONFIG> {\n\n /**\n * 获取配置类\n *\n * @return\n */\n CONFIG getApiConfig();\n}" }, { "identifier": "KD100Req", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/domain/req/KD100Req.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class KD100Req extends BaseReq {\n\n\n /**\n * 查询物流信息\n */\n private KD100QueryTrackReq queryTrackReq;\n\n\n /**\n * 下单\n */\n private KD100PlaceOrderReq placeOrderReq;\n\n /**\n * 取消下单\n */\n private KD100CancelOrderReq cancelOrderReq;\n\n\n /**\n * 查询运力\n */\n private KD100QueryCapacityReq queryCapacityReq;\n\n /**\n * 获取验证码\n */\n private KD100GetCodeReq getCodeReq;\n\n /**\n * 校验地址\n */\n private KD100CheckAddressReq checkAddressReq;\n\n\n /**\n * 订阅接口参数\n */\n private KD100SubscribeReq subscribeReq;\n}" }, { "identifier": "KD100Res", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/domain/res/KD100Res.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class KD100Res extends BaseRes {\n\n\n /**\n * 查询物流信息\n */\n private KD100QueryTrackRes queryTrackRes;\n\n /**\n * 下单\n */\n private KD100PlaceOrderRes placeOrderRes;\n\n /**\n * 取消下单\n */\n private KD100CancelOrderRes cancelOrderRes;\n\n /**\n * 获取验证码\n */\n private KD100GetCodeRes getCodeRes;\n\n /**\n * 校验地址\n */\n private KD100CheckAddressRes checkAddressRes;\n\n\n /**\n * 查询运力\n */\n private KD100QueryCapacityRes<KD100QueryCapacityResParam> queryCapacityRes;\n\n /**\n * 订阅\n */\n private KD100SubscribeRes subscribeRes;\n}" }, { "identifier": "DefaultKD100Client", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/client/DefaultKD100Client.java", "snippet": "@Data\npublic class DefaultKD100Client implements IKD100Client {\n\n private String key;\n\n private String customer;\n\n private String secret;\n\n private String userId;\n\n\n public DefaultKD100Client(String key, String customer, String secret) {\n this.key = key;\n this.customer = customer;\n this.secret = secret;\n }\n\n @Override\n public String execute(String url, Object req) throws ServiceException {\n //TODO 调用第三方物流接口 此次待优化\n return HttpUtils.doPost(url, req);\n }\n}" }, { "identifier": "KD100ApiConfig", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/config/KD100ApiConfig.java", "snippet": "public class KD100ApiConfig {\n\n private String appKey;\n\n private String customer;\n\n private String appSecret;\n\n\n private DefaultKD100Client KD100Client;\n\n\n private KD100ApiConfig() {\n\n }\n\n public static KD100ApiConfig builder() {\n return new KD100ApiConfig();\n }\n\n public KD100ApiConfig build() {\n this.KD100Client = new DefaultKD100Client(getAppKey(), getCustomer(), getAppSecret());\n return this;\n }\n\n public String getAppKey() {\n if (StrUtil.isBlank(appKey)) {\n throw new IllegalStateException(\"appKey 未被赋值\");\n }\n return appKey;\n }\n\n public KD100ApiConfig setKey(String appKey) {\n if (StrUtil.isEmpty(appKey)) {\n throw new IllegalArgumentException(\"appKey 值不能为 null\");\n }\n this.appKey = appKey;\n return this;\n }\n\n public String getCustomer() {\n if (StrUtil.isBlank(customer)) {\n throw new IllegalStateException(\"customer 未被赋值\");\n }\n return customer;\n }\n\n public KD100ApiConfig setCustomer(String customer) {\n if (StrUtil.isEmpty(customer)) {\n throw new IllegalArgumentException(\"customer 值不能为 null\");\n }\n this.customer = customer;\n return this;\n }\n\n public String getAppSecret() {\n if (StrUtil.isBlank(appSecret)) {\n throw new IllegalStateException(\"appSecret 未被赋值\");\n }\n return appSecret;\n }\n\n public KD100ApiConfig setAppSecret(String appSecret) {\n if (StrUtil.isEmpty(appSecret)) {\n throw new IllegalArgumentException(\"appSecret 值不能为 null\");\n }\n this.appSecret = appSecret;\n return this;\n }\n\n\n public DefaultKD100Client getKD100Client() {\n if (KD100Client == null) {\n throw new IllegalStateException(\"KD100Client 未被初始化\");\n }\n return KD100Client;\n }\n}" }, { "identifier": "KD100ApiConfigKit", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/config/KD100ApiConfigKit.java", "snippet": "public class KD100ApiConfigKit {\n\n private static final ThreadLocal<String> TL = new ThreadLocal<>();\n\n private static final Map<String, KD100ApiConfig> CFG_MAP = new ConcurrentHashMap<>();\n private static final String DEFAULT_CFG_KEY = \"_default_key_\";\n\n /**\n * <p>向缓存中设置 KD100ApiConfig </p>\n * <p>每个 appId 只需添加一次,相同 appId 将被覆盖</p>\n *\n * @param KD100ApiConfig 快递100api配置\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig putApiConfig(KD100ApiConfig KD100ApiConfig) {\n if (CFG_MAP.size() == 0) {\n CFG_MAP.put(DEFAULT_CFG_KEY, KD100ApiConfig);\n }\n return CFG_MAP.put(KD100ApiConfig.getAppKey(), KD100ApiConfig);\n }\n\n /**\n * 向当前线程中设置 {@link KD100ApiConfig}\n *\n * @param KD100ApiConfig {@link KD100ApiConfig} 快递100api配置对象\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig setThreadLocalApiConfig(KD100ApiConfig KD100ApiConfig) {\n if (StrUtil.isNotEmpty(KD100ApiConfig.getAppKey())) {\n setThreadLocalAppId(KD100ApiConfig.getAppKey());\n }\n return putApiConfig(KD100ApiConfig);\n }\n\n /**\n * 通过 KD100ApiConfig 移除快递100api配置\n *\n * @param KD100ApiConfig {@link KD100ApiConfig} 京东物流api配置对象\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig removeApiConfig(KD100ApiConfig KD100ApiConfig) {\n return removeApiConfig(KD100ApiConfig.getAppKey());\n }\n\n /**\n * 通过 appKey 移除快递100配置\n *\n * @param appKey 快递100api 应用key\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig removeApiConfig(String appKey) {\n return CFG_MAP.remove(appKey);\n }\n\n /**\n * 向当前线程中设置 appKey\n *\n * @param appKey 快递100 api 应用key\n */\n public static void setThreadLocalAppId(String appKey) {\n if (StrUtil.isEmpty(appKey)) {\n appKey = CFG_MAP.get(DEFAULT_CFG_KEY).getAppKey();\n }\n TL.set(appKey);\n }\n\n /**\n * 移除当前线程中的 appKey\n */\n public static void removeThreadLocalAppId() {\n TL.remove();\n }\n\n /**\n * 获取当前线程中的 appKey\n *\n * @return 快递100 api 应用key\n */\n public static String getAppKey() {\n String appId = TL.get();\n if (StrUtil.isEmpty(appId)) {\n appId = CFG_MAP.get(DEFAULT_CFG_KEY).getAppKey();\n }\n return appId;\n }\n\n /**\n * 获取当前线程中的 KD100ApiConfig\n *\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig getApiConfig() {\n String appId = getAppKey();\n return getApiConfig(appId);\n }\n\n /**\n * 通过 appKey 获取 KD100ApiConfig\n *\n * @param appKey 快递100 api 应用key\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig getApiConfig(String appKey) {\n KD100ApiConfig cfg = CFG_MAP.get(appKey);\n if (cfg == null) {\n throw new IllegalStateException(\"需事先调用 KD100ApiConfigKit.putApiConfig(KD100ApiConfig) 将 appKey对应的 KD100ApiConfig 对象存入,才可以使用 KD100ApiConfigKit.getJdApiConfig() 的系列方法\");\n }\n return cfg;\n }\n}" }, { "identifier": "KD100CheckAddressResParam", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100CheckAddressResParam.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class KD100CheckAddressResParam {\n\n private String taskId;\n\n private List<ToReachableDetail> toReachable;\n\n\n /**\n * @author: fanxiaoning\n * @description: 校验地址详情内部类\n * @date: 2023/5/4\n * @since v1.0.0\n **/\n @Data\n public static class ToReachableDetail {\n\n /**\n * 是否可达,0:不可达,1:可达\n */\n private String reachable;\n\n /**\n * 快递公司编码\n */\n private String expressCode;\n\n /**\n * 不可达的原因\n */\n private String reason;\n }\n}" }, { "identifier": "KD100QueryCapacityResParam", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100QueryCapacityResParam.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class KD100QueryCapacityResParam {\n\n private String province;\n\n private String city;\n\n private String district;\n\n private String addr;\n\n private String latitude;\n\n private String longitude;\n\n private List<KD100QueryCapacityResParameters> queryCapacityResParameters;\n}" }, { "identifier": "SignUtils", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/util/SignUtils.java", "snippet": "public class SignUtils {\n\n\n /**\n * 快递100加密方式统一为MD5后转大写\n *\n * @param msg\n * @return\n */\n public static String sign(String msg) {\n return DigestUtil.md5Hex(msg).toUpperCase();\n }\n\n /**\n * 查询加密\n *\n * @param param\n * @param key\n * @param customer\n * @return\n */\n public static String querySign(String param, String key, String customer) {\n return sign(param + key + customer);\n }\n\n /**\n * 打印/下单 加密\n *\n * @param param\n * @param t\n * @param key\n * @param secret\n * @return\n */\n public static String printSign(String param, String t, String key, String secret) {\n return sign(param + t + key + secret);\n }\n\n /**\n * 云平台 加密\n *\n * @param key\n * @param secret\n * @return\n */\n public static String cloudSign(String key, String secret) {\n return sign(key + secret);\n }\n\n\n /**\n * 短信加密\n *\n * @param key\n * @param userId\n * @return\n */\n public static String smsSign(String key, String userId) {\n return sign(key + userId);\n }\n}" }, { "identifier": "KD100ApiConstant", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/constant/KD100ApiConstant.java", "snippet": "public class KD100ApiConstant {\n\n\n /**\n * 签名盐值\n */\n private static String SALT = \"ecnow\";\n\n /**\n * 查询url\n */\n public static final String QUERY_URL = \"https://poll.kuaidi100.com/poll/query.do\";\n\n /**\n * 商家寄件\n */\n public static final String B_ORDER_URL = \"https://order.kuaidi100.com/order/borderbestapi.do\";\n /**\n * 商家寄件查询运力\n */\n public static final String B_ORDER_QUERY_TRANSPORT_CAPACITY_METHOD = \"querymkt\";\n /**\n * 商家寄件下单\n */\n public static final String B_ORDER_SEND_METHOD = \"bOrderBest\";\n /**\n * 商家寄件获取验证码\n */\n public static final String B_ORDER_CODE_METHOD = \"getCode\";\n /**\n * 商家寄件取消\n */\n public static final String B_ORDER_CANCEL_METHOD = \"cancelBest\";\n\n\n /**\n * 订阅url\n */\n public static final String SUBSCRIBE_URL = \"https://poll.kuaidi100.com/poll\";\n /**\n * 订阅SCHEMA\n */\n public static final String SUBSCRIBE_SCHEMA = \"json\";\n /**\n * 智能单号识别url\n */\n public static final String AUTO_NUM_URL = \"http://www.kuaidi100.com/autonumber/auto?num=%s&key=%s\";\n /**\n * 电子面单html url\n */\n public static final String ELECTRONIC_ORDER_HTML_URL = \"http://poll.kuaidi100.com/eorderapi.do\";\n /**\n * 电子面单html方法\n */\n public static final String ELECTRONIC_ORDER_HTML_METHOD = \"getElecOrder\";\n /**\n * 电子面单获取图片 url\n */\n public static final String ELECTRONIC_ORDER_PIC_URL = \"https://poll.kuaidi100.com/printapi/printtask.do\";\n /**\n * 电子面单获取图片\n */\n public static final String ELECTRONIC_ORDER_PIC_METHOD = \"getPrintImg\";\n /**\n * 电子面单打印 url\n */\n public static final String ELECTRONIC_ORDER_PRINT_URL = \"https://poll.kuaidi100.com/printapi/printtask.do\";\n /**\n * 电子面单打印方法\n */\n public static final String ELECTRONIC_ORDER_PRINT_METHOD = \"eOrder\";\n /**\n * 菜鸟淘宝账号授权\n */\n public static final String AUTH_THIRD_URL = \"https://poll.kuaidi100.com/printapi/authThird.do\";\n /**\n * 云打印url\n */\n public static final String CLOUD_PRINT_URL = \"http://poll.kuaidi100.com/printapi/printtask.do?method=%s&t=%s&key=%s&sign=%s&param=%s\";\n /**\n * 自定义打印方法\n */\n public static final String CLOUD_PRINT_CUSTOM_METHOD = \"printOrder\";\n /**\n * 附件打印方法\n */\n public static final String CLOUD_PRINT_ATTACHMENT_METHOD = \"imgOrder\";\n /**\n * 复打方法\n */\n public static final String CLOUD_PRINT_OLD_METHOD = \"printOld\";\n /**\n * 复打方法\n */\n public static final String SEND_SMS_URL = \"http://apisms.kuaidi100.com:9502/sms/send.do\";\n /**\n * 云平台通用请求url\n */\n public static final String CLOUD_NORMAL_URL = \"http://cloud.kuaidi100.com/api\";\n\n /**\n * 可用性请求地址\n */\n public static final String REACHABLE_URL = \"http://api.kuaidi100.com/reachable.do\";\n /**\n * 可用性方法\n */\n public static final String REACHABLE_METHOD = \"reachable\";\n}" } ]
import cn.hutool.core.lang.TypeReference; import cn.hutool.core.util.ReflectUtil; import com.alibaba.fastjson.JSONObject; import com.famifykit.starter.common.exception.ServiceException; import com.famifykit.starter.common.result.FramifyResult; import com.framifykit.starter.logistics.executor.constant.LogisticsTypeEnum; import com.framifykit.starter.logistics.executor.config.ILogisticsGetConfig; import com.framifykit.starter.logistics.executor.domain.req.KD100Req; import com.framifykit.starter.logistics.executor.domain.res.KD100Res; import com.framifykit.starter.logistics.platform.kd100.client.DefaultKD100Client; import com.framifykit.starter.logistics.platform.kd100.config.KD100ApiConfig; import com.framifykit.starter.logistics.platform.kd100.config.KD100ApiConfigKit; import com.framifykit.starter.logistics.platform.kd100.domain.res.*; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100CheckAddressResParam; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryCapacityResParam; import com.framifykit.starter.logistics.platform.kd100.util.SignUtils; import lombok.extern.slf4j.Slf4j; import java.util.Map; import static com.framifykit.starter.logistics.common.constant.LogisticsErrorCodeConstants.THIRD_PARTY_API_ERROR; import static com.framifykit.starter.logistics.platform.kd100.constant.KD100ApiConstant.*;
7,142
package com.framifykit.starter.logistics.executor; /** * <p> * 调用快递100接口执行器 * </p> * * @author fxn * @since 1.0.0 **/ @Slf4j public class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res> implements ILogisticsExecutor<KD100Req, FramifyResult<KD100Res>>, ILogisticsGetConfig<KD100ApiConfig> { @Override public FramifyResult<KD100Res> execute(KD100Req KD100Req) throws ServiceException { KD100Res KD100Res; try { String methodType = KD100Req.getMethodType(); KD100Res = ReflectUtil.invoke(this, methodType, KD100Req); } catch (Exception e) { log.error("第三方物流平台:{}调用系统异常", LogisticsTypeEnum.KD_100.getName(), e); throw new ServiceException(THIRD_PARTY_API_ERROR); } return FramifyResult.success(KD100Res); } @Override protected KD100Res queryTrack(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryTrackReq()); KD100QueryTrackRes KD100QueryTrackRes = JSONObject.parseObject(result, KD100QueryTrackRes.class); KD100Res kd100Res = KD100Res.builder() .queryTrackRes(KD100QueryTrackRes) .build(); return kd100Res; } @Override protected KD100Res placeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100PlaceOrderRes KD100PlaceOrderRes = JSONObject.parseObject(result, KD100PlaceOrderRes.class); KD100Res kd100Res = KD100Res.builder() .placeOrderRes(KD100PlaceOrderRes) .build(); return kd100Res; } @Override protected KD100Res cancelOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100CancelOrderRes KD100CancelOrderRes = JSONObject.parseObject(result, KD100CancelOrderRes.class); KD100Res kd100Res = KD100Res.builder() .cancelOrderRes(KD100CancelOrderRes) .build(); return kd100Res; } @Override protected KD100Res queryCost(KD100Req KD100Req) { return null; } @Override protected KD100Res subscribeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(SUBSCRIBE_URL, KD100Req.getSubscribeReq()); KD100SubscribeRes KD100SubscribeRes = JSONObject.parseObject(result, KD100SubscribeRes.class); KD100Res kd100Res = KD100Res.builder() .subscribeRes(KD100SubscribeRes) .build(); return kd100Res; } @Override protected KD100Res queryCapacity(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryCapacityReq()); KD100QueryCapacityRes<KD100QueryCapacityResParam> KD100QueryCapacityRes = JSONObject .parseObject(result, new TypeReference<KD100QueryCapacityRes<KD100QueryCapacityResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .queryCapacityRes(KD100QueryCapacityRes) .build(); return kd100Res; } @Override protected KD100Res getCode(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getGetCodeReq()); KD100GetCodeRes<Map<String, String>> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100GetCodeRes<Map<String, String>>>() { }); KD100Res kd100Res = KD100Res.builder() .getCodeRes(KD100GetCodeRes) .build(); return kd100Res; } @Override protected KD100Res checkAddress(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(REACHABLE_URL, KD100Req.getCheckAddressReq()); KD100CheckAddressRes<KD100CheckAddressResParam> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100CheckAddressRes<KD100CheckAddressResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .checkAddressRes(KD100GetCodeRes) .build(); return kd100Res; } @Override public KD100ApiConfig getApiConfig() { return KD100ApiConfigKit.getApiConfig(); } @Override protected String createSign(String signSource) {
package com.framifykit.starter.logistics.executor; /** * <p> * 调用快递100接口执行器 * </p> * * @author fxn * @since 1.0.0 **/ @Slf4j public class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res> implements ILogisticsExecutor<KD100Req, FramifyResult<KD100Res>>, ILogisticsGetConfig<KD100ApiConfig> { @Override public FramifyResult<KD100Res> execute(KD100Req KD100Req) throws ServiceException { KD100Res KD100Res; try { String methodType = KD100Req.getMethodType(); KD100Res = ReflectUtil.invoke(this, methodType, KD100Req); } catch (Exception e) { log.error("第三方物流平台:{}调用系统异常", LogisticsTypeEnum.KD_100.getName(), e); throw new ServiceException(THIRD_PARTY_API_ERROR); } return FramifyResult.success(KD100Res); } @Override protected KD100Res queryTrack(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryTrackReq()); KD100QueryTrackRes KD100QueryTrackRes = JSONObject.parseObject(result, KD100QueryTrackRes.class); KD100Res kd100Res = KD100Res.builder() .queryTrackRes(KD100QueryTrackRes) .build(); return kd100Res; } @Override protected KD100Res placeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100PlaceOrderRes KD100PlaceOrderRes = JSONObject.parseObject(result, KD100PlaceOrderRes.class); KD100Res kd100Res = KD100Res.builder() .placeOrderRes(KD100PlaceOrderRes) .build(); return kd100Res; } @Override protected KD100Res cancelOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100CancelOrderRes KD100CancelOrderRes = JSONObject.parseObject(result, KD100CancelOrderRes.class); KD100Res kd100Res = KD100Res.builder() .cancelOrderRes(KD100CancelOrderRes) .build(); return kd100Res; } @Override protected KD100Res queryCost(KD100Req KD100Req) { return null; } @Override protected KD100Res subscribeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(SUBSCRIBE_URL, KD100Req.getSubscribeReq()); KD100SubscribeRes KD100SubscribeRes = JSONObject.parseObject(result, KD100SubscribeRes.class); KD100Res kd100Res = KD100Res.builder() .subscribeRes(KD100SubscribeRes) .build(); return kd100Res; } @Override protected KD100Res queryCapacity(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryCapacityReq()); KD100QueryCapacityRes<KD100QueryCapacityResParam> KD100QueryCapacityRes = JSONObject .parseObject(result, new TypeReference<KD100QueryCapacityRes<KD100QueryCapacityResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .queryCapacityRes(KD100QueryCapacityRes) .build(); return kd100Res; } @Override protected KD100Res getCode(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getGetCodeReq()); KD100GetCodeRes<Map<String, String>> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100GetCodeRes<Map<String, String>>>() { }); KD100Res kd100Res = KD100Res.builder() .getCodeRes(KD100GetCodeRes) .build(); return kd100Res; } @Override protected KD100Res checkAddress(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(REACHABLE_URL, KD100Req.getCheckAddressReq()); KD100CheckAddressRes<KD100CheckAddressResParam> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100CheckAddressRes<KD100CheckAddressResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .checkAddressRes(KD100GetCodeRes) .build(); return kd100Res; } @Override public KD100ApiConfig getApiConfig() { return KD100ApiConfigKit.getApiConfig(); } @Override protected String createSign(String signSource) {
return SignUtils.sign(signSource);
11
2023-12-31 03:48:33+00:00
8k
yangpluseven/Simulate-Something
simulation/src/test/DisplayerTest.java
[ { "identifier": "Painter", "path": "simulation/src/interfaces/Painter.java", "snippet": "@FunctionalInterface\npublic interface Painter {\n\tpublic abstract void paint(Graphics g, int x, int y, int w, int h);\n}" }, { "identifier": "Displayer", "path": "simulation/src/simulator/Displayer.java", "snippet": "public class Displayer extends JFrame {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate DisplayArea displayArea;\n\n\t/**\n\t * Create a simulator window.\n\t */\n\tpublic Displayer() {\n\n\t\tsetTitle(\"simulation\");\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\t// Create menu bar\n\t\tJMenuBar menuBar = new JMenuBar();\n\t\tsetJMenuBar(menuBar);\n\n\t\t// Create Simulator menu\n\t\tJMenu simulatorMenu = new JMenu(\"Simulator\");\n\t\tmenuBar.add(simulatorMenu);\n\n\t\t// Add Simulator menu items\n\t\tJMenuItem startMenuItem = new JMenuItem(\"Start\");\n\t\tJMenuItem stepMenuItem = new JMenuItem(\"Step\");\n\t\tJMenuItem stopMenuItem = new JMenuItem(\"Stop\");\n\t\tsimulatorMenu.add(startMenuItem);\n\t\tsimulatorMenu.add(stepMenuItem);\n\t\tsimulatorMenu.add(stopMenuItem);\n\n\t\t// Add Simulator menu item listeners\n\t\tstartMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t// TODO start menu item\n\t\t\t\tshowMenuItemName(\"start\");\n\t\t\t}\n\t\t});\n\n\t\tstepMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t// TODO step menu item\n\t\t\t\tshowMenuItemName(\"step\");\n\t\t\t}\n\t\t});\n\n\t\tstopMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t// TODO show menu item\n\t\t\t\tshowMenuItemName(\"stop\");\n\t\t\t}\n\t\t});\n\n\t\t// Create Window menu\n\t\tJMenu windowMenu = new JMenu(\"Window\");\n\t\tmenuBar.add(windowMenu);\n\n\t\t// Add Window menu items\n\t\tJMenuItem packMenuItem = new JMenuItem(\"Pack\");\n\t\tJMenuItem zoomInMenuItem = new JMenuItem(\"Zoom In(+)\");\n\t\tJMenuItem zoomOutMenuItem = new JMenuItem(\"Zoom Out(-)\");\n\t\tJMenuItem fixMenuItem = new JMenuItem(\"Fix\");\n\t\twindowMenu.add(packMenuItem);\n\t\twindowMenu.add(zoomInMenuItem);\n\t\twindowMenu.add(zoomOutMenuItem);\n\t\twindowMenu.add(fixMenuItem);\n\n\t\t// Add Window menu item listeners\n\t\tpackMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tpack();\n\t\t\t\tdisplayArea.refresh();\n\t\t\t\tdisplayArea.drawAll();\n\t\t\t\tdisplayArea.repaint();\n\t\t\t}\n\t\t});\n\t\t\n\t\tzoomInMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tdisplayArea.zoom(Constants.ZOOM_IN);\n\t\t\t}\n\t\t});\n\t\t\n\t\tzoomOutMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tdisplayArea.zoom(Constants.ZOOM_OUT);\n\t\t\t}\n\t\t});\n\t\t\n\t\tfixMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tdisplayArea.fix();\n\t\t\t}\n\t\t});\n\t\t\n\t\taddWindowStateListener(new WindowStateListener() {\n\t\t\t@Override\n\t\t\tpublic void windowStateChanged(WindowEvent e) {\n\t\t\t\tdisplayArea.fix();\n\t\t\t}\n\t\t});\n\n\t\tsetLayout(new BorderLayout());\n\n\t\tdisplayArea = new DisplayArea();\n\t\tgetContentPane().add(displayArea, BorderLayout.CENTER);\n\n\t\t// Add a panel for the bottom area\n\t\tJPanel bottomPanel = new JPanel();\n\t\tbottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT));\n\n\t\t// Add the speed label and value\n\t\tJLabel speedLabel = new JLabel(\"Speed:\");\n\t\t// TODO display speed\n\t\tJLabel speedValueLabel = new JLabel(Integer.toString(0));\n\n\t\tbottomPanel.add(speedLabel);\n\t\tbottomPanel.add(speedValueLabel);\n\n\t\t// Add the bottom panel to the frame\n\t\tadd(bottomPanel, BorderLayout.SOUTH);\n\n\t\tsetLocationRelativeTo(null);\n\t\tpack();\n\t\tsetVisible(true);\n\t}\n\t\n\t\n\t/**\n\t * Return the gridMap of displayArea.\n\t * \n\t * @return the grid map.\n\t */\n\tpublic GridMap getGridMap() {\n\t\treturn displayArea.gridMap;\n\t}\n\n\t/**\n\t * Display the name of the menu item in a message dialog for testing.\n\t * \n\t * @param menuItemName the name of the menu item.\n\t */\n\tprivate void showMenuItemName(String menuItemName) {\n\t\tJOptionPane.showMessageDialog(this, \"Menu Item Clicked: \" + menuItemName);\n\t}\n\n\t/**\n\t * Display the window.\n\t */\n\tpublic void display() {\n\t\tdisplayArea.refresh();\n\t\tdisplayArea.drawAll();\n\t\tdisplayArea.repaint();\n\t\tsetVisible(true);\n\t}\n\n\tpublic void addObjectAt(SimuObject simuObj, Location location) {\n\t\tdisplayArea.gridMap.addObjectAt(simuObj, location);\n\t}\n\n\tprivate class DisplayArea extends JPanel {\n\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\tprivate final Size numCR = Constants.NUM_OF_COL_ROW;\n\t\tprivate Size gridSize = Constants.INIT_GRID_SIZE;\n\t\tprivate Size totalSize = new Size();\n\t\tprivate Image image;\n\t\tprivate Graphics graphic;\n\t\tprivate GridMap gridMap;\n\n\t\tprivate DisplayArea() {\n\t\t\tthis(new GridMap());\n\t\t}\n\n\t\tprivate DisplayArea(GridMap gridMap) {\n\t\t\ttotalSize.update(numCR.getWidth() * gridSize.getWidth(), numCR.getHeight() * gridSize.getHeight());\n\t\t\tthis.gridMap = gridMap;\n\t\t\tsetPreferredSize(new Dimension(totalSize.getWidth(), totalSize.getHeight()));\n\t\t}\n\t\t\n\t\tprivate void fix() {\n\t\t\tdouble xScale = (double) getWidth() / totalSize.getWidth();\n\t\t\tdouble yScale = (double) getHeight() / totalSize.getHeight();\n\t\t\tdouble scale = Math.min(xScale, yScale);\n\t\t\tint newHeight = totalSize.getHeight(), newWidth = totalSize.getWidth();\n\t\t\tint tmpTotalWidth = (int) (totalSize.getWidth() * scale);\n\t\t\tint tmpTotalHeight = (int) (totalSize.getHeight() * scale);\n\t\t\t// Ensure that the view of the simulator object is still an integer after being\n\t\t\t// resized.\n\t\t\tfor (int i = tmpTotalWidth; i >= 0; i--)\n\t\t\t\tif (i % numCR.getWidth() == 0) {\n\t\t\t\t\tnewWidth = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tfor (int i = tmpTotalHeight; i >= 0; i--)\n\t\t\t\tif (i % numCR.getHeight() == 0) {\n\t\t\t\t\tnewHeight = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t// Resize the display area.\n\t\t\tdisplayArea.setPreferredSize(new Dimension(newWidth, newHeight));\n\n\t\t\t// Resize all the simulation objects' view.\n\t\t\ttotalSize.update(newWidth, newHeight);\n\t\t\tint newGridWidth = newWidth / numCR.getWidth();\n\t\t\tint newGridHeight = newHeight / numCR.getHeight();\n\t\t\tgridSize.update(newGridWidth, newGridHeight);\n\t\t\tdisplay();\n\t\t}\n\t\t\n\t\tprivate void zoom(boolean zoomIn) {\n\t\t\tint newGridWidth = gridSize.getWidth() + (zoomIn ? 1 : -1);\n\t\t\tint newGridHeight = gridSize.getHeight() + (zoomIn ? 1 : -1);\n\t\t\tgridSize.update(newGridWidth, newGridHeight);\n\t\t\ttotalSize.update(newGridWidth * numCR.getWidth(), newGridHeight * numCR.getHeight());\n\t\t\tsetSize(new Dimension(totalSize.getWidth(), totalSize.getHeight()));\n\t\t\tdisplay();\n\t\t}\n\n\t\tprivate void refresh() {\n\t\t\timage = createImage(totalSize.getWidth(), totalSize.getHeight());\n\t\t\tgraphic = image.getGraphics();\n\t\t}\n\n\t\tprivate void drawObject(SimuObject simuObj) {\n\t\t\tPainter painter = simuObj.getPainter();\n\t\t\tLocation location = simuObj.getLocation();\n\t\t\tint x = location.getCol() * gridSize.getWidth();\n\t\t\tint y = location.getRow() * gridSize.getHeight();\n\t\t\tgraphic.setColor(simuObj.getColor());\n\t\t\tpainter.paint(graphic, x, y, gridSize.getWidth(), gridSize.getHeight());\n\t\t}\n\n\t\tprivate void drawAll() {\n\t\t\tfor (Iterator<SimuObject> iter : gridMap.getAllIterator()) {\n\t\t\t\twhile (iter.hasNext()) {\n\t\t\t\t\tSimuObject simuObj = iter.next();\n\t\t\t\t\tdrawObject(simuObj);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic Dimension getPreferredSize() {\n\t\t\treturn new Dimension(totalSize.getWidth(), totalSize.getHeight());\n\t\t}\n\n\t\tpublic void paintComponent(Graphics g) {\n\t\t\tg.drawImage(image, 0, 0, null);\n\t\t}\n\t}\n\n}" }, { "identifier": "GridMap", "path": "simulation/src/simulator/GridMap.java", "snippet": "public class GridMap implements Map<Location, simulator.GridMap.Grid> {\n\n\tprivate Grid[][] grids;\n\tprivate Size numCR;\n\tprivate int numOfObjs;\n\n\t/**\n\t * Default constructor.\n\t */\n\tpublic GridMap() {\n\t\tnumCR = Constants.NUM_OF_COL_ROW;\n\t\tint numCol = numCR.getWidth();\n\t\tint numRow = numCR.getHeight();\n\t\tgrids = new Grid[numCol][numRow];\n\t\tnumOfObjs = 0;\n\t}\n\n\t/**\n\t * Create a GridMap with the given numbers of columns and rows.\n\t * \n\t * @param numCR\n\t */\n\tpublic GridMap(Size numCR) {\n\t\tthis.numCR = numCR;\n\t\tint numCol = numCR.getWidth();\n\t\tint numRow = numCR.getHeight();\n\t\tgrids = new Grid[numCol][numRow];\n\t\tnumOfObjs = 0;\n\t}\n\n\t/**\n\t * Add the SimuObject at the given location.\n\t * \n\t * @param simuObj\n\t * @param location\n\t */\n\tpublic void addObjectAt(SimuObject simuObj, Location location) {\n\t\tif (grids[location.getCol()][location.getRow()] == null)\n\t\t\tgrids[location.getCol()][location.getRow()] = new Grid();\n\t\tgrids[location.getCol()][location.getRow()].add(simuObj);\n\t\tnumOfObjs++;\n\t}\n\n\t/**\n\t * Return the Iterator of the Grid at the Given location.\n\t * \n\t * @param location\n\t * @return the Iterator at the given location.\n\t */\n\tpublic Iterator<SimuObject> getIteratorAt(Location location) {\n\t\treturn grids[location.getCol()][location.getRow()].iterator();\n\t}\n\t\n\t/**\n\t * Return iterators of those grids.\n\t * \n\t * @return all the iterators\n\t */\n\tpublic Collection<Iterator<SimuObject>> getAllIterator() {\n\t\tArrayList<Iterator<SimuObject>> iterators = new ArrayList<Iterator<SimuObject>>(size());\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\titerators.add(grids[i][j].iterator());\n\t\treturn iterators;\n\t}\n\n\t/**\n\t * Return the number of SimuObjects in the GridMap.\n\t *\n\t * @return the number of SimuObjects.\n\t */\n\t@Override\n\tpublic int size() {\n\t\treturn numOfObjs;\n\t}\n\n\t/**\n\t * Return {@code true} if there's no SimuObjects in this GridMap.\n\t *\n\t * @return {@code true} if no SimuObjects in map.\n\t */\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn numOfObjs == 0;\n\t}\n\n\t@Override\n\tpublic boolean containsKey(Object key) {\n\t\tif (!(key instanceof Location))\n\t\t\treturn false;\n\t\tLocation location = (Location) key;\n\t\tGrid grid = grids[location.getCol()][location.getRow()];\n\t\treturn grid != null && grid.isEmpty();\n\t}\n\n\t@Override\n\tpublic boolean containsValue(Object value) {\n\t\tif (!(value instanceof SimuObject || value instanceof Grid))\n\t\t\treturn false;\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j].contains(value))\n\t\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Grid get(Object key) {\n\t\tif (!(key instanceof Location))\n\t\t\treturn null;\n\t\tLocation location = (Location) key;\n\t\treturn grids[location.getCol()][location.getRow()];\n\t}\n\n\t@Override\n\tpublic Grid put(Location key, Grid value) {\n\t\tnumOfObjs += value.size();\n\t\treturn grids[key.getCol()][key.getRow()] = value;\n\t}\n\n\t@Override\n\tpublic Grid remove(Object key) {\n\t\tif (!(key instanceof Location))\n\t\t\treturn null;\n\t\tLocation location = (Location) key;\n\t\tGrid grid = grids[location.getCol()][location.getRow()];\n\t\tgrids[location.getCol()][location.getRow()] = null;\n\t\tnumOfObjs -= grid.size();\n\t\treturn grid;\n\t}\n\n\t@Override\n\tpublic void putAll(Map<? extends Location, ? extends Grid> m) {\n\t\tfor (Entry<? extends Location, ? extends Grid> entry : m.entrySet()) {\n\t\t\tput(entry.getKey(), entry.getValue());\n\t\t\tnumOfObjs += entry.getValue().size();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tgrids[i][j] = null;\n\t\tnumOfObjs = 0;\n\t}\n\n\t@Override\n\tpublic Set<Location> keySet() {\n\t\tSet<Location> set = new HashSet<Location>();\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\tset.add(new Location(i, j));\n\t\treturn set;\n\t}\n\n\t@Override\n\tpublic Collection<Grid> values() {\n\t\tCollection<Grid> collection = new ArrayList<Grid>(size());\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\tcollection.add(grids[i][j]);\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Set<Entry<Location, Grid>> entrySet() {\n\t\tSet<Entry<Location, Grid>> set = new HashSet<Entry<Location, Grid>>();\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\tset.add(new Pair<Location, Grid>(new Location(i, j), grids[i][j]));\n\t\treturn set;\n\t}\n\n\t/**\n\t * I don't know why do I need this class. I kinda just encapsulated a ArrayList\n\t * in it.\n\t * \n\t * @author pluseven\n\t */\n\tpublic class Grid implements Collection<SimuObject> {\n\n\t\tprivate ArrayList<SimuObject> simuObjs;\n\n\t\t/**\n\t\t * Default constructor.\n\t\t */\n\t\tpublic Grid() {\n\t\t\tsimuObjs = new ArrayList<SimuObject>();\n\t\t}\n\n\t\t@Override\n\t\tpublic int size() {\n\t\t\treturn simuObjs == null ? 0 : simuObjs.size();\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isEmpty() {\n\t\t\treturn simuObjs == null || simuObjs.size() == 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean contains(Object o) {\n\t\t\treturn simuObjs == null ? false : simuObjs.contains(o);\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<SimuObject> iterator() {\n\t\t\treturn simuObjs.iterator();\n\t\t}\n\n\t\t@Override\n\t\tpublic Object[] toArray() {\n\t\t\treturn simuObjs.toArray();\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> T[] toArray(T[] a) {\n\t\t\treturn simuObjs.toArray(a);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean add(SimuObject e) {\n\t\t\treturn simuObjs.add(e);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean remove(Object o) {\n\t\t\treturn simuObjs.remove(o);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsAll(Collection<?> c) {\n\t\t\treturn simuObjs.containsAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean addAll(Collection<? extends SimuObject> c) {\n\t\t\treturn simuObjs.addAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean removeAll(Collection<?> c) {\n\t\t\treturn simuObjs.removeAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean retainAll(Collection<?> c) {\n\t\t\treturn simuObjs.retainAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic void clear() {\n\t\t\tsimuObjs.clear();\n\t\t}\n\n\t}\n\n}" } ]
import java.awt.Color; import entities.*; import entities.painters.*; import interfaces.Painter; import simulator.Displayer; import simulator.GridMap;
4,220
package test; public class DisplayerTest { public static void main(String[] args) {
package test; public class DisplayerTest { public static void main(String[] args) {
Displayer displayer = new Displayer();
1
2023-12-23 13:51:12+00:00
8k
HChenX/HideCleanUp
app/src/main/java/com/hchen/hidecleanup/HookMain.java
[ { "identifier": "HideCleanUp", "path": "app/src/main/java/com/hchen/hidecleanup/hideCleanUp/HideCleanUp.java", "snippet": "public class HideCleanUp extends Hook {\n\n @Override\n public void init() {\n hookAllMethods(\"com.miui.home.recents.views.RecentsContainer\",\n \"onFinishInflate\",\n new HookAction() {\n @Override\n protected void after(MethodHookParam param) throws Throwable {\n View mView = (View) getObjectField(param.thisObject, \"mClearAnimView\");\n mView.setVisibility(View.GONE);\n }\n }\n );\n }\n}" }, { "identifier": "Hook", "path": "app/src/main/java/com/hchen/hidecleanup/hook/Hook.java", "snippet": "public abstract class Hook extends Log {\n public String tag = getClass().getSimpleName();\n\n public XC_LoadPackage.LoadPackageParam loadPackageParam;\n\n public abstract void init();\n\n public void runHook(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n try {\n SetLoadPackageParam(loadPackageParam);\n init();\n logI(tag, \"Hook Done!\");\n } catch (Throwable s) {\n// logE(tag, \"Hook Failed: \" + e);\n }\n }\n\n public void SetLoadPackageParam(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n this.loadPackageParam = loadPackageParam;\n }\n\n public Class<?> findClass(String className) {\n return findClass(className, loadPackageParam.classLoader);\n }\n\n public Class<?> findClass(String className, ClassLoader classLoader) {\n return XposedHelpers.findClass(className, classLoader);\n }\n\n public Class<?> findClassIfExists(String className) {\n try {\n return findClass(className);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String newClassName, String oldClassName) {\n try {\n return findClass(findClassIfExists(newClassName) != null ? newClassName : oldClassName);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Find \" + newClassName + \" & \" + oldClassName + \" is null: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String className, ClassLoader classLoader) {\n try {\n return findClass(className, classLoader);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found 2: \" + e);\n return null;\n }\n }\n\n public abstract static class HookAction extends XC_MethodHook {\n\n protected void before(MethodHookParam param) throws Throwable {\n }\n\n protected void after(MethodHookParam param) throws Throwable {\n }\n\n public HookAction() {\n super();\n }\n\n public HookAction(int priority) {\n super(priority);\n }\n\n public static HookAction returnConstant(final Object result) {\n return new HookAction(PRIORITY_DEFAULT) {\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(result);\n }\n };\n }\n\n public static final HookAction DO_NOTHING = new HookAction(PRIORITY_HIGHEST * 2) {\n\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(null);\n }\n\n };\n\n @Override\n protected void beforeHookedMethod(MethodHookParam param) {\n try {\n before(param);\n } catch (Throwable e) {\n logE(\"before\", \"\" + e);\n }\n }\n\n @Override\n protected void afterHookedMethod(MethodHookParam param) {\n try {\n after(param);\n } catch (Throwable e) {\n logE(\"after\", \"\" + e);\n }\n }\n }\n\n public abstract static class ReplaceHookedMethod extends HookAction {\n\n public ReplaceHookedMethod() {\n super();\n }\n\n public ReplaceHookedMethod(int priority) {\n super(priority);\n }\n\n protected abstract Object replace(MethodHookParam param) throws Throwable;\n\n @Override\n public void beforeHookedMethod(MethodHookParam param) {\n try {\n Object result = replace(param);\n param.setResult(result);\n } catch (Throwable t) {\n logE(\"replace\", \"\" + t);\n }\n }\n }\n\n public void hookMethod(Method method, HookAction callback) {\n try {\n if (method == null) {\n logE(tag, \"method is null\");\n return;\n }\n XposedBridge.hookMethod(method, callback);\n logI(tag, \"Hook: \" + method);\n } catch (Throwable e) {\n logE(tag, \"Hook: \" + method);\n }\n }\n\n public void findAndHookMethod(Class<?> clazz, String methodName, Object... parameterTypesAndCallback) {\n try {\n /*获取class*/\n if (parameterTypesAndCallback.length != 1) {\n Object[] newArray = new Object[parameterTypesAndCallback.length - 1];\n System.arraycopy(parameterTypesAndCallback, 0, newArray, 0, newArray.length);\n getDeclaredMethod(clazz, methodName, newArray);\n }\n XposedHelpers.findAndHookMethod(clazz, methodName, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz + \" method: \" + methodName);\n } catch (Throwable e) {\n logE(tag, \"Not find method: \" + methodName + \" in: \" + clazz);\n }\n }\n\n public void findAndHookMethod(String className, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className, classLoader), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookConstructor(Class<?> clazz, Object... parameterTypesAndCallback) {\n try {\n XposedHelpers.findAndHookConstructor(clazz, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz);\n } catch (Throwable f) {\n logE(tag, \"findAndHookConstructor: \" + f + \" class: \" + clazz);\n }\n }\n\n public void findAndHookConstructor(String className, Object... parameterTypesAndCallback) {\n findAndHookConstructor(findClassIfExists(className), parameterTypesAndCallback);\n }\n\n public void hookAllMethods(String className, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook The: \" + e);\n }\n }\n\n public void hookAllMethods(String className, ClassLoader classLoader, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className, classLoader);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + className + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllMethods(Class<?> hookClass, String methodName, HookAction callback) {\n try {\n int Num = XposedBridge.hookAllMethods(hookClass, methodName, callback).size();\n logI(tag, \"Hook: \" + hookClass + \" methodName: \" + methodName + \" Num is: \" + Num);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + hookClass.getSimpleName() + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllConstructors(String className, HookAction callback) {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public void hookAllConstructors(Class<?> hookClass, HookAction callback) {\n try {\n XposedBridge.hookAllConstructors(hookClass, callback);\n } catch (Throwable f) {\n logE(tag, \"hookAllConstructors: \" + f + \" class: \" + hookClass);\n }\n }\n\n public void hookAllConstructors(String className, ClassLoader classLoader, HookAction callback) {\n Class<?> hookClass = XposedHelpers.findClassIfExists(className, classLoader);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public Object callMethod(Object obj, String methodName, Object... args) throws Throwable {\n try {\n return XposedHelpers.callMethod(obj, methodName, args);\n } catch (Throwable e) {\n logE(tag, \"callMethod: \" + obj.toString() + \" method: \" + methodName + \" args: \" + Arrays.toString(args) + \" e: \" + e);\n throw new Throwable(tag + \": callMethod error\");\n }\n }\n\n public Object callStaticMethod(Class<?> clazz, String methodName, Object... args) {\n try {\n return XposedHelpers.callStaticMethod(clazz, methodName, args);\n } catch (Throwable throwable) {\n logE(tag, \"callStaticMethod e: \" + throwable);\n return null;\n }\n }\n\n public Method getDeclaredMethod(String className, String method, Object... type) throws NoSuchMethodException {\n return getDeclaredMethod(findClassIfExists(className), method, type);\n }\n\n public Method getDeclaredMethod(Class<?> clazz, String method, Object... type) throws NoSuchMethodException {\n// String tag = \"getDeclaredMethod\";\n ArrayList<Method> haveMethod = new ArrayList<>();\n Method hqMethod = null;\n int methodNum;\n if (clazz == null) {\n logE(tag, \"find class is null: \" + method);\n throw new NoSuchMethodException(\"find class is null\");\n }\n for (Method getMethod : clazz.getDeclaredMethods()) {\n if (getMethod.getName().equals(method)) {\n haveMethod.add(getMethod);\n }\n }\n if (haveMethod.isEmpty()) {\n logE(tag, \"find method is null: \" + method);\n throw new NoSuchMethodException(\"find method is null\");\n }\n methodNum = haveMethod.size();\n if (type != null) {\n Class<?>[] classes = new Class<?>[type.length];\n Class<?> newclass = null;\n Object getType;\n for (int i = 0; i < type.length; i++) {\n getType = type[i];\n if (getType instanceof Class<?>) {\n newclass = (Class<?>) getType;\n }\n if (getType instanceof String) {\n newclass = findClassIfExists((String) getType);\n if (newclass == null) {\n logE(tag, \"get class error: \" + i);\n throw new NoSuchMethodException(\"get class error\");\n }\n }\n classes[i] = newclass;\n }\n boolean noError = true;\n for (int i = 0; i < methodNum; i++) {\n hqMethod = haveMethod.get(i);\n boolean allHave = true;\n if (hqMethod.getParameterTypes().length != classes.length) {\n if (methodNum - 1 == i) {\n logE(tag, \"class length bad: \" + Arrays.toString(hqMethod.getParameterTypes()));\n throw new NoSuchMethodException(\"class length bad\");\n } else {\n noError = false;\n continue;\n }\n }\n for (int t = 0; t < hqMethod.getParameterTypes().length; t++) {\n Class<?> getClass = hqMethod.getParameterTypes()[t];\n if (!getClass.getSimpleName().equals(classes[t].getSimpleName())) {\n allHave = false;\n break;\n }\n }\n if (!allHave) {\n if (methodNum - 1 == i) {\n logE(tag, \"type bad: \" + Arrays.toString(hqMethod.getParameterTypes())\n + \" input: \" + Arrays.toString(classes));\n throw new NoSuchMethodException(\"type bad\");\n } else {\n noError = false;\n continue;\n }\n }\n if (noError) {\n break;\n }\n }\n return hqMethod;\n } else {\n if (methodNum > 1) {\n logE(tag, \"no type method must only have one: \" + haveMethod);\n throw new NoSuchMethodException(\"no type method must only have one\");\n }\n }\n return haveMethod.get(0);\n }\n\n public void getDeclaredField(XC_MethodHook.MethodHookParam param, String iNeedString, Object iNeedTo) {\n if (param != null) {\n try {\n Field setString = param.thisObject.getClass().getDeclaredField(iNeedString);\n setString.setAccessible(true);\n try {\n setString.set(param.thisObject, iNeedTo);\n Object result = setString.get(param.thisObject);\n checkLast(\"getDeclaredField\", iNeedString, iNeedTo, result);\n } catch (IllegalAccessException e) {\n logE(tag, \"IllegalAccessException to: \" + iNeedString + \" Need to: \" + iNeedTo + \" :\" + e);\n }\n } catch (NoSuchFieldException e) {\n logE(tag, \"No such the: \" + iNeedString + \" : \" + e);\n }\n } else {\n logE(tag, \"Param is null Code: \" + iNeedString + \" & \" + iNeedTo);\n }\n }\n\n public void checkLast(String setObject, Object fieldName, Object value, Object last) {\n if (value != null && last != null) {\n if (value == last || value.equals(last)) {\n logSI(tag, setObject + \" Success! set \" + fieldName + \" to \" + value);\n } else {\n logSE(tag, setObject + \" Failed! set \" + fieldName + \" to \" + value + \" hope: \" + value + \" but: \" + last);\n }\n } else {\n logSE(tag, setObject + \" Error value: \" + value + \" or last: \" + last + \" is null\");\n }\n }\n\n public Object getObjectField(Object obj, String fieldName) throws Throwable {\n try {\n return XposedHelpers.getObjectField(obj, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getObjectField: \" + obj.toString() + \" field: \" + fieldName);\n throw new Throwable(tag + \": getObjectField error\");\n }\n }\n\n public Object getStaticObjectField(Class<?> clazz, String fieldName) throws Throwable {\n try {\n return XposedHelpers.getStaticObjectField(clazz, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName);\n throw new Throwable(tag + \": getStaticObjectField error\");\n }\n }\n\n public void setStaticObjectField(Class<?> clazz, String fieldName, Object value) throws Throwable {\n try {\n XposedHelpers.setStaticObjectField(clazz, fieldName, value);\n } catch (Throwable e) {\n logE(tag, \"setStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName + \" value: \" + value);\n throw new Throwable(tag + \": setStaticObjectField error\");\n }\n }\n\n public void setInt(Object obj, String fieldName, int value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setIntField(obj, fieldName, value),\n () -> checkLast(\"setInt\", fieldName, value,\n XposedHelpers.getIntField(obj, fieldName)));\n }\n\n public void setBoolean(Object obj, String fieldName, boolean value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setBooleanField(obj, fieldName, value),\n () -> checkLast(\"setBoolean\", fieldName, value,\n XposedHelpers.getBooleanField(obj, fieldName)));\n }\n\n public void setObject(Object obj, String fieldName, Object value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setObjectField(obj, fieldName, value),\n () -> checkLast(\"setObject\", fieldName, value,\n XposedHelpers.getObjectField(obj, fieldName)));\n }\n\n public void checkDeclaredMethod(String className, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookClass.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n if (clazz != null) {\n clazz.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkAndHookField(Object obj, String fieldName, Runnable setField, Runnable checkLast) {\n try {\n obj.getClass().getDeclaredField(fieldName);\n setField.run();\n checkLast.run();\n } catch (Throwable e) {\n logE(tag, \"No such field: \" + fieldName + \" in param: \" + obj + \" : \" + e);\n }\n }\n\n public static Context findContext() {\n Context context;\n try {\n context = (Application) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\n \"android.app.ActivityThread\", null),\n \"currentApplication\");\n if (context == null) {\n Object currentActivityThread = XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.app.ActivityThread\",\n null),\n \"currentActivityThread\");\n if (currentActivityThread != null)\n context = (Context) XposedHelpers.callMethod(currentActivityThread,\n \"getSystemContext\");\n }\n return context;\n } catch (Throwable ignore) {\n }\n return null;\n }\n\n public static String getProp(String key, String defaultValue) {\n try {\n return (String) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"get\", key, defaultValue);\n } catch (Throwable throwable) {\n logE(\"getProp\", \"key get e: \" + key + \" will return default: \" + defaultValue + \" e:\" + throwable);\n return defaultValue;\n }\n }\n\n public static void setProp(String key, String val) {\n try {\n XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"set\", key, val);\n } catch (Throwable throwable) {\n logE(\"setProp\", \"set key e: \" + key + \" e:\" + throwable);\n }\n }\n\n}" } ]
import com.hchen.hidecleanup.hideCleanUp.HideCleanUp; import com.hchen.hidecleanup.hook.Hook; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
4,667
package com.hchen.hidecleanup; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { if ("com.miui.home".equals(lpparam.packageName)) { initHook(new HideCleanUp(), lpparam); } }
package com.hchen.hidecleanup; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { if ("com.miui.home".equals(lpparam.packageName)) { initHook(new HideCleanUp(), lpparam); } }
public static void initHook(Hook hook, LoadPackageParam param) {
1
2023-12-24 13:57:39+00:00
8k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/config/impl/autogen/LongFieldImpl.java
[ { "identifier": "Option", "path": "common/src/main/java/dev/tcl/api/Option.java", "snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option.\n *\n * @see dev.thaumcraft.tcl.gui.controllers\n */\n @NotNull Controller<T> controller();\n\n /**\n * Binding for the option.\n * Controls setting, getting and default value.\n *\n * @see Binding\n */\n @NotNull Binding<T> binding();\n\n /**\n * If the option can be configured\n */\n boolean available();\n\n /**\n * Sets if the option can be configured after being built\n *\n * @see Option#available()\n */\n void setAvailable(boolean available);\n\n /**\n * Tasks that needs to be executed upon applying changes.\n */\n @NotNull ImmutableSet<OptionFlag> flags();\n\n /**\n * Checks if the pending value is not equal to the current set value\n */\n boolean changed();\n\n /**\n * Value in the GUI, ready to set the actual bound value or be undone.\n */\n @NotNull T pendingValue();\n\n /**\n * Sets the pending value\n */\n void requestSet(@NotNull T value);\n\n /**\n * Applies the pending value to the bound value.\n * Cannot be undone.\n *\n * @return if there were changes to apply {@link Option#changed()}\n */\n boolean applyValue();\n\n /**\n * Sets the pending value to the bound value.\n */\n void forgetPendingValue();\n\n /**\n * Sets the pending value to the default bound value.\n */\n void requestSetDefault();\n\n /**\n * Checks if the current pending value is equal to its default value\n */\n boolean isPendingValueDefault();\n\n default boolean canResetToDefault() {\n return true;\n }\n\n /**\n * Adds a listener for when the pending value changes\n */\n void addListener(BiConsumer<Option<T>, T> changedListener);\n\n static <T> Builder<T> createBuilder() {\n return new OptionImpl.BuilderImpl<>();\n }\n\n interface Builder<T> {\n /**\n * Sets the name to be used by the option.\n *\n * @see Option#name()\n */\n Builder<T> name(@NotNull Component name);\n\n /**\n * Sets the description to be used by the option.\n * @see OptionDescription\n * @param description the static description.\n * @return this builder\n */\n Builder<T> description(@NotNull OptionDescription description);\n\n /**\n * Sets the function to get the description by the option's current value.\n *\n * @see OptionDescription\n * @param descriptionFunction the function to get the description by the option's current value.\n * @return this builder\n */\n Builder<T> description(@NotNull Function<T, OptionDescription> descriptionFunction);\n\n Builder<T> controller(@NotNull Function<Option<T>, ControllerBuilder<T>> controllerBuilder);\n\n /**\n * Sets the controller for the option.\n * This is how you interact and change the options.\n *\n * @see dev.thaumcraft.tcl.gui.controllers\n */\n Builder<T> customController(@NotNull Function<Option<T>, Controller<T>> control);\n\n /**\n * Sets the binding for the option.\n * Used for default, getter and setter.\n *\n * @see Binding\n */\n Builder<T> binding(@NotNull Binding<T> binding);\n\n /**\n * Sets the binding for the option.\n * Shorthand of {@link Binding#generic(Object, Supplier, Consumer)}\n *\n * @param def default value of the option, used to reset\n * @param getter should return the current value of the option\n * @param setter should set the option to the supplied value\n * @see Binding\n */\n Builder<T> binding(@NotNull T def, @NotNull Supplier<@NotNull T> getter, @NotNull Consumer<@NotNull T> setter);\n\n /**\n * Sets if the option can be configured\n *\n * @see Option#available()\n */\n Builder<T> available(boolean available);\n\n /**\n * Adds a flag to the option.\n * Upon applying changes, all flags are executed.\n * {@link Option#flags()}\n */\n Builder<T> flag(@NotNull OptionFlag... flag);\n\n /**\n * Adds a flag to the option.\n * Upon applying changes, all flags are executed.\n * {@link Option#flags()}\n */\n Builder<T> flags(@NotNull Collection<? extends OptionFlag> flags);\n\n /**\n * Instantly invokes the binder's setter when modified in the GUI.\n * Prevents the user from undoing the change\n * <p>\n * Does not support {@link Option#flags()}!\n */\n Builder<T> instant(boolean instant);\n\n /**\n * Adds a listener to the option. Invoked upon changing the pending value.\n *\n * @see Option#addListener(BiConsumer)\n */\n Builder<T> listener(@NotNull BiConsumer<Option<T>, T> listener);\n\n /**\n * Adds multiple listeners to the option. Invoked upon changing the pending value.\n *\n * @see Option#addListener(BiConsumer)\n */\n Builder<T> listeners(@NotNull Collection<BiConsumer<Option<T>, T>> listeners);\n\n Option<T> build();\n }\n}" }, { "identifier": "ControllerBuilder", "path": "common/src/main/java/dev/tcl/api/controller/ControllerBuilder.java", "snippet": "@FunctionalInterface\npublic interface ControllerBuilder<T> {\n @ApiStatus.Internal\n Controller<T> build();\n}" }, { "identifier": "LongFieldControllerBuilder", "path": "common/src/main/java/dev/tcl/api/controller/LongFieldControllerBuilder.java", "snippet": "public interface LongFieldControllerBuilder extends NumberFieldControllerBuilder<Long, LongFieldControllerBuilder> {\n static LongFieldControllerBuilder create(Option<Long> option) {\n return new LongFieldControllerBuilderImpl(option);\n }\n}" }, { "identifier": "ConfigField", "path": "common/src/main/java/dev/tcl/config/api/ConfigField.java", "snippet": "public interface ConfigField<T> {\n /**\n * Gets the accessor for the field on the main instance.\n * (Accessed through {@link ConfigClassHandler#instance()})\n */\n FieldAccess<T> access();\n\n /**\n * Gets the accessor for the field on the default instance.\n */\n ReadOnlyFieldAccess<T> defaultAccess();\n\n /**\n * @return the parent config class handler that manages this field.\n */\n ConfigClassHandler<?> parent();\n\n /**\n * The serial entry metadata for this field, if it exists.\n */\n Optional<SerialField> serial();\n\n /**\n * The auto-gen metadata for this field, if it exists.\n */\n Optional<AutoGenField> autoGen();\n}" }, { "identifier": "OptionAccess", "path": "common/src/main/java/dev/tcl/config/api/autogen/OptionAccess.java", "snippet": "public interface OptionAccess {\n /**\n * Gets an option by its field name.\n * This could be null if the option hasn't been created yet. It is created\n * in order of the fields in the class, so if you are trying to get an option\n * lower-down in the class, this will return null.\n *\n * @param fieldName the exact, case-sensitive name of the field.\n * @return the created option, or {@code null} if it hasn't been created yet.\n */\n @Nullable Option<?> getOption(String fieldName);\n\n /**\n * Schedules an operation to be performed on an option.\n * If the option has already been created, the consumer will be\n * accepted immediately upon calling this method, if not, it will\n * be added to the queue of operations to be performed on the option\n * once it does get created.\n *\n * @param fieldName the exact, case-sensitive name of the field.\n * @param optionConsumer the operation to perform on the option.\n */\n void scheduleOptionOperation(String fieldName, Consumer<Option<?>> optionConsumer);\n}" }, { "identifier": "SimpleOptionFactory", "path": "common/src/main/java/dev/tcl/config/api/autogen/SimpleOptionFactory.java", "snippet": "public abstract class SimpleOptionFactory<A extends Annotation, T> implements OptionFactory<A, T> {\n @Override\n public Option<T> createOption(A annotation, ConfigField<T> field, OptionAccess optionAccess) {\n Option<T> option = Option.<T>createBuilder()\n .name(this.name(annotation, field, optionAccess))\n .description(v -> this.description(v, annotation, field, optionAccess).build())\n .binding(new FieldBackedBinding<>(field.access(), field.defaultAccess()))\n .controller(opt -> {\n ControllerBuilder<T> builder = this.createController(annotation, field, optionAccess, opt);\n\n AutoGenUtils.addCustomFormatterToController(builder, field.access());\n\n return builder;\n })\n .available(this.available(annotation, field, optionAccess))\n .flags(this.flags(annotation, field, optionAccess))\n .listener((opt, v) -> this.listener(annotation, field, optionAccess, opt, v))\n .build();\n\n postInit(annotation, field, optionAccess, option);\n return option;\n }\n\n protected abstract ControllerBuilder<T> createController(A annotation, ConfigField<T> field, OptionAccess storage, Option<T> option);\n\n protected MutableComponent name(A annotation, @NotNull ConfigField<T> field, OptionAccess storage) {\n Optional<CustomName> customName = field.access().getAnnotation(CustomName.class);\n return Component.translatable(customName.map(CustomName::value).orElse(this.getTranslationKey(field, null)));\n }\n\n protected OptionDescription.Builder description(T value, A annotation, ConfigField<T> field, OptionAccess storage) {\n OptionDescription.Builder builder = OptionDescription.createBuilder();\n\n String key = this.getTranslationKey(field, \"desc\");\n if (Language.getInstance().has(key)) {\n builder.text(Component.translatable(key));\n } else {\n key += \".\";\n int i = 1;\n while (Language.getInstance().has(key + i)) {\n builder.text(Component.translatable(key + i));\n i++;\n }\n }\n\n field.access().getAnnotation(CustomDescription.class).ifPresent(customDescription -> {\n for (String line : customDescription.value()) {\n builder.text(Component.translatable(line));\n }\n });\n\n Optional<CustomImage> imageOverrideOpt = field.access().getAnnotation(CustomImage.class);\n if (imageOverrideOpt.isPresent()) {\n CustomImage imageOverride = imageOverrideOpt.get();\n\n if (!imageOverride.factory().equals(EmptyCustomImageFactory.class)) {\n CustomImage.CustomImageFactory<T> imageFactory;\n try {\n imageFactory = (CustomImage.CustomImageFactory<T>) AutoGenUtils.constructNoArgsClass(\n imageOverride.factory(),\n () -> \"'%s': The factory class on @OverrideImage has no no-args constructor.\".formatted(field.access().name()),\n () -> \"'%s': Failed to instantiate factory class %s.\".formatted(field.access().name(), imageOverride.factory().getName())\n );\n } catch (ClassCastException e) {\n throw new TCLAutoGenException(\"'%s': The factory class on @OverrideImage is of incorrect type. Expected %s, got %s.\".formatted(field.access().name(), field.access().type().getTypeName(), imageOverride.factory().getTypeParameters()[0].getName()));\n }\n\n builder.customImage(imageFactory.createImage(value, field, storage).thenApply(Optional::of));\n } else if (!imageOverride.value().isEmpty()) {\n String path = imageOverride.value();\n ResourceLocation imageLocation = new ResourceLocation(field.parent().id().getNamespace(), path);\n String extension = path.substring(path.lastIndexOf('.') + 1);\n\n switch (extension) {\n case \"png\", \"jpg\", \"jpeg\" -> builder.image(imageLocation, imageOverride.width(), imageOverride.height());\n case \"webp\" -> builder.webpImage(imageLocation);\n default ->\n throw new TCLAutoGenException(\"'%s': Invalid image extension '%s' on @OverrideImage. Expected: ('png','jpg','jpeg','webp')\".formatted(field.access().name(), extension));\n }\n } else {\n throw new TCLAutoGenException(\"'%s': @OverrideImage has no value or factory class.\".formatted(field.access().name()));\n }\n } else {\n String imagePath = \"textures/tcl/\" + field.parent().id().getPath() + \"/\" + field.access().name() + \".webp\";\n imagePath = imagePath.toLowerCase().replaceAll(\"[^a-z0-9/._:-]\", \"_\");\n ResourceLocation imageLocation = new ResourceLocation(field.parent().id().getNamespace(), imagePath);\n if (Minecraft.getInstance().getResourceManager().getResource(imageLocation).isPresent()) {\n builder.webpImage(imageLocation);\n }\n }\n\n return builder;\n }\n\n protected boolean available(A annotation, ConfigField<T> field, OptionAccess storage) {\n return true;\n }\n\n protected Set<OptionFlag> flags(A annotation, ConfigField<T> field, OptionAccess storage) {\n return Set.of();\n }\n\n protected void listener(A annotation, ConfigField<T> field, OptionAccess storage, Option<T> option, T value) {\n\n }\n\n protected void postInit(A annotation, ConfigField<T> field, OptionAccess storage, Option<T> option) {\n\n }\n\n public static final Converter<String, String> FIELD_NAME_CONVERTER = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE);\n\n protected String getTranslationKey(@NotNull ConfigField<? extends T> field, @Nullable String suffix) {\n String key = \"tcl.config.%s.%s\".formatted(field.parent().id().toLanguageKey(), FIELD_NAME_CONVERTER.convert(field.access().name()));\n if (suffix != null) key += \".\" + suffix;\n return key;\n }\n\n protected ValueFormatter<T> createMinMaxFormatter(\n @NotNull ConfigField<? extends T> field,\n @NotNull Supplier<? extends T> minValue,\n @NotNull Supplier<? extends T> maxValue,\n @NotNull Supplier<String> format\n ) {\n return v -> {\n String key = null;\n if (v == minValue.get())\n key = getTranslationKey(field, \"fmt.min\");\n else if (v == maxValue.get())\n key = getTranslationKey(field, \"fmt.max\");\n if (key != null && Language.getInstance().has(key))\n return Component.translatable(key);\n key = getTranslationKey(field, \"fmt\");\n if (Language.getInstance().has(key))\n return Component.translatable(key, v);\n return Component.translatable(String.format(format.get(), v));\n };\n }\n}" } ]
import dev.tcl.api.Option; import dev.tcl.api.controller.ControllerBuilder; import dev.tcl.api.controller.LongFieldControllerBuilder; import dev.tcl.config.api.ConfigField; import dev.tcl.config.api.autogen.LongField; import dev.tcl.config.api.autogen.OptionAccess; import dev.tcl.config.api.autogen.SimpleOptionFactory; import net.minecraft.locale.Language; import net.minecraft.network.chat.Component;
3,630
package dev.tcl.config.impl.autogen; public class LongFieldImpl extends SimpleOptionFactory<LongField, Long> { @Override
package dev.tcl.config.impl.autogen; public class LongFieldImpl extends SimpleOptionFactory<LongField, Long> { @Override
protected ControllerBuilder<Long> createController(LongField annotation, ConfigField<Long> field, OptionAccess storage, Option<Long> option) {
4
2023-12-25 14:48:27+00:00
8k
behnamnasehi/playsho
app/src/main/java/com/playsho/android/base/BaseActivity.java
[ { "identifier": "ActivityLauncher", "path": "app/src/main/java/com/playsho/android/component/ActivityLauncher.java", "snippet": "public class ActivityLauncher<Input, Result> {\n /**\n * Register activity result using a {@link ActivityResultContract} and an in-place activity result callback like\n * the default approach. You can still customise callback using {@link #launch(Object, OnActivityResult)}.\n */\n @NonNull\n public static <Input, Result> ActivityLauncher<Input, Result> registerForActivityResult(\n @NonNull ActivityResultCaller caller,\n @NonNull ActivityResultContract<Input, Result> contract,\n @Nullable OnActivityResult<Result> onActivityResult) {\n return new ActivityLauncher<>(caller, contract, onActivityResult);\n }\n\n /**\n * Same as {@link #registerForActivityResult(ActivityResultCaller, ActivityResultContract, OnActivityResult)} except\n * the last argument is set to {@code null}.\n */\n @NonNull\n public static <Input, Result> ActivityLauncher<Input, Result> registerForActivityResult(\n @NonNull ActivityResultCaller caller,\n @NonNull ActivityResultContract<Input, Result> contract) {\n return registerForActivityResult(caller, contract, null);\n }\n\n /**\n * Specialised method for launching new activities.\n */\n @NonNull\n public static ActivityLauncher<Intent, ActivityResult> registerActivityForResult(\n @NonNull ActivityResultCaller caller) {\n return registerForActivityResult(caller, new ActivityResultContracts.StartActivityForResult());\n }\n\n /**\n * Callback interface\n */\n public interface OnActivityResult<O> {\n /**\n * Called after receiving a result from the target activity\n */\n void onActivityResult(O result);\n }\n\n private final ActivityResultLauncher<Input> launcher;\n @Nullable\n private OnActivityResult<Result> onActivityResult;\n\n private ActivityLauncher(@NonNull ActivityResultCaller caller,\n @NonNull ActivityResultContract<Input, Result> contract,\n @Nullable OnActivityResult<Result> onActivityResult) {\n this.onActivityResult = onActivityResult;\n this.launcher = caller.registerForActivityResult(contract, this::callOnActivityResult);\n }\n\n public void setOnActivityResult(@Nullable OnActivityResult<Result> onActivityResult) {\n this.onActivityResult = onActivityResult;\n }\n\n /**\n * Launch activity, same as {@link ActivityResultLauncher#launch(Object)} except that it allows a callback\n * executed after receiving a result from the target activity.\n */\n public void launch(Input input, @Nullable OnActivityResult<Result> onActivityResult) {\n if (onActivityResult != null) {\n this.onActivityResult = onActivityResult;\n }\n launcher.launch(input);\n }\n\n /**\n * Same as {@link #launch(Object, OnActivityResult)} with last parameter set to {@code null}.\n */\n public void launch(Input input) {\n launch(input, this.onActivityResult);\n }\n\n private void callOnActivityResult(Result result) {\n if (onActivityResult != null) onActivityResult.onActivityResult(result);\n }\n}" }, { "identifier": "SessionStorage", "path": "app/src/main/java/com/playsho/android/db/SessionStorage.java", "snippet": "public class SessionStorage {\n private final SharedPreferences pref;\n private final SharedPreferences.Editor editor;\n\n // Name of the shared preference file\n private final String SHARED_PREFERENCE_NAME = \"main_sp\";\n\n /**\n * Constructs a SessionStorage instance and initializes SharedPreferences and its editor.\n */\n public SessionStorage() {\n this.pref = ApplicationLoader.getAppContext().getSharedPreferences(\n SHARED_PREFERENCE_NAME,\n Context.MODE_PRIVATE\n );\n editor = pref.edit();\n editor.apply();\n }\n\n /**\n * Clears all entries in the SharedPreferences.\n */\n public void clearAll(){\n pref.edit().clear().apply();\n }\n\n /**\n * Gets a String value from the SharedPreferences with the specified key.\n *\n * @param key The key for the String value.\n * @return The String value associated with the key, or {@code null} if not found.\n */\n public String getString(String key) {\n return pref.getString(key, null);\n }\n\n\n /**\n * Gets a String value from the SharedPreferences with the specified key, providing a default value if not found.\n *\n * @param key The key for the String value.\n * @param defValue The default value to return if the key is not found.\n * @return The String value associated with the key, or the default value if not found.\n */\n public String getString(String key , String defValue) {\n return pref.getString(key, defValue);\n }\n\n /**\n * Sets a String value in the SharedPreferences with the specified key.\n *\n * @param key The key for the String value.\n * @param value The String value to set.\n */\n public void setString(String key, String value) {\n editor.putString(key, value);\n editor.apply();\n editor.commit();\n }\n\n /**\n * Gets an integer value from the SharedPreferences with the specified key.\n *\n * @param key The key for the integer value.\n * @return The integer value associated with the key, or 0 if not found.\n */\n public int getInteger(String key) {\n return pref.getInt(key, 0);\n }\n\n /**\n * Gets an integer value from the SharedPreferences with the specified key, providing a default value if not found.\n *\n * @param key The key for the integer value.\n * @param defValue The default value to return if the key is not found.\n * @return The integer value associated with the key, or the default value if not found.\n */\n public int getInteger(String key , int defValue) {\n return pref.getInt(key, defValue);\n }\n\n /**\n * Sets an integer value in the SharedPreferences with the specified key.\n *\n * @param key The key for the integer value.\n * @param value The integer value to set.\n */\n public void setInteger(String key, int value) {\n editor.putInt(key, value);\n editor.apply();\n editor.commit();\n }\n\n\n /**\n * Deserializes a JSON string stored in SharedPreferences into an object of the specified class.\n *\n * @param key The key for the JSON string.\n * @param clazz The class type to deserialize the JSON into.\n * @param <T> The type of the class.\n * @return An object of the specified class, or a default object if the JSON is not found.\n */\n public <T> T deserialize(String key, Class<T> clazz) {\n String json = this.getString(key);\n if (Validator.isNullOrEmpty(json)) {\n json = \"{}\";\n }\n return ApplicationLoader.getGson().fromJson(json, clazz);\n }\n\n /**\n * Inserts a JSON-serializable object into SharedPreferences with the specified key.\n *\n * @param key The key for storing the JSON string.\n * @param o The object to be serialized and stored.\n */\n public void insertJson(String key, Object o) {\n this.editor.putString(key,ApplicationLoader.getGson().toJson(o));\n editor.apply();\n editor.commit();\n }\n\n\n /**\n * Gets a boolean value from the SharedPreferences with the specified key.\n *\n * @param key The key for the boolean value.\n * @return The boolean value associated with the key, or {@code false} if not found.\n */\n public boolean getBoolean(String key) {\n return pref.getBoolean(key, false);\n }\n\n /**\n * Gets a boolean value from the SharedPreferences with the specified key, providing a default value if not found.\n *\n * @param key The key for the boolean value.\n * @param defValue The default value to return if the key is not found.\n * @return The boolean value associated with the key, or the default value if not found.\n */\n public boolean getBoolean(String key, boolean defValue) {\n return pref.getBoolean(key, defValue);\n }\n\n /**\n * Sets a boolean value in the SharedPreferences with the specified key.\n *\n * @param key The key for the boolean value.\n * @param value The boolean value to set.\n */\n public void setBoolean(String key, boolean value) {\n editor.putBoolean(key, value);\n editor.apply();\n editor.commit();\n }\n\n}" }, { "identifier": "NetworkListener", "path": "app/src/main/java/com/playsho/android/utils/NetworkListener.java", "snippet": "public class NetworkListener extends ConnectivityManager.NetworkCallback {\n\n // ConnectivityManager instance for network monitoring\n private ConnectivityManager connectivityManager;\n\n // AtomicBoolean to ensure thread-safe access to network availability status\n private final AtomicBoolean isNetworkAvailable = new AtomicBoolean(false);\n\n /**\n * Initializes the NetworkListener by registering it with the ConnectivityManager.\n * This method should be called to start monitoring network changes.\n */\n public void init() {\n // Obtain ConnectivityManager from the application context\n connectivityManager = (ConnectivityManager) ApplicationLoader.getAppContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n\n // Register the NetworkListener to receive network status callbacks\n connectivityManager.registerDefaultNetworkCallback(this);\n }\n\n /**\n * Checks the current network availability status.\n *\n * @return True if the network is available, false otherwise.\n */\n public boolean checkNetworkAvailability() {\n // Obtain the currently active network\n Network network = connectivityManager.getActiveNetwork();\n\n if (network == null) {\n // No active network, set availability to false\n isNetworkAvailable.set(false);\n return isNetworkAvailable();\n }\n\n // Obtain the network capabilities of the active network\n NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);\n\n if (networkCapabilities == null) {\n // Network capabilities not available, set availability to false\n isNetworkAvailable.set(false);\n return isNetworkAvailable();\n }\n\n // Check if the network has any of the specified transport types (e.g., WiFi, Cellular)\n isNetworkAvailable.set(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)\n || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)\n || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)\n || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH));\n\n return isNetworkAvailable();\n }\n\n /**\n * Gets the real-time network availability status.\n *\n * @return True if the network is available, false otherwise.\n */\n public boolean isNetworkAvailable() {\n return isNetworkAvailable.get();\n }\n\n /**\n * Called when a network becomes available.\n *\n * @param network The Network object representing the available network.\n */\n @Override\n public void onAvailable(@NonNull Network network) {\n // Set network availability status to true\n isNetworkAvailable.set(true);\n }\n\n /**\n * Called when a network is lost or becomes unavailable.\n *\n * @param network The Network object representing the lost network.\n */\n @Override\n public void onLost(@NonNull Network network) {\n // Set network availability status to false\n isNetworkAvailable.set(false);\n }\n}" }, { "identifier": "SystemUtilities", "path": "app/src/main/java/com/playsho/android/utils/SystemUtilities.java", "snippet": "public class SystemUtilities {\n /**\n * Tag for logging purposes.\n */\n private static final String TAG = \"SystemUtils\";\n\n /**\n * Changes the color of status bar icons based on the specified mode.\n *\n * @param activity The activity where the status bar icons are changed.\n * @param isDark True if the status bar icons should be dark, false otherwise.\n */\n public static void changeStatusBarIconColor(Activity activity, boolean isDark) {\n View decorView = activity.getWindow().getDecorView();\n int flags = decorView.getSystemUiVisibility();\n if (!isDark) {\n // Make status bar icons dark (e.g., for light background)\n flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;\n } else {\n // Make status bar icons light (e.g., for dark background)\n flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;\n }\n decorView.setSystemUiVisibility(flags);\n }\n\n /**\n * Changes the background color of the status bar and adjusts the icon color.\n *\n * @param activity The activity where the status bar color is changed.\n * @param color The color resource ID for the status bar.\n * @param isDark True if the status bar icons should be dark, false otherwise.\n */\n public static void changeStatusBarBackgroundColor(Activity activity, int color, boolean isDark) {\n changeStatusBarIconColor(activity, isDark);\n activity.getWindow().setStatusBarColor(LocalController.getColor(color));\n }\n\n /**\n * Shares plain text through the available sharing options.\n *\n * @param context The context from which the sharing is initiated.\n * @param title The title of the shared content.\n * @param body The body or content to be shared.\n */\n public static void sharePlainText(Context context, String title, String body) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"text/plain\");\n intent.putExtra(Intent.EXTRA_SUBJECT, title);\n intent.putExtra(Intent.EXTRA_TEXT, body);\n context.startActivity(Intent.createChooser(intent, title));\n }\n\n /**\n * Initiates a phone call to the specified phone number.\n *\n * @param context The context from which the phone call is initiated.\n * @param phone The phone number to call.\n */\n public static void callPhoneNumber(Context context, String phone) {\n context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts(\"tel\", phone, null)));\n }\n\n /**\n * Vibrates the device for the specified duration.\n *\n * @param milisecond The duration of the vibration in milliseconds.\n */\n public static void doVibrate(int milisecond) {\n Vibrator v = (Vibrator) ApplicationLoader.getAppContext().getSystemService(Context.VIBRATOR_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n Objects.requireNonNull(v).vibrate(VibrationEffect.createOneShot(milisecond, VibrationEffect.DEFAULT_AMPLITUDE));\n } else {\n Objects.requireNonNull(v).vibrate(milisecond);\n }\n }\n\n /**\n * Copies the specified text to the clipboard.\n *\n * @param label The label for the copied text.\n * @param text The text to be copied.\n */\n public static void copyToClipboard(String label, String text) {\n ClipboardManager clipboard = (ClipboardManager) ApplicationLoader.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);\n ClipData clip = ClipData.newPlainText(label, text);\n clipboard.setPrimaryClip(clip);\n }\n\n /**\n * Sets the navigation bar to have light icons on a light background.\n *\n * @param window The window for which the navigation bar color is set.\n * @param enable True if the light navigation bar should be enabled, false otherwise.\n */\n public static void setLightNavigationBar(Window window, boolean enable) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n final View decorView = window.getDecorView();\n int flags = decorView.getSystemUiVisibility();\n if (enable) {\n flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;\n } else {\n flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;\n }\n decorView.setSystemUiVisibility(flags);\n }\n }\n\n /**\n * Shows the soft keyboard for the specified view.\n *\n * @param view The view for which the soft keyboard is shown.\n */\n public static void showKeyboard(View view) {\n if (view == null) {\n return;\n }\n try {\n InputMethodManager inputManager = (InputMethodManager) ApplicationLoader.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);\n } catch (Exception ignored) {\n }\n }\n\n /**\n * Hides the soft keyboard for the specified view.\n *\n * @param view The view for which the soft keyboard is hidden.\n */\n public static void hideKeyboard(View view) {\n if (view == null) {\n return;\n }\n try {\n InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n if (!imm.isActive()) {\n return;\n }\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n } catch (Exception e) {\n Log.e(TAG, \"hideKeyboard: \", e);\n }\n }\n\n /**\n * Sets the navigation bar color to white for dialogs on API level 23 and above.\n *\n * @param dialog The dialog for which the navigation bar color is set to white.\n */\n public static void setWhiteNavigationBar(@NonNull Dialog dialog) {\n Window window = dialog.getWindow();\n if (window != null) {\n DisplayMetrics metrics = new DisplayMetrics();\n window.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n\n GradientDrawable dimDrawable = new GradientDrawable();\n\n GradientDrawable navigationBarDrawable = new GradientDrawable();\n navigationBarDrawable.setShape(GradientDrawable.RECTANGLE);\n navigationBarDrawable.setColor(Color.WHITE);\n\n Drawable[] layers = {dimDrawable, navigationBarDrawable};\n\n LayerDrawable windowBackground = new LayerDrawable(layers);\n windowBackground.setLayerInsetTop(1, metrics.heightPixels);\n\n window.setBackgroundDrawable(windowBackground);\n }\n }\n}" } ]
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.activity.OnBackPressedCallback; import androidx.activity.result.ActivityResult; import androidx.annotation.ColorRes; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import com.playsho.android.component.ActivityLauncher; import com.playsho.android.db.SessionStorage; import com.playsho.android.utils.NetworkListener; import com.playsho.android.utils.SystemUtilities;
4,441
package com.playsho.android.base; /** * A base activity class that provides common functionality and structure for other activities. * * @param <B> The type of ViewDataBinding used by the activity. */ public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity { // Flag to enable or disable the custom back press callback private boolean isBackPressCallbackEnable = false; /** * Abstract method to get the layout resource ID for the activity. * * @return The layout resource ID. */ protected abstract int getLayoutResourceId(); /** * Abstract method to handle custom behavior on back press. */ protected abstract void onBackPress(); // View binding instance protected B binding;
package com.playsho.android.base; /** * A base activity class that provides common functionality and structure for other activities. * * @param <B> The type of ViewDataBinding used by the activity. */ public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity { // Flag to enable or disable the custom back press callback private boolean isBackPressCallbackEnable = false; /** * Abstract method to get the layout resource ID for the activity. * * @return The layout resource ID. */ protected abstract int getLayoutResourceId(); /** * Abstract method to handle custom behavior on back press. */ protected abstract void onBackPress(); // View binding instance protected B binding;
protected NetworkListener networkListener;
2
2023-12-26 08:14:29+00:00
8k
lunasaw/voglander
voglander-service/src/main/java/io/github/lunasaw/voglander/service/login/DeviceRegisterServiceImpl.java
[ { "identifier": "DeviceChannelReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceChannelReq.java", "snippet": "@Data\npublic class DeviceChannelReq {\n\n /**\n * 设备Id\n */\n private String deviceId;\n\n /**\n * 通道Id\n */\n private String channelId;\n\n /**\n * 通道信息\n */\n private String channelInfo;\n\n /**\n * 通道名称\n */\n private String channelName;\n}" }, { "identifier": "DeviceInfoReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceInfoReq.java", "snippet": "@Data\npublic class DeviceInfoReq {\n\n private String deviceId;\n\n private String deviceInfo;\n}" }, { "identifier": "DeviceQueryReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceQueryReq.java", "snippet": "@Data\npublic class DeviceQueryReq {\n\n private String deviceId;\n\n}" }, { "identifier": "DeviceReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceReq.java", "snippet": "@Data\npublic class DeviceReq {\n\n /**\n * 设备Id\n */\n private String deviceId;\n\n /**\n * 注册时间\n */\n private Date registerTime;\n\n /**\n * 注册过期时间\n */\n private Integer expire;\n\n /**\n * 注册协议\n */\n private String transport;\n\n /**\n * 设备注册地址当前IP\n */\n private String localIp;\n\n /**\n * nat转换后看到的IP\n */\n private String remoteIp;\n\n /**\n * 经过rpotocol转换后的端口\n */\n private Integer remotePort;\n\n /**\n * 协议类型 {@link DeviceAgreementEnum}\n */\n private Integer type;\n\n}" }, { "identifier": "DeviceCommandService", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/service/DeviceCommandService.java", "snippet": "public interface DeviceCommandService {\n\n /**\n * 通道查询\n *\n * @param deviceQueryReq\n */\n void queryChannel(DeviceQueryReq deviceQueryReq);\n\n /**\n * 设备查询\n *\n * @param deviceQueryReq\n */\n void queryDevice(DeviceQueryReq deviceQueryReq);\n\n}" }, { "identifier": "DeviceRegisterService", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/service/DeviceRegisterService.java", "snippet": "public interface DeviceRegisterService {\n\n /**\n * 注册登陆\n *\n * @param device\n */\n void login(DeviceReq device);\n\n /**\n * 保持活跃\n * @param deviceId\n */\n void keepalive(String deviceId);\n\n /**\n * 更新设备地址\n * @param deviceId\n * @param ip\n * @param port\n */\n void updateRemoteAddress(String deviceId, String ip, Integer port);\n\n /**\n * 设备离线\n * @param userId\n */\n void offline(String userId);\n\n /**\n * 添加设备通道\n *\n * @param req\n */\n void addChannel(DeviceChannelReq req);\n\n /**\n * 更新设备信息\n *\n * @param req\n */\n void updateDeviceInfo(DeviceInfoReq req);\n}" }, { "identifier": "DeviceConstant", "path": "voglander-common/src/main/java/io/github/lunasaw/voglander/common/constant/DeviceConstant.java", "snippet": "public interface DeviceConstant {\n\n interface DeviceCommandService {\n String DEVICE_AGREEMENT_SERVICE_NAME_GB28181 = \"GbDeviceCommandService\";\n }\n\n interface Status {\n int OFFLINE = 0;\n int ONLINE = 1;\n }\n\n interface LocalConfig {\n String DEVICE_ID = \"0\";\n String DEVICE_NAME = \"voglander\";\n String DEVICE_GB_SIP = \"gb_sip\";\n String DEVICE_GB_SIP_DEFAULT = \"41010500002000000001\";\n\n String DEVICE_GB_PASSWORD = \"gb_password\";\n String DEVICE_GB_PASSWORD_DEFAULT = \"bajiuwulian1006\";\n\n }\n\n\n /**\n * 字符集, 支持 UTF-8 与 GB2312\n */\n\n String CHARSET = \"charset\";\n\n /**\n * 数据流传输模式\n * UDP:udp传输\n * TCP-ACTIVE:tcp主动模式\n * TCP-PASSIVE:tcp被动模式\n */\n String STREAM_MODE = \"streamMode\";\n\n /**\n * 目录订阅周期,0为不订阅\n */\n String SUBSCRIBE_CYCLE_FOR_CATALOG = \"subscribeCycleForCatalog\";\n\n /**\n * 移动设备位置订阅周期,0为不订阅\n */\n String SUBSCRIBE_CYCLE_FOR_MOBILE_POSITION = \"subscribeCycleForMobilePosition\";\n\n /**\n * 移动设备位置信息上报时间间隔,单位:秒,默认值5\n */\n String MOBILE_POSITION_SUBMISSION_INTERVAL = \"mobilePositionSubmissionInterval\";\n\n /**\n * 报警订阅周期,0为不订阅\n */\n String SUBSCRIBE_CYCLE_FOR_ALARM = \"subscribeCycleForAlarm\";\n\n /**\n * 是否开启ssrc校验,默认关闭,开启可以防止串流\n */\n String SSRC_CHECK = \"ssrcCheck\";\n\n /**\n * 地理坐标系, 目前支持 WGS84,GCJ02\n */\n String GEO_COORD_SYS = \"geoCoordSys\";\n\n /**\n * 设备使用的媒体id, 默认为null\n */\n String MEDIA_SERVER_ID = \"mediaServerId\";\n\n}" }, { "identifier": "DeviceChannelDTO", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/domaon/dto/DeviceChannelDTO.java", "snippet": "@Data\npublic class DeviceChannelDTO {\n\n private Long id;\n /**\n * 创建时间\n */\n private Date createTime;\n /**\n * 修改时间\n */\n private Date updateTime;\n /**\n * 状态 1在线 0离线\n */\n private Integer status;\n /**\n * 通道Id\n */\n private String channelId;\n /**\n * 设备ID\n */\n private String deviceId;\n /**\n * 通道名称\n */\n private String name;\n /**\n * 扩展字段\n */\n private String extend;\n\n\n private ExtendInfo extendInfo;\n\n public static DeviceChannelDTO convertDTO(DeviceChannelDO deviceChannelDO) {\n if (deviceChannelDO == null) {\n return null;\n }\n DeviceChannelDTO dto = new DeviceChannelDTO();\n dto.setId(deviceChannelDO.getId());\n dto.setCreateTime(deviceChannelDO.getCreateTime());\n dto.setUpdateTime(deviceChannelDO.getUpdateTime());\n dto.setStatus(deviceChannelDO.getStatus());\n dto.setChannelId(deviceChannelDO.getChannelId());\n dto.setDeviceId(deviceChannelDO.getDeviceId());\n dto.setName(deviceChannelDO.getName());\n dto.setExtend(deviceChannelDO.getExtend());\n dto.setExtendInfo(getExtendObj(deviceChannelDO.getExtend()));\n return dto;\n }\n\n public static DeviceChannelDO convertDO(DeviceChannelDTO dto) {\n if (dto == null) {\n return null;\n }\n DeviceChannelDO deviceChannelDO = new DeviceChannelDO();\n deviceChannelDO.setId(dto.getId());\n deviceChannelDO.setCreateTime(dto.getCreateTime());\n deviceChannelDO.setUpdateTime(dto.getUpdateTime());\n deviceChannelDO.setStatus(dto.getStatus());\n deviceChannelDO.setChannelId(dto.getChannelId());\n deviceChannelDO.setDeviceId(dto.getDeviceId());\n deviceChannelDO.setName(dto.getName());\n deviceChannelDO.setExtend(JSON.toJSONString(dto.getExtendInfo()));\n return deviceChannelDO;\n }\n\n public static DeviceChannelDTO req2dto(DeviceChannelReq req) {\n if (req == null) {\n return null;\n }\n DeviceChannelDTO dto = new DeviceChannelDTO();\n dto.setStatus(DeviceConstant.Status.ONLINE);\n dto.setDeviceId(req.getDeviceId());\n dto.setName(req.getChannelName());\n dto.setChannelId(req.getChannelId());\n ExtendInfo extendInfo = new ExtendInfo();\n extendInfo.setChannelInfo(req.getChannelInfo());\n dto.setExtendInfo(extendInfo);\n\n return dto;\n }\n\n private static ExtendInfo getExtendObj(String extentInfo) {\n if (StringUtils.isBlank(extentInfo)) {\n return new ExtendInfo();\n }\n String extend = Optional.of(extentInfo).orElse(StringUtils.EMPTY);\n return Optional.ofNullable(JSON.parseObject(extend, ExtendInfo.class)).orElse(new ExtendInfo());\n }\n\n @Data\n public static class ExtendInfo {\n /**\n * 设备通道信息\n */\n private String channelInfo;\n }\n}" }, { "identifier": "DeviceDTO", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/domaon/dto/DeviceDTO.java", "snippet": "@SuppressWarnings(\"serial\")\n@Data\npublic class DeviceDTO implements Serializable {\n\n @TableField(exist = false)\n private static final long serialVersionUID = 1L;\n private Long id;\n private Date createTime;\n private Date updateTime;\n //设备ID\n private String deviceId;\n //状态 1在线 0离线\n private Integer status;\n //自定义名称\n private String name;\n //IP\n private String ip;\n //端口\n private Integer port;\n //注册时间\n private Date registerTime;\n //心跳时间\n private Date keepaliveTime;\n //注册节点\n private String serverIp;\n /**\n * 协议类型 {@link DeviceAgreementEnum}\n */\n private Integer type;\n //扩展字段\n private String extend;\n\n private ExtendInfo extendInfo;\n\n public static DeviceDTO req2dto(DeviceReq deviceReq) {\n DeviceDTO dto = new DeviceDTO();\n\n dto.setDeviceId(deviceReq.getDeviceId());\n dto.setStatus(DeviceConstant.Status.ONLINE);\n dto.setIp(deviceReq.getRemoteIp());\n dto.setPort(deviceReq.getRemotePort());\n dto.setRegisterTime(deviceReq.getRegisterTime());\n dto.setKeepaliveTime(new Date());\n dto.setServerIp(deviceReq.getLocalIp());\n dto.setType(deviceReq.getType());\n ExtendInfo extendInfo = new ExtendInfo();\n extendInfo.setTransport(deviceReq.getTransport());\n extendInfo.setExpires(deviceReq.getExpire());\n dto.setExtendInfo(extendInfo);\n return dto;\n }\n\n public static DeviceDO convertDO(DeviceDTO dto) {\n if (dto == null) {\n return null;\n }\n DeviceDO deviceDO = new DeviceDO();\n deviceDO.setId(dto.getId());\n deviceDO.setCreateTime(dto.getCreateTime());\n deviceDO.setUpdateTime(dto.getUpdateTime());\n deviceDO.setDeviceId(dto.getDeviceId());\n deviceDO.setStatus(dto.getStatus());\n deviceDO.setName(dto.getName());\n deviceDO.setIp(dto.getIp());\n deviceDO.setPort(dto.getPort());\n deviceDO.setRegisterTime(dto.getRegisterTime());\n deviceDO.setKeepaliveTime(dto.getKeepaliveTime());\n deviceDO.setServerIp(dto.getServerIp());\n deviceDO.setType(dto.getType());\n deviceDO.setExtend(JSON.toJSONString(dto.getExtendInfo()));\n return deviceDO;\n }\n\n public static DeviceDTO convertDTO(DeviceDO deviceDO) {\n if (deviceDO == null) {\n return null;\n }\n DeviceDTO deviceDTO = new DeviceDTO();\n deviceDTO.setId(deviceDO.getId());\n deviceDTO.setCreateTime(deviceDO.getCreateTime());\n deviceDTO.setUpdateTime(deviceDO.getUpdateTime());\n deviceDTO.setDeviceId(deviceDO.getDeviceId());\n deviceDTO.setStatus(deviceDO.getStatus());\n deviceDTO.setName(deviceDO.getName());\n deviceDTO.setIp(deviceDO.getIp());\n deviceDTO.setPort(deviceDO.getPort());\n deviceDTO.setRegisterTime(deviceDO.getRegisterTime());\n deviceDTO.setKeepaliveTime(deviceDO.getKeepaliveTime());\n deviceDTO.setServerIp(deviceDO.getServerIp());\n deviceDTO.setType(deviceDTO.getType());\n deviceDTO.setExtend(deviceDO.getExtend());\n\n ExtendInfo extendObj = getExtendObj(deviceDO.getExtend());\n if (extendObj.getCharset() == null) {\n extendObj.setCharset(CharsetUtil.UTF_8);\n }\n if (extendObj.getStreamMode() == null) {\n extendObj.setStreamMode(StreamModeEnum.UDP.getType());\n }\n deviceDTO.setExtendInfo(extendObj);\n return deviceDTO;\n }\n\n private static ExtendInfo getExtendObj(String extentInfo) {\n if (StringUtils.isBlank(extentInfo)) {\n return new ExtendInfo();\n }\n String extend = Optional.of(extentInfo).orElse(StringUtils.EMPTY);\n return Optional.ofNullable(JSON.parseObject(extend, ExtendInfo.class)).orElse(new ExtendInfo());\n }\n\n @Data\n public static class ExtendInfo {\n\n /**\n * 设备序列号\n */\n private String serialNumber;\n\n /**\n * 传输协议\n * UDP/TCP\n */\n private String transport;\n\n /**\n * 注册有效期\n */\n private int expires;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 数据流传输模式\n * UDP:udp传输\n * TCP-ACTIVE:tcp主动模式\n * TCP-PASSIVE:tcp被动模式\n */\n private String streamMode;\n\n /**\n * 编码\n */\n private String charset;\n\n /**\n * 设备信息\n */\n private String deviceInfo;\n\n }\n\n}" }, { "identifier": "DeviceChannelManager", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/manager/DeviceChannelManager.java", "snippet": "@Component\npublic class DeviceChannelManager {\n\n @Autowired\n private DeviceChannelService deviceChannelService;\n\n @Autowired\n private DeviceManager deviceManager;\n\n public Long saveOrUpdate(DeviceChannelDTO dto) {\n Assert.notNull(dto, \"dto can not be null\");\n Assert.notNull(dto.getDeviceId(), \"deviceId can not be null\");\n\n DeviceDTO dtoByDeviceId = deviceManager.getDtoByDeviceId(dto.getDeviceId());\n if (dtoByDeviceId == null) {\n return null;\n }\n\n DeviceChannelDO deviceChannelDO = DeviceChannelDTO.convertDO(dto);\n DeviceChannelDO byDeviceId = getByDeviceId(dto.getDeviceId(), dto.getChannelId());\n if (byDeviceId != null) {\n deviceChannelDO.setId(byDeviceId.getId());\n deviceChannelService.updateById(deviceChannelDO);\n return byDeviceId.getId();\n }\n deviceChannelService.save(deviceChannelDO);\n return deviceChannelDO.getId();\n }\n\n public void method() {\n\n }\n\n public void updateStatus(String deviceId, String channelId, int status) {\n DeviceChannelDO DeviceChannelDO = getByDeviceId(deviceId, channelId);\n if (DeviceChannelDO == null) {\n return;\n }\n DeviceChannelDO.setStatus(status);\n deviceChannelService.updateById(DeviceChannelDO);\n }\n\n public DeviceChannelDO getByDeviceId(String deviceId, String channelId) {\n Assert.notNull(deviceId, \"userId can not be null\");\n QueryWrapper<DeviceChannelDO> queryWrapper = new QueryWrapper<DeviceChannelDO>().eq(\"device_id\", deviceId)\n .eq(\"channel_id\", channelId).last(\"limit 1\");\n return deviceChannelService.getOne(queryWrapper);\n }\n\n public DeviceChannelDTO getDtoByDeviceId(String deviceId, String channelId) {\n DeviceChannelDO byDeviceId = getByDeviceId(deviceId, channelId);\n return DeviceChannelDTO.convertDTO(byDeviceId);\n }\n}" }, { "identifier": "DeviceManager", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/manager/DeviceManager.java", "snippet": "@Component\npublic class DeviceManager {\n\n @Autowired\n private DeviceService deviceService;\n\n public Long saveOrUpdate(DeviceDTO dto) {\n Assert.notNull(dto, \"dto can not be null\");\n Assert.notNull(dto.getDeviceId(), \"deviceId can not be null\");\n DeviceDO deviceDO = DeviceDTO.convertDO(dto);\n\n DeviceDO byDeviceId = getByDeviceId(dto.getDeviceId());\n if (byDeviceId != null) {\n deviceDO.setId(byDeviceId.getId());\n deviceService.updateById(deviceDO);\n return byDeviceId.getId();\n }\n deviceService.save(deviceDO);\n return deviceDO.getId();\n }\n\n public void updateStatus(String deviceId, int status) {\n DeviceDO deviceDO = getByDeviceId(deviceId);\n if (deviceDO == null) {\n return;\n }\n deviceDO.setStatus(status);\n deviceService.updateById(deviceDO);\n }\n\n public DeviceDO getByDeviceId(String deviceId) {\n Assert.notNull(deviceId, \"userId can not be null\");\n QueryWrapper<DeviceDO> queryWrapper = new QueryWrapper<DeviceDO>().eq(\"device_id\", deviceId).last(\"limit 1\");\n return deviceService.getOne(queryWrapper);\n }\n\n public DeviceDTO getDtoByDeviceId(String deviceId) {\n DeviceDO byDeviceId = getByDeviceId(deviceId);\n return DeviceDTO.convertDTO(byDeviceId);\n }\n}" }, { "identifier": "DeviceAgreementService", "path": "voglander-service/src/main/java/io/github/lunasaw/voglander/service/command/DeviceAgreementService.java", "snippet": "@Service\npublic class DeviceAgreementService {\n\n public DeviceCommandService getCommandService(Integer type) {\n Assert.notNull(type, \"协议类型不能为空\");\n\n\n DeviceCommandService deviceCommandService = null;\n if (type.equals(DeviceAgreementEnum.GB28181.getType())) {\n deviceCommandService = SpringBeanFactory.getBean(DeviceConstant.DeviceCommandService.DEVICE_AGREEMENT_SERVICE_NAME_GB28181);\n }\n Assert.notNull(deviceCommandService, \"该协议没有对应的实现方法\");\n\n return deviceCommandService;\n }\n\n}" } ]
import io.github.lunasaw.voglander.client.domain.qo.DeviceChannelReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceInfoReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceQueryReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceReq; import io.github.lunasaw.voglander.client.service.DeviceCommandService; import io.github.lunasaw.voglander.client.service.DeviceRegisterService; import io.github.lunasaw.voglander.common.constant.DeviceConstant; import io.github.lunasaw.voglander.manager.domaon.dto.DeviceChannelDTO; import io.github.lunasaw.voglander.manager.domaon.dto.DeviceDTO; import io.github.lunasaw.voglander.manager.manager.DeviceChannelManager; import io.github.lunasaw.voglander.manager.manager.DeviceManager; import io.github.lunasaw.voglander.service.command.DeviceAgreementService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.util.Date;
4,887
package io.github.lunasaw.voglander.service.login; /** * @author luna * @date 2023/12/29 */ @Slf4j @Service public class DeviceRegisterServiceImpl implements DeviceRegisterService { @Autowired private DeviceManager deviceManager; @Autowired private DeviceChannelManager deviceChannelManager; @Autowired private DeviceAgreementService deviceAgreementService; @Override public void login(DeviceReq deviceReq) { DeviceDTO dto = DeviceDTO.req2dto(deviceReq); Long deviceId = deviceManager.saveOrUpdate(dto); log.info("login::deviceReq = {}, deviceId = {}", deviceReq, deviceId); DeviceCommandService deviceCommandService = deviceAgreementService.getCommandService(dto.getType()); DeviceQueryReq deviceQueryReq = new DeviceQueryReq(); deviceQueryReq.setDeviceId(dto.getDeviceId()); // 查下设备信息 deviceCommandService.queryDevice(deviceQueryReq); // 通道查查询 deviceCommandService.queryChannel(deviceQueryReq); } @Override
package io.github.lunasaw.voglander.service.login; /** * @author luna * @date 2023/12/29 */ @Slf4j @Service public class DeviceRegisterServiceImpl implements DeviceRegisterService { @Autowired private DeviceManager deviceManager; @Autowired private DeviceChannelManager deviceChannelManager; @Autowired private DeviceAgreementService deviceAgreementService; @Override public void login(DeviceReq deviceReq) { DeviceDTO dto = DeviceDTO.req2dto(deviceReq); Long deviceId = deviceManager.saveOrUpdate(dto); log.info("login::deviceReq = {}, deviceId = {}", deviceReq, deviceId); DeviceCommandService deviceCommandService = deviceAgreementService.getCommandService(dto.getType()); DeviceQueryReq deviceQueryReq = new DeviceQueryReq(); deviceQueryReq.setDeviceId(dto.getDeviceId()); // 查下设备信息 deviceCommandService.queryDevice(deviceQueryReq); // 通道查查询 deviceCommandService.queryChannel(deviceQueryReq); } @Override
public void addChannel(DeviceChannelReq req) {
0
2023-12-27 07:28:18+00:00
8k
GrailStack/grail-codegen
src/main/java/com/itgrail/grail/codegen/custom/grailframework/GrailFrameWorkTemplate.java
[ { "identifier": "GrailFrameworkGenRequest", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/dto/GrailFrameworkGenRequest.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkGenRequest extends TemplateGenRequest {\n\n private String javaVersion;\n private String grailFrameworkVersion;\n\n private String groupId;\n private String artifactId;\n private String description;\n\n private String basePackage;\n\n private List<SubModuleDTO> subModules;\n\n private DbModelDTO dbModel;\n\n private DomainDTO domain;\n\n /**\n * 是否需要连接数据库,不需要连接数据库,就不添加Grail MyBatis\n */\n private Boolean dbConfigure;\n\n /**\n * 模块依赖\n */\n private List<ModuleDependencyModel> moduleDependencyModels;\n\n}" }, { "identifier": "DbDataModel", "path": "src/main/java/com/itgrail/grail/codegen/components/db/DbDataModel.java", "snippet": "@Data\npublic class DbDataModel {\n\n private List<Table> tables;\n\n private String dbName;\n private String dbUrl;\n private String dbUserName;\n private String dbPassword;\n private String dbDriver;\n\n //用于迭代\n private Table table;\n\n}" }, { "identifier": "DBProperties", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DBProperties.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DBProperties {\n\n private String dbType;\n private String dbUrl;\n private String dbUserName;\n private String dbPassword;\n\n}" }, { "identifier": "Database", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/Database.java", "snippet": "public interface Database extends Closeable {\n\n String getDbUrl();\n\n String getDbName();\n\n String getDbUserName();\n\n String getDbPassword();\n\n String getDriverClassName();\n\n Connection getConnection();\n\n DbTypeEnum getDbType();\n\n /**\n * 获取表名称列表\n *\n * @param tableNamePattern 获取表名时使用的表达式\n * @return 表名列表\n */\n List<String> getTableNames(String tableNamePattern);\n\n /**\n * 获取数据库所有表名称\n *\n * @return 所有表名称\n */\n List<String> getAllTableNames();\n\n /**\n * 查询表所有列\n *\n * @param tableName 表名\n * @return 所有列\n */\n List<Column> getColumns(String tableName);\n\n /**\n * 查询表主键列\n *\n * @param tableName 表名\n * @return 主键列\n */\n List<PrimaryKeyColumn> getPrimaryColumns(String tableName);\n\n\n /**\n * 查询数据库中所有表\n *\n * @return 数据表列表\n */\n List<Table> getAllTables();\n\n /**\n * 查询表\n *\n * @param tableNamePattern 表名称表达式过滤,如:sys_%,则仅仅查询出【sys_】开头的所有表\n * @return 数据表列表\n */\n List<Table> getTables(String tableNamePattern);\n\n /**\n * 查询表\n *\n * @param tableNames 表名称列表\n * @return 数据表列表\n */\n List<Table> getTables(List<String> tableNames);\n\n /**\n * 查询表\n *\n * @param tableName 表名\n * @return 表对象实例\n */\n Table getTable(String tableName);\n\n\n /**\n * 是否为主键列\n *\n * @param tableName 表名\n * @param columnName 列名\n * @return 是否为主键,true:主键,false:非主键\n */\n boolean isPrimaryKey(String tableName, String columnName);\n\n /**\n * 获取表备注信息\n *\n * @param tableName 表名\n * @return 表备注信息\n */\n String getTableComment(String tableName);\n\n}" }, { "identifier": "DatabaseFactory", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DatabaseFactory.java", "snippet": "@Slf4j\npublic class DatabaseFactory {\n\n private DatabaseFactory() {\n }\n\n public static Database create(DBProperties dbProperties) throws DbException {\n DbTypeEnum dbTypeEnum = DbTypeEnum.get(dbProperties.getDbType());\n if (dbTypeEnum == null) {\n throw new DbException(String.format(\"暂不支持该数据库类型, dbType=%s\", dbProperties.getDbType()));\n }\n try {\n Constructor<? extends Database> constructor = dbTypeEnum.getDataBaseImplClass().getConstructor(DBProperties.class);\n return constructor.newInstance(dbProperties);\n } catch (InvocationTargetException ex) {\n log.error(\"创建database对象失败\", ex);\n throw new DbException(ex.getCause().getMessage());\n } catch (Exception ex) {\n log.error(\"创建database对象失败\", ex);\n throw new DbException(ex.getMessage());\n }\n }\n\n}" }, { "identifier": "DbMetaData", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DbMetaData.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DbMetaData {\n private String dbType;\n}" }, { "identifier": "Table", "path": "src/main/java/com/itgrail/grail/codegen/components/db/model/Table.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class Table {\n\n private String tableName;\n\n /**\n * 数据对象名称\n */\n private String doName;\n\n /**\n * 数据访问对象名称\n */\n private String daoName;\n\n /**\n * 表备注信息\n */\n private String comment;\n\n /**\n * 数据列列表\n */\n private List<Column> columns;\n\n /**\n * 主键列表\n */\n private List<PrimaryKeyColumn> primaryKeys;\n\n @Override\n public String toString() {\n return JSONObject.toJSONString(this, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat);\n }\n\n}" }, { "identifier": "SubModuleDTO", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/dto/SubModuleDTO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class SubModuleDTO implements Serializable {\n private String subModuleName;\n private String packaging;\n}" }, { "identifier": "GrailFrameworkMetadata", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/metadata/GrailFrameworkMetadata.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkMetadata extends TemplateMetaData {\n\n private List<GrailVersionMetaData> grailVersions;\n private List<ModuleMetaData> subModules;\n private List<String> dependencies;\n private List<DbMetaData> databases;\n private ModuleMetaData parentModule;\n}" }, { "identifier": "GrailVersionMetaData", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/metadata/GrailVersionMetaData.java", "snippet": "@Data\npublic class GrailVersionMetaData {\n private String grailFrameworkVersion;\n private String javaVersion;\n private String springBootVersion;\n private String springCloudVersion;\n}" }, { "identifier": "DomainDataModel", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/model/DomainDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DomainDataModel implements Serializable {\n\n /**\n * 当前应用所属域的唯一code\n */\n private String code;\n\n /**\n * 父域的唯一code\n */\n private String parentCode;\n\n /**\n * 当前域的名称\n */\n private String name;\n\n /**\n * 当前域的描述\n */\n private String desc;\n\n}" }, { "identifier": "GrailFrameworkDataModel", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/model/GrailFrameworkDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkDataModel extends CodeGenDataModel {\n private String grailFrameworkVersion;\n\n private DbDataModel db;\n\n private DomainDataModel domain;\n}" }, { "identifier": "CustomizedTemplate", "path": "src/main/java/com/itgrail/grail/codegen/template/custom/CustomizedTemplate.java", "snippet": "public abstract class CustomizedTemplate {\n\n @Autowired\n private TemplateProcessor templateProcessor;\n\n private static final String TEMPLATE_LOCATE_BASE_PATH = \"templates/\";\n\n public GenResult gen(Map<String, Object> req) throws IllegalArgumentException {\n CodeGenDataModel dataModel = convert(req);\n byte[] fileBytes = templateProcessor.process(dataModel);\n return new GenResult().setFileBytes(fileBytes).setFileName(genFileName(dataModel));\n }\n\n public abstract String getTemplateName();\n\n public abstract List<ModuleMetaData> initSubModules();\n\n public abstract List<String> getSubModules();\n\n public abstract ModuleMetaData getParentModule();\n\n\n public abstract String getTemplateLocatePath();\n\n public String getDefaultGenFileName() {\n return \"init-\" + getTemplateName().toLowerCase();\n }\n\n public boolean hasSubModel(String subModel) {\n String subModelTmp = subModel.replaceFirst(\"-\", \"\");\n return Optional.ofNullable(getSubModules()).orElse(Lists.newArrayList())\n .stream().anyMatch(e -> e.equalsIgnoreCase(subModelTmp));\n }\n\n public String getBasePath() {\n return TEMPLATE_LOCATE_BASE_PATH;\n }\n\n public abstract TemplateMetaData getTemplateMetadata();\n\n public abstract CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException;\n\n public abstract String genFileName(CodeGenDataModel dataModel);\n\n}" }, { "identifier": "ModuleMetaData", "path": "src/main/java/com/itgrail/grail/codegen/template/custom/ModuleMetaData.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class ModuleMetaData implements Serializable {\n private String subModuleName;\n private List<String> packagingTypes;\n private List<DependencyModel> dependencys;\n}" }, { "identifier": "CodeGenDataModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/CodeGenDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class CodeGenDataModel {\n private String templateName;\n private String javaVersion;\n private MavenProjectDataModel project;\n}" }, { "identifier": "MavenModuleDataModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/MavenModuleDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class MavenModuleDataModel {\n private String groupId;\n private String artifactId;\n private String basePackage;\n private String packaging;\n\n /**\n * @see CustomizedTemplate#getSubModules()\n */\n private String moduleName;\n}" }, { "identifier": "MavenProjectDataModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/MavenProjectDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class MavenProjectDataModel {\n private String groupId;\n\n private String artifactId;\n\n private String basePackage;\n\n private String description;\n\n private Boolean dbConfigure=false;\n\n /**\n * key:\n *\n * @see MavenModuleDataModel#getModuleName()\n */\n private Map<String, MavenModuleDataModel> subModules;\n\n\n /**\n * 依赖\n */\n private List<ModuleDependencyModel> dependencies;\n\n /**\n * 用于判断某个 module 中是否包含了特定 dependency, 用于针对不同 dependency 生成对应的代码\n * @param moduleName\n * @param artifactId\n * @return\n */\n public boolean hasDependencyForModule(String moduleName, String artifactId) {\n Optional<ModuleDependencyModel> module = dependencies.stream()\n .filter(mod -> moduleName.equals(mod.getModulekey()))\n .findFirst();\n if (!module.isPresent()) {\n return false;\n }\n return module.get().getDependencyModels().stream().anyMatch(dep -> artifactId.equals(dep.getArtifactId()));\n }\n}" }, { "identifier": "ModuleDependencyModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/ModuleDependencyModel.java", "snippet": "@Data\npublic class ModuleDependencyModel implements Serializable {\n\n /**\n * 模块唯一的key\n */\n private String modulekey;\n\n /**\n * 依赖\n */\n private List<DependencyModel> dependencyModels;\n\n\n}" }, { "identifier": "CommonUtil", "path": "src/main/java/com/itgrail/grail/codegen/utils/CommonUtil.java", "snippet": "public class CommonUtil {\n\n public static void closeClosable(Closeable closeable) {\n try {\n if (closeable != null) {\n closeable.close();\n }\n } catch (Exception ex) {\n }\n }\n\n public static UUID genUUID() {\n ThreadLocalRandom random = ThreadLocalRandom.current();\n return new UUID(random.nextLong(), random.nextLong());\n }\n\n}" }, { "identifier": "PropertiesUtils", "path": "src/main/java/com/itgrail/grail/codegen/utils/PropertiesUtils.java", "snippet": "public class PropertiesUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);\n\n /**\n * 读取json文件,返回json字符串\n * @param fileName\n * @return\n */\n public static String readJsonFile(String fileName) {\n ClassPathResource classPathResource = new ClassPathResource(fileName);\n try {\n InputStream inputStream =classPathResource.getInputStream();\n return inputStreamToString(inputStream);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n private static String inputStreamToString(InputStream inputStream) {\n StringBuffer buffer = new StringBuffer();\n InputStreamReader inputStreamReader;\n try {\n inputStreamReader = new InputStreamReader(inputStream, \"utf-8\");\n BufferedReader bufferedReader = new BufferedReader(inputStreamReader);\n String str = null;\n while ((str = bufferedReader.readLine()) != null) {\n buffer.append(str);\n }\n // 释放资源\n bufferedReader.close();\n inputStreamReader.close();\n inputStream.close();\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return buffer.toString();\n }\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.itgrail.grail.codegen.custom.grailframework.dto.GrailFrameworkGenRequest; import com.itgrail.grail.codegen.components.db.DbDataModel; import com.itgrail.grail.codegen.components.db.database.DBProperties; import com.itgrail.grail.codegen.components.db.database.Database; import com.itgrail.grail.codegen.components.db.database.DatabaseFactory; import com.itgrail.grail.codegen.components.db.database.DbMetaData; import com.itgrail.grail.codegen.components.db.model.Table; import com.itgrail.grail.codegen.custom.grailframework.dto.SubModuleDTO; import com.itgrail.grail.codegen.custom.grailframework.metadata.GrailFrameworkMetadata; import com.itgrail.grail.codegen.custom.grailframework.metadata.GrailVersionMetaData; import com.itgrail.grail.codegen.custom.grailframework.model.DomainDataModel; import com.itgrail.grail.codegen.custom.grailframework.model.GrailFrameworkDataModel; import com.itgrail.grail.codegen.template.custom.CustomizedTemplate; import com.itgrail.grail.codegen.template.custom.ModuleMetaData; import com.itgrail.grail.codegen.template.datamodel.CodeGenDataModel; import com.itgrail.grail.codegen.template.datamodel.MavenModuleDataModel; import com.itgrail.grail.codegen.template.datamodel.MavenProjectDataModel; import com.itgrail.grail.codegen.template.datamodel.ModuleDependencyModel; import com.itgrail.grail.codegen.utils.CommonUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.itgrail.grail.codegen.utils.PropertiesUtils; import java.util.List; import java.util.Map;
5,359
} subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); subModules.add(moduleMetaData4); subModules.add(moduleMetaData5); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("app","client","domain","start","infrastructure"); } @Override public ModuleMetaData getParentModule() { ModuleMetaData moduleMetaData = new ModuleMetaData(); String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("parent".equals(mo.getModulekey())){ moduleMetaData.setDependencys(mo.getDependencyModels()); moduleMetaData.setPackagingTypes(Lists.newArrayList("pom")); } } } return moduleMetaData; } @Override public String getTemplateLocatePath() { return getBasePath() + getTemplateName().toLowerCase(); } @Override public GrailFrameworkMetadata getTemplateMetadata() { GrailFrameworkMetadata metadata = new GrailFrameworkMetadata(); metadata.setTemplateName(getTemplateName()); metadata.setGrailVersions(getGrailVersionMetaDataList()); metadata.setSubModules(initSubModules()); metadata.setParentModule(getParentModule()); metadata.setDatabases(getDbMetaDataList()); return metadata; } protected List<DbMetaData> getDbMetaDataList() { DbMetaData dbMetaData = new DbMetaData(); dbMetaData.setDbType("MySql"); return Lists.newArrayList(dbMetaData); } protected List<GrailVersionMetaData> getGrailVersionMetaDataList() { GrailVersionMetaData grailVersionMetaData = new GrailVersionMetaData(); grailVersionMetaData.setGrailFrameworkVersion("1.0.0.RELEASE"); grailVersionMetaData.setJavaVersion("1.8"); grailVersionMetaData.setSpringBootVersion("2.4.1"); grailVersionMetaData.setSpringCloudVersion("2020.0.0"); GrailVersionMetaData grailVersionMetaData2 = new GrailVersionMetaData(); grailVersionMetaData2.setGrailFrameworkVersion("1.0.0-SNAPSHOT"); grailVersionMetaData2.setJavaVersion("1.8"); grailVersionMetaData2.setSpringBootVersion("2.4.1"); grailVersionMetaData2.setSpringCloudVersion("2020.0.0"); return Lists.newArrayList(grailVersionMetaData, grailVersionMetaData2); } @Override public CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException { GrailFrameworkGenRequest genRequest = check(request); GrailFrameworkDataModel dataModel = new GrailFrameworkDataModel(); dataModel.setTemplateName(genRequest.getTemplateName()); dataModel.setGrailFrameworkVersion(genRequest.getGrailFrameworkVersion()); dataModel.setJavaVersion("1.8"); MavenProjectDataModel project = new MavenProjectDataModel(); dataModel.setProject(project); project.setGroupId(genRequest.getGroupId()); project.setArtifactId(genRequest.getArtifactId()); project.setDescription(genRequest.getDescription()); project.setBasePackage(genRequest.getBasePackage()); if(null!=genRequest.getDbModel()){ project.setDbConfigure(true); } //处理依赖 List<ModuleDependencyModel> moduleDependencyModels=genRequest.getModuleDependencyModels(); if(null==moduleDependencyModels||moduleDependencyModels.isEmpty()){ String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)) { List<ModuleDependencyModel> list = JSON.parseArray(json, ModuleDependencyModel.class); project.setDependencies(list); } }else{ project.setDependencies(moduleDependencyModels); } project.setSubModules(Maps.newHashMap()); for (SubModuleDTO subModuleDTO : genRequest.getSubModules()) { String subModuleName = subModuleDTO.getSubModuleName(); MavenModuleDataModel subModule = new MavenModuleDataModel(); subModule.setModuleName(subModuleName); subModule.setArtifactId(genRequest.getArtifactId() + "-" + subModuleName); subModule.setGroupId(genRequest.getGroupId()); subModule.setBasePackage(genRequest.getBasePackage() + "." + subModuleName); subModule.setPackaging(subModuleDTO.getPackaging()); project.getSubModules().put(subModuleName, subModule); } if (genRequest.getDomain() != null) { DomainDataModel domainDataModel = new DomainDataModel(); domainDataModel.setCode(genRequest.getDomain().getCode()); domainDataModel.setParentCode(genRequest.getDomain().getParentCode()); domainDataModel.setName(genRequest.getDomain().getName()); domainDataModel.setDesc(genRequest.getDomain().getDesc()); dataModel.setDomain(domainDataModel); } if (genRequest.getDbModel() != null) {
package com.itgrail.grail.codegen.custom.grailframework; /** * @author xujin * created at 2019/5/24 20:50 **/ @Component public class GrailFrameWorkTemplate extends CustomizedTemplate { @Override public String getTemplateName() { return "GrailFramework"; } @Override public List<ModuleMetaData> initSubModules() { List<ModuleMetaData> subModules = Lists.newArrayList(); ModuleMetaData moduleMetaData1=new ModuleMetaData().setSubModuleName("infrastructure").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData2=new ModuleMetaData().setSubModuleName("domain").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData3=new ModuleMetaData().setSubModuleName("client").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData4=new ModuleMetaData().setSubModuleName("app").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData5=new ModuleMetaData().setSubModuleName("start").setPackagingTypes(Lists.newArrayList("jar", "war")); String json= PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("infrastructure".equals(mo.getModulekey())){ moduleMetaData1.setDependencys(mo.getDependencyModels()); } if("domain".equals(mo.getModulekey())){ moduleMetaData2.setDependencys(mo.getDependencyModels()); } if("client".equals(mo.getModulekey())){ moduleMetaData3.setDependencys(mo.getDependencyModels()); } if("app".equals(mo.getModulekey())){ moduleMetaData4.setDependencys(mo.getDependencyModels()); } if("start".equals(mo.getModulekey())){ moduleMetaData5.setDependencys(mo.getDependencyModels()); } } } subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); subModules.add(moduleMetaData4); subModules.add(moduleMetaData5); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("app","client","domain","start","infrastructure"); } @Override public ModuleMetaData getParentModule() { ModuleMetaData moduleMetaData = new ModuleMetaData(); String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("parent".equals(mo.getModulekey())){ moduleMetaData.setDependencys(mo.getDependencyModels()); moduleMetaData.setPackagingTypes(Lists.newArrayList("pom")); } } } return moduleMetaData; } @Override public String getTemplateLocatePath() { return getBasePath() + getTemplateName().toLowerCase(); } @Override public GrailFrameworkMetadata getTemplateMetadata() { GrailFrameworkMetadata metadata = new GrailFrameworkMetadata(); metadata.setTemplateName(getTemplateName()); metadata.setGrailVersions(getGrailVersionMetaDataList()); metadata.setSubModules(initSubModules()); metadata.setParentModule(getParentModule()); metadata.setDatabases(getDbMetaDataList()); return metadata; } protected List<DbMetaData> getDbMetaDataList() { DbMetaData dbMetaData = new DbMetaData(); dbMetaData.setDbType("MySql"); return Lists.newArrayList(dbMetaData); } protected List<GrailVersionMetaData> getGrailVersionMetaDataList() { GrailVersionMetaData grailVersionMetaData = new GrailVersionMetaData(); grailVersionMetaData.setGrailFrameworkVersion("1.0.0.RELEASE"); grailVersionMetaData.setJavaVersion("1.8"); grailVersionMetaData.setSpringBootVersion("2.4.1"); grailVersionMetaData.setSpringCloudVersion("2020.0.0"); GrailVersionMetaData grailVersionMetaData2 = new GrailVersionMetaData(); grailVersionMetaData2.setGrailFrameworkVersion("1.0.0-SNAPSHOT"); grailVersionMetaData2.setJavaVersion("1.8"); grailVersionMetaData2.setSpringBootVersion("2.4.1"); grailVersionMetaData2.setSpringCloudVersion("2020.0.0"); return Lists.newArrayList(grailVersionMetaData, grailVersionMetaData2); } @Override public CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException { GrailFrameworkGenRequest genRequest = check(request); GrailFrameworkDataModel dataModel = new GrailFrameworkDataModel(); dataModel.setTemplateName(genRequest.getTemplateName()); dataModel.setGrailFrameworkVersion(genRequest.getGrailFrameworkVersion()); dataModel.setJavaVersion("1.8"); MavenProjectDataModel project = new MavenProjectDataModel(); dataModel.setProject(project); project.setGroupId(genRequest.getGroupId()); project.setArtifactId(genRequest.getArtifactId()); project.setDescription(genRequest.getDescription()); project.setBasePackage(genRequest.getBasePackage()); if(null!=genRequest.getDbModel()){ project.setDbConfigure(true); } //处理依赖 List<ModuleDependencyModel> moduleDependencyModels=genRequest.getModuleDependencyModels(); if(null==moduleDependencyModels||moduleDependencyModels.isEmpty()){ String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)) { List<ModuleDependencyModel> list = JSON.parseArray(json, ModuleDependencyModel.class); project.setDependencies(list); } }else{ project.setDependencies(moduleDependencyModels); } project.setSubModules(Maps.newHashMap()); for (SubModuleDTO subModuleDTO : genRequest.getSubModules()) { String subModuleName = subModuleDTO.getSubModuleName(); MavenModuleDataModel subModule = new MavenModuleDataModel(); subModule.setModuleName(subModuleName); subModule.setArtifactId(genRequest.getArtifactId() + "-" + subModuleName); subModule.setGroupId(genRequest.getGroupId()); subModule.setBasePackage(genRequest.getBasePackage() + "." + subModuleName); subModule.setPackaging(subModuleDTO.getPackaging()); project.getSubModules().put(subModuleName, subModule); } if (genRequest.getDomain() != null) { DomainDataModel domainDataModel = new DomainDataModel(); domainDataModel.setCode(genRequest.getDomain().getCode()); domainDataModel.setParentCode(genRequest.getDomain().getParentCode()); domainDataModel.setName(genRequest.getDomain().getName()); domainDataModel.setDesc(genRequest.getDomain().getDesc()); dataModel.setDomain(domainDataModel); } if (genRequest.getDbModel() != null) {
DbDataModel dbDataModel = new DbDataModel();
1
2023-12-30 15:32:55+00:00
8k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/category/StackedAreaRendererTest.java
[ { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "Range", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/Range.java", "snippet": "public strictfp class Range implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -906333695431863380L;\r\n\r\n /** The lower bound of the range. */\r\n private double lower;\r\n\r\n /** The upper bound of the range. */\r\n private double upper;\r\n\r\n /**\r\n * Creates a new range.\r\n *\r\n * @param lower the lower bound (must be &lt;= upper bound).\r\n * @param upper the upper bound (must be &gt;= lower bound).\r\n */\r\n public Range(double lower, double upper) {\r\n if (lower > upper) {\r\n String msg = \"Range(double, double): require lower (\" + lower\r\n + \") <= upper (\" + upper + \").\";\r\n throw new IllegalArgumentException(msg);\r\n }\r\n this.lower = lower;\r\n this.upper = upper;\r\n }\r\n\r\n /**\r\n * Returns the lower bound for the range.\r\n *\r\n * @return The lower bound.\r\n */\r\n public double getLowerBound() {\r\n return this.lower;\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the range.\r\n *\r\n * @return The upper bound.\r\n */\r\n public double getUpperBound() {\r\n return this.upper;\r\n }\r\n\r\n /**\r\n * Returns the length of the range.\r\n *\r\n * @return The length.\r\n */\r\n public double getLength() {\r\n return this.upper - this.lower;\r\n }\r\n\r\n /**\r\n * Returns the central value for the range.\r\n *\r\n * @return The central value.\r\n */\r\n public double getCentralValue() {\r\n return this.lower / 2.0 + this.upper / 2.0;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range contains the specified value and\r\n * <code>false</code> otherwise.\r\n *\r\n * @param value the value to lookup.\r\n *\r\n * @return <code>true</code> if the range contains the specified value.\r\n */\r\n public boolean contains(double value) {\r\n return (value >= this.lower && value <= this.upper);\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param b0 the lower bound (should be &lt;= b1).\r\n * @param b1 the upper bound (should be &gt;= b0).\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean intersects(double b0, double b1) {\r\n if (b0 <= this.lower) {\r\n return (b1 > this.lower);\r\n }\r\n else {\r\n return (b0 < this.upper && b1 >= b0);\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param range another range (<code>null</code> not permitted).\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.9\r\n */\r\n public boolean intersects(Range range) {\r\n return intersects(range.getLowerBound(), range.getUpperBound());\r\n }\r\n\r\n /**\r\n * Returns the value within the range that is closest to the specified\r\n * value.\r\n *\r\n * @param value the value.\r\n *\r\n * @return The constrained value.\r\n */\r\n public double constrain(double value) {\r\n double result = value;\r\n if (!contains(value)) {\r\n if (value > this.upper) {\r\n result = this.upper;\r\n }\r\n else if (value < this.lower) {\r\n result = this.lower;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a new range by combining two existing ranges.\r\n * <P>\r\n * Note that:\r\n * <ul>\r\n * <li>either range can be <code>null</code>, in which case the other\r\n * range is returned;</li>\r\n * <li>if both ranges are <code>null</code> the return value is\r\n * <code>null</code>.</li>\r\n * </ul>\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n */\r\n public static Range combine(Range range1, Range range2) {\r\n if (range1 == null) {\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n return range1;\r\n }\r\n double l = Math.min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = Math.max(range1.getUpperBound(), range2.getUpperBound());\r\n return new Range(l, u);\r\n }\r\n\r\n /**\r\n * Returns a new range that spans both <code>range1</code> and \r\n * <code>range2</code>. This method has a special handling to ignore\r\n * Double.NaN values.\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.15\r\n */\r\n public static Range combineIgnoringNaN(Range range1, Range range2) {\r\n if (range1 == null) {\r\n if (range2 != null && range2.isNaNRange()) {\r\n return null;\r\n }\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n if (range1.isNaNRange()) {\r\n return null;\r\n }\r\n return range1;\r\n }\r\n double l = min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = max(range1.getUpperBound(), range2.getUpperBound());\r\n if (Double.isNaN(l) && Double.isNaN(u)) {\r\n return null;\r\n }\r\n return new Range(l, u);\r\n }\r\n \r\n /**\r\n * Returns the minimum value. If either value is NaN, the other value is \r\n * returned. If both are NaN, NaN is returned.\r\n * \r\n * @param d1 value 1.\r\n * @param d2 value 2.\r\n * \r\n * @return The minimum of the two values. \r\n */\r\n private static double min(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.min(d1, d2);\r\n }\r\n\r\n private static double max(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.max(d1, d2);\r\n }\r\n\r\n /**\r\n * Returns a range that includes all the values in the specified\r\n * <code>range</code> AND the specified <code>value</code>.\r\n *\r\n * @param range the range (<code>null</code> permitted).\r\n * @param value the value that must be included.\r\n *\r\n * @return A range.\r\n *\r\n * @since 1.0.1\r\n */\r\n public static Range expandToInclude(Range range, double value) {\r\n if (range == null) {\r\n return new Range(value, value);\r\n }\r\n if (value < range.getLowerBound()) {\r\n return new Range(value, range.getUpperBound());\r\n }\r\n else if (value > range.getUpperBound()) {\r\n return new Range(range.getLowerBound(), value);\r\n }\r\n else {\r\n return range;\r\n }\r\n }\r\n\r\n /**\r\n * Creates a new range by adding margins to an existing range.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param lowerMargin the lower margin (expressed as a percentage of the\r\n * range length).\r\n * @param upperMargin the upper margin (expressed as a percentage of the\r\n * range length).\r\n *\r\n * @return The expanded range.\r\n */\r\n public static Range expand(Range range,\r\n double lowerMargin, double upperMargin) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n double length = range.getLength();\r\n double lower = range.getLowerBound() - length * lowerMargin;\r\n double upper = range.getUpperBound() + length * upperMargin;\r\n if (lower > upper) {\r\n lower = lower / 2.0 + upper / 2.0;\r\n upper = lower;\r\n }\r\n return new Range(lower, upper);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta) {\r\n return shift(base, delta, false);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n * @param allowZeroCrossing a flag that determines whether or not the\r\n * bounds of the range are allowed to cross\r\n * zero after adjustment.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta,\r\n boolean allowZeroCrossing) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (allowZeroCrossing) {\r\n return new Range(base.getLowerBound() + delta,\r\n base.getUpperBound() + delta);\r\n }\r\n else {\r\n return new Range(shiftWithNoZeroCrossing(base.getLowerBound(),\r\n delta), shiftWithNoZeroCrossing(base.getUpperBound(),\r\n delta));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the given <code>value</code> adjusted by <code>delta</code> but\r\n * with a check to prevent the result from crossing <code>0.0</code>.\r\n *\r\n * @param value the value.\r\n * @param delta the adjustment.\r\n *\r\n * @return The adjusted value.\r\n */\r\n private static double shiftWithNoZeroCrossing(double value, double delta) {\r\n if (value > 0.0) {\r\n return Math.max(value + delta, 0.0);\r\n }\r\n else if (value < 0.0) {\r\n return Math.min(value + delta, 0.0);\r\n }\r\n else {\r\n return value + delta;\r\n }\r\n }\r\n\r\n /**\r\n * Scales the range by the specified factor.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param factor the scaling factor (must be non-negative).\r\n *\r\n * @return A new range.\r\n *\r\n * @since 1.0.9\r\n */\r\n public static Range scale(Range base, double factor) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (factor < 0) {\r\n throw new IllegalArgumentException(\"Negative 'factor' argument.\");\r\n }\r\n return new Range(base.getLowerBound() * factor,\r\n base.getUpperBound() * factor);\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (!(obj instanceof Range)) {\r\n return false;\r\n }\r\n Range range = (Range) obj;\r\n if (!(this.lower == range.lower)) {\r\n return false;\r\n }\r\n if (!(this.upper == range.upper)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if both the lower and upper bounds are \r\n * <code>Double.NaN</code>, and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isNaNRange() {\r\n return Double.isNaN(this.lower) && Double.isNaN(this.upper);\r\n }\r\n \r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n long temp;\r\n temp = Double.doubleToLongBits(this.lower);\r\n result = (int) (temp ^ (temp >>> 32));\r\n temp = Double.doubleToLongBits(this.upper);\r\n result = 29 * result + (int) (temp ^ (temp >>> 32));\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a string representation of this Range.\r\n *\r\n * @return A String \"Range[lower,upper]\" where lower=lower range and\r\n * upper=upper range.\r\n */\r\n @Override\r\n public String toString() {\r\n return (\"Range[\" + this.lower + \",\" + this.upper + \"]\");\r\n }\r\n\r\n}\r" }, { "identifier": "DefaultCategoryDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/category/DefaultCategoryDataset.java", "snippet": "public class DefaultCategoryDataset extends AbstractDataset\r\n implements CategoryDataset, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -8168173757291644622L;\r\n\r\n /** A storage structure for the data. */\r\n private DefaultKeyedValues2D data;\r\n\r\n /**\r\n * Creates a new (empty) dataset.\r\n */\r\n public DefaultCategoryDataset() {\r\n this.data = new DefaultKeyedValues2D();\r\n }\r\n\r\n /**\r\n * Returns the number of rows in the table.\r\n *\r\n * @return The row count.\r\n *\r\n * @see #getColumnCount()\r\n */\r\n @Override\r\n public int getRowCount() {\r\n return this.data.getRowCount();\r\n }\r\n\r\n /**\r\n * Returns the number of columns in the table.\r\n *\r\n * @return The column count.\r\n *\r\n * @see #getRowCount()\r\n */\r\n @Override\r\n public int getColumnCount() {\r\n return this.data.getColumnCount();\r\n }\r\n\r\n /**\r\n * Returns a value from the table.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n *\r\n * @see #addValue(Number, Comparable, Comparable)\r\n * @see #removeValue(Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getValue(int row, int column) {\r\n return this.data.getValue(row, column);\r\n }\r\n\r\n /**\r\n * Returns the key for the specified row.\r\n *\r\n * @param row the row index (zero-based).\r\n *\r\n * @return The row key.\r\n *\r\n * @see #getRowIndex(Comparable)\r\n * @see #getRowKeys()\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public Comparable getRowKey(int row) {\r\n return this.data.getRowKey(row);\r\n }\r\n\r\n /**\r\n * Returns the row index for a given key.\r\n *\r\n * @param key the row key (<code>null</code> not permitted).\r\n *\r\n * @return The row index.\r\n *\r\n * @see #getRowKey(int)\r\n */\r\n @Override\r\n public int getRowIndex(Comparable key) {\r\n // defer null argument check\r\n return this.data.getRowIndex(key);\r\n }\r\n\r\n /**\r\n * Returns the row keys.\r\n *\r\n * @return The keys.\r\n *\r\n * @see #getRowKey(int)\r\n */\r\n @Override\r\n public List getRowKeys() {\r\n return this.data.getRowKeys();\r\n }\r\n\r\n /**\r\n * Returns a column key.\r\n *\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The column key.\r\n *\r\n * @see #getColumnIndex(Comparable)\r\n */\r\n @Override\r\n public Comparable getColumnKey(int column) {\r\n return this.data.getColumnKey(column);\r\n }\r\n\r\n /**\r\n * Returns the column index for a given key.\r\n *\r\n * @param key the column key (<code>null</code> not permitted).\r\n *\r\n * @return The column index.\r\n *\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public int getColumnIndex(Comparable key) {\r\n // defer null argument check\r\n return this.data.getColumnIndex(key);\r\n }\r\n\r\n /**\r\n * Returns the column keys.\r\n *\r\n * @return The keys.\r\n *\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public List getColumnKeys() {\r\n return this.data.getColumnKeys();\r\n }\r\n\r\n /**\r\n * Returns the value for a pair of keys.\r\n *\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n *\r\n * @throws UnknownKeyException if either key is not defined in the dataset.\r\n *\r\n * @see #addValue(Number, Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getValue(Comparable rowKey, Comparable columnKey) {\r\n return this.data.getValue(rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Adds a value to the table. Performs the same function as setValue().\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n * @see #removeValue(Comparable, Comparable)\r\n */\r\n public void addValue(Number value, Comparable rowKey,\r\n Comparable columnKey) {\r\n this.data.addValue(value, rowKey, columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds a value to the table.\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n */\r\n public void addValue(double value, Comparable rowKey,\r\n Comparable columnKey) {\r\n addValue(new Double(value), rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Adds or updates a value in the table and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param value the value (<code>null</code> permitted).\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n */\r\n public void setValue(Number value, Comparable rowKey,\r\n Comparable columnKey) {\r\n this.data.setValue(value, rowKey, columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds or updates a value in the table and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n */\r\n public void setValue(double value, Comparable rowKey,\r\n Comparable columnKey) {\r\n setValue(new Double(value), rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Adds the specified value to an existing value in the dataset (if the\r\n * existing value is <code>null</code>, it is treated as if it were 0.0).\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @throws UnknownKeyException if either key is not defined in the dataset.\r\n */\r\n public void incrementValue(double value,\r\n Comparable rowKey,\r\n Comparable columnKey) {\r\n double existing = 0.0;\r\n Number n = getValue(rowKey, columnKey);\r\n if (n != null) {\r\n existing = n.doubleValue();\r\n }\r\n setValue(existing + value, rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Removes a value from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n *\r\n * @see #addValue(Number, Comparable, Comparable)\r\n */\r\n public void removeValue(Comparable rowKey, Comparable columnKey) {\r\n this.data.removeValue(rowKey, columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a row from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param rowIndex the row index.\r\n *\r\n * @see #removeColumn(int)\r\n */\r\n public void removeRow(int rowIndex) {\r\n this.data.removeRow(rowIndex);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a row from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param rowKey the row key.\r\n *\r\n * @see #removeColumn(Comparable)\r\n */\r\n public void removeRow(Comparable rowKey) {\r\n this.data.removeRow(rowKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a column from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param columnIndex the column index.\r\n *\r\n * @see #removeRow(int)\r\n */\r\n public void removeColumn(int columnIndex) {\r\n this.data.removeColumn(columnIndex);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a column from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @see #removeRow(Comparable)\r\n *\r\n * @throws UnknownKeyException if <code>columnKey</code> is not defined\r\n * in the dataset.\r\n */\r\n public void removeColumn(Comparable columnKey) {\r\n this.data.removeColumn(columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Clears all data from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n */\r\n public void clear() {\r\n this.data.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Tests this dataset for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof CategoryDataset)) {\r\n return false;\r\n }\r\n CategoryDataset that = (CategoryDataset) obj;\r\n if (!getRowKeys().equals(that.getRowKeys())) {\r\n return false;\r\n }\r\n if (!getColumnKeys().equals(that.getColumnKeys())) {\r\n return false;\r\n }\r\n int rowCount = getRowCount();\r\n int colCount = getColumnCount();\r\n for (int r = 0; r < rowCount; r++) {\r\n for (int c = 0; c < colCount; c++) {\r\n Number v1 = getValue(r, c);\r\n Number v2 = that.getValue(r, c);\r\n if (v1 == null) {\r\n if (v2 != null) {\r\n return false;\r\n }\r\n }\r\n else if (!v1.equals(v2)) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for the dataset.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.data.hashCode();\r\n }\r\n\r\n /**\r\n * Returns a clone of the dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning the\r\n * dataset.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultCategoryDataset clone = (DefaultCategoryDataset) super.clone();\r\n clone.data = (DefaultKeyedValues2D) this.data.clone();\r\n return clone;\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import org.jfree.chart.TestUtilities; import org.jfree.data.Range; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.util.PublicCloneable; import org.junit.Test;
7,028
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * StackedAreaRendererTest.java * ---------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG); * 04-Feb-2009 : Added testFindRangeBounds (DG); * */ package org.jfree.chart.renderer.category; /** * Tests for the {@link StackedAreaRenderer} class. */ public class StackedAreaRendererTest { /** * Some checks for the findRangeBounds() method. */ @Test public void testFindRangeBounds() { StackedAreaRenderer r = new StackedAreaRenderer(); assertNull(r.findRangeBounds(null)); // an empty dataset should return a null range
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * StackedAreaRendererTest.java * ---------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG); * 04-Feb-2009 : Added testFindRangeBounds (DG); * */ package org.jfree.chart.renderer.category; /** * Tests for the {@link StackedAreaRenderer} class. */ public class StackedAreaRendererTest { /** * Some checks for the findRangeBounds() method. */ @Test public void testFindRangeBounds() { StackedAreaRenderer r = new StackedAreaRenderer(); assertNull(r.findRangeBounds(null)); // an empty dataset should return a null range
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
2
2023-12-24 12:36:47+00:00
8k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/mixin/render/MixinModelBiped.java
[ { "identifier": "RotationHandler", "path": "src/main/java/com/github/may2beez/mayobees/handler/RotationHandler.java", "snippet": "public class RotationHandler {\n private static RotationHandler instance;\n private final Minecraft mc = Minecraft.getMinecraft();\n private final Rotation startRotation = new Rotation(0f, 0f);\n private final Rotation targetRotation = new Rotation(0f, 0f);\n private final Clock dontRotate = new Clock();\n @Getter\n private boolean rotating;\n private long startTime;\n private long endTime;\n @Getter\n private float clientSideYaw = 0;\n @Getter\n private float clientSidePitch = 0;\n @Getter\n private float serverSideYaw = 0;\n @Getter\n private float serverSidePitch = 0;\n @Getter\n private RotationConfiguration configuration;\n\n private final Random random = new Random();\n\n public static RotationHandler getInstance() {\n if (instance == null) {\n instance = new RotationHandler();\n }\n return instance;\n }\n\n public void easeTo(RotationConfiguration configuration) {\n this.configuration = configuration;\n easingModifier = (random.nextFloat() * 0.5f - 0.25f);\n dontRotate.reset();\n startTime = System.currentTimeMillis();\n startRotation.setRotation(configuration.getFrom());\n Rotation neededChange;\n randomAddition = (Math.random() * 0.3 - 0.15);\n if (configuration.bowRotation()) {\n neededChange = getNeededChange(startRotation, getBowRotation(configuration.getTarget().get().getEntity()));\n } else if (configuration.getTarget().isPresent() && configuration.getTarget().get().getTarget().isPresent()) {\n neededChange = getNeededChange(startRotation, configuration.getTarget().get().getTarget().get());\n } else if (configuration.getTo().isPresent()) {\n neededChange = getNeededChange(startRotation, configuration.getTo().get());\n } else {\n throw new IllegalArgumentException(\"No target or rotation specified!\");\n }\n\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n\n LogUtils.debug(\"[Rotation] Needed change: \" + neededChange.getYaw() + \" \" + neededChange.getPitch());\n\n float absYaw = Math.max(Math.abs(neededChange.getYaw()), 1);\n float absPitch = Math.max(Math.abs(neededChange.getPitch()), 1);\n float pythagoras = pythagoras(absYaw, absPitch);\n float time = getTime(pythagoras, configuration.getTime());\n endTime = (long) (System.currentTimeMillis() + Math.max(time, 50 + Math.random() * 100));\n rotating = true;\n }\n\n private float getTime(float pythagoras, float time) {\n if (pythagoras < 25) {\n LogUtils.debug(\"[Rotation] Very close rotation, speeding up by 0.65\");\n return (long) (time * 0.65);\n }\n if (pythagoras < 45) {\n LogUtils.debug(\"[Rotation] Close rotation, speeding up by 0.77\");\n return (long) (time * 0.77);\n }\n if (pythagoras < 80) {\n LogUtils.debug(\"[Rotation] Not so close, but not that far rotation, speeding up by 0.9\");\n return (long) (time * 0.9);\n }\n if (pythagoras > 100) {\n LogUtils.debug(\"[Rotation] Far rotation, slowing down by 1.1\");\n return (long) (time * 1.1);\n }\n LogUtils.debug(\"[Rotation] Normal rotation\");\n return (long) (time * 1.0);\n }\n\n public void easeBackFromServerRotation() {\n if (configuration == null) return;\n LogUtils.debug(\"[Rotation] Easing back from server rotation\");\n configuration.goingBackToClientSide(true);\n startTime = System.currentTimeMillis();\n configuration.setTarget(Optional.empty());\n startRotation.setRotation(new Rotation(serverSideYaw, serverSidePitch));\n Rotation neededChange = getNeededChange(startRotation, new Rotation(clientSideYaw, clientSidePitch));\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n\n LogUtils.debug(\"[Rotation] Needed change: \" + neededChange.getYaw() + \" \" + neededChange.getPitch());\n\n float time = configuration.getTime();\n endTime = System.currentTimeMillis() + Math.max((long) time, 50);\n configuration.setCallback(Optional.of(this::reset));\n rotating = true;\n }\n\n private float pythagoras(float a, float b) {\n return (float) Math.sqrt(a * a + b * b);\n }\n\n public Rotation getNeededChange(Rotation target) {\n if (configuration != null && configuration.getRotationType() == RotationConfiguration.RotationType.SERVER) {\n return getNeededChange(new Rotation(serverSideYaw, serverSidePitch), target);\n } else {\n return getNeededChange(new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch), target);\n }\n }\n\n public Rotation getNeededChange(Rotation startRot, Vec3 target) {\n Rotation targetRot;\n if (configuration != null && random.nextGaussian() > 0.8) {\n targetRot = getRotation(target, configuration.randomness());\n } else {\n targetRot = getRotation(target);\n }\n return getNeededChange(startRot, targetRot);\n }\n\n public Rotation getNeededChange(Rotation startRot, Rotation endRot) {\n float yawDiff = (float) (wrapAngleTo180(endRot.getYaw()) - wrapAngleTo180(startRot.getYaw()));\n\n yawDiff = AngleUtils.normalizeAngle(yawDiff);\n\n return new Rotation(yawDiff, endRot.getPitch() - startRot.getPitch());\n }\n\n private double randomAddition = (Math.random() * 0.3 - 0.15);\n\n public Rotation getBowRotation(Entity entity) {\n System.out.println(\"Getting bow rotation\");\n double xDelta = (entity.posX - entity.lastTickPosX) * 0.4d;\n double zDelta = (entity.posZ - entity.lastTickPosZ) * 0.4d;\n double d = mc.thePlayer.getDistanceToEntity(entity);\n d -= d % 0.8d;\n double xMulti = d / 0.8 * xDelta;\n double zMulti = d / 0.8 * zDelta;\n double x = entity.posX + xMulti - mc.thePlayer.posX;\n double z = entity.posZ + zMulti - mc.thePlayer.posZ;\n double y = mc.thePlayer.posY + mc.thePlayer.getEyeHeight() - (entity.posY + entity.height / 2 + randomAddition);\n double dist = mc.thePlayer.getDistanceToEntity(entity);\n float yaw = (float) Math.toDegrees(Math.atan2(z, x)) - 90f;\n double d2 = Math.sqrt(x * x + z * z);\n float pitch = (float) (-(Math.atan2(y, d2) * 180.0 / Math.PI)) + (float) dist * 0.11f;\n return new Rotation(yaw, -pitch);\n }\n\n public Rotation getRotation(Vec3 to) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), to, false);\n }\n\n public Rotation getRotation(Vec3 to, boolean randomness) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), to, randomness);\n }\n\n public Rotation getRotation(Entity to) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), to.getPositionVector().addVector(0, Math.min(to.getEyeHeight() - 0.15, 1.5) + randomAddition, 0), false);\n }\n\n public Rotation getRotation(Vec3 from, Vec3 to) {\n if (configuration != null && random.nextGaussian() > 0.8) {\n return getRotation(from, to, configuration.randomness());\n }\n return getRotation(from, to, false);\n }\n\n public Rotation getRotation(BlockPos pos) {\n if (configuration != null && random.nextGaussian() > 0.8) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), configuration.randomness());\n }\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), false);\n }\n\n public Rotation getRotation(BlockPos pos, boolean randomness) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), randomness);\n }\n\n public Rotation getRotation(Vec3 from, Vec3 to, boolean randomness) {\n double xDiff = to.xCoord - from.xCoord;\n double yDiff = to.yCoord - from.yCoord;\n double zDiff = to.zCoord - from.zCoord;\n\n double dist = Math.sqrt(xDiff * xDiff + zDiff * zDiff);\n\n float yaw = (float) Math.toDegrees(Math.atan2(zDiff, xDiff)) - 90F;\n float pitch = (float) -Math.toDegrees(Math.atan2(yDiff, dist));\n\n if (randomness) {\n yaw += (float) ((Math.random() - 1) * 4);\n pitch += (float) ((Math.random() - 1) * 4);\n }\n\n return new Rotation(yaw, pitch);\n }\n\n public boolean shouldRotate(Rotation to) {\n Rotation neededChange = getNeededChange(to);\n return Math.abs(neededChange.getYaw()) > 0.1 || Math.abs(neededChange.getPitch()) > 0.1;\n }\n\n public void reset() {\n LogUtils.debug(\"[Rotation] Resetting\");\n rotating = false;\n configuration = null;\n startTime = 0;\n endTime = 0;\n }\n\n private float interpolate(float start, float end, Function<Float, Float> function) {\n float t = (float) (System.currentTimeMillis() - startTime) / (endTime - startTime);\n return (end - start) * function.apply(t) + start;\n }\n\n private float easingModifier = 0;\n\n private float easeOutQuart(float x) {\n return (float) (1 - Math.pow(1 - x, 4));\n }\n\n private float easeOutExpo(float x) {\n return x == 1 ? 1 : 1 - (float) Math.pow(2, -10 * x);\n }\n\n private float easeOutBack(float x) {\n float c1 = 1.70158f + easingModifier;\n float c3 = c1 + 1;\n return 1 + c3 * (float) Math.pow(x - 1, 3) + c1 * (float) Math.pow(x - 1, 2);\n }\n\n @SubscribeEvent\n public void onRender(RenderWorldLastEvent event) {\n if (!rotating || configuration == null || configuration.getRotationType() != RotationConfiguration.RotationType.CLIENT)\n return;\n\n if (mc.currentScreen != null || dontRotate.isScheduled() && !dontRotate.passed()) {\n endTime = System.currentTimeMillis() + configuration.getTime();\n return;\n }\n\n if (System.currentTimeMillis() >= endTime) {\n // finish\n if (configuration.getCallback().isPresent()) {\n configuration.getCallback().get().run();\n } else { // No callback, just reset\n if (Math.abs(mc.thePlayer.rotationYaw - targetRotation.getYaw()) < 0.1 && Math.abs(mc.thePlayer.rotationPitch - targetRotation.getPitch()) < 0.1) {\n mc.thePlayer.rotationYaw = targetRotation.getYaw();\n mc.thePlayer.rotationPitch = targetRotation.getPitch();\n }\n reset();\n return;\n }\n if (configuration == null || !configuration.goingBackToClientSide()) { // Reset was called in callback\n return;\n }\n return;\n }\n\n if (configuration.followTarget() && configuration.getTarget().isPresent()) {\n Target target = configuration.getTarget().get();\n Rotation rot;\n if (target.getEntity() != null) {\n if (configuration.bowRotation()) {\n rot = getBowRotation(target.getEntity());\n } else {\n rot = getRotation(target.getEntity());\n }\n } else if (target.getBlockPos() != null) {\n rot = getRotation(target.getBlockPos());\n } else if (target.getTarget().isPresent()) {\n rot = getRotation(target.getTarget().get());\n } else {\n throw new IllegalArgumentException(\"No target specified!\");\n }\n Rotation neededChange = getNeededChange(startRotation, rot);\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n }\n mc.thePlayer.rotationYaw = interpolate(startRotation.getYaw(), targetRotation.getYaw(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutExpo);\n mc.thePlayer.rotationPitch = interpolate(startRotation.getPitch(), targetRotation.getPitch(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutQuart);\n }\n\n @SubscribeEvent(receiveCanceled = true)\n public void onUpdatePre(MotionUpdateEvent.Pre event) {\n if (!rotating || configuration == null || configuration.getRotationType() != RotationConfiguration.RotationType.SERVER)\n return;\n\n if (System.currentTimeMillis() >= endTime) {\n // finish\n if (configuration.getCallback().isPresent()) {\n configuration.getCallback().get().run();\n } else { // No callback, just reset\n reset();\n return;\n }\n if (configuration == null || !configuration.goingBackToClientSide()) { // Reset was called in callback\n return;\n }\n }\n clientSidePitch = mc.thePlayer.rotationPitch;\n clientSideYaw = mc.thePlayer.rotationYaw;\n // rotating\n if (configuration.followTarget() && configuration.getTarget().isPresent() && !configuration.goingBackToClientSide()) {\n Target target = configuration.getTarget().get();\n Rotation rot;\n if (target.getEntity() != null) {\n if (configuration.bowRotation()) {\n rot = getBowRotation(target.getEntity());\n } else {\n rot = getRotation(target.getEntity());\n }\n } else if (target.getBlockPos() != null) {\n rot = getRotation(target.getBlockPos());\n } else if (target.getTarget().isPresent()) {\n rot = getRotation(target.getTarget().get());\n } else {\n throw new IllegalArgumentException(\"No target specified!\");\n }\n// if (distanceTraveled > 180) {\n// distanceTraveled = 0;\n// startRotation.setRotation(new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch));\n// }\n Rotation neededChange = getNeededChange(startRotation, rot);\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n// distanceTraveled += Math.abs(neededChange.getYaw());\n// long time = (long) getTime(pythagoras(Math.abs(neededChange.getYaw()), Math.abs(neededChange.getPitch())), configuration.getTime());\n// endTime = System.currentTimeMillis() + Math.max(time, (long) (50 + Math.random() * 100));\n }\n if (configuration.goingBackToClientSide()) {\n LogUtils.debug(\"Going back to client side\");\n targetRotation.setYaw(clientSideYaw);\n targetRotation.setPitch(clientSidePitch);\n }\n if (mc.currentScreen != null || dontRotate.isScheduled() && !dontRotate.passed()) {\n event.yaw = serverSideYaw;\n event.pitch = serverSidePitch;\n endTime = System.currentTimeMillis() + configuration.getTime();\n } else {\n float interX = interpolate(startRotation.getYaw(), targetRotation.getYaw(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutExpo);\n float interY = interpolate(startRotation.getPitch(), targetRotation.getPitch(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutExpo);\n float absDiffX = Math.abs(interX - targetRotation.getYaw());\n float absDiffY = Math.abs(interY - targetRotation.getPitch());\n event.yaw = absDiffX < 0.1 ? targetRotation.getYaw() : interX;\n event.pitch = absDiffY < 0.1 ? targetRotation.getPitch() : interY;\n }\n serverSidePitch = event.pitch;\n serverSideYaw = event.yaw;\n mc.thePlayer.rotationYaw = serverSideYaw;\n mc.thePlayer.rotationPitch = serverSidePitch;\n }\n\n @SubscribeEvent(receiveCanceled = true)\n public void onUpdatePost(MotionUpdateEvent.Post event) {\n if (!rotating) return;\n if (configuration == null || configuration.getRotationType() != RotationConfiguration.RotationType.SERVER)\n return;\n\n mc.thePlayer.rotationYaw = clientSideYaw;\n mc.thePlayer.rotationPitch = clientSidePitch;\n }\n}" }, { "identifier": "EntityPlayerSPAccessor", "path": "src/main/java/com/github/may2beez/mayobees/mixin/client/EntityPlayerSPAccessor.java", "snippet": "@Mixin(EntityPlayerSP.class)\npublic interface EntityPlayerSPAccessor {\n @Accessor\n float getLastReportedYaw();\n\n @Accessor\n void setLastReportedYaw(float lastReportedYaw);\n\n @Accessor\n float getLastReportedPitch();\n\n @Accessor\n void setLastReportedPitch(float lastReportedPitch);\n}" }, { "identifier": "MinecraftAccessor", "path": "src/main/java/com/github/may2beez/mayobees/mixin/client/MinecraftAccessor.java", "snippet": "@Mixin(Minecraft.class)\npublic interface MinecraftAccessor {\n @Accessor(\"timer\")\n Timer getTimer();\n}" }, { "identifier": "RotationConfiguration", "path": "src/main/java/com/github/may2beez/mayobees/util/helper/RotationConfiguration.java", "snippet": "public class RotationConfiguration {\n private final Minecraft mc = Minecraft.getMinecraft();\n @Getter\n @Setter\n private Rotation from;\n @Getter\n @Setter\n private Optional<Rotation> to = Optional.empty();\n @Getter\n @Setter\n private Optional<Target> target = Optional.empty();\n @Getter\n @Setter\n private long time;\n @Getter\n @Setter\n private Optional<Runnable> callback;\n @Setter\n @Getter\n @Accessors(fluent = true)\n private boolean goingBackToClientSide = false;\n @Getter\n @Setter\n @Accessors(fluent = true)\n private boolean followTarget = false;\n @Getter\n @Setter\n private RotationType rotationType = RotationType.CLIENT;\n @Accessors(fluent = true)\n @Getter\n @Setter\n private boolean easeOutBack = false;\n @Accessors(fluent = true)\n @Getter\n @Setter\n private boolean randomness = false;\n @Accessors(fluent = true)\n @Getter\n @Setter\n private boolean bowRotation = false;\n\n public RotationConfiguration(Rotation from, Rotation to, long time, RotationType rotationType, Runnable callback) {\n this.from = from;\n this.to = Optional.ofNullable(to);\n this.time = time;\n this.rotationType = rotationType;\n this.callback = Optional.ofNullable(callback);\n }\n\n public RotationConfiguration(Rotation from, Target target, long time, RotationType rotationType, Runnable callback) {\n this.from = from;\n this.time = time;\n this.target = Optional.ofNullable(target);\n this.rotationType = rotationType;\n this.callback = Optional.ofNullable(callback);\n }\n\n public RotationConfiguration(Rotation to, long time, Runnable callback) {\n this.from = RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().goingBackToClientSide() ? new Rotation(RotationHandler.getInstance().getServerSideYaw(), RotationHandler.getInstance().getServerSidePitch()) : new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);\n this.to = Optional.ofNullable(to);\n this.time = time;\n this.callback = Optional.ofNullable(callback);\n }\n\n public RotationConfiguration(Rotation to, long time, RotationType rotationType, Runnable callback) {\n this.from = RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().goingBackToClientSide() ? new Rotation(RotationHandler.getInstance().getServerSideYaw(), RotationHandler.getInstance().getServerSidePitch()) : new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);\n this.to = Optional.ofNullable(to);\n this.time = time;\n this.rotationType = rotationType;\n this.callback = Optional.ofNullable(callback);\n }\n\n public RotationConfiguration(Target target, long time, Runnable callback) {\n this.from = RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().goingBackToClientSide() ? new Rotation(RotationHandler.getInstance().getServerSideYaw(), RotationHandler.getInstance().getServerSidePitch()) : new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);\n this.time = time;\n this.target = Optional.ofNullable(target);\n this.callback = Optional.ofNullable(callback);\n }\n\n public RotationConfiguration(Target target, long time, RotationType rotationType, Runnable callback) {\n this.from = RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().goingBackToClientSide() ? new Rotation(RotationHandler.getInstance().getServerSideYaw(), RotationHandler.getInstance().getServerSidePitch()) : new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);\n this.time = time;\n this.target = Optional.ofNullable(target);\n this.rotationType = rotationType;\n this.callback = Optional.ofNullable(callback);\n }\n\n public enum RotationType {\n SERVER,\n CLIENT\n }\n\n @Override\n public Object clone() {\n try {\n return super.clone();\n } catch (CloneNotSupportedException e) {\n throw new RuntimeException(e);\n }\n }\n}" } ]
import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.mixin.client.EntityPlayerSPAccessor; import com.github.may2beez.mayobees.mixin.client.MinecraftAccessor; import com.github.may2beez.mayobees.util.helper.RotationConfiguration; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; 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;
5,784
package com.github.may2beez.mayobees.mixin.render; @Mixin(value = ModelBiped.class, priority = Integer.MAX_VALUE) public class MixinModelBiped { @Unique private final Minecraft farmHelperV2$mc = Minecraft.getMinecraft(); @Shadow public ModelRenderer bipedHead; @Inject(method = {"setRotationAngles"}, at = {@At(value = "FIELD", target = "Lnet/minecraft/client/model/ModelBiped;swingProgress:F")}) public void onSetRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn, CallbackInfo ci) { if (!RotationHandler.getInstance().isRotating() || RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().getRotationType() != RotationConfiguration.RotationType.SERVER) return; if (entityIn != null && entityIn.equals(Minecraft.getMinecraft().thePlayer)) { this.bipedHead.rotateAngleX = ((EntityPlayerSPAccessor) entityIn).getLastReportedPitch() / 57.295776f;
package com.github.may2beez.mayobees.mixin.render; @Mixin(value = ModelBiped.class, priority = Integer.MAX_VALUE) public class MixinModelBiped { @Unique private final Minecraft farmHelperV2$mc = Minecraft.getMinecraft(); @Shadow public ModelRenderer bipedHead; @Inject(method = {"setRotationAngles"}, at = {@At(value = "FIELD", target = "Lnet/minecraft/client/model/ModelBiped;swingProgress:F")}) public void onSetRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn, CallbackInfo ci) { if (!RotationHandler.getInstance().isRotating() || RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().getRotationType() != RotationConfiguration.RotationType.SERVER) return; if (entityIn != null && entityIn.equals(Minecraft.getMinecraft().thePlayer)) { this.bipedHead.rotateAngleX = ((EntityPlayerSPAccessor) entityIn).getLastReportedPitch() / 57.295776f;
float partialTicks = ((MinecraftAccessor) farmHelperV2$mc).getTimer().renderPartialTicks;
2
2023-12-24 15:39:11+00:00
8k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/tasks/ImportGDriveCar.java
[ { "identifier": "XMLHandler", "path": "app/src/main/java/de/anipe/verbrauchsapp/io/XMLHandler.java", "snippet": "public class XMLHandler {\n\n\tprivate Car car;\n\tprivate double cons;\n\tprivate List<Consumption> consumptions;\n\n\tprivate static ConsumptionDataSource dataSource;\n\n\tprivate SimpleDateFormat dateFormat = new SimpleDateFormat(\n\t\t\t\"dd.MM.yyyy-HH.mm.ss\", Locale.getDefault());\n\tprivate SimpleDateFormat shortDateFormat = new SimpleDateFormat(\n\t\t\t\"dd.MM.yyyy\", Locale.getDefault());\n\n\tprivate static final String ROOT_ELEMENT_NAME = \"ConsumptionData\";\n\tprivate static final String CAR_ELEMENT_NAME = \"Car\";\n\tprivate static final String CAR_ID_NAME = \"InAppCarID\";\n\tprivate static final String EXPORT_DATE = \"ExportDatum\";\n\tprivate static final String MANUFACTURER = \"Hersteller\";\n\tprivate static final String TYPE = \"Typ\";\n\tprivate static final String NUMBERPLATE = \"Kennzeichen\";\n\tprivate static final String START_KILOMETER = \"Startkilometer\";\n\tprivate static final String FUELTYPE = \"Kraftstoff\";\n\tprivate static final String OVERALL_CONSUMPTION = \"Durchschnittsverbrauch\";\n\n\tprivate static final String CONSUMPTIONS_ROOT_NAME = \"Consumptions\";\n\tprivate static final String CONSUMPTION_ELEMENT_NAME = \"Consumption\";\n\tprivate static final String DATE_ELEMENT_NAME = \"Datum\";\n\tprivate static final String KILOMETER_STATE_NAME = \"Kilometerstand\";\n\tprivate static final String DRIVEN_KILOMETER_NAME = \"GefahreneKilometer\";\n\tprivate static final String REFUEL_LITER_NAME = \"LiterGetankt\";\n\tprivate static final String LITER_PRICE_NAME = \"PreisJeLiter\";\n\tprivate static final String CONSUMPTION_NAME = \"Verbrauch\";\n\n\tpublic XMLHandler(Context context) {\n\t\tthis(context, null, 0, null);\n\t}\n\n\tpublic XMLHandler(Context context, Car car, double cons,\n\t\t\tList<Consumption> consumptions) {\n\t\tthis.car = car;\n\t\tthis.cons = cons;\n\t\tthis.consumptions = consumptions;\n\n\t\tif (context != null) {\n\t\t\tdataSource = ConsumptionDataSource.getInstance(context);\n\t\t\ttry {\n\t\t\t\tdataSource.open();\n\t\t\t} catch (SQLException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic long importXMLCarData(File inputFile) {\n\t\ttry {\n\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\tDocument doc = builder.build(inputFile);\n\t\t\treturn dataSource.addCar(parseCarFromDocument(doc));\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tLog.e(\"XMLHandler\", \"Exception while parsing XML document\");\n\t\t}\n\t\treturn -1;\n\t}\n\n public int importXMLCarDataWithConsumption(InputStream input) {\n try {\n SAXBuilder builder = new SAXBuilder();\n Document doc = builder.build(input);\n long carId = dataSource.addCar(parseCarFromDocument(doc));\n List<Consumption> conList = parseConsumptionFromDocument(doc, carId);\n if (conList.size() > 0) {\n dataSource.addConsumptions(conList);\n }\n return conList.size();\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(\"XMLHandler\", \"Exception while parsing XML document\");\n }\n return -1;\n }\n\n\tpublic int importXMLConsumptionDataForCar(long carId, File inputFile) {\n\t\t// remove old entries\n\t\tdataSource.deleteConsumptionsForCar(carId);\n\n\t\ttry {\n\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\tDocument doc = builder.build(inputFile);\n\t\t\tList<Consumption> conList = parseConsumptionFromDocument(doc, carId);\n\t\t\tif (conList.size() > 0) {\n\t\t\t\tdataSource.addConsumptions(conList);\n\t\t\t}\n\t\t\treturn conList.size();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tLog.e(\"XMLHandler\", \"Exception while parsing XML document\");\n\t\t}\n\t\treturn 0;\n\t}\n\n public int importXMLConsumptionDataForCar(long carId, InputStream inputFile) {\n // remove old entries\n dataSource.deleteConsumptionsForCar(carId);\n\n try {\n SAXBuilder builder = new SAXBuilder();\n Document doc = builder.build(inputFile);\n List<Consumption> conList = parseConsumptionFromDocument(doc, carId);\n if (conList.size() > 0) {\n dataSource.addConsumptions(conList);\n }\n return conList.size();\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(\"XMLHandler\", \"Exception while parsing XML document\");\n }\n return 0;\n }\n\n\tpublic Car parseCarFromDocument(Document doc) {\n\n\t\tElement rootElem = doc.getRootElement();\n\t\tElement carElement = rootElem.getChild(CAR_ELEMENT_NAME);\n\n\t\tCar car = new Car();\n\t\tcar.setCarId(Long.parseLong(carElement.getAttributeValue(CAR_ID_NAME)));\n\t\tcar.setBrand(Brand.fromValue(carElement.getChildText(MANUFACTURER)));\n\t\tcar.setType(carElement.getChildText(TYPE));\n\t\tcar.setNumberPlate(carElement.getChildText(NUMBERPLATE));\n\t\tcar.setStartKm(Integer.parseInt(carElement\n\t\t\t\t.getChildText(START_KILOMETER)));\n\t\tcar.setFuelType(Fueltype.fromValue(carElement.getChildText(FUELTYPE)));\n\n\t\treturn car;\n\t}\n\n\tpublic List<Consumption> parseConsumptionFromDocument(Document doc,\n\t\t\tlong carId) {\n\t\tList<Consumption> cons = new LinkedList<>();\n\t\tList<Element> conList = doc.getRootElement()\n\t\t\t\t.getChild(CONSUMPTIONS_ROOT_NAME)\n\t\t\t\t.getChildren(CONSUMPTION_ELEMENT_NAME);\n\t\tfor (int i = 0; i < conList.size(); i++) {\n\t\t\tElement elem = conList.get(i);\n\n\t\t\tConsumption conElem = new Consumption();\n\t\t\tconElem.setCarId(carId);\n\t\t\tconElem.setDate(getDateFromString(elem\n\t\t\t\t\t.getChildText(DATE_ELEMENT_NAME)));\n\t\t\tconElem.setRefuelmileage(Integer.parseInt(elem\n\t\t\t\t\t.getChildText(KILOMETER_STATE_NAME)));\n\t\t\tconElem.setDrivenmileage(Integer.parseInt(elem\n\t\t\t\t\t.getChildText(DRIVEN_KILOMETER_NAME)));\n\t\t\tconElem.setRefuelliters(Double.parseDouble(elem\n\t\t\t\t\t.getChildText(REFUEL_LITER_NAME)));\n\t\t\tconElem.setRefuelprice(Double.parseDouble(elem\n\t\t\t\t\t.getChildText(LITER_PRICE_NAME)));\n\t\t\tconElem.setConsumption(Double.parseDouble(elem\n\t\t\t\t\t.getChildText(CONSUMPTION_NAME)));\n\n\t\t\tcons.add(conElem);\n\t\t}\n\n\t\treturn cons;\n\t}\n\n\tpublic Document createConsumptionDocument() {\n\t\tElement root = new Element(ROOT_ELEMENT_NAME);\n\t\tDocument doc = new Document(root);\n\t\tdoc.getRootElement().addContent(getCarData(doc, car));\n\t\tdoc.getRootElement().addContent(getConsumptionData(doc, consumptions));\n\n\t\treturn doc;\n\t}\n\n\tprivate Element getCarData(Document doc, Car car) {\n\t\tElement carData = new Element(CAR_ELEMENT_NAME);\n\t\tcarData.setAttribute(new Attribute(CAR_ID_NAME, String.valueOf(car\n\t\t\t\t.getCarId())));\n\n\t\tcarData.addContent(new Element(EXPORT_DATE).setText(getDateTime(\n\t\t\t\tnew Date(), false)));\n\t\tcarData.addContent(new Element(MANUFACTURER).setText(car.getBrand()\n\t\t\t\t.value()));\n\t\tcarData.addContent(new Element(TYPE).setText(car.getType()));\n\t\tcarData.addContent(new Element(NUMBERPLATE).setText(car\n\t\t\t\t.getNumberPlate()));\n\t\tcarData.addContent(new Element(START_KILOMETER).setText(String\n\t\t\t\t.valueOf(car.getStartKm())));\n\t\tcarData.addContent(new Element(FUELTYPE).setText(String.valueOf(car\n\t\t\t\t.getFuelType().value())));\n\t\tcarData.addContent(new Element(OVERALL_CONSUMPTION).setText(String\n\t\t\t\t.valueOf(cons)));\n\n\t\treturn carData;\n\t}\n\n\tprivate Element getConsumptionData(Document doc,\n\t\t\tList<Consumption> consumptions) {\n\t\tElement consumptionData = new Element(CONSUMPTIONS_ROOT_NAME);\n\t\tfor (Consumption con : consumptions) {\n\t\t\tElement consumptionNode = new Element(CONSUMPTION_ELEMENT_NAME);\n\n\t\t\tconsumptionNode.addContent(new Element(DATE_ELEMENT_NAME)\n\t\t\t\t\t.setText(getDateTime(con.getDate(), true)));\n\t\t\tconsumptionNode.addContent(new Element(KILOMETER_STATE_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getRefuelmileage())));\n\t\t\tconsumptionNode.addContent(new Element(DRIVEN_KILOMETER_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getDrivenmileage())));\n\t\t\tconsumptionNode.addContent(new Element(REFUEL_LITER_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getRefuelliters())));\n\t\t\tconsumptionNode.addContent(new Element(LITER_PRICE_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getRefuelprice())));\n\t\t\tconsumptionNode.addContent(new Element(CONSUMPTION_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getConsumption())));\n\n\t\t\tconsumptionData.addContent(consumptionNode);\n\t\t}\n\t\treturn consumptionData;\n\t}\n\n\tprivate String getDateTime(Date date, boolean shortFormat) {\n\t\tif (!shortFormat) {\n\t\t\treturn dateFormat.format(date);\n\t\t}\n\t\treturn shortDateFormat.format(date);\n\t}\n\n\tprivate Date getDateFromString(String dateString) {\n\t\ttry {\n\t\t\treturn shortDateFormat.parse(dateString);\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "ResetableCountDownLatch", "path": "app/src/main/java/de/anipe/verbrauchsapp/util/ResetableCountDownLatch.java", "snippet": "public class ResetableCountDownLatch {\n /**\n * Synchronization control For CountDownLatch.\n * Uses AQS state to represent count.\n */\n private static final class Sync extends AbstractQueuedSynchronizer {\n private static final long serialVersionUID = 4982264981922014374L;\n\n public final int startCount;\n\n Sync(int count) {\n this.startCount = count;\n setState(startCount);\n }\n\n int getCount() {\n return getState();\n }\n\n public int tryAcquireShared(int acquires) {\n return getState() == 0? 1 : -1;\n }\n\n public boolean tryReleaseShared(int releases) {\n // Decrement count; signal when transition to zero\n for (;;) {\n int c = getState();\n if (c == 0)\n return false;\n int nextc = c-1;\n if (compareAndSetState(c, nextc))\n return nextc == 0;\n }\n }\n\n public void reset() {\n setState(startCount);\n }\n }\n\n private final Sync sync;\n\n /**\n * Constructs a {@code CountDownLatch} initialized with the given count.\n *\n * @param count the number of times {@link #countDown} must be invoked\n * before threads can pass through {@link #await}\n * @throws IllegalArgumentException if {@code count} is negative\n */\n public ResetableCountDownLatch(int count) {\n if (count < 0) throw new IllegalArgumentException(\"count < 0\");\n this.sync = new Sync(count);\n }\n\n /**\n * Causes the current thread to wait until the latch has counted down to\n * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.\n *\n * <p>If the current count is zero then this method returns immediately.\n *\n * <p>If the current count is greater than zero then the current\n * thread becomes disabled for thread scheduling purposes and lies\n * dormant until one of two things happen:\n * <ul>\n * <li>The count reaches zero due to invocations of the\n * {@link #countDown} method; or\n * <li>Some other thread {@linkplain Thread#interrupt interrupts}\n * the current thread.\n * </ul>\n *\n * <p>If the current thread:\n * <ul>\n * <li>has its interrupted status set on entry to this method; or\n * <li>is {@linkplain Thread#interrupt interrupted} while waiting,\n * </ul>\n * then {@link InterruptedException} is thrown and the current thread's\n * interrupted status is cleared.\n *\n * @throws InterruptedException if the current thread is interrupted\n * while waiting\n */\n public void await() throws InterruptedException {\n sync.acquireSharedInterruptibly(1);\n }\n\n public void reset() {\n sync.reset();\n }\n\n /**\n * Causes the current thread to wait until the latch has counted down to\n * zero, unless the thread is {@linkplain Thread#interrupt interrupted},\n * or the specified waiting time elapses.\n *\n * <p>If the current count is zero then this method returns immediately\n * with the value {@code true}.\n *\n * <p>If the current count is greater than zero then the current\n * thread becomes disabled for thread scheduling purposes and lies\n * dormant until one of three things happen:\n * <ul>\n * <li>The count reaches zero due to invocations of the\n * {@link #countDown} method; or\n * <li>Some other thread {@linkplain Thread#interrupt interrupts}\n * the current thread; or\n * <li>The specified waiting time elapses.\n * </ul>\n *\n * <p>If the count reaches zero then the method returns with the\n * value {@code true}.\n *\n * <p>If the current thread:\n * <ul>\n * <li>has its interrupted status set on entry to this method; or\n * <li>is {@linkplain Thread#interrupt interrupted} while waiting,\n * </ul>\n * then {@link InterruptedException} is thrown and the current thread's\n * interrupted status is cleared.\n *\n * <p>If the specified waiting time elapses then the value {@code false}\n * is returned. If the time is less than or equal to zero, the method\n * will not wait at all.\n *\n * @param timeout the maximum time to wait\n * @param unit the time unit of the {@code timeout} argument\n * @return {@code true} if the count reached zero and {@code false}\n * if the waiting time elapsed before the count reached zero\n * @throws InterruptedException if the current thread is interrupted\n * while waiting\n */\n public boolean await(long timeout, TimeUnit unit)\n throws InterruptedException {\n return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));\n }\n\n /**\n * Decrements the count of the latch, releasing all waiting threads if\n * the count reaches zero.\n *\n * <p>If the current count is greater than zero then it is decremented.\n * If the new count is zero then all waiting threads are re-enabled for\n * thread scheduling purposes.\n *\n * <p>If the current count equals zero then nothing happens.\n */\n public void countDown() {\n sync.releaseShared(1);\n }\n\n /**\n * Returns the current count.\n *\n * <p>This method is typically used for debugging and testing purposes.\n *\n * @return the current count\n */\n public long getCount() {\n return sync.getCount();\n }\n\n /**\n * Returns a string identifying this latch, as well as its state.\n * The state, in brackets, includes the String {@code \"Count =\"}\n * followed by the current count.\n *\n * @return a string identifying this latch, as well as its state\n */\n public String toString() {\n return super.toString() + \"[Count = \" + sync.getCount() + \"]\";\n }\n}" } ]
import android.app.Activity; import android.app.ProgressDialog; import android.content.IntentSender; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.drive.Drive; import com.google.android.gms.drive.DriveContents; import com.google.android.gms.drive.DriveFile; import com.google.android.gms.drive.DriveId; import java.io.InputStream; import de.anipe.verbrauchsapp.io.XMLHandler; import de.anipe.verbrauchsapp.util.ResetableCountDownLatch; import static com.google.android.gms.common.api.GoogleApiClient.Builder; import static com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import static com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import static com.google.android.gms.drive.DriveApi.DriveContentsResult;
4,147
package de.anipe.verbrauchsapp.tasks; public class ImportGDriveCar extends AsyncTask<String, Void, Void> { private Activity mCon; private ProgressDialog myprogsdial; private int dataSets = -2; private GoogleApiClient mClient; private Throwable _error = null; public ImportGDriveCar(Activity con) { mCon = con; Builder builder = new Builder(con) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE); mClient = builder.build(); } @Override protected void onPreExecute() { myprogsdial = ProgressDialog.show(mCon, "Datensatz-Import", "Bitte warten ...", true); } @Override protected Void doInBackground(String... params) { Log.d("ImportGDriveCar", "Importing gdrive file."); try {
package de.anipe.verbrauchsapp.tasks; public class ImportGDriveCar extends AsyncTask<String, Void, Void> { private Activity mCon; private ProgressDialog myprogsdial; private int dataSets = -2; private GoogleApiClient mClient; private Throwable _error = null; public ImportGDriveCar(Activity con) { mCon = con; Builder builder = new Builder(con) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE); mClient = builder.build(); } @Override protected void onPreExecute() { myprogsdial = ProgressDialog.show(mCon, "Datensatz-Import", "Bitte warten ...", true); } @Override protected Void doInBackground(String... params) { Log.d("ImportGDriveCar", "Importing gdrive file."); try {
final ResetableCountDownLatch latch = new ResetableCountDownLatch(1);
1
2023-12-28 12:33:52+00:00
8k
PSButlerII/SqlScriptGen
src/main/java/com/recondev/Main.java
[ { "identifier": "Enums", "path": "src/main/java/com/recondev/helpers/Enums.java", "snippet": "public class Enums {\n\n public enum DatabaseType {\n POSTGRESQL(\"PostgreSQL\"),\n MYSQL(\"MySQL\"),\n MONGODB(\"MongoDB\");\n\n private final String type;\n\n DatabaseType(String type) {\n this.type = type;\n }\n\n public static DatabaseType fromInt(int index) {\n return DatabaseType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n\n public int getValue() {\n return this.ordinal() + 1;\n }\n }\n\n public enum PostgreSQLDataType {\n SMALLINT(\"smallint\"),\n INTEGER(\"integer\"),\n BIGINT(\"bigint\"),\n DECIMAL(\"decimal\"),\n NUMERIC(\"numeric\"),\n REAL(\"real\"),\n DOUBLE_PRECISION(\"double precision\"),\n SERIAL(\"serial\"),\n BIGSERIAL(\"bigserial\"),\n MONEY(\"money\"),\n VARCHAR(\"varchar\"),\n CHAR(\"char\"),\n TEXT(\"text\"),\n BYTEA(\"bytea\"),\n TIMESTAMP(\"timestamp\"),\n DATE(\"date\"),\n TIME(\"time\"),\n INTERVAL(\"interval\"),\n BOOLEAN(\"boolean\"),\n BIT(\"bit\"),\n VARBIT(\"varbit\"),\n UUID(\"uuid\"),\n XML(\"xml\"),\n JSON(\"json\"),\n JSONB(\"jsonb\");\n\n private final String type;\n\n PostgreSQLDataType(String type) {\n this.type = type;\n }\n\n public static PostgreSQLDataType fromInt(int index) {\n return PostgreSQLDataType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n }\n\n public enum PostgreSQLComplexDataType {\n POINT(\"point\"),\n LINE(\"line\"),\n LSEG(\"lseg\"),\n BOX(\"box\"),\n PATH(\"path\"),\n POLYGON(\"polygon\"),\n CIRCLE(\"circle\"),\n CIDR(\"cidr\"),\n INET(\"inet\"),\n MACADDR(\"macaddr\"),\n ARRAY(\"array\"); // Note: Array is a more complex type\n\n private final String complexType;\n\n PostgreSQLComplexDataType(String complexType) {\n this.complexType = complexType;\n }\n\n public static PostgreSQLComplexDataType fromInt(int index) {\n return PostgreSQLComplexDataType.values()[index];\n }\n\n public String getComplexType() {\n return complexType;\n }\n }\n\n public enum MySQLDataType {\n TINYINT(\"TINYINT\"),\n SMALLINT(\"SMALLINT\"),\n MEDIUMINT(\"MEDIUMINT\"),\n INT(\"INT\"),\n BIGINT(\"BIGINT\"),\n DECIMAL(\"DECIMAL\"),\n FLOAT(\"FLOAT\"),\n DOUBLE(\"DOUBLE\"),\n BIT(\"BIT\"),\n CHAR(\"CHAR\"),\n VARCHAR(\"VARCHAR\"),\n TINYTEXT(\"TINYTEXT\"),\n TEXT(\"TEXT\"),\n MEDIUMTEXT(\"MEDIUMTEXT\"),\n LONGTEXT(\"LONGTEXT\"),\n DATE(\"DATE\"),\n DATETIME(\"DATETIME\"),\n TIMESTAMP(\"TIMESTAMP\"),\n TIME(\"TIME\"),\n YEAR(\"YEAR\"),\n BINARY(\"BINARY\"),\n VARBINARY(\"VARBINARY\"),\n TINYBLOB(\"TINYBLOB\"),\n BLOB(\"BLOB\"),\n MEDIUMBLOB(\"MEDIUMBLOB\"),\n LONGBLOB(\"LONGBLOB\"),\n ENUM(\"ENUM\"),\n SET(\"SET\");\n\n private final String type;\n\n MySQLDataType(String type) {\n this.type = type;\n }\n\n public static MySQLDataType fromInt(int index) {\n return MySQLDataType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n }\n\n public enum MongoDBDataType {\n DOUBLE(\"Double\"),\n STRING(\"String\"),\n BINARY_DATA(\"Binary data\"),\n OBJECT_ID(\"ObjectId\"),\n BOOLEAN(\"Boolean\"),\n DATE(\"Date\"),\n NULL(\"Null\"),\n JAVASCRIPT(\"JavaScript\"),\n INT(\"32-bit integer\"),\n TIMESTAMP(\"Timestamp\"),\n LONG(\"64-bit integer\"),\n DECIMAL128(\"Decimal128\");\n\n private final String type;\n\n MongoDBDataType(String type) {\n this.type = type;\n }\n\n public static MongoDBDataType fromInt(int index) {\n return MongoDBDataType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n }\n\n public enum MongoDBComplexDataType {\n OBJECT(\"Object\"), // Object or embedded document\n ARRAY(\"Array\"), // Array type\n JAVASCRIPT_WITH_SCOPE(\"JavaScript (with scope)\"), // JavaScript code with scope\n DB_POINTER(\"DBPointer (Deprecated)\"), // Reference to another document\n REGEX(\"Regular Expression\"); // Regular expression type\n\n private final String complexType;\n\n MongoDBComplexDataType(String complexType) {\n this.complexType = complexType;\n }\n\n public static MongoDBComplexDataType fromInt(int index) {\n return MongoDBComplexDataType.values()[index];\n }\n\n public String getComplexType() {\n return complexType;\n }\n }\n\n // TODO: Add PostgreSQLConstraintType\n public enum PostgreSQLConstraintType implements DatabaseConstraintType {\n PRIMARY_KEY(\"PRIMARY KEY\"),\n UNIQUE(\"UNIQUE\"),\n CHECK(\"CHECK\"),\n FOREIGN_KEY(\"FOREIGN KEY\"),\n EXCLUSION(\"EXCLUSION\");\n\n private final String constraintType;\n private boolean requiresAdditionalInput;\n\n PostgreSQLConstraintType(String constraintType) {\n this.constraintType = constraintType;\n }\n\n public static PostgreSQLConstraintType fromInt(int index) {\n return PostgreSQLConstraintType.values()[index];\n }\n\n public static PostgreSQLConstraintType fromString(String constraintType) {\n for (PostgreSQLConstraintType type : PostgreSQLConstraintType.values()) {\n if (type.getConstraintType().equals(constraintType)) {\n return type;\n }\n }\n throw new IllegalArgumentException(\"Invalid constraint type\");\n }\n\n public String getConstraintType() {\n return constraintType;\n }\n\n public boolean requiresAdditionalInput() {\n if (this == CHECK || this == FOREIGN_KEY || this == fromString(\"CHECK\") || this == fromString(\"FOREIGN KEY\")) {\n return this.requiresAdditionalInput = true;\n }\n return this.requiresAdditionalInput;\n }\n\n public String getConstraintSQL(String columnName, String additionalInput) {\n switch (this) {\n case PRIMARY_KEY:\n return \"CONSTRAINT \" + columnName + \"_pk \" + this.getConstraintType() + \" (\" + columnName + \")\";\n case UNIQUE:\n return \"CONSTRAINT \" + columnName + \"_unique \" + this.getConstraintType() + \" (\" + columnName + \")\";\n case CHECK:\n return \"CONSTRAINT \" + columnName + \"_check \" + this.getConstraintType() + \" (\" + columnName + \" \" + additionalInput + \")\";\n case FOREIGN_KEY:\n return \"CONSTRAINT \" + columnName + \"_fk \" + this.getConstraintType() + \" (\" + columnName + \") REFERENCES \" + \"(\" + additionalInput + \")\";\n// case EXCLUSION:\n// return \"CONSTRAINT \" + columnName + \"_exclusion \" + this.getConstraintType() + \" USING gist (\" + columnName + \" WITH =)\";\n default:\n throw new IllegalArgumentException(\"Invalid constraint type\");\n }\n }\n }\n\n // TODO: Add MySQLConstraintType\n public enum MySQLConstraintType implements DatabaseConstraintType {\n PRIMARY_KEY(\"PRIMARY KEY\"),\n UNIQUE(\"UNIQUE\"),\n FOREIGN_KEY(\"FOREIGN KEY\"),\n CHECK(\"CHECK\");\n\n private final String constraintType;\n\n MySQLConstraintType(String constraintType) {\n this.constraintType = constraintType;\n }\n\n public static MySQLConstraintType fromInt(int index) {\n return MySQLConstraintType.values()[index];\n }\n\n public String getConstraintType() {\n return constraintType;\n }\n\n /**\n * @return\n */\n @Override\n public boolean requiresAdditionalInput() {\n return false;\n }\n\n /**\n * @param columnName\n * @param additionalInput\n * @return\n */\n @Override\n public String getConstraintSQL(String columnName, String additionalInput) {\n return null;\n }\n }\n\n // TODO: Add MongoDBConstraintType\n}" }, { "identifier": "DatabaseScriptGenerator", "path": "src/main/java/com/recondev/interfaces/DatabaseScriptGenerator.java", "snippet": "public interface DatabaseScriptGenerator {\n String generateCreateTableScript(String table, Map<String, String> columns, List<String> constraints);\n\n String generateCreateDatabaseScript(String name);\n}" }, { "identifier": "ScriptGeneratorFactory", "path": "src/main/java/com/recondev/service/ScriptGeneratorFactory.java", "snippet": "public class ScriptGeneratorFactory {\n public static DatabaseScriptGenerator getScriptGenerator(int dbType) {\n switch (dbType) {\n case 1:\n return new PostgreSQLScriptGenerator();\n case 2:\n return new MySQLScriptGenerator();\n // other cases will go here if i ever get that far\n default:\n throw new IllegalArgumentException(\"Invalid database type\");\n }\n }\n}" }, { "identifier": "UserInteraction", "path": "src/main/java/com/recondev/userinteraction/UserInteraction.java", "snippet": "public class UserInteraction {\n // private String getConstraintString(int constraintCount) {\n//\n// //TODO: Make this method more generic so it can be used for other databases\n// String constraintSQL = null;\n// for (int i = 0; i < constraintCount; i++) {\n// System.out.println(\"Choose constraint type:\");\n//\n// // print out the constraint types\n// for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) {\n// System.out.println(j + \": \" + Enums.PostgreSQLConstraintType.values()[j].getConstraintType());\n// }\n//\n// int constraintTypeIndex = Integer.parseInt(scanner.nextLine());\n// Enums.PostgreSQLConstraintType constraintType = Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex);\n//\n// System.out.println(\"Enter column name for constraint:\");\n// String columnName = scanner.nextLine();\n//\n// String additionalInput = \"\";\n// if (constraintType.requiresAdditionalInput()) {\n// if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) {\n// System.out.println(\"Enter table name for the constraint:\");\n// String tableName = scanner.nextLine();\n//\n// System.out.println(\"Enter column name for the constraint:\");\n// String foreignKeyColumnName = scanner.nextLine();\n//\n// additionalInput = tableName + \"(\" + foreignKeyColumnName + \")\";\n// } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) {\n// System.out.println(\"Enter check condition (e.g., column_name > 5):\");\n// additionalInput = scanner.nextLine();\n// }\n//\n// // Assuming other constraint types might need a generic input\n// else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE ||\n// constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*||\n// constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) {\n// System.out.println(\"Enter additional input for the constraint:\");\n// additionalInput = scanner.nextLine();\n// }\n// // Handle any other constraints that might need additional input\n// else {\n// System.out.println(\"Enter additional input for the constraint:\");\n// additionalInput = scanner.nextLine();\n// }\n// }\n// constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput);\n// }\n// return constraintSQL;\n// }\n private final Scanner scanner = new Scanner(System.in);\n\n public Enums.DatabaseType getDatabaseType() {\n System.out.println(\"Enter database type\\n (1)PostgreSQL\\n (2)MySQL\\n (3)MongoDB)[**Currently only PostgreSQL and MySQL are supported**]\");\n int dbType;\n try {\n try {\n dbType = Integer.parseInt(scanner.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getDatabaseType();\n }\n //get a map of the database types and their corresponding numbers\n Map<Integer, String> dbTypes = new HashMap<>();\n int index = 1;\n for (Enums.DatabaseType type : Enums.DatabaseType.values()) {\n dbTypes.put(index, String.valueOf(type));\n index++;\n }\n //if the user entered a valid number, return the corresponding database type\n if (dbTypes.containsKey(dbType)) {\n return Enums.DatabaseType.valueOf(dbTypes.get(dbType));\n }\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getDatabaseType();\n } catch (IllegalArgumentException e) {\n System.out.println(e.getMessage());\n return getDatabaseType();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return getDatabaseType();\n }\n return null;\n }\n public String getTableName() {\n System.out.println(\"Enter table name:\");\n return scanner.nextLine();\n }\n public Map<String, String> getColumns(Enums.DatabaseType dbType) {\n System.out.println(\"Enter number of columns:\");\n int columnCount;\n Map<String, String> columns;\n\n try {\n try {\n columnCount = Integer.parseInt(scanner.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getColumns(dbType);\n }\n columns = new HashMap<>();\n\n for (int i = 0; i < columnCount; i++) {\n System.out.println(\"Enter column name for column \" + (i + 1) + \":\");\n String columnName = scanner.nextLine();\n System.out.println(\"Enter data type for column \" + columnName + \":\");\n String dataType = promptForDataType(dbType);\n columns.put(columnName, dataType);\n }\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getColumns(dbType);\n } catch (IllegalArgumentException e) {\n System.out.println(e.getMessage());\n return getColumns(dbType);\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return getColumns(dbType);\n }\n return columns;\n }\n\n public List<String> addSQLConstraints(Enums.DatabaseType dbType) {\n List<String> constraints = new ArrayList<>();\n System.out.println(\"Do you want to add constraints? (yes/no)\");\n String addConstraints;\n String constraintSQL;\n try {\n\n try {\n addConstraints = scanner.nextLine();\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter yes or no\");\n return addSQLConstraints(dbType);\n }\n\n if (addConstraints.equalsIgnoreCase(\"yes\") || addConstraints.equalsIgnoreCase(\"y\")) {\n System.out.println(\"Enter number of constraints:\");\n int constraintCount = Integer.parseInt(scanner.nextLine());\n\n //TODO: Make this method more generic so it can be used for other databases. Maybe pass in the database type?\n// constraintSQL = getConstraint(constraintCount,dbType);\n// constraints.add(constraintSQL);\n\n for (int i = 0; i < constraintCount; i++) {\n String constraint = getConstraint(dbType);\n constraints.add(constraint);\n }\n } else if (addConstraints.equalsIgnoreCase(\"no\") || addConstraints.equalsIgnoreCase(\"n\")) {\n System.out.println(\"No constraints added\");\n } else {\n System.out.println(\"Please enter yes or no\");\n return addSQLConstraints(dbType);\n }\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return addSQLConstraints(dbType);\n } catch (IllegalArgumentException e) {\n System.out.println(\"Input \" + e.getMessage() + \" is not valid\" + \"\\nPlease enter a valid input\");\n return addSQLConstraints(dbType);\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return addSQLConstraints(dbType);\n }\n return constraints;\n }\n\n private String getConstraint(Enums.DatabaseType dbType) {\n\n //TODO: Make this method more generic so it can be used for other databases\n String constraintSQL = null;\n int constraintTypeIndex;\n String columnName;\n System.out.println(\"Choose constraint type:\");\n\n constraintTypeIndex = getConstraintValues(dbType);\n\n //Should this be a method that takes in the database type and returns the appropriate constraint types?\n DatabaseConstraintType constraintType = getSelectedConstraintType(dbType, constraintTypeIndex);\n\n System.out.println(\"Enter column name for constraint:\");\n columnName = scanner.nextLine();\n\n String additionalInput = \"\";\n if (constraintType.requiresAdditionalInput()) {\n if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) {\n System.out.println(\"Enter table name for the constraint:\");\n String tableName = scanner.nextLine();\n\n System.out.println(\"Enter column name for the constraint:\");\n String foreignKeyColumnName = scanner.nextLine();\n\n additionalInput = tableName + \"(\" + foreignKeyColumnName + \")\";\n } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) {\n System.out.println(\"Enter check condition (e.g., column_name > 5):\");\n additionalInput = scanner.nextLine();\n }\n\n // Assuming other constraint types might need a generic input\n else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE ||\n constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*||\n constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) {\n System.out.println(\"Enter additional input for the constraint:\");\n additionalInput = scanner.nextLine();\n }\n // Handle any other constraints that might need additional input\n else {\n System.out.println(\"Enter additional input for the constraint:\");\n additionalInput = scanner.nextLine();\n }\n }\n constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput);\n\n\n return constraintSQL;\n }\n\n public int getConstraintValues(Enums.DatabaseType dbType) {\n // Use the dbtype to print out the appropriate constraint types\n int constraintTypeIndex = 0;\n switch (dbType) {\n case POSTGRESQL:\n for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) {\n System.out.println(j + \": \" + Enums.PostgreSQLConstraintType.values()[j].getConstraintType());\n }\n constraintTypeIndex = Integer.parseInt(scanner.nextLine());\n return constraintTypeIndex;\n case MYSQL:\n for (int j = 0; j < Enums.MySQLConstraintType.values().length; j++) {\n System.out.println(j + \": \" + Enums.MySQLConstraintType.values()[j].getConstraintType());\n }\n constraintTypeIndex = Integer.parseInt(scanner.nextLine());\n return constraintTypeIndex;\n// case MONGODB:\n// for (int j = 0; j < Enums.MongoDBConstraintType.values().length; j++) {\n// System.out.println(j + \": \" + Enums.MongoDBConstraintType.values()[j].getConstraintType());\n// }\n// break;\n }\n return constraintTypeIndex;\n }\n\n private DatabaseConstraintType getSelectedConstraintType(Enums.DatabaseType dbType, int constraintTypeIndex) {\n switch (dbType) {\n case POSTGRESQL:\n return Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex);\n case MYSQL:\n return Enums.MySQLConstraintType.fromInt(constraintTypeIndex);\n // Add cases for other databases\n default:\n throw new IllegalArgumentException(\"Unsupported database type\");\n }\n }\n\n private String promptForDataType(Enums.DatabaseType dbType) {\n List<String> dataTypes = getDataTypesForDatabase(dbType);\n for (int i = 0; i < dataTypes.size(); i++) {\n System.out.println(i + \": \" + dataTypes.get(i));\n }\n System.out.println(\"Select the data type by number:\");\n int dataTypeIndex = scanner.nextInt();\n scanner.nextLine();\n return dataTypes.get(dataTypeIndex);\n }\n private List<String> getDataTypesForDatabase(Enums.DatabaseType dbType) {\n List<String> dataTypes = new ArrayList<>();\n switch (dbType) {\n case POSTGRESQL:\n for (Enums.PostgreSQLDataType type : Enums.PostgreSQLDataType.values()) {\n dataTypes.add(type.getType());\n }\n break;\n case MYSQL:\n for (Enums.MySQLDataType type : Enums.MySQLDataType.values()) {\n dataTypes.add(type.getType());\n }\n break;\n case MONGODB:\n for (Enums.MongoDBDataType type : Enums.MongoDBDataType.values()) {\n dataTypes.add(type.getType());\n }\n break;\n }\n return dataTypes;\n }\n\n}" } ]
import com.recondev.helpers.Enums; import com.recondev.interfaces.DatabaseScriptGenerator; import com.recondev.service.ScriptGeneratorFactory; import com.recondev.userinteraction.UserInteraction; import java.util.List; import java.util.Map;
4,971
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction(); Enums.DatabaseType dbType = ui.getDatabaseType();
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction(); Enums.DatabaseType dbType = ui.getDatabaseType();
DatabaseScriptGenerator scriptGenerator = ScriptGeneratorFactory.getScriptGenerator(dbType.getValue());
2
2023-12-29 01:53:43+00:00
8k
drSolutions-OpenSource/Utilizar_JDBC
psql/src/main/java/Main.java
[ { "identifier": "TipoTelefone", "path": "psql/src/main/java/configuracoes/TipoTelefone.java", "snippet": "public class TipoTelefone {\n\tpublic static final String CELULAR = \"Celular\";\n\tpublic static final String FIXO = \"Fixo\";\n\tpublic static final String COMERCIAL = \"Comercial\";\n\tpublic static final String FAX = \"Fax\";\n}" }, { "identifier": "TelefonesDAO", "path": "psql/src/main/java/dao/TelefonesDAO.java", "snippet": "public class TelefonesDAO {\n\tprivate Connection connection;\n\tprivate String erro;\n\n\t/**\n\t * Construtor que realiza a conexão com o banco de dados\n\t */\n\tpublic TelefonesDAO() {\n\t\tconnection = SingleConnection.getConnection();\n\t}\n\n\t/**\n\t * Salvar um telefone de usuário no banco de dados\n\t * \n\t * @param Telefones sendo as informações do telefone\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean salvar(Telefones telefone) {\n\t\tString sql = \"insert into telefones (tipo,telefone,usuariosid) values (?, ?, ?)\";\n\t\ttry {\n\t\t\tPreparedStatement insert = connection.prepareStatement(sql);\n\t\t\tinsert.setString(1, telefone.getTipo());\n\t\t\tinsert.setString(2, telefone.getTelefone());\n\t\t\tinsert.setLong(3, telefone.getUsuarioid());\n\n\t\t\tint retorno = insert.executeUpdate();\n\t\t\tconnection.commit();\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (PSQLException epsql) {\n\t\t\tepsql.printStackTrace();\n\t\t\tthis.erro = epsql.getMessage();\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Alterar telefone no banco de dados\n\t * \n\t * @param Telefones sendo as informações dp telefone\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean alterar(Telefones telefone) {\n\t\tString sql = \"update telefone set tipo = ? , telefone = ? , usuariosid = ? where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement update = connection.prepareStatement(sql);\n\t\t\tupdate.setString(1, telefone.getTipo());\n\t\t\tupdate.setString(2, telefone.getTelefone());\n\t\t\tupdate.setLong(3, telefone.getUsuarioid());\n\t\t\tupdate.setLong(4, telefone.getId());\n\t\t\tint retorno = update.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException esql) {\n\t\t\t\tesql.printStackTrace();\n\t\t\t\tthis.erro = esql.getMessage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Excluir um telefone do banco de dados\n\t * \n\t * @param Long id sendo o id do telefone\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean excluir(Long id) {\n\t\tString sql = \"delete from telefone where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement delete = connection.prepareStatement(sql);\n\t\t\tdelete.setLong(1, id);\n\t\t\tint retorno = delete.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException esql) {\n\t\t\t\tesql.printStackTrace();\n\t\t\t\tthis.erro = esql.getMessage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Listar todos os telefones do banco de dados\n\t * \n\t * @return List<Telefones> sendo a lista de telefones\n\t */\n\tpublic List<Telefones> listar() {\n\t\tList<Telefones> lista = new ArrayList<Telefones>();\n\n\t\tString sql = \"select * from telefones order by id\";\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tTelefones telefone = new Telefones();\n\t\t\t\ttelefone.setId(resultado.getLong(\"id\"));\n\t\t\t\ttelefone.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\ttelefone.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t\ttelefone.setUsuarioid(resultado.getLong(\"usuariosid\"));\n\t\t\t\tlista.add(telefone);\n\t\t\t}\n\t\t\treturn lista;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn lista;\n\t\t}\n\t}\n\n\t/**\n\t * Lista um telefone do banco de dados\n\t * \n\t * @param Long sendo o id do telefone\n\t * @return Telefones sendo o telefone\n\t */\n\tpublic Telefones buscar(Long id) {\n\t\tTelefones telefone = new Telefones();\n\n\t\tString sql = \"select * from telefones where id = \" + id;\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\ttelefone.setId(resultado.getLong(\"id\"));\n\t\t\t\ttelefone.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\ttelefone.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t\ttelefone.setUsuarioid(resultado.getLong(\"usuariosid\"));\n\t\t\t}\n\t\t\treturn telefone;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn telefone;\n\t\t}\n\t}\n\n\tpublic String getErro() {\n\t\treturn erro;\n\t}\n}" }, { "identifier": "UsuariosDAO", "path": "psql/src/main/java/dao/UsuariosDAO.java", "snippet": "public class UsuariosDAO {\n\tprivate Connection connection;\n\n\t/**\n\t * Construtor que realiza a conexão com o banco de dados\n\t */\n\tpublic UsuariosDAO() {\n\t\tconnection = SingleConnection.getConnection();\n\t}\n\n\t/**\n\t * Salvar um novo usuário no banco de dados\n\t * \n\t * @param Usuarios sendo as informações do usuário\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean salvar(Usuarios usuario) {\n\t\tString sql = \"insert into usuarios (nome,email,login,senha) values (?, ?, ?, ?)\";\n\t\ttry {\n\t\t\tPreparedStatement insert = connection.prepareStatement(sql);\n\t\t\tinsert.setString(1, usuario.getNome());\n\t\t\tinsert.setString(2, usuario.getEmail());\n\t\t\tinsert.setString(3, usuario.getLogin());\n\t\t\tinsert.setString(4, usuario.getSenha());\n\t\t\tint retorno = insert.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException sqle) {\n\t\t\t\tsqle.printStackTrace();\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Alterar um usuário no banco de dados\n\t * \n\t * @param Usuarios sendo as informações do usuário\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean alterar(Usuarios usuario) {\n\t\tString sql = \"update usuarios set nome = ? , email = ? , login = ? , senha = ? where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement update = connection.prepareStatement(sql);\n\t\t\tupdate.setString(1, usuario.getNome());\n\t\t\tupdate.setString(2, usuario.getEmail());\n\t\t\tupdate.setString(3, usuario.getLogin());\n\t\t\tupdate.setString(4, usuario.getSenha());\n\t\t\tupdate.setLong(5, usuario.getId());\n\t\t\tint retorno = update.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException sqle) {\n\t\t\t\tsqle.printStackTrace();\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Excluir um usuário do banco de dados\n\t * \n\t * @param Long id sendo o id do usuário\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean excluir(Long id) {\n\t\tString sql = \"delete from usuarios where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement delete = connection.prepareStatement(sql);\n\t\t\tdelete.setLong(1, id);\n\t\t\tint retorno = delete.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException sqle) {\n\t\t\t\tsqle.printStackTrace();\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Listar todos os usuários do banco de dados\n\t * \n\t * @return List<Usuarios> sendo a lista de usuários\n\t */\n\tpublic List<Usuarios> listar() {\n\t\tList<Usuarios> lista = new ArrayList<Usuarios>();\n\n\t\tString sql = \"select * from usuarios order by id\";\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tUsuarios usuario = new Usuarios();\n\t\t\t\tusuario.setId(resultado.getLong(\"id\"));\n\t\t\t\tusuario.setNome(resultado.getString(\"nome\"));\n\t\t\t\tusuario.setEmail(resultado.getString(\"email\"));\n\t\t\t\tusuario.setLogin(resultado.getString(\"login\"));\n\t\t\t\tusuario.setSenha(resultado.getString(\"senha\"));\n\t\t\t\tlista.add(usuario);\n\t\t\t}\n\t\t\treturn lista;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn lista;\n\t\t}\n\t}\n\n\t/**\n\t * Listar todos os usuários do banco de dados com seus telefones\n\t * \n\t * @return List<UsuarioTelefone> sendo a lista de usuários\n\t */\n\tpublic List<UsuarioTelefone> listarComTelefones() {\n\t\tList<UsuarioTelefone> lista = new ArrayList<UsuarioTelefone>();\n\n\t\tString sql = \"select usuario.nome, usuario.email, usuario.login, usuario.senha, telefone.tipo, telefone.telefone\"\n\t\t\t\t+ \"\tfrom telefones as telefone\" + \"\tinner join usuarios as usuario\"\n\t\t\t\t+ \"\ton telefone.usuariosid = usuario.id \" + \"\torder by telefone.id\";\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tUsuarioTelefone usuarioTelefone = new UsuarioTelefone();\n\t\t\t\tusuarioTelefone.setNome(resultado.getString(\"nome\"));\n\t\t\t\tusuarioTelefone.setEmail(resultado.getString(\"email\"));\n\t\t\t\tusuarioTelefone.setLogin(resultado.getString(\"login\"));\n\t\t\t\tusuarioTelefone.setSenha(resultado.getString(\"senha\"));\n\t\t\t\tusuarioTelefone.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\tusuarioTelefone.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t\tlista.add(usuarioTelefone);\n\t\t\t}\n\t\t\treturn lista;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn lista;\n\t\t}\n\t}\n\n\t/**\n\t * Listar um usuário do banco de dados\n\t * \n\t * @param Long sendo o id do usuário\n\t * @return Usuarios sendo o usuário\n\t */\n\tpublic Usuarios buscar(Long id) {\n\t\tUsuarios retorno = new Usuarios();\n\t\tString sql = \"select * from usuarios where id = ?\";\n\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tselect.setLong(1, id);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tretorno.setId(resultado.getLong(\"id\"));\n\t\t\t\tretorno.setNome(resultado.getString(\"nome\"));\n\t\t\t\tretorno.setEmail(resultado.getString(\"email\"));\n\t\t\t\tretorno.setLogin(resultado.getString(\"login\"));\n\t\t\t\tretorno.setSenha(resultado.getString(\"senha\"));\n\t\t\t}\n\t\t\treturn retorno;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn retorno;\n\t\t}\n\t}\n\n\t/**\n\t * Listar um usuário do banco de dados com seu telefone\n\t * \n\t * @param Long sendo o id do usuário\n\t * @return UsuarioTelefone sendo o usuário\n\t */\n\tpublic UsuarioTelefone buscarComTelefone(Long id) {\n\t\tUsuarioTelefone usuario = new UsuarioTelefone();\n\n\t\tString sql = \"select usuario.nome, usuario.email, usuario.login, usuario.senha, telefone.tipo, telefone.telefone\"\n\t\t\t\t+ \"\tfrom telefones as telefone\" + \"\tinner join usuarios as usuario\"\n\t\t\t\t+ \"\ton telefone.usuariosid = usuario.id \" + \"\twhere usuario.id = \" + id;\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tusuario.setNome(resultado.getString(\"nome\"));\n\t\t\t\tusuario.setEmail(resultado.getString(\"email\"));\n\t\t\t\tusuario.setLogin(resultado.getString(\"login\"));\n\t\t\t\tusuario.setSenha(resultado.getString(\"senha\"));\n\t\t\t\tusuario.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\tusuario.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t}\n\t\t\treturn usuario;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn usuario;\n\t\t}\n\t}\n\n\t/**\n\t * Gerar um hash de senha\n\t * \n\t * @param senha String sendo a senha original\n\t * @return String sendo a senha com hash\n\t */\n\tpublic String gerarSenhaHash(String senha) {\n\t\tSecureRandom random = new SecureRandom();\n\t\tbyte[] salt = new byte[16];\n\t\trandom.nextBytes(salt);\n\t\tKeySpec spec = new PBEKeySpec(senha.toCharArray(), salt, 65536, 128);\n\t\tSecretKeyFactory f;\n\t\tbyte[] hash = null;\n\t\ttry {\n\t\t\tf = SecretKeyFactory.getInstance(\"PBKDF2WithHmacSHA1\");\n\t\t\thash = f.generateSecret(spec).getEncoded();\n\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidKeySpecException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tBase64.Encoder enc = Base64.getEncoder();\n\t\treturn enc.encodeToString(hash);\n\t}\n}" }, { "identifier": "Telefones", "path": "psql/src/main/java/model/Telefones.java", "snippet": "public class Telefones {\n\tprivate Long id;\n\tprivate String tipo;\n\tprivate String telefone;\n\tprivate Long usuarioid;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Long getUsuarioid() {\n\t\treturn usuarioid;\n\t}\n\n\tpublic void setUsuarioid(Long usuarioid) {\n\t\tthis.usuarioid = usuarioid;\n\t}\n\n\tpublic String getTipo() {\n\t\treturn tipo;\n\t}\n\n\tpublic void setTipo(String tipo) {\n\t\tthis.tipo = tipo;\n\t}\n\n\tpublic String getTelefone() {\n\t\treturn telefone;\n\t}\n\n\tpublic void setTelefone(String telefone) {\n\t\tthis.telefone = telefone;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Telefones [id=\" + id + \", tipo=\" + tipo + \", telefone=\" + telefone + \", usuarioid=\" + usuarioid + \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, telefone, tipo, usuarioid);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tTelefones other = (Telefones) obj;\n\t\treturn Objects.equals(id, other.id) && Objects.equals(telefone, other.telefone)\n\t\t\t\t&& Objects.equals(tipo, other.tipo) && Objects.equals(usuarioid, other.usuarioid);\n\t}\n}" }, { "identifier": "UsuarioTelefone", "path": "psql/src/main/java/model/UsuarioTelefone.java", "snippet": "public class UsuarioTelefone {\n\tString nome;\n\tString email;\n\tString login;\n\tString senha;\n\tString tipo;\n\tString telefone;\n\n\tpublic String getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getTipo() {\n\t\treturn tipo;\n\t}\n\n\tpublic void setTipo(String tipo) {\n\t\tthis.tipo = tipo;\n\t}\n\n\tpublic String getTelefone() {\n\t\treturn telefone;\n\t}\n\n\tpublic void setTelefone(String telefone) {\n\t\tthis.telefone = telefone;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getSenha() {\n\t\treturn senha;\n\t}\n\n\tpublic void setSenha(String senha) {\n\t\tthis.senha = senha;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UsuarioTelefone [nome=\" + nome + \", email=\" + email + \", login=\" + login + \", senha=\" + senha\n\t\t\t\t+ \", tipo=\" + tipo + \", telefone=\" + telefone + \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(email, login, nome, senha, telefone, tipo);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tUsuarioTelefone other = (UsuarioTelefone) obj;\n\t\treturn Objects.equals(email, other.email) && Objects.equals(login, other.login)\n\t\t\t\t&& Objects.equals(nome, other.nome) && Objects.equals(senha, other.senha)\n\t\t\t\t&& Objects.equals(telefone, other.telefone) && Objects.equals(tipo, other.tipo);\n\t}\n}" }, { "identifier": "Usuarios", "path": "psql/src/main/java/model/Usuarios.java", "snippet": "public class Usuarios {\n\tprivate Long id;\n\tprivate String nome;\n\tprivate String email;\n\tprivate String login;\n\tprivate String senha;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getSenha() {\n\t\treturn senha;\n\t}\n\n\tpublic void setSenha(String senha) {\n\t\tthis.senha = senha;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Usuarios [id=\" + id + \", nome=\" + nome + \", email=\" + email + \", login=\" + login + \", senha=\" + senha\n\t\t\t\t+ \"]\";\n\t}\n}" } ]
import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.List; import configuracoes.TipoTelefone; import dao.TelefonesDAO; import dao.UsuariosDAO; import model.Telefones; import model.UsuarioTelefone; import model.Usuarios;
6,016
/** * Utilizar o JDBC (Java Database Connectivity) com o banco de dados PostgreSQL * 13.10 Utilizou-se a plataforma ElephantSQL - PostgreSQL as a Service como a * provedora do banco de dados Foram criadas 2 tabelas: - Usuarios: id (UNIQUE), * nome, email, login e senha - Telefones: id (PK), tipo, telefone e usuariosid * . O campo usuariosid é uma FK para a tabela Usuarios, com ON DELETE CASCADE . * No campo tipo, pode-se apenas preencher 'Celular', 'Fixo', 'Comercial' ou * 'Fax' * * @author Diego Mendes Rodrigues * @version 1.0 */ public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // incluirUsuario(); // alterarUsuario(); listarUsuarios(); // incluirTelefone(); listarTelefones(); /* Listagens utilizando INNER JOIN */ listarUsuariosComTelefones(); listarUmUsuario(); } /** * Incluir um usuário na tabela Usuarios */ public static void incluirUsuario() { System.out.println("# Cadastrar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); // usuario.setNome("Diego Rodrigues"); // usuario.setEmail("[email protected]"); // usuario.setLogin("drodrigues"); // String senha = dao.gerarSenhaHash("senha2023"); // usuario.setSenha(senha); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoFada"); usuario.setSenha(senha); if (dao.salvar(usuario)) { System.out.println("Usuário incluído com sucesso"); } else { System.out.println("Falha ao incluir o usuário"); } } /** * Alterar um usuário na tabela Usuarios */ public static void alterarUsuario() { System.out.println("# Alterar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); System.out.println("# Cadastrar um usuário"); usuario.setId(2L); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoF@da88"); usuario.setSenha(senha); if (dao.alterar(usuario)) { System.out.println("Usuário alterado com sucesso"); } else { System.out.println("Falha ao alterado o usuário"); } } /** * Listar todos os usuários da tabela Usuarios */ public static void listarUsuarios() { System.out.println("# Listar os usuários"); UsuariosDAO dao = new UsuariosDAO(); List<Usuarios> listaUsuarios = new ArrayList<Usuarios>(); listaUsuarios = dao.listar(); for (Usuarios usuario : listaUsuarios) { System.out.println(usuario.toString()); } } /** * Incluir um telefone na tabela Telefones */ public static void incluirTelefone() { System.out.println("# Cadastrar um telefone"); TelefonesDAO dao = new TelefonesDAO(); Telefones telefone = new Telefones(); // telefone.setTipo(TipoTelefone.CELULAR); // telefone.setTelefone("(11) 98355-4235"); // telefone.setUsuarioid(1L); // telefone.setTipo(TipoTelefone.COMERCIAL); // telefone.setTelefone("(12) 98657-8745"); // telefone.setUsuarioid(1L); telefone.setTipo(TipoTelefone.CELULAR); telefone.setTelefone("(19) 98789-3456"); telefone.setUsuarioid(2L); if (dao.salvar(telefone)) { System.out.println("Telefone incluído com sucesso"); } else { System.out.println("Falha ao incluir o telefone"); } } /** * Listar todos os telefones da tabela Telefones */ public static void listarTelefones() { System.out.println("# Listar os telefones"); TelefonesDAO dao = new TelefonesDAO(); List<Telefones> listaTelefones = new ArrayList<Telefones>(); listaTelefones = dao.listar(); for (Telefones telefone : listaTelefones) { System.out.println(telefone.toString()); } } /** * Listar todos os usuários (tabela Usuários) com os telefones (tabela * Telefones) utilizando INNER JOIN */ public static void listarUsuariosComTelefones() { System.out.println("# Listar os usuários com telefones"); UsuariosDAO dao = new UsuariosDAO();
/** * Utilizar o JDBC (Java Database Connectivity) com o banco de dados PostgreSQL * 13.10 Utilizou-se a plataforma ElephantSQL - PostgreSQL as a Service como a * provedora do banco de dados Foram criadas 2 tabelas: - Usuarios: id (UNIQUE), * nome, email, login e senha - Telefones: id (PK), tipo, telefone e usuariosid * . O campo usuariosid é uma FK para a tabela Usuarios, com ON DELETE CASCADE . * No campo tipo, pode-se apenas preencher 'Celular', 'Fixo', 'Comercial' ou * 'Fax' * * @author Diego Mendes Rodrigues * @version 1.0 */ public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // incluirUsuario(); // alterarUsuario(); listarUsuarios(); // incluirTelefone(); listarTelefones(); /* Listagens utilizando INNER JOIN */ listarUsuariosComTelefones(); listarUmUsuario(); } /** * Incluir um usuário na tabela Usuarios */ public static void incluirUsuario() { System.out.println("# Cadastrar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); // usuario.setNome("Diego Rodrigues"); // usuario.setEmail("[email protected]"); // usuario.setLogin("drodrigues"); // String senha = dao.gerarSenhaHash("senha2023"); // usuario.setSenha(senha); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoFada"); usuario.setSenha(senha); if (dao.salvar(usuario)) { System.out.println("Usuário incluído com sucesso"); } else { System.out.println("Falha ao incluir o usuário"); } } /** * Alterar um usuário na tabela Usuarios */ public static void alterarUsuario() { System.out.println("# Alterar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); System.out.println("# Cadastrar um usuário"); usuario.setId(2L); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoF@da88"); usuario.setSenha(senha); if (dao.alterar(usuario)) { System.out.println("Usuário alterado com sucesso"); } else { System.out.println("Falha ao alterado o usuário"); } } /** * Listar todos os usuários da tabela Usuarios */ public static void listarUsuarios() { System.out.println("# Listar os usuários"); UsuariosDAO dao = new UsuariosDAO(); List<Usuarios> listaUsuarios = new ArrayList<Usuarios>(); listaUsuarios = dao.listar(); for (Usuarios usuario : listaUsuarios) { System.out.println(usuario.toString()); } } /** * Incluir um telefone na tabela Telefones */ public static void incluirTelefone() { System.out.println("# Cadastrar um telefone"); TelefonesDAO dao = new TelefonesDAO(); Telefones telefone = new Telefones(); // telefone.setTipo(TipoTelefone.CELULAR); // telefone.setTelefone("(11) 98355-4235"); // telefone.setUsuarioid(1L); // telefone.setTipo(TipoTelefone.COMERCIAL); // telefone.setTelefone("(12) 98657-8745"); // telefone.setUsuarioid(1L); telefone.setTipo(TipoTelefone.CELULAR); telefone.setTelefone("(19) 98789-3456"); telefone.setUsuarioid(2L); if (dao.salvar(telefone)) { System.out.println("Telefone incluído com sucesso"); } else { System.out.println("Falha ao incluir o telefone"); } } /** * Listar todos os telefones da tabela Telefones */ public static void listarTelefones() { System.out.println("# Listar os telefones"); TelefonesDAO dao = new TelefonesDAO(); List<Telefones> listaTelefones = new ArrayList<Telefones>(); listaTelefones = dao.listar(); for (Telefones telefone : listaTelefones) { System.out.println(telefone.toString()); } } /** * Listar todos os usuários (tabela Usuários) com os telefones (tabela * Telefones) utilizando INNER JOIN */ public static void listarUsuariosComTelefones() { System.out.println("# Listar os usuários com telefones"); UsuariosDAO dao = new UsuariosDAO();
List<UsuarioTelefone> listaUsuariosTelefones = new ArrayList<UsuarioTelefone>();
4
2023-12-30 14:50:31+00:00
8k
JoshiCodes/NewLabyAPI
src/main/java/de/joshicodes/newlabyapi/api/LabyModAPI.java
[ { "identifier": "LabyModProtocol", "path": "src/main/java/de/joshicodes/newlabyapi/LabyModProtocol.java", "snippet": "public class LabyModProtocol {\n\n /**\n * Send a message to LabyMod\n * @param player Minecraft Client\n * @param key LabyMod message key\n * @param messageContent json object content\n */\n public static void sendLabyModMessage(Player player, String key, JsonElement messageContent ) {\n\n // Send Plugin Message to Player\n // a String consists of two components:\n // - varint: the string's length\n // - byte-array: the string's content\n //\n // The packet's data consists of two strings:\n // - the message's key\n // - the message's contents\n\n // Getting the bytes that should be sent\n byte[] bytes = getBytesToSend( key, messageContent.toString() );\n\n // Sending the bytes to the player\n player.sendPluginMessage( NewLabyPlugin.getInstance(), \"labymod3:main\", bytes );\n\n }\n\n /**\n * Gets the bytes that are required to send the given message\n *\n * @param messageKey the message's key\n * @param messageContents the message's contents\n * @return the byte array that should be the payload\n */\n public static byte[] getBytesToSend( String messageKey, String messageContents ) {\n // Getting an empty buffer\n ByteBuf byteBuf = Unpooled.buffer();\n\n // Writing the message-key to the buffer\n writeString( byteBuf, messageKey );\n\n // Writing the contents to the buffer\n writeString( byteBuf, messageContents );\n\n // Copying the buffer's bytes to the byte array\n byte[] bytes = new byte[byteBuf.readableBytes()];\n byteBuf.readBytes( bytes );\n\n // Release the buffer\n byteBuf.release();\n\n // Returning the byte array\n return bytes;\n }\n\n /**\n * Writes a varint to the given byte buffer\n *\n * @param buf the byte buffer the int should be written to\n * @param input the int that should be written to the buffer\n */\n private static void writeVarIntToBuffer( ByteBuf buf, int input ) {\n while ( (input & -128) != 0 ) {\n buf.writeByte( input & 127 | 128 );\n input >>>= 7;\n }\n\n buf.writeByte( input );\n }\n\n /**\n * Writes a string to the given byte buffer\n *\n * @param buf the byte buffer the string should be written to\n * @param string the string that should be written to the buffer\n */\n private static void writeString( ByteBuf buf, String string ) {\n byte[] abyte = string.getBytes(StandardCharsets.UTF_8);\n\n if ( abyte.length > Short.MAX_VALUE ) {\n throw new EncoderException( \"String too big (was \" + string.length() + \" bytes encoded, max \" + Short.MAX_VALUE + \")\" );\n } else {\n writeVarIntToBuffer( buf, abyte.length );\n buf.writeBytes( abyte );\n }\n }\n\n /**\n * Reads a varint from the given byte buffer\n *\n * @param buf the byte buffer the varint should be read from\n * @return the int read\n */\n public static int readVarIntFromBuffer( ByteBuf buf ) {\n int i = 0;\n int j = 0;\n\n byte b0;\n do {\n b0 = buf.readByte();\n i |= (b0 & 127) << j++ * 7;\n if ( j > 5 ) {\n throw new RuntimeException( \"VarInt too big\" );\n }\n } while ( (b0 & 128) == 128 );\n\n return i;\n }\n\n /**\n * Reads a string from the given byte buffer\n *\n * @param buf the byte buffer the string should be read from\n * @param maxLength the string's max-length\n * @return the string read\n */\n public static String readString( ByteBuf buf, int maxLength ) {\n int i = readVarIntFromBuffer( buf );\n\n if ( i > maxLength * 4 ) {\n throw new DecoderException( \"The received encoded string buffer length is longer than maximum allowed (\" + i + \" > \" + maxLength * 4 + \")\" );\n } else if ( i < 0 ) {\n throw new DecoderException( \"The received encoded string buffer length is less than zero! Weird string!\" );\n } else {\n byte[] bytes = new byte[i];\n buf.readBytes( bytes );\n\n String s = new String( bytes, StandardCharsets.UTF_8);\n if ( s.length() > maxLength ) {\n throw new DecoderException( \"The received string length is longer than maximum allowed (\" + i + \" > \" + maxLength + \")\" );\n } else {\n return s;\n }\n }\n }\n\n}" }, { "identifier": "NewLabyPlugin", "path": "src/main/java/de/joshicodes/newlabyapi/NewLabyPlugin.java", "snippet": "public final class NewLabyPlugin extends JavaPlugin {\n\n public static final Component PREFIX = MiniMessage.miniMessage().deserialize(\n \"<b><gradient:#227eb8:#53bbfb>NewLabyAPI</gradient></b> <gray>»</gray>\"\n );\n\n private static NewLabyPlugin instance;\n\n @Override\n public void onEnable() {\n instance = this;\n\n if (!getDataFolder().exists())\n getDataFolder().mkdir();\n saveDefaultConfig();\n\n LabyModAPI.init(this);\n\n getServer().getMessenger().registerIncomingPluginChannel(this, \"labymod3:main\", new LabyPluginMessageListener());\n getServer().getMessenger().registerOutgoingPluginChannel(this, \"labymod3:main\");\n\n PluginManager pluginManager = getServer().getPluginManager();\n pluginManager.registerEvents(new PlayerListener(), this);\n\n pluginManager.registerEvents(new ConfigListener(getConfig()), this);\n\n if (getConfig().getBoolean(\"updateChecks.enabled\", true)) {\n final NewLabyPlugin instance = this;\n new BukkitRunnable() {\n @Override\n public void run() {\n getLogger().info(\"Checking for updates...\");\n String version = getDescription().getVersion();\n if (version.contains(\"-dev\")) {\n // Don't check for updates if the version is a dev version\n getLogger().info(\"You are running a dev version, so no update check will be performed!\");\n return;\n }\n UpdateChecker updateChecker = new UpdateChecker(instance);\n try {\n updateChecker.checkForUpdate();\n } catch (IOException e) {\n getLogger().warning(\"Could not check for updates!\");\n return;\n }\n if (!updateChecker.isUpToDate()) {\n final String url = \"https://github.com/JoshiCodes/NewLabyAPI/releases/latest\";\n final String current = getDescription().getVersion();\n getLogger().info(\" \");\n getLogger().info(\" \");\n getLogger().info(\"There is a new version available! (\" + updateChecker.getLatestVersion() + \")\");\n getLogger().info(\"You are running:\" + current);\n getLogger().info(\"Download it here: \" + url);\n if (getConfig().getBoolean(\"updateChecks.joinNotify\", true)) {\n final String permission = getConfig().getString(\"updateChecks.joinNotifyPerm\", \"newlabyapi.update\");\n pluginManager.registerEvents(new Listener() {\n @EventHandler\n public void onJoin(PlayerJoinEvent e) {\n if (e.getPlayer().hasPermission(permission)) {\n e.getPlayer().sendMessage(Component.space());\n e.getPlayer().sendMessage(\n Component.join(\n JoinConfiguration.separator(Component.space()),\n PREFIX,\n MiniMessage.miniMessage().deserialize(\n \"<gradient:#227eb8:#53bbfb>There is a new version available! (\" + updateChecker.getLatestVersion() + \")</gradient>\"\n )\n )\n );\n e.getPlayer().sendMessage(\n Component.join(\n JoinConfiguration.separator(Component.space()),\n PREFIX,\n MiniMessage.miniMessage().deserialize(\n \"<gradient:#227eb8:#53bbfb>You are running:</gradient> <b><color:#53bbfb>\" + current + \"</color></b>\"\n )\n )\n );\n e.getPlayer().sendMessage(\n Component.join(\n JoinConfiguration.separator(Component.space()),\n PREFIX,\n MiniMessage.miniMessage().deserialize(\n \"<gradient:#227eb8:#53bbfb>Download it here:</gradient> <b><color:#53bbfb><click:open_url:'\" + url + \"'>\" + url + \"</click></color></b>\"\n )\n )\n );\n }\n }\n }, instance);\n }\n } else {\n getLogger().info(\"You are running the latest version!\");\n }\n }\n }.runTaskLater(this, 20);\n }\n\n }\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n\n public static NewLabyPlugin getInstance() {\n return instance;\n }\n\n public static void debug(String s) {\n NewLabyPlugin instance = NewLabyPlugin.getInstance();\n if (instance.getConfig().getBoolean(\"debug\")) {\n instance.getLogger().info(\"[DEBUG] \" + s);\n }\n }\n\n}" }, { "identifier": "LabyModPlayerJoinEvent", "path": "src/main/java/de/joshicodes/newlabyapi/api/event/player/LabyModPlayerJoinEvent.java", "snippet": "public class LabyModPlayerJoinEvent extends LabyModPlayerEvent {\n\n private final String rawJson;\n\n public LabyModPlayerJoinEvent(LabyModPlayer player, String json) {\n super(player);\n this.rawJson = json;\n }\n\n public String getRawJson() {\n return rawJson;\n }\n\n @Override\n public HandlerList getHandlers() {\n return super.getHandlers();\n }\n\n}" }, { "identifier": "InputPrompt", "path": "src/main/java/de/joshicodes/newlabyapi/api/object/InputPrompt.java", "snippet": "public class InputPrompt implements LabyProtocolObject {\n\n private int id;\n private String message;\n private String value;\n private String placeholder;\n private int maxLength;\n\n /**\n * @param id A unique id for each packet, use a static number and increase it for each prompt request\n * @param message The message above the text field\n * @param value The value inside of the text field\n * @param placeholder A placeholder text inside of the text field if there is no value given\n * @param maxLength Max amount of characters of the text field value\n */\n public InputPrompt(final int id, String message, String value, String placeholder, int maxLength) {\n this.id = id;\n this.message = message;\n this.value = value;\n this.placeholder = placeholder;\n this.maxLength = maxLength;\n }\n\n /**\n * @param id A unique id for each packet, use a static number and increase it for each prompt request\n * @param message The message above the text field\n * @param value The value inside of the text field\n * @param placeholder A placeholder text inside of the text field if there is no value given\n */\n public InputPrompt(final int id, String message, String value, String placeholder) {\n this(id, message, value, placeholder, 0);\n }\n\n public InputPrompt setMessage(String message) {\n this.message = message;\n return this;\n }\n\n public InputPrompt setValue(String value) {\n this.value = value;\n return this;\n }\n\n public InputPrompt setPlaceholder(String placeholder) {\n this.placeholder = placeholder;\n return this;\n }\n\n public InputPrompt setMaxLength(int maxLength) {\n this.maxLength = maxLength;\n return this;\n }\n\n @Override\n public JsonObject toJson() {\n JsonObject object = new JsonObject();\n object.addProperty(\"id\", id);\n if(message != null)\n object.addProperty(\"message\", message);\n if(value != null)\n object.addProperty(\"value\", value);\n if(placeholder != null)\n object.addProperty(\"placeholder\", placeholder);\n if(maxLength > 0)\n object.addProperty(\"max_length\", maxLength);\n return object;\n }\n\n}" }, { "identifier": "LabyModPlayerSubtitle", "path": "src/main/java/de/joshicodes/newlabyapi/api/object/LabyModPlayerSubtitle.java", "snippet": "public class LabyModPlayerSubtitle implements LabyProtocolObject {\n\n private final UUID uuid;\n private double size;\n private @Nullable String value;\n private @Nullable Component valueComponent;\n\n public LabyModPlayerSubtitle(final UUID uuid) {\n this.uuid = uuid;\n this.value = null;\n this.size = 0.8d;\n }\n\n public LabyModPlayerSubtitle(final UUID uuid, final double size, final @Nullable String value) {\n this.uuid = uuid;\n this.value = value;\n setSize(size);\n }\n\n public LabyModPlayerSubtitle(final UUID uuid, final double size, final @Nullable Component valueComponent) {\n this.uuid = uuid;\n this.valueComponent = valueComponent;\n setSize(size);\n }\n\n /**\n * Set the size of the subtitle<br>\n * This should be between 0.8 and 1.6.\n * @param size The size of the subtitle\n * @throws IllegalArgumentException if the size is not between 0.8 and 1.6\n * @return The current instance\n */\n public LabyModPlayerSubtitle setSize(double size) {\n if(size < 0.8 || size > 1.6) throw new IllegalArgumentException(\"Size must be between 0.8 and 1.6\");\n this.size = size;\n return this;\n }\n\n /**\n * Set the subtitle text. <br>\n * Set to null to remove the subtitle.\n * @param value The subtitle text or null\n * @return The current instance\n */\n public LabyModPlayerSubtitle setValue(@Nullable String value) {\n this.value = value;\n return this;\n }\n\n /**\n * Set the subtitle text. <br>\n * Set to null to remove the subtitle.\n * @param value The subtitle text or null\n * @return The current instance\n */\n public LabyModPlayerSubtitle setValue(@Nullable Component value) {\n this.valueComponent = value;\n return this;\n }\n\n public UUID getUUID() {\n return uuid;\n }\n\n public double getSize() {\n return size;\n }\n\n @Nullable\n public String getValue() {\n return value;\n }\n\n @Nullable\n public Component getValueComponent() {\n return valueComponent;\n }\n\n @Override\n public JsonElement toJson() {\n JsonObject object = new JsonObject();\n object.addProperty(\"uuid\", uuid.toString());\n object.addProperty(\"size\", size);\n if(valueComponent != null)\n object.addProperty(\"raw_json_text\", JSONComponentSerializer.json().serialize(valueComponent));\n else if(value != null)\n object.addProperty(\"value\", value);\n return object;\n }\n\n}" }, { "identifier": "LabyProtocolObject", "path": "src/main/java/de/joshicodes/newlabyapi/api/object/LabyProtocolObject.java", "snippet": "public interface LabyProtocolObject {\n\n JsonElement toJson();\n\n}" } ]
import com.google.gson.JsonObject; import de.joshicodes.newlabyapi.LabyModProtocol; import de.joshicodes.newlabyapi.NewLabyPlugin; import de.joshicodes.newlabyapi.api.event.player.LabyModPlayerJoinEvent; import de.joshicodes.newlabyapi.api.object.InputPrompt; import de.joshicodes.newlabyapi.api.object.LabyModPlayerSubtitle; import de.joshicodes.newlabyapi.api.object.LabyProtocolObject; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID;
4,253
package de.joshicodes.newlabyapi.api; public class LabyModAPI { private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>(); private static boolean updateExistingPlayersOnJoin = false; public static void init(NewLabyPlugin plugin) { updateExistingPlayersOnJoin = plugin.getConfig().getBoolean("updateExistingPlayersOnJoin", true); } public static void sendObject(Player player, String key, LabyProtocolObject obj) { LabyModProtocol.sendLabyModMessage(player, key, obj.toJson()); } public static void sendPrompt(Player player, InputPrompt prompt) { LabyModProtocol.sendLabyModMessage(player, "input_prompt", prompt.toJson()); } public static LabyModPlayer getLabyModPlayer(Player player) { if (!labyModPlayers.containsKey(player)) return null; return labyModPlayers.get(player); } public static LabyModPlayer getLabyModPlayer(UUID uuid) { for (Player player : labyModPlayers.keySet()) { if (player.getUniqueId().equals(uuid)) return labyModPlayers.get(player); } return null; } public static void executeLabyModJoin(Player player, String version, String json) { LabyModPlayer labyModPlayer = new LabyModPlayer(player, version); labyModPlayers.put(player, labyModPlayer); LabyModPlayerJoinEvent event = new LabyModPlayerJoinEvent(labyModPlayer, json); player.getServer().getPluginManager().callEvent(event); // Update existing players (if enabled) if (!updateExistingPlayersOnJoin) return; NewLabyPlugin.debug("Updating existing players for " + player.getName() + " (" + player.getUniqueId() + ")"); new BukkitRunnable() { @Override public void run() {
package de.joshicodes.newlabyapi.api; public class LabyModAPI { private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>(); private static boolean updateExistingPlayersOnJoin = false; public static void init(NewLabyPlugin plugin) { updateExistingPlayersOnJoin = plugin.getConfig().getBoolean("updateExistingPlayersOnJoin", true); } public static void sendObject(Player player, String key, LabyProtocolObject obj) { LabyModProtocol.sendLabyModMessage(player, key, obj.toJson()); } public static void sendPrompt(Player player, InputPrompt prompt) { LabyModProtocol.sendLabyModMessage(player, "input_prompt", prompt.toJson()); } public static LabyModPlayer getLabyModPlayer(Player player) { if (!labyModPlayers.containsKey(player)) return null; return labyModPlayers.get(player); } public static LabyModPlayer getLabyModPlayer(UUID uuid) { for (Player player : labyModPlayers.keySet()) { if (player.getUniqueId().equals(uuid)) return labyModPlayers.get(player); } return null; } public static void executeLabyModJoin(Player player, String version, String json) { LabyModPlayer labyModPlayer = new LabyModPlayer(player, version); labyModPlayers.put(player, labyModPlayer); LabyModPlayerJoinEvent event = new LabyModPlayerJoinEvent(labyModPlayer, json); player.getServer().getPluginManager().callEvent(event); // Update existing players (if enabled) if (!updateExistingPlayersOnJoin) return; NewLabyPlugin.debug("Updating existing players for " + player.getName() + " (" + player.getUniqueId() + ")"); new BukkitRunnable() { @Override public void run() {
List<LabyModPlayerSubtitle> subtitles = new ArrayList<>();
4
2023-12-24 15:00:08+00:00
8k
1752597830/admin-common
qf-admin/back/admin-init-main/src/main/java/com/qf/server/Server.java
[ { "identifier": "Arith", "path": "qf-admin/back/admin-init-main/src/main/java/com/qf/server/util/Arith.java", "snippet": "public class Arith\n{\n\n /** 默认除法运算精度 */\n private static final int DEF_DIV_SCALE = 10;\n\n /** 这个类不能实例化 */\n private Arith()\n {\n }\n\n /**\n * 提供精确的加法运算。\n * @param v1 被加数\n * @param v2 加数\n * @return 两个参数的和\n */\n public static double add(double v1, double v2)\n {\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n return b1.add(b2).doubleValue();\n }\n\n /**\n * 提供精确的减法运算。\n * @param v1 被减数\n * @param v2 减数\n * @return 两个参数的差\n */\n public static double sub(double v1, double v2)\n {\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n return b1.subtract(b2).doubleValue();\n }\n\n /**\n * 提供精确的乘法运算。\n * @param v1 被乘数\n * @param v2 乘数\n * @return 两个参数的积\n */\n public static double mul(double v1, double v2)\n {\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n return b1.multiply(b2).doubleValue();\n }\n\n /**\n * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到\n * 小数点以后10位,以后的数字四舍五入。\n * @param v1 被除数\n * @param v2 除数\n * @return 两个参数的商\n */\n public static double div(double v1, double v2)\n {\n return div(v1, v2, DEF_DIV_SCALE);\n }\n\n /**\n * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指\n * 定精度,以后的数字四舍五入。\n * @param v1 被除数\n * @param v2 除数\n * @param scale 表示表示需要精确到小数点以后几位。\n * @return 两个参数的商\n */\n public static double div(double v1, double v2, int scale)\n {\n if (scale < 0)\n {\n throw new IllegalArgumentException(\n \"The scale must be a positive integer or zero\");\n }\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n if (b1.compareTo(BigDecimal.ZERO) == 0)\n {\n return BigDecimal.ZERO.doubleValue();\n }\n return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();\n }\n\n /**\n * 提供精确的小数位四舍五入处理。\n * @param v 需要四舍五入的数字\n * @param scale 小数点后保留几位\n * @return 四舍五入后的结果\n */\n public static double round(double v, int scale)\n {\n if (scale < 0)\n {\n throw new IllegalArgumentException(\n \"The scale must be a positive integer or zero\");\n }\n BigDecimal b = new BigDecimal(Double.toString(v));\n BigDecimal one = BigDecimal.ONE;\n return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();\n }\n}" }, { "identifier": "IpUtils", "path": "qf-admin/back/admin-init-main/src/main/java/com/qf/server/util/IpUtils.java", "snippet": "public class IpUtils\n{\n public final static String REGX_0_255 = \"(25[0-5]|2[0-4]\\\\d|1\\\\d{2}|[1-9]\\\\d|\\\\d)\";\n // 匹配 ip\n public final static String REGX_IP = \"((\" + REGX_0_255 + \"\\\\.){3}\" + REGX_0_255 + \")\";\n public final static String REGX_IP_WILDCARD = \"(((\\\\*\\\\.){3}\\\\*)|(\" + REGX_0_255 + \"(\\\\.\\\\*){3})|(\" + REGX_0_255 + \"\\\\.\" + REGX_0_255 + \")(\\\\.\\\\*){2}\" + \"|((\" + REGX_0_255 + \"\\\\.){3}\\\\*))\";\n // 匹配网段\n public final static String REGX_IP_SEG = \"(\" + REGX_IP + \"\\\\-\" + REGX_IP + \")\";\n\n /**\n * 获取客户端IP\n * \n * @return IP地址\n */\n //public static String getIpAddr()\n //{\n // return getIpAddr(ServletUtils.getRequest());\n //}\n\n /**\n * 获取客户端IP\n * \n * @param request 请求对象\n * @return IP地址\n */\n public static String getIpAddr(HttpServletRequest request)\n {\n if (request == null)\n {\n return \"unknown\";\n }\n String ip = request.getHeader(\"x-forwarded-for\");\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"X-Forwarded-For\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"X-Real-IP\");\n }\n\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getRemoteAddr();\n }\n\n return \"0:0:0:0:0:0:0:1\".equals(ip) ? \"127.0.0.1\" : getMultistageReverseProxyIp(ip);\n }\n\n /**\n * 检查是否为内部IP地址\n * \n * @param ip IP地址\n * @return 结果\n */\n public static boolean internalIp(String ip)\n {\n byte[] addr = textToNumericFormatV4(ip);\n return internalIp(addr) || \"127.0.0.1\".equals(ip);\n }\n\n /**\n * 检查是否为内部IP地址\n * \n * @param addr byte地址\n * @return 结果\n */\n private static boolean internalIp(byte[] addr)\n {\n if (addr == null || addr.length < 2)\n {\n return true;\n }\n final byte b0 = addr[0];\n final byte b1 = addr[1];\n // 10.x.x.x/8\n final byte SECTION_1 = 0x0A;\n // 172.16.x.x/12\n final byte SECTION_2 = (byte) 0xAC;\n final byte SECTION_3 = (byte) 0x10;\n final byte SECTION_4 = (byte) 0x1F;\n // 192.168.x.x/16\n final byte SECTION_5 = (byte) 0xC0;\n final byte SECTION_6 = (byte) 0xA8;\n switch (b0)\n {\n case SECTION_1:\n return true;\n case SECTION_2:\n if (b1 >= SECTION_3 && b1 <= SECTION_4)\n {\n return true;\n }\n case SECTION_5:\n switch (b1)\n {\n case SECTION_6:\n return true;\n }\n default:\n return false;\n }\n }\n\n /**\n * 将IPv4地址转换成字节\n * \n * @param text IPv4地址\n * @return byte 字节\n */\n public static byte[] textToNumericFormatV4(String text)\n {\n if (text.length() == 0)\n {\n return null;\n }\n\n byte[] bytes = new byte[4];\n String[] elements = text.split(\"\\\\.\", -1);\n try\n {\n long l;\n int i;\n switch (elements.length)\n {\n case 1:\n l = Long.parseLong(elements[0]);\n if ((l < 0L) || (l > 4294967295L))\n {\n return null;\n }\n bytes[0] = (byte) (int) (l >> 24 & 0xFF);\n bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);\n bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);\n bytes[3] = (byte) (int) (l & 0xFF);\n break;\n case 2:\n l = Integer.parseInt(elements[0]);\n if ((l < 0L) || (l > 255L))\n {\n return null;\n }\n bytes[0] = (byte) (int) (l & 0xFF);\n l = Integer.parseInt(elements[1]);\n if ((l < 0L) || (l > 16777215L))\n {\n return null;\n }\n bytes[1] = (byte) (int) (l >> 16 & 0xFF);\n bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);\n bytes[3] = (byte) (int) (l & 0xFF);\n break;\n case 3:\n for (i = 0; i < 2; ++i)\n {\n l = Integer.parseInt(elements[i]);\n if ((l < 0L) || (l > 255L))\n {\n return null;\n }\n bytes[i] = (byte) (int) (l & 0xFF);\n }\n l = Integer.parseInt(elements[2]);\n if ((l < 0L) || (l > 65535L))\n {\n return null;\n }\n bytes[2] = (byte) (int) (l >> 8 & 0xFF);\n bytes[3] = (byte) (int) (l & 0xFF);\n break;\n case 4:\n for (i = 0; i < 4; ++i)\n {\n l = Integer.parseInt(elements[i]);\n if ((l < 0L) || (l > 255L))\n {\n return null;\n }\n bytes[i] = (byte) (int) (l & 0xFF);\n }\n break;\n default:\n return null;\n }\n }\n catch (NumberFormatException e)\n {\n return null;\n }\n return bytes;\n }\n\n /**\n * 获取IP地址\n * \n * @return 本地IP地址\n */\n public static String getHostIp()\n {\n try\n {\n return InetAddress.getLocalHost().getHostAddress();\n }\n catch (UnknownHostException e)\n {\n }\n return \"127.0.0.1\";\n }\n\n /**\n * 获取主机名\n * \n * @return 本地主机名\n */\n public static String getHostName()\n {\n try\n {\n return InetAddress.getLocalHost().getHostName();\n }\n catch (UnknownHostException e)\n {\n }\n return \"未知\";\n }\n\n /**\n * 从多级反向代理中获得第一个非unknown IP地址\n *\n * @param ip 获得的IP地址\n * @return 第一个非unknown IP地址\n */\n public static String getMultistageReverseProxyIp(String ip)\n {\n // 多级反向代理检测\n if (ip != null && ip.indexOf(\",\") > 0)\n {\n final String[] ips = ip.trim().split(\",\");\n for (String subIp : ips)\n {\n if (false == isUnknown(subIp))\n {\n ip = subIp;\n break;\n }\n }\n }\n return StringUtils.substring(ip, 0, 255);\n }\n\n /**\n * 检测给定字符串是否为未知,多用于检测HTTP请求相关\n *\n * @param checkString 被检测的字符串\n * @return 是否未知\n */\n public static boolean isUnknown(String checkString)\n {\n return StringUtils.isBlank(checkString) || \"unknown\".equalsIgnoreCase(checkString);\n }\n\n /**\n * 是否为IP\n */\n public static boolean isIP(String ip)\n {\n return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP);\n }\n\n /**\n * 是否为IP,或 *为间隔的通配符地址\n */\n public static boolean isIpWildCard(String ip)\n {\n return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP_WILDCARD);\n }\n\n /**\n * 检测参数是否在ip通配符里\n */\n public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip)\n {\n String[] s1 = ipWildCard.split(\"\\\\.\");\n String[] s2 = ip.split(\"\\\\.\");\n boolean isMatchedSeg = true;\n for (int i = 0; i < s1.length && !s1[i].equals(\"*\"); i++)\n {\n if (!s1[i].equals(s2[i]))\n {\n isMatchedSeg = false;\n break;\n }\n }\n return isMatchedSeg;\n }\n\n /**\n * 是否为特定格式如:“10.10.10.1-10.10.10.99”的ip段字符串\n */\n public static boolean isIPSegment(String ipSeg)\n {\n return StringUtils.isNotBlank(ipSeg) && ipSeg.matches(REGX_IP_SEG);\n }\n\n /**\n * 判断ip是否在指定网段中\n */\n public static boolean ipIsInNetNoCheck(String iparea, String ip)\n {\n int idx = iparea.indexOf('-');\n String[] sips = iparea.substring(0, idx).split(\"\\\\.\");\n String[] sipe = iparea.substring(idx + 1).split(\"\\\\.\");\n String[] sipt = ip.split(\"\\\\.\");\n long ips = 0L, ipe = 0L, ipt = 0L;\n for (int i = 0; i < 4; ++i)\n {\n ips = ips << 8 | Integer.parseInt(sips[i]);\n ipe = ipe << 8 | Integer.parseInt(sipe[i]);\n ipt = ipt << 8 | Integer.parseInt(sipt[i]);\n }\n if (ips > ipe)\n {\n long t = ips;\n ips = ipe;\n ipe = t;\n }\n return ips <= ipt && ipt <= ipe;\n }\n\n /**\n * 校验ip是否符合过滤串规则\n * \n * @param filter 过滤IP列表,支持后缀'*'通配,支持网段如:`10.10.10.1-10.10.10.99`\n * @param ip 校验IP地址\n * @return boolean 结果\n */\n public static boolean isMatchedIp(String filter, String ip)\n {\n if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip))\n {\n return false;\n }\n String[] ips = filter.split(\";\");\n for (String iStr : ips)\n {\n if (isIP(iStr) && iStr.equals(ip))\n {\n return true;\n }\n else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip))\n {\n return true;\n }\n else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip))\n {\n return true;\n }\n }\n return false;\n }\n}" } ]
import com.qf.server.util.Arith; import com.qf.server.util.IpUtils; import lombok.ToString; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.CentralProcessor.TickType; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.Util; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.List; import java.util.Properties;
5,395
this.jvm = jvm; } public Sys getSys() { return sys; } public void setSys(Sys sys) { this.sys = sys; } public List<SysFile> getSysFiles() { return sysFiles; } public void setSysFiles(List<SysFile> sysFiles) { this.sysFiles = sysFiles; } public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem()); } /** * 设置CPU信息 */ private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; cpu.setCpuNum(processor.getLogicalProcessorCount()); cpu.setTotal(totalCpu); cpu.setSys(cSys); cpu.setUsed(user); cpu.setWait(iowait); cpu.setFree(idle); } /** * 设置内存信息 */ private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties(); sys.setComputerName(IpUtils.getHostName()); sys.setComputerIp(IpUtils.getHostIp()); sys.setOsName(props.getProperty("os.name")); sys.setOsArch(props.getProperty("os.arch")); sys.setUserDir(props.getProperty("user.dir")); } /** * 设置Java虚拟机 */ private void setJvmInfo() throws UnknownHostException { Properties props = System.getProperties(); jvm.setTotal(Runtime.getRuntime().totalMemory()); jvm.setMax(Runtime.getRuntime().maxMemory()); jvm.setFree(Runtime.getRuntime().freeMemory()); jvm.setVersion(props.getProperty("java.version")); jvm.setHome(props.getProperty("java.home")); } /** * 设置磁盘信息 */ private void setSysFiles(OperatingSystem os) { FileSystem fileSystem = os.getFileSystem(); List<OSFileStore> fsArray = fileSystem.getFileStores(); for (OSFileStore fs : fsArray) { long free = fs.getUsableSpace(); long total = fs.getTotalSpace(); long used = total - free; SysFile sysFile = new SysFile(); sysFile.setDirName(fs.getMount()); sysFile.setSysTypeName(fs.getType()); sysFile.setTypeName(fs.getName()); sysFile.setTotal(convertFileSize(total)); sysFile.setFree(convertFileSize(free)); sysFile.setUsed(convertFileSize(used));
package com.qf.server; /** * 服务器相关信息 * * @author ruoyi */ @ToString public class Server { private static final int OSHI_WAIT_SECOND = 1000; /** * CPU相关信息 */ private Cpu cpu = new Cpu(); /** * 內存相关信息 */ private Mem mem = new Mem(); /** * JVM相关信息 */ private Jvm jvm = new Jvm(); /** * 服务器相关信息 */ private Sys sys = new Sys(); /** * 磁盘相关信息 */ private List<SysFile> sysFiles = new LinkedList<SysFile>(); public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Mem getMem() { return mem; } public void setMem(Mem mem) { this.mem = mem; } public Jvm getJvm() { return jvm; } public void setJvm(Jvm jvm) { this.jvm = jvm; } public Sys getSys() { return sys; } public void setSys(Sys sys) { this.sys = sys; } public List<SysFile> getSysFiles() { return sysFiles; } public void setSysFiles(List<SysFile> sysFiles) { this.sysFiles = sysFiles; } public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem()); } /** * 设置CPU信息 */ private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; cpu.setCpuNum(processor.getLogicalProcessorCount()); cpu.setTotal(totalCpu); cpu.setSys(cSys); cpu.setUsed(user); cpu.setWait(iowait); cpu.setFree(idle); } /** * 设置内存信息 */ private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties(); sys.setComputerName(IpUtils.getHostName()); sys.setComputerIp(IpUtils.getHostIp()); sys.setOsName(props.getProperty("os.name")); sys.setOsArch(props.getProperty("os.arch")); sys.setUserDir(props.getProperty("user.dir")); } /** * 设置Java虚拟机 */ private void setJvmInfo() throws UnknownHostException { Properties props = System.getProperties(); jvm.setTotal(Runtime.getRuntime().totalMemory()); jvm.setMax(Runtime.getRuntime().maxMemory()); jvm.setFree(Runtime.getRuntime().freeMemory()); jvm.setVersion(props.getProperty("java.version")); jvm.setHome(props.getProperty("java.home")); } /** * 设置磁盘信息 */ private void setSysFiles(OperatingSystem os) { FileSystem fileSystem = os.getFileSystem(); List<OSFileStore> fsArray = fileSystem.getFileStores(); for (OSFileStore fs : fsArray) { long free = fs.getUsableSpace(); long total = fs.getTotalSpace(); long used = total - free; SysFile sysFile = new SysFile(); sysFile.setDirName(fs.getMount()); sysFile.setSysTypeName(fs.getType()); sysFile.setTypeName(fs.getName()); sysFile.setTotal(convertFileSize(total)); sysFile.setFree(convertFileSize(free)); sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
0
2023-12-30 13:42:53+00:00
8k
JIGerss/Salus
salus-web/src/main/java/team/glhf/salus/service/Impl/ArticleServiceImpl.java
[ { "identifier": "Article", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/Article.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"tb_article\")\r\npublic class Article implements Serializable {\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"images\")\r\n private String images;\r\n\r\n @TableField(\"title\")\r\n private String title;\r\n\r\n @TableField(\"content\")\r\n private String content;\r\n\r\n @TableField(\"position\")\r\n private String position;\r\n\r\n @TableField(\"likes\")\r\n private Long likes;\r\n\r\n @TableField(\"comments\")\r\n private Long comments;\r\n\r\n @TableField(fill = FieldFill.INSERT)\r\n private String createTime;\r\n\r\n @TableLogic()\r\n private String exist;\r\n\r\n @Version()\r\n private Long version;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n\r\n /**\r\n * 已初始化的builder\r\n */\r\n public static ArticleBuilder initedBuilder() {\r\n return Article.builder()\r\n .images(\"[]\")\r\n .position(\"{}\")\r\n .comments(0L)\r\n .likes(0L);\r\n }\r\n}\r" }, { "identifier": "ArticleOwnComment", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/relation/ArticleOwnComment.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"article_own_comment\")\r\npublic class ArticleOwnComment implements Serializable {\r\n\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"article_id\")\r\n private String articleId;\r\n\r\n @TableField(\"user_id\")\r\n private String userId;\r\n\r\n @TableField(\"comment\")\r\n private String comment;\r\n\r\n @TableField(fill = FieldFill.INSERT)\r\n private String createTime;\r\n\r\n @TableLogic()\r\n private String exist;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "ArticleOwnTag", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/relation/ArticleOwnTag.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"article_own_tag\")\r\npublic class ArticleOwnTag implements Serializable {\r\n\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"article_id\")\r\n private String articleId;\r\n\r\n @TableField(\"tag\")\r\n private String tag;\r\n\r\n @TableLogic()\r\n private String exist;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "UserLikeArticle", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/relation/UserLikeArticle.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"user_like_article\")\r\npublic class UserLikeArticle implements Serializable {\r\n\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"user_id\")\r\n private String userId;\r\n\r\n @TableField(\"article_id\")\r\n private String articleId;\r\n\r\n @TableLogic()\r\n private String exist;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "UserOwnArticle", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/relation/UserOwnArticle.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"user_own_article\")\r\npublic class UserOwnArticle implements Serializable {\r\n\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"user_id\")\r\n private String userId;\r\n\r\n @TableField(\"article_id\")\r\n private String articleId;\r\n\r\n @TableLogic()\r\n private String exist;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "FilePathEnum", "path": "salus-common/src/main/java/team/glhf/salus/enumeration/FilePathEnum.java", "snippet": "public enum FilePathEnum {\r\n ARTICLE_IMAGE(\"article/\"),\r\n PLACE_IMAGE(\"place/\"),\r\n USER_AVATAR(\"avatar/\");\r\n\r\n FilePathEnum(String path) {\r\n this.path = path;\r\n }\r\n\r\n private final String path;\r\n\r\n public String getPath() {\r\n return path;\r\n }\r\n}\r" }, { "identifier": "HttpCodeEnum", "path": "salus-common/src/main/java/team/glhf/salus/enumeration/HttpCodeEnum.java", "snippet": "public enum HttpCodeEnum {\r\n // Success ==> 200\r\n SUCCESS(200, \"操作成功\"),\r\n\r\n // Timeout ==> 400\r\n TIME_OUT(400, \"系统超时\"),\r\n\r\n // Login Error ==> 1~50\r\n NEED_LOGIN_AFTER(1, \"需要登录后操作\"),\r\n LOGIN_PASSWORD_ERROR(2, \"密码错误\"),\r\n ACCOUNT_NOT_FOUND(3, \"账号不存在\"),\r\n ACCOUNT_DISABLED(4, \"账号被禁用\"),\r\n NUMBER_CODE_NOT_EQUAL(4, \"验证码不匹配\"),\r\n NUMBER_CODE_NOT_EXIST(5, \"请先发送验证码\"),\r\n ACCOUNT_PASSWORD_ERROR(6, \"账号或密码错误\"),\r\n\r\n // Token ==> 50~100\r\n TOKEN_INVALID(50, \"无效的TOKEN\"),\r\n TOKEN_REQUIRE(51, \"TOKEN是必须的\"),\r\n TOKEN_EXPIRED_TIME(52, \"TOKEN已过期\"),\r\n TOKEN_ALGORITHM_SIGNATURE_INVALID(53, \"TOKEN的算法或签名不对\"),\r\n TOKEN_CANT_EMPTY(54, \"TOKEN不能为空\"),\r\n\r\n // Sign Verification ==> 100~120\r\n SIGN_INVALID(100, \"无效的SIGN\"),\r\n SIG_TIMEOUT(101, \"SIGN已过期\"),\r\n\r\n // Args Error ==> 500~1000\r\n PARAM_REQUIRE(500, \"缺少参数\"),\r\n PARAM_INVALID(501, \"无效参数\"),\r\n PARAM_IMAGE_FORMAT_ERROR(502, \"图片格式有误\"),\r\n INVALID_ID(503, \"该ID查无数据\"),\r\n SERVER_ERROR(503, \"服务器内部错误\"),\r\n SERVER_BUSY(504, \"服务器繁忙\"),\r\n USER_NOT_REGISTERED(505, \"用户未注册\"),\r\n USER_REGISTERED(506, \"用户已注册\"),\r\n REQUEST_ERROR(507, \"请求出错\"),\r\n\r\n // Data Error ==> 1000~2000\r\n DATA_EXIST(1000, \"数据已经存在\"),\r\n DATA_PART_NOT_EXIST(1002, \"前端请求,部分必要数据不能为空\"),\r\n DATA_ALL_NOT_EXIST(1002, \"前端请求,数据完全为空\"),\r\n DATA_PART_ILLEGAL(1003, \"部分数据不合法\"),\r\n DATA_UPLOAD_ERROR(1004, \"服务器上传失败\"),\r\n PHONE_ILLEGAL(1005, \"手机号为空或者格式不合法\"),\r\n PASSWORD_ILLEGAL(1006, \"密码为空或者格式不合法\"),\r\n NUMBER_CODE_ILLEGAL(1007, \"未获取验证码或者格式不合法\"),\r\n TOKEN_DATA_INVALID(1008, \"token里的荷载数据有误\"),\r\n USERNAME_PASSWORD_ILLEGAL(1009, \"账号或密码为空或长度过长\"),\r\n EMAIL_SEND_ERROR(1010, \"发送邮件失败,请重试\"),\r\n SMS_SEND_ERROR(1011, \"发送短信失败,请重试\"),\r\n GET_LOCATION_ERROR(1012, \"获取地址失败,请检查参数是否正确\"),\r\n\r\n // Article Error\r\n ARTICLE_NOT_EXIST(1101, \"文章不存在,请检查参数是否正确\"),\r\n ARTICLE_ALREADY_LIKED(1102, \"文章已被点赞\"),\r\n ARTICLE_NOT_LIKED(1103, \"文章没有被点赞\"),\r\n ARTICLE_PERMISSION_ERROR(1104, \"你没有权限操作该文章\"),\r\n UPLOAD_ERROR(1105, \"上传文件失败,可能文件太大了,请重试\"),\r\n\r\n // User Error\r\n USER_ALREADY_SUBSCRIBED(1201, \"用户已被关注\"),\r\n USER_NOT_SUBSCRIBED(1202, \"用户没有被关注\"),\r\n USER_SUBSCRIBED_ITSELF(1203, \"用户不能关注自己\"),\r\n\r\n //Place Error\r\n PLACE_NOT_EXIST(1301,\"场所不存在,请检查参数是否正确\"),\r\n PLACE_ALREADY_POINTED(1302, \"场所已被该用户评分\"),\r\n PLACE_NOT_POINTED(1303, \"场所没有被该用户评分\"),\r\n\r\n // Game Error\r\n FAIL_TO_JOIN_GAME(1401, \"加入失败,请检查参数是否正确\"),\r\n SEND_MESSAGE_ERROR(1402, \"消息发送失败,请检查参数是否正确\"),\r\n GAME_NOT_EXIST(1403, \"游戏不存在,请检查参数是否正确\"),\r\n GAME_PERMISSION_ERROR(1404, \"你不是房主\"),\r\n GAME_ALREADY_STARTED(1405, \"游戏已经开始\"),\r\n USER_NOT_JOIN_GAME(1406, \"你尚未加入该游戏\"),\r\n GAME_CONFIGURATION_ERROR(1407, \"玩家尚未选择角色,或者游戏时间未配置\"),\r\n GAME_NO_BOTH_ROLES(1408, \"缺少至少一个猫或至少一个老鼠\"),\r\n GAME_STAGE_ERROR(1409, \"游戏还未开始或者已经结束\"),\r\n GAME_CAUGHT_MOUSE(1410, \"你已被抓住\");\r\n\r\n private final Integer code;\r\n private final String message;\r\n\r\n HttpCodeEnum(Integer code, String message) {\r\n this.code = code;\r\n this.message = message;\r\n }\r\n\r\n public Integer getCode() {\r\n return code;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n}\r" }, { "identifier": "ArticleException", "path": "salus-common/src/main/java/team/glhf/salus/exception/ArticleException.java", "snippet": "public class ArticleException extends SalusException {\r\n public ArticleException(HttpCodeEnum enums) {\r\n super(enums);\r\n }\r\n}\r" }, { "identifier": "ArticleService", "path": "salus-web/src/main/java/team/glhf/salus/service/ArticleService.java", "snippet": "@SuppressWarnings(\"UnusedReturnValue\")\r\npublic interface ArticleService {\r\n /**\r\n * 创建文章\r\n */\r\n CreateRes createArticle(CreateReq createReq);\r\n\r\n /**\r\n * 获取文章\r\n */\r\n ArticleVo getArticleById(String articleId);\r\n\r\n /**\r\n * 随机获取几篇文章\r\n */\r\n List<ArticleVo> getRecommendArticles(List<String> articleIds);\r\n\r\n /**\r\n * 获取已经点赞的文章\r\n */\r\n List<ArticleVo> getLikedArticles(String userId);\r\n\r\n /**\r\n * 获取自己的文章\r\n */\r\n List<ArticleVo> getOwnedArticles(String userId);\r\n\r\n /**\r\n * 随机获取几个热门标签\r\n */\r\n List<TagVo> getRecommendTags();\r\n\r\n /**\r\n * 更新文章,除了tags\r\n */\r\n void updateArticle(ModifyReq modifyReq);\r\n\r\n /**\r\n * 删除文章\r\n */\r\n void deleteArticle(DeleteReq deleteReq);\r\n\r\n /**\r\n * 点赞文章\r\n */\r\n void likeArticle(LikeReq likeReq, boolean isLike);\r\n\r\n /**\r\n * 评论文章\r\n */\r\n void commentArticle(CommentReq commentReq, boolean isComment);\r\n\r\n // -------------------------------------------------------------------------------------------\r\n\r\n /**\r\n * 查询该文章是否存在,若orElseThrow为true则在不存在时抛出异常\r\n */\r\n boolean checkHasArticle(String articleId, boolean orElseThrow);\r\n\r\n /**\r\n * 查询用户是否拥有该文章,若不拥有时抛出异常\r\n */\r\n boolean checkOwnArticle(String userId, String articleId);\r\n\r\n /**\r\n * 查询用户是否点赞该文章,若不拥有时抛出异常\r\n */\r\n boolean checkLikeArticle(String userId, String articleId);\r\n\r\n /**\r\n * 查询哪个用户拥有该文章\r\n */\r\n String whoOwnArticle(String articleId);\r\n\r\n}\r" }, { "identifier": "CommonService", "path": "salus-web/src/main/java/team/glhf/salus/service/CommonService.java", "snippet": "public interface CommonService {\r\n /**\r\n * 发送邮件验证码\r\n */\r\n void sendEmailCode(String to, String code);\r\n\r\n /**\r\n * 发送手机验证码\r\n */\r\n void sendSmsCode(String phone, String code);\r\n\r\n /**\r\n * 上传一张图片\r\n */\r\n String uploadImage(MultipartFile file, FilePathEnum pathEnum);\r\n\r\n /**\r\n * 批量图片\r\n */\r\n List<String> uploadAllImages(Collection<MultipartFile> files, FilePathEnum pathEnum);\r\n\r\n /**\r\n * 经纬度逆向地址获取\r\n */\r\n LocationRes getLocation(String position);\r\n}\r" }, { "identifier": "ArticleVo", "path": "salus-pojo/src/main/java/team/glhf/salus/vo/ArticleVo.java", "snippet": "@Data\r\n@Builder\r\npublic class ArticleVo implements Serializable {\r\n\r\n private String id;\r\n\r\n private List<String> images;\r\n\r\n private String title;\r\n\r\n private String content;\r\n\r\n private List<String> tags;\r\n\r\n private List<CommentVo> commentList;\r\n\r\n private String position;\r\n\r\n private Long likes;\r\n\r\n private Long comments;\r\n\r\n private String createTime;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "CommentVo", "path": "salus-pojo/src/main/java/team/glhf/salus/vo/CommentVo.java", "snippet": "@Data\r\n@Builder\r\npublic class CommentVo implements Serializable {\r\n\r\n private String userId;\r\n\r\n private String comment;\r\n\r\n private String createTime;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "TagVo", "path": "salus-pojo/src/main/java/team/glhf/salus/vo/TagVo.java", "snippet": "@Data\r\n@Builder\r\npublic class TagVo implements Serializable {\r\n\r\n private String tag;\r\n\r\n private String image;\r\n\r\n private Long hot;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" } ]
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Opt; import cn.hutool.core.util.RandomUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; import team.glhf.salus.dto.article.*; import team.glhf.salus.entity.Article; import team.glhf.salus.entity.relation.ArticleOwnComment; import team.glhf.salus.entity.relation.ArticleOwnTag; import team.glhf.salus.entity.relation.UserLikeArticle; import team.glhf.salus.entity.relation.UserOwnArticle; import team.glhf.salus.enumeration.FilePathEnum; import team.glhf.salus.enumeration.HttpCodeEnum; import team.glhf.salus.exception.ArticleException; import team.glhf.salus.mapper.*; import team.glhf.salus.service.ArticleService; import team.glhf.salus.service.CommonService; import team.glhf.salus.vo.ArticleVo; import team.glhf.salus.vo.CommentVo; import team.glhf.salus.vo.TagVo; import java.util.ArrayList; import java.util.List;
4,682
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/10/30 */ @Slf4j @Service public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService { private final CommonService commonService; private final TransactionTemplate transactionTemplate; private final UserOwnArticleMapper userOwnArticleMapper; private final UserLikeArticleMapper userLikeArticleMapper; private final ArticleOwnTagMapper articleOwnTagMapper; private final ArticleOwnCommentMapper articleOwnCommentMapper; public ArticleServiceImpl(UserOwnArticleMapper userOwnArticleMapper, TransactionTemplate transactionTemplate, UserLikeArticleMapper userLikeArticleMapper, ArticleOwnTagMapper articleOwnTagMapper, ArticleOwnCommentMapper articleOwnCommentMapper, CommonService commonService) { this.commonService = commonService; this.userOwnArticleMapper = userOwnArticleMapper; this.transactionTemplate = transactionTemplate; this.userLikeArticleMapper = userLikeArticleMapper; this.articleOwnTagMapper = articleOwnTagMapper; this.articleOwnCommentMapper = articleOwnCommentMapper; } @Override public CreateRes createArticle(CreateReq createReq) { // upload images List<String> urlList = new ArrayList<>(); if (null != createReq.getImages()) { urlList = commonService.uploadAllImages(createReq.getImages(), FilePathEnum.ARTICLE_IMAGE); } // generate new article instance Article article = Article.initedBuilder() .title(createReq.getTitle()) .images(JSONUtil.toJsonStr(urlList)) .content(createReq.getContent()) .position(createReq.getPosition()) .build(); // start a transaction transactionTemplate.execute((status) -> { save(article); UserOwnArticle userOwnArticle = UserOwnArticle.builder() .userId(createReq.getUserId()) .articleId(article.getId()) .build(); userOwnArticleMapper.insert(userOwnArticle); List<String> tagList = createReq.getTags().stream().distinct().toList(); for (String tag : tagList) { ArticleOwnTag articleOwnTag = ArticleOwnTag.builder() .articleId(article.getId()) .tag(tag) .build(); articleOwnTagMapper.insert(articleOwnTag); } return Boolean.TRUE; }); return CreateRes.builder().articleId(article.getId()).build(); } @Override public ArticleVo getArticleById(String articleId) { checkHasArticle(articleId, true); return article2ArticleVo(getById(articleId)); } @Override public List<ArticleVo> getRecommendArticles(List<String> articleIds) { // 排除已经推荐过的文章 articleIds = Opt.ofNullable(articleIds).orElseGet(ArrayList::new); LambdaQueryWrapper<Article> qw = Wrappers.lambdaQuery(Article.class) .notIn(!articleIds.isEmpty(), Article::getId, articleIds); List<ArticleVo> articleVoList = new ArrayList<>(10); Page<Article> page = new Page<>(1, 1); int count = (int) count(qw); for (int i = 0; i < 10 && count > 0; i++) { page.setCurrent(RandomUtil.randomInt(1, count + 1)); List<Article> oneArticleList = list(page, qw.notIn(!articleIds.isEmpty(), Article::getId, articleIds) ); Article oneArticle = oneArticleList.get(0); articleVoList.add(article2ArticleVo(oneArticle)); articleIds.add(oneArticle.getId()); count = count - 1; } return articleVoList; } @Override public List<ArticleVo> getLikedArticles(String userId) { List<UserLikeArticle> likeArticles = userLikeArticleMapper.selectList(Wrappers.lambdaQuery(UserLikeArticle.class) .eq(UserLikeArticle::getUserId, userId) ); List<String> idList = likeArticles.stream().map(UserLikeArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override public List<ArticleVo> getOwnedArticles(String userId) { List<UserOwnArticle> ownArticles = userOwnArticleMapper.selectList(Wrappers.lambdaQuery(UserOwnArticle.class) .eq(UserOwnArticle::getUserId, userId) ); List<String> idList = ownArticles.stream().map(UserOwnArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/10/30 */ @Slf4j @Service public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService { private final CommonService commonService; private final TransactionTemplate transactionTemplate; private final UserOwnArticleMapper userOwnArticleMapper; private final UserLikeArticleMapper userLikeArticleMapper; private final ArticleOwnTagMapper articleOwnTagMapper; private final ArticleOwnCommentMapper articleOwnCommentMapper; public ArticleServiceImpl(UserOwnArticleMapper userOwnArticleMapper, TransactionTemplate transactionTemplate, UserLikeArticleMapper userLikeArticleMapper, ArticleOwnTagMapper articleOwnTagMapper, ArticleOwnCommentMapper articleOwnCommentMapper, CommonService commonService) { this.commonService = commonService; this.userOwnArticleMapper = userOwnArticleMapper; this.transactionTemplate = transactionTemplate; this.userLikeArticleMapper = userLikeArticleMapper; this.articleOwnTagMapper = articleOwnTagMapper; this.articleOwnCommentMapper = articleOwnCommentMapper; } @Override public CreateRes createArticle(CreateReq createReq) { // upload images List<String> urlList = new ArrayList<>(); if (null != createReq.getImages()) { urlList = commonService.uploadAllImages(createReq.getImages(), FilePathEnum.ARTICLE_IMAGE); } // generate new article instance Article article = Article.initedBuilder() .title(createReq.getTitle()) .images(JSONUtil.toJsonStr(urlList)) .content(createReq.getContent()) .position(createReq.getPosition()) .build(); // start a transaction transactionTemplate.execute((status) -> { save(article); UserOwnArticle userOwnArticle = UserOwnArticle.builder() .userId(createReq.getUserId()) .articleId(article.getId()) .build(); userOwnArticleMapper.insert(userOwnArticle); List<String> tagList = createReq.getTags().stream().distinct().toList(); for (String tag : tagList) { ArticleOwnTag articleOwnTag = ArticleOwnTag.builder() .articleId(article.getId()) .tag(tag) .build(); articleOwnTagMapper.insert(articleOwnTag); } return Boolean.TRUE; }); return CreateRes.builder().articleId(article.getId()).build(); } @Override public ArticleVo getArticleById(String articleId) { checkHasArticle(articleId, true); return article2ArticleVo(getById(articleId)); } @Override public List<ArticleVo> getRecommendArticles(List<String> articleIds) { // 排除已经推荐过的文章 articleIds = Opt.ofNullable(articleIds).orElseGet(ArrayList::new); LambdaQueryWrapper<Article> qw = Wrappers.lambdaQuery(Article.class) .notIn(!articleIds.isEmpty(), Article::getId, articleIds); List<ArticleVo> articleVoList = new ArrayList<>(10); Page<Article> page = new Page<>(1, 1); int count = (int) count(qw); for (int i = 0; i < 10 && count > 0; i++) { page.setCurrent(RandomUtil.randomInt(1, count + 1)); List<Article> oneArticleList = list(page, qw.notIn(!articleIds.isEmpty(), Article::getId, articleIds) ); Article oneArticle = oneArticleList.get(0); articleVoList.add(article2ArticleVo(oneArticle)); articleIds.add(oneArticle.getId()); count = count - 1; } return articleVoList; } @Override public List<ArticleVo> getLikedArticles(String userId) { List<UserLikeArticle> likeArticles = userLikeArticleMapper.selectList(Wrappers.lambdaQuery(UserLikeArticle.class) .eq(UserLikeArticle::getUserId, userId) ); List<String> idList = likeArticles.stream().map(UserLikeArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override public List<ArticleVo> getOwnedArticles(String userId) { List<UserOwnArticle> ownArticles = userOwnArticleMapper.selectList(Wrappers.lambdaQuery(UserOwnArticle.class) .eq(UserOwnArticle::getUserId, userId) ); List<String> idList = ownArticles.stream().map(UserOwnArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override
public List<TagVo> getRecommendTags() {
12
2023-12-23 15:03:37+00:00
8k
swsm/proxynet
proxynet-client/src/main/java/com/swsm/proxynet/client/handler/ClientServerChannelHandler.java
[ { "identifier": "ConfigUtil", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/config/ConfigUtil.java", "snippet": "@Component\n@Slf4j\npublic class ConfigUtil {\n \n @Autowired\n private ProxyConfig proxyConfig;\n \n private static ProxyConfig myProxyConfig;\n \n @PostConstruct\n public void init() {\n myProxyConfig = proxyConfig;\n }\n \n public static String getServerIp() {\n return myProxyConfig.getServerIp();\n }\n \n public static int getServerPort() {\n return myProxyConfig.getServerPort();\n }\n \n \n}" }, { "identifier": "SpringInitRunner", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/init/SpringInitRunner.java", "snippet": "@Component\n@Slf4j\npublic class SpringInitRunner implements CommandLineRunner {\n \n @Autowired\n private ProxyConfig proxyConfig;\n \n public static Bootstrap bootstrapForTarget;\n public static Bootstrap bootstrapForServer;\n \n \n @Override\n public void run(String... args) throws Exception {\n log.info(\"proxyclient spring启动完成,接下来启动 连接代理服务器的客户端\");\n \n log.info(\"启动 连接代理服务器的客户端...\");\n bootstrapForServer = new Bootstrap();\n bootstrapForServer.group(new NioEventLoopGroup(4))\n .channel(NioSocketChannel.class)\n .handler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel socketChannel) throws Exception {\n socketChannel.pipeline().addLast(\n new ProxyNetMessageDecoder(PROXY_MESSAGE_MAX_SIZE, PROXY_MESSAGE_LENGTH_FILED_OFFSET, PROXY_MESSAGE_LENGTH_FILED_LENGTH));\n socketChannel.pipeline().addLast(new ProxyNetMessageEncoder());\n socketChannel.pipeline().addLast(new IdleStateHandler(READ_IDLE_SECOND_TIME, WRITE_IDLE_SECOND_TIME, ALL_IDLE_SECOND_TIME));\n socketChannel.pipeline().addLast(new ClientServerChannelHandler());\n \n }\n });\n bootstrapForServer.connect(proxyConfig.getServerIp(), proxyConfig.getServerPort())\n .addListener((ChannelFutureListener) future -> {\n if (future.isSuccess()) {\n log.info(\"连接代理服务器的客户端 成功...\");\n // 向服务端发送 客户端id信息 \n future.channel().writeAndFlush(\n ProxyNetMessage.buildCommandMessage(ProxyNetMessage.COMMAND_AUTH, \n String.valueOf(proxyConfig.getClientId())));\n } else {\n log.info(\"连接代理服务器的客户端 失败...\");\n System.exit(-1);\n }\n }).sync();\n log.info(\"启动 连接代理服务器的客户端 成功...\");\n\n log.info(\"初始化 连接被代理服务器的客户端...\");\n bootstrapForTarget = new Bootstrap();\n bootstrapForTarget.group(new NioEventLoopGroup(4))\n .channel(NioSocketChannel.class)\n .handler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel socketChannel) throws Exception {\n socketChannel.pipeline().addLast(new ClientTargetChannelHandler());\n }\n });\n log.info(\"初始化 连接被代理服务器的客户端 完成...\");\n }\n}" }, { "identifier": "Constants", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public class Constants {\n\n public static final AttributeKey<Channel> NEXT_CHANNEL = AttributeKey.newInstance(\"nxt_channel\");\n public static final AttributeKey<String> VISITOR_ID = AttributeKey.newInstance(\"visitor_id\");\n \n public static final Integer PROXY_MESSAGE_MAX_SIZE = Integer.MAX_VALUE;\n public static final Integer PROXY_MESSAGE_LENGTH_FILED_OFFSET = 0;\n public static final Integer PROXY_MESSAGE_LENGTH_FILED_LENGTH = 4;\n \n public static final Integer READ_IDLE_SECOND_TIME = 3;\n public static final Integer WRITE_IDLE_SECOND_TIME = 3;\n public static final Integer ALL_IDLE_SECOND_TIME = 3;\n \n \n \n public static final Integer PROXY_MESSAGE_TOTAL_SIZE = 4;\n public static final Integer PROXY_MESSAGE_TYPE_SIZE = 1;\n public static final Integer PROXY_MESSAGE_INFO_SIZE = 4;\n \n}" }, { "identifier": "ChannelRelationCache", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/cache/ChannelRelationCache.java", "snippet": "public class ChannelRelationCache {\n \n private static ConcurrentMap<ChannelId, Channel> channelMap = new ConcurrentHashMap<>();\n \n private static ConcurrentMap<ChannelId, Set<Integer>> clientServerChannelIdToServerPort = new ConcurrentHashMap<>();\n \n private static ConcurrentMap<Integer, Set<ChannelId>> serverPortToUserServerChannelId = new ConcurrentHashMap<>();\n \n private static ConcurrentHashMap<ChannelId, Set<ChannelId>> clientServerChannelIdToUserChannelIds = new ConcurrentHashMap<>();\n \n private static ConcurrentMap<String, Channel> targetAddressToTargetChannel = new ConcurrentHashMap<>();\n \n private static ConcurrentMap<Channel, Channel> targetChannelToClientChannel = new ConcurrentHashMap<>();\n private static ConcurrentMap<String, Channel> userIdToTargetChannel = new ConcurrentHashMap<>();\n private static ConcurrentMap<String, ChannelId> userIdToUserChannel = new ConcurrentHashMap<>();\n \n \n public static Channel getTargetChannel(String targetIp, Integer targetPort) {\n return targetAddressToTargetChannel.get(targetIp + \"-\" + targetPort);\n }\n \n public static String getUserIdFromUserChannel(Channel channel) {\n for (String userId : userIdToUserChannel.keySet()) {\n if (userIdToUserChannel.get(userId).equals(channel)) {\n return userId;\n }\n }\n return null;\n }\n \n public static Channel getClientChannel(Channel targetChannel) {\n return targetChannelToClientChannel.get(targetChannel);\n }\n \n public static Channel getClientToServerChannel(int serverPort) {\n for (ChannelId channelId : clientServerChannelIdToServerPort.keySet()) {\n for (Integer port : clientServerChannelIdToServerPort.get(channelId)) {\n if (port == serverPort) {\n return channelMap.get(channelId);\n }\n }\n }\n return null;\n }\n \n public static List<Channel> getUserChannelList(ChannelId clientChannelId) {\n List<Channel> res = new ArrayList<>();\n Set<ChannelId> channelIds = clientServerChannelIdToUserChannelIds.get(clientChannelId);\n if (!CollectionUtils.isEmpty(channelIds)) {\n for (ChannelId channelId : channelIds) {\n if (channelMap.containsKey(channelId)) {\n res.add(channelMap.get(channelId));\n }\n }\n }\n return res;\n }\n\n public static String getUserIdByTargetChannel(Channel targetChannel) {\n for (String userId : userIdToTargetChannel.keySet()) {\n if (userIdToTargetChannel.get(userId) == targetChannel) {\n return userId;\n }\n }\n return null;\n }\n\n public static Channel getUserChannel(String userId) {\n return channelMap.get(userIdToUserChannel.get(userId));\n }\n \n public synchronized static void putClientUserChannelRelation(Channel clientChannel, Channel userChanel) {\n if (clientServerChannelIdToUserChannelIds.contains(clientChannel.id())) {\n clientServerChannelIdToUserChannelIds.get(clientChannel.id()).add(userChanel.id());\n } else {\n clientServerChannelIdToUserChannelIds.put(clientChannel.id(), Sets.newHashSet(userChanel.id()));\n }\n }\n \n public synchronized static void putClientChannel (int serverPort, Channel channel) {\n if (clientServerChannelIdToServerPort.containsKey(channel.id())) {\n clientServerChannelIdToServerPort.get(channel.id()).add(serverPort);\n } else {\n clientServerChannelIdToServerPort.put(channel.id(), Sets.newHashSet(serverPort));\n }\n channelMap.put(channel.id(), channel);\n }\n\n public synchronized static void putUserChannel (int serverPort, Channel channel) {\n if (serverPortToUserServerChannelId.containsKey(serverPort)) {\n serverPortToUserServerChannelId.get(serverPort).add(channel.id());\n } else {\n serverPortToUserServerChannelId.put(serverPort, Sets.newHashSet(channel.id()));\n }\n channelMap.put(channel.id(), channel);\n }\n \n public synchronized static void putTargetChannel(String targetIp, Integer targetPort, Channel channel) {\n targetAddressToTargetChannel.put(targetIp + \"-\" + targetPort, channel);\n }\n \n public synchronized static void putTargetChannelToClientChannel(Channel targetChannel, Channel clientChannel) {\n targetChannelToClientChannel.put(targetChannel, clientChannel);\n }\n\n public synchronized static void putUserIdToTargetChannel(String userId, Channel targetChannel) {\n userIdToTargetChannel.put(userId, targetChannel);\n }\n\n public static synchronized void putUserIdToUserChannel(String userId, Channel userChannel) {\n userIdToUserChannel.put(userId, userChannel.id());\n }\n \n public static void removeTargetChannelToClientChannel(Channel targetChannel) {\n targetChannelToClientChannel.remove(targetChannel);\n }\n \n public static void removeTargetChannel(Channel channel) {\n for (String targetAddress : targetAddressToTargetChannel.keySet()) {\n if (targetAddressToTargetChannel.get(targetAddress) == channel) {\n targetAddressToTargetChannel.remove(targetAddress);\n }\n }\n }\n\n\n public static void removeClientChannel (ChannelId channelId) {\n clientServerChannelIdToServerPort.remove(channelId);\n channelMap.remove(channelId);\n }\n\n public static void removeUserChannel (int serverPort, ChannelId channelId) {\n Set<ChannelId> channelIds = serverPortToUserServerChannelId.getOrDefault(serverPort, new HashSet<>());\n channelIds.remove(channelId);\n channelMap.remove(channelId);\n for (String userId : userIdToUserChannel.keySet()) {\n if (userIdToUserChannel.get(userId).equals(channelId)) {\n userIdToUserChannel.remove(userId);\n }\n }\n }\n\n\n public static void removeClientUserChannelRelation(ChannelId id) {\n for (ChannelId channelId : clientServerChannelIdToUserChannelIds.keySet()) {\n clientServerChannelIdToUserChannelIds.get(channelId).remove(id);\n }\n }\n\n\n \n}" }, { "identifier": "CommandInfoMessage", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/CommandInfoMessage.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommandInfoMessage {\n \n private ChannelId userChannelId;\n private String targetIp;\n private Integer targetPort;\n private byte[] info;\n \n \n}" }, { "identifier": "CommandMessage", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/CommandMessage.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommandMessage {\n private String type;\n private String message;\n}" }, { "identifier": "ConnectMessage", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/ConnectMessage.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ConnectMessage {\n \n private String userId;\n private String targetIp;\n private Integer targetPort;\n \n \n \n}" }, { "identifier": "ProxyNetMessage", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/ProxyNetMessage.java", "snippet": "@Data\npublic class ProxyNetMessage {\n\n public static final byte CONNECT = 0x01;\n public static final byte CONNECT_RESP = 0x02;\n public static final byte COMMAND = 0x03;\n \n public static final String COMMAND_AUTH = \"AUTH\";\n public static final String COMMAND_INFO = \"INFO\";\n public static final String COMMAND_RESP = \"RESP\";\n\n // 类型\n private byte type;\n // 消息实际信息\n private String info;\n // 用户请求消息 及 目标服务响应消息 原始数据\n private byte[] data;\n \n \n \n public static ProxyNetMessage buildCommandMessage(String type, String message) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(COMMAND);\n if (COMMAND_AUTH.equals(type)) {\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_AUTH, message)));\n } else if (COMMAND_INFO.equals(type)){\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_INFO, message)));\n proxyNetMessage.setData(JSON.parseObject(message, CommandInfoMessage.class).getInfo());\n } else if (COMMAND_RESP.equals(type)){\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_RESP, message)));\n proxyNetMessage.setData(JSON.parseObject(message, CommandRespMessage.class).getRespInfo());\n } else {\n throw new RuntimeException(\"invalid command type:\" + type);\n }\n return proxyNetMessage;\n }\n \n public static ProxyNetMessage buildConnectMessage(String userId, String ip, Integer port) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(CONNECT);\n proxyNetMessage.setInfo(JSON.toJSONString(new ConnectMessage(userId, ip, port)));\n return proxyNetMessage;\n }\n\n public static ProxyNetMessage buildConnectRespMessage(String message, Boolean result, String userId) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(CONNECT_RESP);\n proxyNetMessage.setInfo(JSON.toJSONString(new ConnectRespMessage(result, message, userId)));\n return proxyNetMessage;\n }\n \n \n \n}" } ]
import com.alibaba.fastjson.JSON; import com.swsm.proxynet.client.config.ConfigUtil; import com.swsm.proxynet.client.init.SpringInitRunner; import com.swsm.proxynet.common.Constants; import com.swsm.proxynet.common.cache.ChannelRelationCache; import com.swsm.proxynet.common.model.CommandInfoMessage; import com.swsm.proxynet.common.model.CommandMessage; import com.swsm.proxynet.common.model.ConnectMessage; import com.swsm.proxynet.common.model.ProxyNetMessage; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOption; import io.netty.channel.SimpleChannelInboundHandler; import lombok.extern.slf4j.Slf4j;
3,712
package com.swsm.proxynet.client.handler; /** * @author liujie * @date 2023-04-15 */ @Slf4j public class ClientServerChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception { if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT) { executeConnect(proxyNetMessage, channelHandlerContext); } else if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) { executeCommand(proxyNetMessage, channelHandlerContext); } } private void executeCommand(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { Channel clientChannel = channelHandlerContext.channel(); CommandMessage commandMessage = JSON.parseObject(proxyNetMessage.getInfo(), CommandMessage.class); if (ProxyNetMessage.COMMAND_INFO.equals(commandMessage.getType())) { CommandInfoMessage commandInfoMessage = JSON.parseObject(commandMessage.getMessage(), CommandInfoMessage.class); Channel targetChannel = clientChannel.attr(Constants.NEXT_CHANNEL).get(); if (targetChannel == null) { log.info("targetInfo={}的客户端还未和代理客户端建立连接", commandInfoMessage.getTargetIp() + ":" + commandInfoMessage.getTargetPort()); return; } ByteBuf data = channelHandlerContext.alloc().buffer(proxyNetMessage.getData().length); data.writeBytes(proxyNetMessage.getData()); targetChannel.writeAndFlush(data); } } private void executeConnect(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { ConnectMessage connectMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectMessage.class); log.info("收到服务端发送的connect消息:{}", proxyNetMessage); log.info("向目标服务={}发起连接...", proxyNetMessage); try { SpringInitRunner.bootstrapForTarget.connect(connectMessage.getTargetIp(), connectMessage.getTargetPort()) .addListener((ChannelFutureListener) future -> { Channel targetChannel = future.channel(); if (future.isSuccess()) { targetChannel.config().setOption(ChannelOption.AUTO_READ, false); log.info("向目标服务={}发起连接 成功...", proxyNetMessage);
package com.swsm.proxynet.client.handler; /** * @author liujie * @date 2023-04-15 */ @Slf4j public class ClientServerChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception { if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT) { executeConnect(proxyNetMessage, channelHandlerContext); } else if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) { executeCommand(proxyNetMessage, channelHandlerContext); } } private void executeCommand(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { Channel clientChannel = channelHandlerContext.channel(); CommandMessage commandMessage = JSON.parseObject(proxyNetMessage.getInfo(), CommandMessage.class); if (ProxyNetMessage.COMMAND_INFO.equals(commandMessage.getType())) { CommandInfoMessage commandInfoMessage = JSON.parseObject(commandMessage.getMessage(), CommandInfoMessage.class); Channel targetChannel = clientChannel.attr(Constants.NEXT_CHANNEL).get(); if (targetChannel == null) { log.info("targetInfo={}的客户端还未和代理客户端建立连接", commandInfoMessage.getTargetIp() + ":" + commandInfoMessage.getTargetPort()); return; } ByteBuf data = channelHandlerContext.alloc().buffer(proxyNetMessage.getData().length); data.writeBytes(proxyNetMessage.getData()); targetChannel.writeAndFlush(data); } } private void executeConnect(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { ConnectMessage connectMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectMessage.class); log.info("收到服务端发送的connect消息:{}", proxyNetMessage); log.info("向目标服务={}发起连接...", proxyNetMessage); try { SpringInitRunner.bootstrapForTarget.connect(connectMessage.getTargetIp(), connectMessage.getTargetPort()) .addListener((ChannelFutureListener) future -> { Channel targetChannel = future.channel(); if (future.isSuccess()) { targetChannel.config().setOption(ChannelOption.AUTO_READ, false); log.info("向目标服务={}发起连接 成功...", proxyNetMessage);
String serverIp = ConfigUtil.getServerIp();
0
2023-12-25 03:25:38+00:00
8k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/adapters/LocationAdapter.java
[ { "identifier": "EmailQrFullActivity", "path": "app/src/main/java/com/trodev/scanhub/detail_activity/EmailQrFullActivity.java", "snippet": "public class EmailQrFullActivity extends AppCompatActivity {\n\n TextView from_tv, to_tv, text_tv;\n String from, to, text;\n Button generate, qr_download, pdf_download;\n public final static int QRCodeWidth = 500;\n Bitmap card, qrimage;\n ImageView qr_image;\n LinearLayout infoLl;\n CardView cardView;\n final static int REQUEST_CODE = 1232;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_email_qr_full);\n\n /*init*/\n from_tv = findViewById(R.id.from_tv);\n to_tv = findViewById(R.id.recevier_tv);\n text_tv = findViewById(R.id.text_tv);\n\n from = getIntent().getStringExtra(\"mFrom\");\n to = getIntent().getStringExtra(\"mTo\");\n text = getIntent().getStringExtra(\"mText\");\n\n from_tv.setText(from);\n to_tv.setText(to);\n text_tv.setText(text);\n\n /*init buttons*/\n // generate = findViewById(R.id.generate);\n qr_download = findViewById(R.id.qr_download);\n pdf_download = findViewById(R.id.pdf_download);\n\n /*image*/\n qr_image = findViewById(R.id.qr_image);\n\n /*card view init*/\n infoLl = findViewById(R.id.infoLl);\n cardView = findViewById(R.id.cardView);\n\n askPermissions();\n\n /*call method*/\n create_qr();\n\n pdf_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n make_pdf();\n }\n });\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n card = null;\n card = getBitmapFromUiView(infoLl);\n saveBitmapImage(card);\n\n }\n });\n\n }\n\n private void askPermissions() {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);\n }\n\n private void create_qr() {\n if (from_tv.getText().toString().trim().length() + to_tv.getText().toString().length() + text_tv.getText().toString().length() == 0) {\n } else {\n try {\n qrimage = textToImageEncode(\n \"Manufacture Date: \" + from_tv.getText().toString() +\n \"\\nExpire Date: \" + to_tv.getText().toString().trim() +\n \"\\nProduct Name: \" + text_tv.getText().toString().trim());\n\n qr_image.setImageBitmap(qrimage);\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n MediaStore.Images.Media.insertImage(getContentResolver(), qrimage, \"product_qr_image\"\n , null);\n Toast.makeText(EmailQrFullActivity.this, \"Download Complete\", Toast.LENGTH_SHORT).show();\n }\n });\n } catch (WriterException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n private Bitmap textToImageEncode(String value) throws WriterException {\n BitMatrix bitMatrix;\n try {\n\n bitMatrix = new MultiFormatWriter().encode(value, BarcodeFormat.DATA_MATRIX.QR_CODE, QRCodeWidth, QRCodeWidth, null);\n\n } catch (IllegalArgumentException e) {\n return null;\n }\n\n int bitMatrixWidth = bitMatrix.getWidth();\n int bitMatrixHeight = bitMatrix.getHeight();\n\n int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];\n for (int y = 0; y < bitMatrixHeight; y++) {\n int offSet = y * bitMatrixWidth;\n for (int x = 0; x < bitMatrixWidth; x++) {\n pixels[offSet + x] = bitMatrix.get(x, y) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white);\n }\n }\n Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);\n bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);\n return bitmap;\n }\n\n /* ##################################################################### */\n /* ##################################################################### */\n /*method\n * qr image downloader*/\n private Bitmap getBitmapFromUiView(View view) {\n\n //Define a bitmap with the same size as the view\n Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);\n //Bind a canvas to it\n Canvas canvas = new Canvas(returnedBitmap);\n //Get the view's background\n Drawable bgDrawable = view.getBackground();\n if (bgDrawable != null) {\n //has background drawable, then draw it on the canvas\n bgDrawable.draw(canvas);\n } else {\n //does not have background drawable, then draw white background on the canvas\n canvas.drawColor(Color.WHITE);\n }\n // draw the view on the canvas\n view.draw(canvas);\n\n //return the bitmap\n return returnedBitmap;\n }\n\n private void saveBitmapImage(Bitmap card) {\n\n long timestamp = System.currentTimeMillis();\n\n //Tell the media scanner about the new file so that it is immediately available to the user.\n ContentValues values = new ContentValues();\n\n values.put(MediaStore.Images.Media.MIME_TYPE, \"image/png\");\n values.put(MediaStore.Images.Media.DATE_ADDED, timestamp);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n\n values.put(MediaStore.Images.Media.DATE_TAKEN, timestamp);\n values.put(MediaStore.Images.Media.RELATIVE_PATH, \"Pictures/\" + getString(R.string.app_name));\n values.put(MediaStore.Images.Media.IS_PENDING, true);\n Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n\n if (uri != null) {\n try {\n OutputStream outputStream = getContentResolver().openOutputStream(uri);\n if (outputStream != null) {\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n }\n\n values.put(MediaStore.Images.Media.IS_PENDING, false);\n getContentResolver().update(uri, values, null, null);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n\n } else {\n File imageFileFolder = new File(Environment.getExternalStorageDirectory().toString() + '/' + getString(R.string.app_name));\n if (!imageFileFolder.exists()) {\n imageFileFolder.mkdirs();\n }\n String mImageName = \"\" + timestamp + \".png\";\n\n File imageFile = new File(imageFileFolder, mImageName);\n try {\n OutputStream outputStream = new FileOutputStream(imageFile);\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());\n getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n private void make_pdf() {\n\n DisplayMetrics displayMetrics = new DisplayMetrics();\n\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n this.getDisplay().getRealMetrics(displayMetrics);\n } else\n this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);\n\n cardView.measure(View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY),\n View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.EXACTLY));\n\n Log.d(\"my log\", \"Width Now \" + cardView.getMeasuredWidth());\n\n // cardView.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);\n\n // Create a new PdfDocument instance\n PdfDocument document = new PdfDocument();\n\n // Obtain the width and height of the view\n int viewWidth = cardView.getMeasuredWidth();\n int viewHeight = cardView.getMeasuredHeight();\n\n\n // Create a PageInfo object specifying the page attributes\n PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(viewWidth, viewHeight, 1).create();\n\n // Start a new page\n PdfDocument.Page page = document.startPage(pageInfo);\n\n // Get the Canvas object to draw on the page\n Canvas canvas = page.getCanvas();\n\n // Create a Paint object for styling the view\n Paint paint = new Paint();\n paint.setColor(Color.WHITE);\n\n // Draw the view on the canvas\n cardView.draw(canvas);\n\n // Finish the page\n document.finishPage(page);\n\n // Specify the path and filename of the output PDF file\n File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);\n\n /*time wise print*/\n /*eikhane millisecond ta niye lopping vabe pdf banacche*/\n long timestamps = System.currentTimeMillis();\n String fileName = \"Email_\" + timestamps + \".pdf\";\n\n File filePath = new File(downloadsDir, fileName);\n\n try {\n // Save the document to a file\n FileOutputStream fos = new FileOutputStream(filePath);\n document.writeTo(fos);\n document.close();\n fos.close();\n // PDF conversion successful\n Toast.makeText(this, \"pdf download successful\", Toast.LENGTH_LONG).show();\n } catch (IOException e) {\n e.printStackTrace();\n Toast.makeText(this, \"pdf download un-successful\", Toast.LENGTH_SHORT).show();\n }\n\n }\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n\n}" }, { "identifier": "LocationQrFullActivity", "path": "app/src/main/java/com/trodev/scanhub/detail_activity/LocationQrFullActivity.java", "snippet": "public class LocationQrFullActivity extends AppCompatActivity {\n\n TextView from_tv, to_tv, text_tv;\n String from, to, text;\n Button generate, qr_download, pdf_download;\n public final static int QRCodeWidth = 500;\n Bitmap card, qrimage;\n ImageView qr_image;\n LinearLayout infoLl;\n CardView cardView;\n final static int REQUEST_CODE = 1232;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_location_qr_full);\n\n /*init*/\n from_tv = findViewById(R.id.from_tv);\n to_tv = findViewById(R.id.recevier_tv);\n text_tv = findViewById(R.id.text_tv);\n\n from = getIntent().getStringExtra(\"mFrom\");\n to = getIntent().getStringExtra(\"mTo\");\n text = getIntent().getStringExtra(\"mText\");\n\n from_tv.setText(from);\n to_tv.setText(to);\n text_tv.setText(text);\n\n /*init buttons*/\n // generate = findViewById(R.id.generate);\n qr_download = findViewById(R.id.qr_download);\n pdf_download = findViewById(R.id.pdf_download);\n\n /*image*/\n qr_image = findViewById(R.id.qr_image);\n\n /*card view init*/\n infoLl = findViewById(R.id.infoLl);\n cardView = findViewById(R.id.cardView);\n\n askPermissions();\n\n /*call method*/\n create_qr();\n\n pdf_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n make_pdf();\n }\n });\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n card = null;\n card = getBitmapFromUiView(infoLl);\n saveBitmapImage(card);\n\n }\n });\n\n }\n\n private void askPermissions() {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);\n }\n\n private void create_qr() {\n if (from_tv.getText().toString().trim().length() + to_tv.getText().toString().length() + text_tv.getText().toString().length() == 0) {\n } else {\n try {\n qrimage = textToImageEncode(\n \"Manufacture Date: \" + from_tv.getText().toString() +\n \"\\nExpire Date: \" + to_tv.getText().toString().trim() +\n \"\\nProduct Name: \" + text_tv.getText().toString().trim());\n\n qr_image.setImageBitmap(qrimage);\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n MediaStore.Images.Media.insertImage(getContentResolver(), qrimage, \"product_qr_image\"\n , null);\n Toast.makeText(LocationQrFullActivity.this, \"Download Complete\", Toast.LENGTH_SHORT).show();\n }\n });\n } catch (WriterException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n private Bitmap textToImageEncode(String value) throws WriterException {\n BitMatrix bitMatrix;\n try {\n\n bitMatrix = new MultiFormatWriter().encode(value, BarcodeFormat.DATA_MATRIX.QR_CODE, QRCodeWidth, QRCodeWidth, null);\n\n } catch (IllegalArgumentException e) {\n return null;\n }\n\n int bitMatrixWidth = bitMatrix.getWidth();\n int bitMatrixHeight = bitMatrix.getHeight();\n\n int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];\n for (int y = 0; y < bitMatrixHeight; y++) {\n int offSet = y * bitMatrixWidth;\n for (int x = 0; x < bitMatrixWidth; x++) {\n pixels[offSet + x] = bitMatrix.get(x, y) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white);\n }\n }\n Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);\n bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);\n return bitmap;\n }\n\n /* ##################################################################### */\n /* ##################################################################### */\n /*method\n * qr image downloader*/\n private Bitmap getBitmapFromUiView(View view) {\n\n //Define a bitmap with the same size as the view\n Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);\n //Bind a canvas to it\n Canvas canvas = new Canvas(returnedBitmap);\n //Get the view's background\n Drawable bgDrawable = view.getBackground();\n if (bgDrawable != null) {\n //has background drawable, then draw it on the canvas\n bgDrawable.draw(canvas);\n } else {\n //does not have background drawable, then draw white background on the canvas\n canvas.drawColor(Color.WHITE);\n }\n // draw the view on the canvas\n view.draw(canvas);\n\n //return the bitmap\n return returnedBitmap;\n }\n\n private void saveBitmapImage(Bitmap card) {\n\n long timestamp = System.currentTimeMillis();\n\n //Tell the media scanner about the new file so that it is immediately available to the user.\n ContentValues values = new ContentValues();\n\n values.put(MediaStore.Images.Media.MIME_TYPE, \"image/png\");\n values.put(MediaStore.Images.Media.DATE_ADDED, timestamp);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n\n values.put(MediaStore.Images.Media.DATE_TAKEN, timestamp);\n values.put(MediaStore.Images.Media.RELATIVE_PATH, \"Pictures/\" + getString(R.string.app_name));\n values.put(MediaStore.Images.Media.IS_PENDING, true);\n Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n\n if (uri != null) {\n try {\n OutputStream outputStream = getContentResolver().openOutputStream(uri);\n if (outputStream != null) {\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n }\n\n values.put(MediaStore.Images.Media.IS_PENDING, false);\n getContentResolver().update(uri, values, null, null);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n\n } else {\n File imageFileFolder = new File(Environment.getExternalStorageDirectory().toString() + '/' + getString(R.string.app_name));\n if (!imageFileFolder.exists()) {\n imageFileFolder.mkdirs();\n }\n String mImageName = \"\" + timestamp + \".png\";\n\n File imageFile = new File(imageFileFolder, mImageName);\n try {\n OutputStream outputStream = new FileOutputStream(imageFile);\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());\n getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n private void make_pdf() {\n\n DisplayMetrics displayMetrics = new DisplayMetrics();\n\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n this.getDisplay().getRealMetrics(displayMetrics);\n } else\n this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);\n\n cardView.measure(View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY),\n View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.EXACTLY));\n\n Log.d(\"my log\", \"Width Now \" + cardView.getMeasuredWidth());\n\n // cardView.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);\n\n // Create a new PdfDocument instance\n PdfDocument document = new PdfDocument();\n\n // Obtain the width and height of the view\n int viewWidth = cardView.getMeasuredWidth();\n int viewHeight = cardView.getMeasuredHeight();\n\n\n // Create a PageInfo object specifying the page attributes\n PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(viewWidth, viewHeight, 1).create();\n\n // Start a new page\n PdfDocument.Page page = document.startPage(pageInfo);\n\n // Get the Canvas object to draw on the page\n Canvas canvas = page.getCanvas();\n\n // Create a Paint object for styling the view\n Paint paint = new Paint();\n paint.setColor(Color.WHITE);\n\n // Draw the view on the canvas\n cardView.draw(canvas);\n\n // Finish the page\n document.finishPage(page);\n\n // Specify the path and filename of the output PDF file\n File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);\n\n /*time wise print*/\n /*eikhane millisecond ta niye lopping vabe pdf banacche*/\n long timestamps = System.currentTimeMillis();\n String fileName = \"Email_\" + timestamps + \".pdf\";\n\n File filePath = new File(downloadsDir, fileName);\n\n try {\n // Save the document to a file\n FileOutputStream fos = new FileOutputStream(filePath);\n document.writeTo(fos);\n document.close();\n fos.close();\n // PDF conversion successful\n Toast.makeText(this, \"pdf download successful\", Toast.LENGTH_LONG).show();\n } catch (IOException e) {\n e.printStackTrace();\n Toast.makeText(this, \"pdf download un-successful\", Toast.LENGTH_SHORT).show();\n }\n\n }\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n}" }, { "identifier": "EmailModel", "path": "app/src/main/java/com/trodev/scanhub/models/EmailModel.java", "snippet": "public class EmailModel {\n\n public String email_from, email_to, email_sms, date, time, uid;\n\n public EmailModel() {\n }\n\n public EmailModel(String email_from, String email_to, String email_sms, String date, String time, String uid) {\n this.email_from = email_from;\n this.email_to = email_to;\n this.email_sms = email_sms;\n this.date = date;\n this.time = time;\n this.uid = uid;\n }\n\n public String getEmail_from() {\n return email_from;\n }\n\n public void setEmail_from(String email_from) {\n this.email_from = email_from;\n }\n\n public String getEmail_to() {\n return email_to;\n }\n\n public void setEmail_to(String email_to) {\n this.email_to = email_to;\n }\n\n public String getEmail_sms() {\n return email_sms;\n }\n\n public void setEmail_sms(String email_sms) {\n this.email_sms = email_sms;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n}" }, { "identifier": "LocationModel", "path": "app/src/main/java/com/trodev/scanhub/models/LocationModel.java", "snippet": "public class LocationModel {\n\n String loc_from, loc_to, loc_sms, date, time, uid;\n\n public LocationModel() {\n }\n\n public LocationModel(String loc_from, String loc_to, String loc_sms, String date, String time, String uid) {\n this.loc_from = loc_from;\n this.loc_to = loc_to;\n this.loc_sms = loc_sms;\n this.date = date;\n this.time = time;\n this.uid = uid;\n }\n\n public String getLoc_from() {\n return loc_from;\n }\n\n public void setLoc_from(String loc_from) {\n this.loc_from = loc_from;\n }\n\n public String getLoc_to() {\n return loc_to;\n }\n\n public void setLoc_to(String loc_to) {\n this.loc_to = loc_to;\n }\n\n public String getLoc_sms() {\n return loc_sms;\n }\n\n public void setLoc_sms(String loc_sms) {\n this.loc_sms = loc_sms;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n}" } ]
import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.trodev.scanhub.R; import com.trodev.scanhub.detail_activity.EmailQrFullActivity; import com.trodev.scanhub.detail_activity.LocationQrFullActivity; import com.trodev.scanhub.models.EmailModel; import com.trodev.scanhub.models.LocationModel; import java.util.ArrayList;
5,872
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context;
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context;
private ArrayList<LocationModel> list;
3
2023-12-26 05:10:38+00:00
8k
Deepennn/NetAPP
src/main/java/com/netapp/device/router/Router.java
[ { "identifier": "ArpEntry", "path": "src/main/java/com/netapp/device/ArpEntry.java", "snippet": "public class ArpEntry\n{\n\n /** 对应于MAC地址的IP地址 */\n private String ip;\n\n /** 对应于IP地址的MAC地址 */\n private String mac;\n\n /** 映射创建时的时间 */\n private long timeAdded;\n\n /**\n * 创建一个将IP地址映射到MAC地址的ARP表条目。\n * @param ip 对应于MAC地址的IP地址\n * @param mac 对应于IP地址的MAC地址\n */\n public ArpEntry(String ip, String mac)\n {\n this.ip = ip;\n this.mac = mac;\n this.timeAdded = System.currentTimeMillis();\n }\n\n /**\n * @return 对应于MAC地址的IP地址\n */\n public String getIp()\n { return this.ip; }\n\n /**\n * @return 对应于IP地址的MAC地址\n */\n public String getMac()\n { return this.mac; }\n\n\n /**\n * @return 映射创建时的时间(自纪元以来的毫秒数)\n */\n public long getTimeAdded()\n { return this.timeAdded; }\n\n public String toString()\n {\n return String.format(\"%s \\t%s\", this.ip,\n this.mac);\n }\n}" }, { "identifier": "Iface", "path": "src/main/java/com/netapp/device/Iface.java", "snippet": "public class Iface\n{\n protected String iName; // 接口名称\n protected String macAddress; // MAC地址\n protected BlockingQueue<Ethernet> inputQueue; // 输入队列\n protected BlockingQueue<Ethernet> outputQueue; // 输出队列\n\n public Iface(String iName, String macAddress) {\n this.iName = iName;\n this.macAddress = macAddress;\n this.inputQueue = new LinkedBlockingQueue<>();\n this.outputQueue = new LinkedBlockingQueue<>();\n }\n\n /**---------------------------------putters:放入(阻塞)-------------------------------------*/\n\n // 由 Net 放入数据包\n public void putInputPacket(Ethernet etherPacket) {\n System.out.println(this.iName + \" is receiving Ether packet: \" + etherPacket);\n try {\n inputQueue.put(etherPacket);\n } catch (InterruptedException e) {\n// System.out.println(this.iName + \" blocked a receiving Ether packet: \" + etherPacket);\n e.printStackTrace();\n }\n }\n\n // 由 Device 放入数据包\n public void putOutputPacket(Ethernet etherPacket) {\n System.out.println(this.iName + \" is sending Ether packet: \" + etherPacket);\n try {\n// System.out.println(this.iName + \" blocked a sending Ether packet: \" + etherPacket);\n outputQueue.put(etherPacket);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n /**---------------------------------putters:放入(不阻塞)-------------------------------------*/\n\n\n // 由 Net 放入数据包\n public void offerInputPacket(Ethernet etherPacket) {\n if(inputQueue.offer(etherPacket)){\n System.out.println(this.iName + \" succeed in receiving Ether packet: \" + etherPacket);\n }else{\n System.out.println(this.iName + \" failed in receiving Ether packet: \" + etherPacket);\n }\n }\n\n // 由 Device 放入数据包\n public void offerOutputPacket(Ethernet etherPacket) {\n if(outputQueue.offer(etherPacket)){\n System.out.println(this.iName + \" succeed in sending Ether packet: \" + etherPacket);\n }else{\n System.out.println(this.iName + \" failed in sending Ether packet: \" + etherPacket);\n }\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n /**----------------------------------peekers:查看--------------------------------------------*/\n\n // 由 Device 查看数据包\n public Ethernet peekInputPacket() {\n return inputQueue.peek();\n }\n\n // 由 Net 查看数据包\n public Ethernet peekOutputPacket() {\n return outputQueue.peek();\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n /**---------------------------------pollers:取出(不阻塞)-------------------------------------*/\n\n // 由 Device 取出数据包\n public Ethernet pollInputPacket() {\n return inputQueue.poll();\n }\n\n // 由 Net 取出数据包\n public Ethernet pollOutputPacket() {\n return outputQueue.poll();\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n public String getiName()\n { return this.iName; }\n\n public void setiName(String iName) {\n this.iName = iName;\n }\n\n public String getMacAddress() {\n return macAddress;\n }\n\n public void setMacAddress(String macAddress) {\n this.macAddress = macAddress;\n }\n\n public BlockingQueue<Ethernet> getInputQueue() {\n return inputQueue;\n }\n\n public void setInputQueue(BlockingQueue<Ethernet> inputQueue) {\n this.inputQueue = inputQueue;\n }\n\n public BlockingQueue<Ethernet> getOutputQueue() {\n return outputQueue;\n }\n\n public void setOutputQueue(BlockingQueue<Ethernet> outputQueue) {\n this.outputQueue = outputQueue;\n }\n\n}" }, { "identifier": "NetDevice", "path": "src/main/java/com/netapp/device/NetDevice.java", "snippet": "public abstract class NetDevice extends Device\n{\n\n /** ARP 缓存 */\n protected AtomicReference<ArpCache> atomicCache;\n\n /** 为ARP设置的输出缓存区 (不知道目的 MAC 的目的 IP) --> (对应数据包队列) */\n protected HashMap<String, BlockingQueue<Ethernet>> outputQueueMap;\n\n /**\n * 创建设备。\n * @param hostname 设备的主机名\n * @param interfaces 接口映射\n */\n public NetDevice(String hostname, Map<String, Iface> interfaces)\n {\n super(hostname, interfaces);\n this.atomicCache = new AtomicReference<>(new ArpCache());\n this.outputQueueMap = new HashMap<>();\n this.loadArpCache(ARP_CACHE_PREFFIX + this.hostname + ARP_CACHE_SUFFIX);\n }\n\n /**\n * 处理在特定接口接收到的以太网数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n */\n public void handlePacket(Ethernet etherPacket, Iface inIface) {\n System.out.println(this.hostname + \" is receiving Ether packet: \" + etherPacket.toString());\n\n /********************************************************************/\n\n /* 检验 MAC */\n if(!inIface.getMacAddress().equals(etherPacket.getDestinationMAC()) &&\n !etherPacket.isBroadcast()){\n return;\n }\n\n /* 检验校验和 */\n int origCksum = etherPacket.getChecksum();\n etherPacket.updateChecksum();\n int calcCksum = etherPacket.getChecksum();\n if (origCksum != calcCksum) {\n System.out.println(this.hostname + \" found Ether packet's checksum is wrong: \");\n return;\n }\n /* 处理数据包 */\n switch (etherPacket.getEtherType()) {\n case Ethernet.TYPE_IPv4:\n this.handleIPPacket(etherPacket, inIface);\n break;\n case Ethernet.TYPE_ARP:\n this.handleARPPacket(etherPacket, inIface);\n break;\n // 暂时忽略其他数据包类型\n }\n\n /********************************************************************/\n }\n\n\n /**\n * 处理 IP 数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n */\n protected abstract void handleIPPacket(Ethernet etherPacket, Iface inIface);\n\n\n /**\n * 发送 ICMP 数据包。(错误响应)\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n * @param type ICMP 类型\n * @param code ICMP 代码\n * @param echo 是否回显\n */\n protected abstract void sendICMPPacket(Ethernet etherPacket, Iface inIface, int type, int code, boolean echo);\n\n\n /**\n * 处理 ARP 数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n */\n protected void handleARPPacket(Ethernet etherPacket, Iface inIface) {\n if (etherPacket.getEtherType() != Ethernet.TYPE_ARP) {\n return;\n }\n\n ARP arpPacket = (ARP) etherPacket.getPayload();\n System.out.println(this.hostname + \" is handling ARP packet: \" + arpPacket);\n\n if (arpPacket.getOpCode() != ARP.OP_REQUEST) {\n if (arpPacket.getOpCode() == ARP.OP_REPLY) { // 收到的是 ARP 响应数据包\n\n // 放入 ARP 缓存\n String srcIp = arpPacket.getSenderProtocolAddress();\n atomicCache.get().insert(srcIp, arpPacket.getSenderHardwareAddress());\n\n Queue<Ethernet> packetsToSend = outputQueueMap.get(srcIp); // outputQueueMap 中目的 IP 是响应源 IP 的数据包队列\n while(packetsToSend != null && packetsToSend.peek() != null){\n Ethernet packet = packetsToSend.poll();\n packet.setDestinationMAC(arpPacket.getSenderHardwareAddress());\n packet.updateChecksum();\n this.sendPacket(packet, inIface);\n }\n }\n return;\n }\n\n // ARP 请求数据包\n\n String targetIp = arpPacket.getTargetProtocolAddress();\n if (!Objects.equals(targetIp, ((NetIface) inIface).getIpAddress())) // 不是对应接口 IP 则不处理\n return;\n\n Ethernet ether = new Ethernet();\n ether.setEtherType(Ethernet.TYPE_ARP);\n ether.setSourceMAC(inIface.getMacAddress());\n ether.setDestinationMAC(etherPacket.getSourceMAC());\n\n ARP arp = new ARP();\n arp.setHardwareType(ARP.HW_TYPE_ETHERNET);\n arp.setProtocolType(ARP.PROTO_TYPE_IP);\n arp.setOpCode(ARP.OP_REPLY);\n arp.setSenderHardwareAddress(inIface.getMacAddress());\n arp.setSenderProtocolAddress(((NetIface)inIface).getIpAddress());\n arp.setTargetHardwareAddress(arpPacket.getSenderHardwareAddress());\n arp.setTargetProtocolAddress(arpPacket.getSenderProtocolAddress());\n\n ether.setPayload(arp);\n\n System.out.println(this.hostname + \" is sending ARP packet:\" + ether);\n\n ether.updateChecksum();\n this.sendPacket(ether, inIface);\n return;\n }\n\n /**\n * 发送 ARP 数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param dstIp ICMP 类型\n * @param outIface 发送数据包的接口\n */\n protected void sendARPPacket(Ethernet etherPacket, String dstIp, Iface outIface){\n ARP arp = new ARP();\n arp.setHardwareType(ARP.HW_TYPE_ETHERNET);\n arp.setProtocolType(ARP.PROTO_TYPE_IP);\n arp.setOpCode(ARP.OP_REQUEST);\n arp.setSenderHardwareAddress(outIface.getMacAddress());\n arp.setSenderProtocolAddress(((NetIface)outIface).getIpAddress());\n arp.setTargetHardwareAddress(null);\n arp.setTargetProtocolAddress(dstIp);\n\n final AtomicReference<Ethernet> atomicEtherPacket = new AtomicReference<>(new Ethernet());\n final AtomicReference<Iface> atomicIface = new AtomicReference<>(outIface);\n final AtomicReference<Ethernet> atomicInPacket = new AtomicReference<>(etherPacket);\n\n atomicEtherPacket.get().setEtherType(Ethernet.TYPE_ARP);\n atomicEtherPacket.get().setSourceMAC(outIface.getMacAddress());\n\n atomicEtherPacket.get().setPayload(arp);\n atomicEtherPacket.get().setDestinationMAC(Ethernet.BROADCAST_MAC); // 广播 ARP 请求数据包\n atomicEtherPacket.get().updateChecksum();\n\n\n if (!outputQueueMap.containsKey(dstIp)) {\n outputQueueMap.put(dstIp, new LinkedBlockingQueue<>());\n System.out.println(hostname + \" is making a new buffer queue for: \" + dstIp);\n }\n BlockingQueue<Ethernet> nextHopQueue = outputQueueMap.get(dstIp);\n\n // 放入(不阻塞)\n try {\n nextHopQueue.put(etherPacket);\n } catch (InterruptedException e) {\n// System.out.println(this.hostname + \" blocked a sending Ether packet: \" + etherPacket);\n e.printStackTrace();\n }\n\n final AtomicReference<BlockingQueue<Ethernet>> atomicQueue = new AtomicReference<BlockingQueue<Ethernet>>(nextHopQueue); // 线程安全\n\n Thread waitForReply = new Thread(new Runnable() {\n\n public void run() {\n\n try {\n System.out.println(hostname + \" is sending ARP packet:\" + atomicEtherPacket.get());\n sendPacket(atomicEtherPacket.get(), atomicIface.get());\n Thread.sleep(1000);\n if (atomicCache.get().lookup(dstIp) != null) {\n System.out.println(hostname + \": Found it: \" + atomicCache.get().lookup(dstIp));\n return;\n }\n System.out.println(hostname + \" is sending ARP packet:\" + atomicEtherPacket.get());\n sendPacket(atomicEtherPacket.get(), atomicIface.get());\n Thread.sleep(1000);\n if (atomicCache.get().lookup(dstIp) != null) {\n System.out.println(hostname + \": Found it: \" + atomicCache.get().lookup(dstIp));\n return;\n }\n System.out.println(hostname + \" is sending ARP packet:\" + atomicEtherPacket.get());\n sendPacket(atomicEtherPacket.get(), atomicIface.get());\n Thread.sleep(1000);\n if (atomicCache.get().lookup(dstIp) != null) {\n System.out.println(hostname + \": Found it: \" + atomicCache.get().lookup(dstIp));\n return;\n }\n\n // 都发了 3 次了,实在是真的是找不着 MAC,那就放弃吧,发送一个`目的主机不可达`的 ICMP\n System.out.println(hostname + \": Not found: \" + dstIp);\n\n while (atomicQueue.get() != null && atomicQueue.get().peek() != null) {\n atomicQueue.get().poll();\n }\n sendICMPPacket(atomicInPacket.get(), atomicIface.get(), 3, 1, false);\n return;\n } catch (InterruptedException e) {\n System.out.println(e);\n }\n }\n });\n waitForReply.start();\n return;\n }\n\n\n /**\n * 从文件加载 ARP 缓存。\n * @param arpCacheFile 包含 ARP 缓存的文件名\n */\n public void loadArpCache(String arpCacheFile) {\n if (!atomicCache.get().load(arpCacheFile)) {\n System.err.println(\"Error setting up ARP cache from file \" + arpCacheFile);\n System.exit(1);\n }\n\n System.out.println(this.hostname + \" loaded static ARP cache\");\n System.out.println(\"----------------------------------\");\n System.out.print(this.atomicCache.get().toString());\n System.out.println(\"----------------------------------\");\n }\n\n public AtomicReference<ArpCache> getAtomicCache() {\n return atomicCache;\n }\n\n public void setAtomicCache(AtomicReference<ArpCache> atomicCache) {\n this.atomicCache = atomicCache;\n }\n\n}" }, { "identifier": "NetIface", "path": "src/main/java/com/netapp/device/NetIface.java", "snippet": "public class NetIface extends Iface {\n\n protected String ipAddress; // IP地址\n protected String subnetMask; // 所在子网子网掩码\n\n public NetIface(String name, String ipAddress, String macAddress, String subnetMask) {\n super(name, macAddress);\n this.ipAddress = ipAddress;\n this.subnetMask = subnetMask;\n }\n\n public String getIpAddress() {\n return ipAddress;\n }\n\n public void setIpAddress(String ipAddress) {\n this.ipAddress = ipAddress;\n }\n\n public String getSubnetMask()\n { return this.subnetMask; }\n\n public void setSubnetMask(String subnetMask)\n { this.subnetMask = subnetMask; }\n\n}" } ]
import com.netapp.device.ArpEntry; import com.netapp.device.Iface; import com.netapp.device.NetDevice; import com.netapp.device.NetIface; import com.netapp.packet.*; import java.util.Map; import java.util.Objects; import static com.netapp.config.DeviceConfig.ROUTE_TABLE_PREFFIX; import static com.netapp.config.DeviceConfig.ROUTE_TABLE_SUFFIX;
5,245
package com.netapp.device.router; public class Router extends NetDevice { /** 路由表 */ private RouteTable routeTable; /** * 创建路由器。 * @param hostname 设备的主机名 * @param interfaces 接口映射 */ public Router(String hostname, Map<String, Iface> interfaces) { super(hostname, interfaces); routeTable = new RouteTable(); this.loadRouteTable(ROUTE_TABLE_PREFFIX + this.hostname + ROUTE_TABLE_SUFFIX); } /** * 处理 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ @Override protected void handleIPPacket(Ethernet etherPacket, Iface inIface) { if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is handling IP packet: " + ipPacket); // 检验校验和 int origCksum = ipPacket.getChecksum(); ipPacket.updateChecksum(); int calcCksum = ipPacket.getChecksum(); if (origCksum != calcCksum) { System.out.println(this.hostname + " found IP packet's checksum is wrong: "); return; } // TTL-1 ipPacket.setTtl((ipPacket.getTtl() - 1)); if (0 == ipPacket.getTtl()) { this.sendICMPPacket(etherPacket, inIface, 11, 0, false); return; } // 更新校验和 ipPacket.updateChecksum(); // 检查数据包的目的 IP 是否为接口 IP 之一 for (Iface iface : this.interfaces.values()) { if (Objects.equals(ipPacket.getDestinationIP(), ((NetIface) iface).getIpAddress())) { byte protocol = ipPacket.getProtocol(); // System.out.println("ipPacket protocol: " + protocol); if (protocol == IPv4.PROTOCOL_ICMP) { ICMP icmp = (ICMP) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + icmp); if (icmp.getIcmpType() == 8) { this.sendICMPPacket(etherPacket, inIface, 0, 0, true); } } else if (protocol == IPv4.PROTOCOL_DEFAULT){ Data data = (Data) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + data.getData()); } return; } } // 检查路由表并转发 this.forwardIPPacket(etherPacket, inIface); } /** * 转发 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ private void forwardIPPacket(Ethernet etherPacket, Iface inIface) { // 确保是 IP 数据包 if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is forwarding IP packet: " + ipPacket); // 获取目的 IP String dstIp = ipPacket.getDestinationIP(); // 查找匹配的路由表项 RouteEntry bestMatch = this.routeTable.lookup(dstIp); // 这种情况会转发到默认网关 /* // 如果没有匹配的项,则发 ICMP if (null == bestMatch) { this.sendICMPPacket(etherPacket, inIface, 3, 0, false); return; } */ // 确保不将数据包发送回它进入的接口 Iface outIface = bestMatch.getInterface(); if (outIface == inIface) { return; } // 设置以太网头部中的源 MAC 地址 String srcMac = outIface.getMacAddress(); etherPacket.setSourceMAC(srcMac); // 如果没有网关,那么下一跳是目的地 IP ,设置目的 MAC 的时候可以直接设置目的地的MAC,否则设置网关的MAC String nextHop = bestMatch.getGatewayAddress(); if (IPv4.DEFAULT_IP.equals(nextHop)) { nextHop = dstIp; } // 设置以太网头部中的目标 MAC 地址
package com.netapp.device.router; public class Router extends NetDevice { /** 路由表 */ private RouteTable routeTable; /** * 创建路由器。 * @param hostname 设备的主机名 * @param interfaces 接口映射 */ public Router(String hostname, Map<String, Iface> interfaces) { super(hostname, interfaces); routeTable = new RouteTable(); this.loadRouteTable(ROUTE_TABLE_PREFFIX + this.hostname + ROUTE_TABLE_SUFFIX); } /** * 处理 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ @Override protected void handleIPPacket(Ethernet etherPacket, Iface inIface) { if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is handling IP packet: " + ipPacket); // 检验校验和 int origCksum = ipPacket.getChecksum(); ipPacket.updateChecksum(); int calcCksum = ipPacket.getChecksum(); if (origCksum != calcCksum) { System.out.println(this.hostname + " found IP packet's checksum is wrong: "); return; } // TTL-1 ipPacket.setTtl((ipPacket.getTtl() - 1)); if (0 == ipPacket.getTtl()) { this.sendICMPPacket(etherPacket, inIface, 11, 0, false); return; } // 更新校验和 ipPacket.updateChecksum(); // 检查数据包的目的 IP 是否为接口 IP 之一 for (Iface iface : this.interfaces.values()) { if (Objects.equals(ipPacket.getDestinationIP(), ((NetIface) iface).getIpAddress())) { byte protocol = ipPacket.getProtocol(); // System.out.println("ipPacket protocol: " + protocol); if (protocol == IPv4.PROTOCOL_ICMP) { ICMP icmp = (ICMP) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + icmp); if (icmp.getIcmpType() == 8) { this.sendICMPPacket(etherPacket, inIface, 0, 0, true); } } else if (protocol == IPv4.PROTOCOL_DEFAULT){ Data data = (Data) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + data.getData()); } return; } } // 检查路由表并转发 this.forwardIPPacket(etherPacket, inIface); } /** * 转发 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ private void forwardIPPacket(Ethernet etherPacket, Iface inIface) { // 确保是 IP 数据包 if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is forwarding IP packet: " + ipPacket); // 获取目的 IP String dstIp = ipPacket.getDestinationIP(); // 查找匹配的路由表项 RouteEntry bestMatch = this.routeTable.lookup(dstIp); // 这种情况会转发到默认网关 /* // 如果没有匹配的项,则发 ICMP if (null == bestMatch) { this.sendICMPPacket(etherPacket, inIface, 3, 0, false); return; } */ // 确保不将数据包发送回它进入的接口 Iface outIface = bestMatch.getInterface(); if (outIface == inIface) { return; } // 设置以太网头部中的源 MAC 地址 String srcMac = outIface.getMacAddress(); etherPacket.setSourceMAC(srcMac); // 如果没有网关,那么下一跳是目的地 IP ,设置目的 MAC 的时候可以直接设置目的地的MAC,否则设置网关的MAC String nextHop = bestMatch.getGatewayAddress(); if (IPv4.DEFAULT_IP.equals(nextHop)) { nextHop = dstIp; } // 设置以太网头部中的目标 MAC 地址
ArpEntry arpEntry = this.atomicCache.get().lookup(nextHop);
0
2023-12-23 13:03:07+00:00
8k
strokegmd/StrokeClient
stroke/client/clickgui/ClickGuiScreen.java
[ { "identifier": "StrokeClient", "path": "stroke/client/StrokeClient.java", "snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpublic static String name = \"[stroke] client ・ \";\r\n\tpublic static String version = \"v1.0.00\";\r\n\t\r\n\tpublic static StrokeClient instance;\r\n\tpublic static ClickGuiScreen clickGui;\r\n\t\r\n\tpublic static SettingsManager settingsManager;\r\n\t\r\n\tpublic static boolean destructed = false;\r\n\t\r\n\tpublic StrokeClient()\r\n\t{\r\n\t\tinstance = this;\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t}\r\n\t\r\n\tpublic static void launchClient() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\t\r\n\t\tViaMCP.getInstance().start();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] Launching Stroke Client \" + version + \"!\");\r\n\t\t\r\n\t\tModuleManager.loadModules();\r\n\t\tCommandManager.loadCommands();\r\n\t\t\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.autoenable) {\r\n\t\t\t\tmodule.toggle(); module.toggle(); // bugfix lmao\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] All done!\");\r\n\t}\r\n\t\r\n\tpublic static void onKeyPress(int key) {\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.keybind == key && !(mc.currentScreen instanceof GuiChat) && !(mc.currentScreen instanceof GuiContainer) && !(mc.currentScreen instanceof GuiEditSign)) {\r\n\t\t\t\tmodule.toggle();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static int getScaledWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledWidth();\r\n\t}\r\n\t\r\n\tpublic static int getScaledHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledHeight();\r\n\t}\r\n\t\r\n\tpublic static int getDisplayWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayWidth / 2;\r\n\t}\r\n\t\r\n\tpublic static int getDisplayHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayHeight / 2;\r\n\t}\r\n\t\r\n\tpublic static String getUsername() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.getSession().getUsername();\r\n\t}\r\n\t\r\n\tpublic static void sendChatMessage(String message) {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tTextComponentString component = new TextComponentString(\"[\\2479Stroke§r] \" + message);\r\n\t\tmc.ingameGUI.getChatGUI().printChatMessage(component);\r\n\t}\r\n}" }, { "identifier": "Component", "path": "stroke/client/clickgui/component/Component.java", "snippet": "public class Component {\n\n\tpublic void renderComponent() {\n\t\t\n\t}\n\t\n\tpublic void updateComponent(int mouseX, int mouseY) {\n\t\t\n\t}\n\t\n\tpublic void mouseClicked(int mouseX, int mouseY, int button) {\n\t\t\n\t}\n\t\n\tpublic void mouseReleased(int mouseX, int mouseY, int mouseButton) {\n\t}\n\t\n\tpublic int getParentHeight() {\n\t\treturn 0;\n\t}\n\t\n\tpublic void keyTyped(char typedChar, int key) {\n\t\t\n\t}\n\t\n\tpublic void setOff(int newOff) {\n\t\t\n\t}\n\t\n\tpublic int getHeight() {\n\t\treturn 0;\n\t}\n}" }, { "identifier": "Frame", "path": "stroke/client/clickgui/component/Frame.java", "snippet": "public class Frame {\n\n\tpublic ArrayList<Component> components;\n\tpublic ModuleCategory category;\n\tprivate boolean open;\n\tprivate int width;\n\tprivate int y;\n\tprivate int x;\n\tprivate int barHeight;\n\tprivate boolean isDragging;\n\tpublic int dragX;\n\tpublic int dragY;\n\tpublic static int color;\n\t\n\tpublic Frame(ModuleCategory cat) {\n\t\tthis.components = new ArrayList<Component>();\n\t\tthis.category = cat;\n\t\tthis.width = 88;\n\t\tthis.x = 0;\n\t\tthis.y = 60;\n\t\tthis.dragX = 0;\n\t\tthis.barHeight = 12;\n\t\tthis.open = false;\n\t\tthis.isDragging = false;\n\t\tint tY = this.barHeight;\n\n\t\tfor(BaseModule mod : ModuleManager.getModulesInCategory(category)) {\n\t\t\tButton modButton = new Button(\n\t\t\t\t\tmod, \n\t\t\t\t\tthis, \n\t\t\t\t\ttY);\n\t\t\tthis.components.add(modButton);\n\t\t\ttY += 12;\n\t\t}\n\t}\n\t\n\tpublic ArrayList<Component> getComponents() {\n\t\treturn components;\n\t}\n\t\n\tpublic void setX(int newX) {\n\t\tthis.x = newX;\n\t}\n\t\n\tpublic void setY(int newY) {\n\t\tthis.y = newY;\n\t}\n\t\n\tpublic void setDrag(boolean drag) {\n\t\tthis.isDragging = drag;\n\t}\n\t\n\tpublic boolean isOpen() {\n\t\treturn open;\n\t}\n\t\n\tpublic void setOpen(boolean open) {\n\t\tthis.open = open;\n\t}\n\t\n\tpublic void renderFrame(FontRenderer fontRenderer) {\n\t\tGui.drawRect(this.x, this.y-1, this.x + this.width, this.y, ColorUtils.secondaryObjectColor);\n\t\tGui.drawRect(this.x, this.y, this.x + this.width, this.y + 12, ColorUtils.secondaryObjectColor);\n\t\tMinecraft.getMinecraft().fontRendererObj.drawStringWithShadow(this.category.name(), this.x + 5, this.y + 2, -1);\n\n\t\tif(this.open) {\n\t\t\tif(!this.components.isEmpty()) {\n\t\t\t\tfor(Component component : components) {\n\t\t\t\t\tcomponent.renderComponent();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void refresh() {\n\t\tint off = this.barHeight;\n\t\tfor(Component comp : components) {\n\t\t\tcomp.setOff(off);\n\t\t\toff += comp.getHeight();\n\t\t}\n\t}\n\t\n\tpublic int getX() {\n\t\treturn x;\n\t}\n\t\n\tpublic int getY() {\n\t\treturn y;\n\t}\n\t\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\t\n\tpublic void updatePosition(int mouseX, int mouseY) {\n\t\tif(this.isDragging) {\n\t\t\tthis.setX(mouseX - dragX);\n\t\t\tthis.setY(mouseY - dragY);\n\t\t}\n\t}\n\t\n\tpublic boolean isWithinHeader(int x, int y) {\n\t\tif(x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.barHeight) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n}" }, { "identifier": "ModuleCategory", "path": "stroke/client/modules/ModuleCategory.java", "snippet": "public enum ModuleCategory {\r\n\tCombat, Movement, Player, Render, Fun, Misc\r\n}\r" }, { "identifier": "ClickGui", "path": "stroke/client/modules/render/ClickGui.java", "snippet": "public class ClickGui extends BaseModule {\r\n public static ClickGui instance;\r\n \r\n public ClickGui() {\r\n super(\"ClickGui\", \"Manage module options\", Keyboard.KEY_RSHIFT, ModuleCategory.Render, false);\r\n StrokeClient.instance.settingsManager.rSetting(new Setting(\"Tooltips\", this, true));\r\n StrokeClient.instance.settingsManager.rSetting(new Setting(\"Snow\", this, true));\r\n instance = this;\r\n }\r\n \r\n public void onUpdate() {\r\n \tthis.mc.displayGuiScreen(StrokeClient.clickGui);\r\n }\r\n \r\n public void onDisable() {\r\n \tthis.mc.displayGuiScreen((GuiScreen)null);\r\n this.mc.setIngameFocus();\r\n }\r\n}" }, { "identifier": "ParticleEngine", "path": "stroke/client/util/ParticleEngine.java", "snippet": "public class ParticleEngine\n{\n public CopyOnWriteArrayList<Particle> particles;\n public float lastMouseX;\n public float lastMouseY;\n \n public ParticleEngine() {\n this.particles = Lists.newCopyOnWriteArrayList();\n }\n \n public static void drawCircle(final double x, final double y, final float radius, final int color) {\n final float alpha = (color >> 24 & 0xFF) / 255.0f;\n final float red = (color >> 16 & 0xFF) / 255.0f;\n final float green = (color >> 8 & 0xFF) / 255.0f;\n final float blue = (color & 0xFF) / 255.0f;\n GL11.glColor4f(red, green, blue, alpha);\n GL11.glBegin(9);\n for (int i = 0; i <= 360; ++i) {\n GL11.glVertex2d(x + Math.sin(i * 3.141526 / 180.0) * radius, y + Math.cos(i * 3.141526 / 180.0) * radius);\n }\n GL11.glEnd();\n }\n \n public static void disableRender2D() {\n GL11.glDisable(3042);\n GL11.glEnable(2884);\n GL11.glEnable(3553);\n GL11.glDisable(2848);\n GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n GlStateManager.shadeModel(7424);\n GlStateManager.disableBlend();\n GlStateManager.enableTexture2D();\n }\n \n public static void enableRender2D() {\n GL11.glEnable(3042);\n GL11.glDisable(2884);\n GL11.glDisable(3553);\n GL11.glEnable(2848);\n GL11.glBlendFunc(770, 771);\n GL11.glLineWidth(1.0f);\n }\n \n public static void setColor(final int colorHex) {\n final float alpha = (colorHex >> 24 & 0xFF) / 255.0f;\n final float red = (colorHex >> 16 & 0xFF) / 255.0f;\n final float green = (colorHex >> 8 & 0xFF) / 255.0f;\n final float blue = (colorHex & 0xFF) / 255.0f;\n GL11.glColor4f(red, green, blue, (alpha == 0.0f) ? 1.0f : alpha);\n }\n \n public static void drawLine(final double startX, final double startY, final double endX, final double endY, final float thickness, final int color) {\n enableRender2D();\n setColor(color);\n GL11.glLineWidth(thickness);\n GL11.glBegin(1);\n GL11.glVertex2d(startX, startY);\n GL11.glVertex2d(endX, endY);\n GL11.glEnd();\n disableRender2D();\n }\n \n public void render(final float mouseX, final float mouseY) {\n GlStateManager.enableBlend();\n GlStateManager.disableAlpha();\n GlStateManager.color(1.0f, 1.0f, 1.0f, 0.2f);\n final ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());\n final float xOffset = 0.0f;\n final float yOffset = 0.0f;\n while (this.particles.size() < sr.getScaledWidth() / 8.0f) {\n this.particles.add(new Particle(sr, new Random().nextFloat() + 1.0f, new Random().nextFloat() * 5.0f + 5.0f));\n }\n final ArrayList toRemove = Lists.newArrayList();\n final int maxOpacity = 52;\n final int color = -570425345;\n final int mouseRadius = 100;\n for (final Particle particle : this.particles) {\n final double particleX = particle.x + Math.sin(particle.ticks / 10.0f) * 50.0 + -xOffset / 5.0f;\n final double particleY = particle.ticks * particle.speed * particle.ticks / 10.0f + -yOffset / 5.0f;\n if (particleY < sr.getScaledHeight()) {\n if (particle.opacity < maxOpacity) {\n final Particle particle2 = particle;\n particle2.opacity += 2.0f;\n }\n if (particle.opacity > maxOpacity) {\n particle.opacity = (float)maxOpacity;\n }\n final Color c = new Color(255, 255, 255, (int)particle.opacity);\n final float particle_thickness = 1.0f;\n final int line_color = new Color(1.0f, (1.0f - (float)(particleY / sr.getScaledHeight())) / 2.0f, 1.0f, 1.0f).getRGB();\n GlStateManager.enableBlend();\n this.drawBorderedCircle(particleX, particleY, particle.radius * particle.opacity / maxOpacity, color, color);\n }\n particle.ticks += (float)0.05;\n if (particleY <= sr.getScaledHeight() && particleY >= 0.0 && particleX <= sr.getScaledWidth() && particleX >= 0.0) {\n continue;\n }\n toRemove.add(particle);\n }\n this.particles.removeAll(toRemove);\n GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);\n GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n GlStateManager.enableBlend();\n GlStateManager.disableAlpha();\n this.lastMouseX = (float)GLUtils.getMouseX();\n this.lastMouseY = (float)GLUtils.getMouseY();\n }\n \n public void drawBorderedCircle(final double x, final double y, final float radius, final int outsideC, final int insideC) {\n GL11.glDisable(3553);\n GL11.glBlendFunc(770, 771);\n GL11.glEnable(2848);\n GL11.glPushMatrix();\n GL11.glScalef(0.1f, 0.1f, 0.1f);\n drawCircle(x * 10.0, y * 10.0, radius * 10.0f, insideC);\n GL11.glScalef(10.0f, 10.0f, 10.0f);\n GL11.glPopMatrix();\n GL11.glEnable(3553);\n GL11.glDisable(2848);\n }\n}" } ]
import java.io.IOException; import java.util.ArrayList; import org.lwjgl.input.Keyboard; import net.minecraft.client.gui.GuiScreen; import net.stroke.client.StrokeClient; import net.stroke.client.clickgui.component.Component; import net.stroke.client.clickgui.component.Frame; import net.stroke.client.modules.ModuleCategory; import net.stroke.client.modules.render.ClickGui; import net.stroke.client.util.ParticleEngine;
3,690
package net.stroke.client.clickgui; public class ClickGuiScreen extends GuiScreen { public static ArrayList<Frame> frames; public static int color; public ParticleEngine particleEngine; public ClickGuiScreen() { this.frames = new ArrayList<Frame>(); int frameX = 10; int frameY = 10; for(ModuleCategory category : ModuleCategory.values()) { Frame frame = new Frame(category); frame.setY(frameY); frame.setX(frameX); frames.add(frame); frameX += 100; } } @Override public void initGui() { this.particleEngine = new ParticleEngine(); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) {
package net.stroke.client.clickgui; public class ClickGuiScreen extends GuiScreen { public static ArrayList<Frame> frames; public static int color; public ParticleEngine particleEngine; public ClickGuiScreen() { this.frames = new ArrayList<Frame>(); int frameX = 10; int frameY = 10; for(ModuleCategory category : ModuleCategory.values()) { Frame frame = new Frame(category); frame.setY(frameY); frame.setX(frameX); frames.add(frame); frameX += 100; } } @Override public void initGui() { this.particleEngine = new ParticleEngine(); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) {
boolean snow = StrokeClient.instance.settingsManager.getSettingByName("ClickGui", "Snow").getValBoolean();
0
2023-12-31 10:56:59+00:00
8k
piovas-lu/condominio
src/main/java/app/condominio/controller/CobrancaController.java
[ { "identifier": "Cobranca", "path": "src/main/java/app/condominio/domain/Cobranca.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"cobrancas\")\r\npublic class Cobranca implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idcobranca\")\r\n\tprivate Long idCobranca;\r\n\r\n\t@NotNull\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"motivoemissao\")\r\n\tprivate MotivoEmissao motivoEmissao;\r\n\r\n\t@Size(max = 10)\r\n\t@NotBlank\r\n\tprivate String numero;\r\n\r\n\t@Size(max = 3)\r\n\tprivate String parcela;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"dataemissao\")\r\n\tprivate LocalDate dataEmissao;\r\n\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"datavencimento\")\r\n\tprivate LocalDate dataVencimento;\r\n\r\n\t@NotNull\r\n\t@Min(0)\r\n\tprivate BigDecimal valor;\r\n\r\n\t@Min(0)\r\n\tprivate BigDecimal desconto;\r\n\r\n\t@Min(0)\r\n\tprivate BigDecimal abatimento;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"outrasdeducoes\")\r\n\tprivate BigDecimal outrasDeducoes;\r\n\r\n\t// Juros tem atualização no banco de dados\r\n\t@Min(0)\r\n\t@Column(name = \"jurosmora\")\r\n\tprivate BigDecimal jurosMora;\r\n\r\n\t// Multa tem atualização no banco de dados\r\n\t@Min(0)\r\n\tprivate BigDecimal multa;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"outrosacrescimos\")\r\n\tprivate BigDecimal outrosAcrescimos;\r\n\r\n\t// Total é atualizado no banco de dados quando Juros e Multa são atualizados\r\n\t@Min(0)\r\n\t@NotNull\r\n\tprivate BigDecimal total;\r\n\r\n\t@Size(max = 255)\r\n\tprivate String descricao;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"percentualjurosmes\")\r\n\tprivate Float percentualJurosMes;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"percentualmulta\")\r\n\tprivate Float percentualMulta;\r\n\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate SituacaoCobranca situacao;\r\n\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"datarecebimento\")\r\n\tprivate LocalDate dataRecebimento;\r\n\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"motivobaixa\")\r\n\tprivate MotivoBaixa motivoBaixa;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idmoradia\")\r\n\tprivate Moradia moradia;\r\n\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idcondominio\")\r\n\tprivate Condominio condominio;\r\n\r\n\tpublic Long getIdCobranca() {\r\n\t\treturn idCobranca;\r\n\t}\r\n\r\n\tpublic void setIdCobranca(Long idCobranca) {\r\n\t\tthis.idCobranca = idCobranca;\r\n\t}\r\n\r\n\tpublic Moradia getMoradia() {\r\n\t\treturn moradia;\r\n\t}\r\n\r\n\tpublic void setMoradia(Moradia moradia) {\r\n\t\tthis.moradia = moradia;\r\n\t}\r\n\r\n\tpublic MotivoEmissao getMotivoEmissao() {\r\n\t\treturn motivoEmissao;\r\n\t}\r\n\r\n\tpublic void setMotivoEmissao(MotivoEmissao motivoEmissao) {\r\n\t\tthis.motivoEmissao = motivoEmissao;\r\n\t}\r\n\r\n\tpublic String getNumero() {\r\n\t\treturn numero;\r\n\t}\r\n\r\n\tpublic void setNumero(String numero) {\r\n\t\tthis.numero = numero;\r\n\t}\r\n\r\n\tpublic String getParcela() {\r\n\t\treturn parcela;\r\n\t}\r\n\r\n\tpublic void setParcela(String parcela) {\r\n\t\tthis.parcela = parcela;\r\n\t}\r\n\r\n\tpublic LocalDate getDataEmissao() {\r\n\t\treturn dataEmissao;\r\n\t}\r\n\r\n\tpublic void setDataEmissao(LocalDate dataEmissao) {\r\n\t\tthis.dataEmissao = dataEmissao;\r\n\t}\r\n\r\n\tpublic LocalDate getDataVencimento() {\r\n\t\treturn dataVencimento;\r\n\t}\r\n\r\n\tpublic void setDataVencimento(LocalDate dataVencimento) {\r\n\t\tthis.dataVencimento = dataVencimento;\r\n\t}\r\n\r\n\tpublic BigDecimal getValor() {\r\n\t\treturn valor;\r\n\t}\r\n\r\n\tpublic void setValor(BigDecimal valor) {\r\n\t\tthis.valor = valor;\r\n\t}\r\n\r\n\tpublic BigDecimal getDesconto() {\r\n\t\treturn desconto;\r\n\t}\r\n\r\n\tpublic void setDesconto(BigDecimal desconto) {\r\n\t\tthis.desconto = desconto;\r\n\t}\r\n\r\n\tpublic BigDecimal getAbatimento() {\r\n\t\treturn abatimento;\r\n\t}\r\n\r\n\tpublic void setAbatimento(BigDecimal abatimento) {\r\n\t\tthis.abatimento = abatimento;\r\n\t}\r\n\r\n\tpublic BigDecimal getOutrasDeducoes() {\r\n\t\treturn outrasDeducoes;\r\n\t}\r\n\r\n\tpublic void setOutrasDeducoes(BigDecimal outrasDeducoes) {\r\n\t\tthis.outrasDeducoes = outrasDeducoes;\r\n\t}\r\n\r\n\tpublic BigDecimal getJurosMora() {\r\n\t\treturn jurosMora;\r\n\t}\r\n\r\n\tpublic void setJurosMora(BigDecimal jurosMora) {\r\n\t\tthis.jurosMora = jurosMora;\r\n\t}\r\n\r\n\tpublic BigDecimal getMulta() {\r\n\t\treturn multa;\r\n\t}\r\n\r\n\tpublic void setMulta(BigDecimal multa) {\r\n\t\tthis.multa = multa;\r\n\t}\r\n\r\n\tpublic BigDecimal getOutrosAcrescimos() {\r\n\t\treturn outrosAcrescimos;\r\n\t}\r\n\r\n\tpublic void setOutrosAcrescimos(BigDecimal outrosAcrescimos) {\r\n\t\tthis.outrosAcrescimos = outrosAcrescimos;\r\n\t}\r\n\r\n\tpublic BigDecimal getTotal() {\r\n\t\treturn total;\r\n\t}\r\n\r\n\tpublic void setTotal(BigDecimal total) {\r\n\t\tthis.total = total;\r\n\t}\r\n\r\n\tpublic String getDescricao() {\r\n\t\treturn descricao;\r\n\t}\r\n\r\n\tpublic void setDescricao(String descricao) {\r\n\t\tthis.descricao = descricao;\r\n\t}\r\n\r\n\tpublic Float getPercentualJurosMes() {\r\n\t\treturn percentualJurosMes;\r\n\t}\r\n\r\n\tpublic void setPercentualJurosMes(Float percentualJurosMes) {\r\n\t\tthis.percentualJurosMes = percentualJurosMes;\r\n\t}\r\n\r\n\tpublic Float getPercentualMulta() {\r\n\t\treturn percentualMulta;\r\n\t}\r\n\r\n\tpublic void setPercentualMulta(Float percentualMulta) {\r\n\t\tthis.percentualMulta = percentualMulta;\r\n\t}\r\n\r\n\tpublic SituacaoCobranca getSituacao() {\r\n\t\treturn situacao;\r\n\t}\r\n\r\n\tpublic void setSituacao(SituacaoCobranca situacao) {\r\n\t\tthis.situacao = situacao;\r\n\t}\r\n\r\n\tpublic LocalDate getDataRecebimento() {\r\n\t\treturn dataRecebimento;\r\n\t}\r\n\r\n\tpublic void setDataRecebimento(LocalDate dataRecebimento) {\r\n\t\tthis.dataRecebimento = dataRecebimento;\r\n\t}\r\n\r\n\tpublic MotivoBaixa getMotivoBaixa() {\r\n\t\treturn motivoBaixa;\r\n\t}\r\n\r\n\tpublic void setMotivoBaixa(MotivoBaixa motivoBaixa) {\r\n\t\tthis.motivoBaixa = motivoBaixa;\r\n\t}\r\n\r\n\tpublic Condominio getCondominio() {\r\n\t\treturn condominio;\r\n\t}\r\n\r\n\tpublic void setCondominio(Condominio condominio) {\r\n\t\tthis.condominio = condominio;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tString s = numero;\r\n\t\tif (parcela != null) {\r\n\t\t\ts += \" - \" + parcela;\r\n\t\t}\r\n\t\treturn s;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idCobranca == null) ? 0 : idCobranca.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tCobranca other = (Cobranca) obj;\r\n\t\tif (idCobranca == null) {\r\n\t\t\tif (other.idCobranca != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idCobranca.equals(other.idCobranca)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r" }, { "identifier": "Moradia", "path": "src/main/java/app/condominio/domain/Moradia.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"moradias\")\r\npublic class Moradia implements Serializable, Comparable<Moradia> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idmoradia\")\r\n\tprivate Long idMoradia;\r\n\r\n\t@Size(min = 1, max = 10)\r\n\t@NotBlank\r\n\tprivate String sigla;\r\n\r\n\t@NotNull\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate TipoMoradia tipo;\r\n\r\n\tprivate Float area;\r\n\r\n\t@Max(100)\r\n\t@Min(0)\r\n\t@Column(name = \"fracaoideal\")\r\n\tprivate Float fracaoIdeal;\r\n\r\n\t@Size(max = 30)\r\n\tprivate String matricula;\r\n\r\n\tprivate Integer vagas;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idbloco\")\r\n\tprivate Bloco bloco;\r\n\r\n\t@OneToMany(mappedBy = \"moradia\", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)\r\n\t@OrderBy(value = \"dataEntrada\")\r\n\t@Valid\r\n\tprivate List<Relacao> relacoes = new ArrayList<>();\r\n\r\n\t@OneToMany(mappedBy = \"moradia\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\t@OrderBy(value = \"numero, parcela\")\r\n\tprivate List<Cobranca> cobrancas = new ArrayList<>();\r\n\r\n\tpublic Long getIdMoradia() {\r\n\t\treturn idMoradia;\r\n\t}\r\n\r\n\tpublic void setIdMoradia(Long idMoradia) {\r\n\t\tthis.idMoradia = idMoradia;\r\n\t}\r\n\r\n\tpublic String getSigla() {\r\n\t\treturn sigla;\r\n\t}\r\n\r\n\tpublic void setSigla(String sigla) {\r\n\t\tthis.sigla = sigla;\r\n\t}\r\n\r\n\tpublic TipoMoradia getTipo() {\r\n\t\treturn tipo;\r\n\t}\r\n\r\n\tpublic void setTipo(TipoMoradia tipo) {\r\n\t\tthis.tipo = tipo;\r\n\t}\r\n\r\n\tpublic Float getArea() {\r\n\t\treturn area;\r\n\t}\r\n\r\n\tpublic void setArea(Float area) {\r\n\t\tthis.area = area;\r\n\t}\r\n\r\n\tpublic Float getFracaoIdeal() {\r\n\t\treturn fracaoIdeal;\r\n\t}\r\n\r\n\tpublic void setFracaoIdeal(Float fracaoIdeal) {\r\n\t\tthis.fracaoIdeal = fracaoIdeal;\r\n\t}\r\n\r\n\tpublic String getMatricula() {\r\n\t\treturn matricula;\r\n\t}\r\n\r\n\tpublic void setMatricula(String matricula) {\r\n\t\tthis.matricula = matricula;\r\n\t}\r\n\r\n\tpublic Integer getVagas() {\r\n\t\treturn vagas;\r\n\t}\r\n\r\n\tpublic void setVagas(Integer vagas) {\r\n\t\tthis.vagas = vagas;\r\n\t}\r\n\r\n\tpublic Bloco getBloco() {\r\n\t\treturn bloco;\r\n\t}\r\n\r\n\tpublic void setBloco(Bloco bloco) {\r\n\t\tthis.bloco = bloco;\r\n\t}\r\n\r\n\tpublic List<Relacao> getRelacoes() {\r\n\t\treturn relacoes;\r\n\t}\r\n\r\n\tpublic void setRelacoes(List<Relacao> relacoes) {\r\n\t\tthis.relacoes = relacoes;\r\n\t}\r\n\r\n\tpublic List<Cobranca> getCobrancas() {\r\n\t\treturn cobrancas;\r\n\t}\r\n\r\n\tpublic void setCobrancas(List<Cobranca> cobrancas) {\r\n\t\tthis.cobrancas = cobrancas;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn bloco.toString() + \" - \" + sigla;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idMoradia == null) ? 0 : idMoradia.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tMoradia other = (Moradia) obj;\r\n\t\tif (idMoradia == null) {\r\n\t\t\tif (other.idMoradia != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idMoradia.equals(other.idMoradia)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Moradia arg0) {\r\n\t\treturn this.toString().compareTo(arg0.toString());\r\n\t}\r\n}\r" }, { "identifier": "MotivoBaixa", "path": "src/main/java/app/condominio/domain/enums/MotivoBaixa.java", "snippet": "public enum MotivoBaixa {\r\n\r\n\t// @formatter:off\r\n\tN(\"Recebimento normal\"),\r\n\tR(\"Renegociação de dívida\"),\r\n\tP(\"Prescrição\"),\r\n\tO(\"Outras\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\r\n\tprivate MotivoBaixa(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n}\r" }, { "identifier": "MotivoEmissao", "path": "src/main/java/app/condominio/domain/enums/MotivoEmissao.java", "snippet": "public enum MotivoEmissao {\r\n\r\n\t// @formatter:off\r\n\tO(\"Normal\"),\r\n\tE(\"Extra\"),\r\n\tA(\"Avulsa\"),\r\n\tR(\"Renegociação\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\r\n\tprivate MotivoEmissao(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n}\r" }, { "identifier": "SituacaoCobranca", "path": "src/main/java/app/condominio/domain/enums/SituacaoCobranca.java", "snippet": "public enum SituacaoCobranca {\r\n\r\n\t// @formatter:off\r\n\tN(\"Normal\"),\r\n\tA(\"Notificado\"),\r\n\tP(\"Protestado\"),\r\n\tJ(\"Ação Judicial\"),\r\n\tO(\"Outras\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\r\n\tprivate SituacaoCobranca(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n\r\n}\r" }, { "identifier": "CobrancaService", "path": "src/main/java/app/condominio/service/CobrancaService.java", "snippet": "public interface CobrancaService extends CrudService<Cobranca, Long> {\r\n\r\n\t/**\r\n\t * @return Retorna um BigDecimal com o valor total da inadimplência do\r\n\t * Condomínio na data atual (considera o valor total da Cobrança, com\r\n\t * acréscimos e deduções). Nunca retorna nulo, se não houver\r\n\t * inadimplência, retorna BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal inadimplencia();\r\n\r\n\t/**\r\n\t * @return Retorna uma lista do tipo List{@literal <}Cobranca{@literal >} com\r\n\t * todas as Cobrancas do Condomínio vencidas na data atual (considera o\r\n\t * valor total da Cobrança, com acréscimos e deduções). Nunca retorna\r\n\t * nulo, se não houver inadimplência, retorna uma lista vazia.\r\n\t */\r\n\tpublic List<Cobranca> listarInadimplencia();\r\n\r\n}\r" }, { "identifier": "MoradiaService", "path": "src/main/java/app/condominio/service/MoradiaService.java", "snippet": "public interface MoradiaService extends CrudService<Moradia, Long> {\r\n\r\n}\r" } ]
import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import app.condominio.domain.Cobranca; import app.condominio.domain.Moradia; import app.condominio.domain.enums.MotivoBaixa; import app.condominio.domain.enums.MotivoEmissao; import app.condominio.domain.enums.SituacaoCobranca; import app.condominio.service.CobrancaService; import app.condominio.service.MoradiaService;
4,611
package app.condominio.controller; @Controller @RequestMapping("sindico/cobrancas") public class CobrancaController { @Autowired private CobrancaService cobrancaService; @Autowired MoradiaService moradiaService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "financeiro", "cobrancas" }; } @ModelAttribute("motivosEmissao") public MotivoEmissao[] motivosEmissao() { return MotivoEmissao.values(); } @ModelAttribute("motivosBaixa") public MotivoBaixa[] motivosBaixa() { return MotivoBaixa.values(); } @ModelAttribute("situacoes") public SituacaoCobranca[] situacoes() { return SituacaoCobranca.values(); } @ModelAttribute("moradias")
package app.condominio.controller; @Controller @RequestMapping("sindico/cobrancas") public class CobrancaController { @Autowired private CobrancaService cobrancaService; @Autowired MoradiaService moradiaService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "financeiro", "cobrancas" }; } @ModelAttribute("motivosEmissao") public MotivoEmissao[] motivosEmissao() { return MotivoEmissao.values(); } @ModelAttribute("motivosBaixa") public MotivoBaixa[] motivosBaixa() { return MotivoBaixa.values(); } @ModelAttribute("situacoes") public SituacaoCobranca[] situacoes() { return SituacaoCobranca.values(); } @ModelAttribute("moradias")
public List<Moradia> moradias() {
1
2023-12-29 22:19:42+00:00
8k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/distribution/service/DistributionOrderService.java
[ { "identifier": "DistributionOrder", "path": "framework/src/main/java/cn/lili/modules/distribution/entity/dos/DistributionOrder.java", "snippet": "@Data\n@ApiModel(value = \"分销订单\")\n@TableName(\"li_distribution_order\")\n@NoArgsConstructor\npublic class DistributionOrder extends BaseIdEntity {\n\n private static final long serialVersionUID = 501799944909496507L;\n\n @CreatedDate\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @TableField(fill = FieldFill.INSERT)\n @ApiModelProperty(value = \"创建时间\", hidden = true)\n private Date createTime;\n\n /**\n * @see DistributionOrderStatusEnum\n */\n @ApiModelProperty(value = \"分销订单状态\")\n private String distributionOrderStatus;\n @ApiModelProperty(value = \"购买会员的id\")\n private String memberId;\n @ApiModelProperty(value = \"购买会员的名称\")\n private String memberName;\n @ApiModelProperty(value = \"分销员id\")\n private String distributionId;\n @ApiModelProperty(value = \"分销员名称\")\n private String distributionName;\n\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(value = \"解冻日期\")\n private Date settleCycle;\n @ApiModelProperty(value = \"提成金额\")\n private Double rebate;\n @ApiModelProperty(value = \"退款金额\")\n private Double sellBackRebate;\n @ApiModelProperty(value = \"店铺id\")\n private String storeId;\n @ApiModelProperty(value = \"店铺名称\")\n private String storeName;\n @ApiModelProperty(value = \"订单编号\")\n private String orderSn;\n @ApiModelProperty(value = \"子订单编号\")\n private String orderItemSn;\n @ApiModelProperty(value = \"商品ID\")\n private String goodsId;\n @ApiModelProperty(value = \"商品名称\")\n private String goodsName;\n @ApiModelProperty(value = \"货品ID\")\n private String skuId;\n @ApiModelProperty(value = \"规格\")\n private String specs;\n @ApiModelProperty(value = \"图片\")\n private String image;\n @ApiModelProperty(value = \"商品数量\")\n private Integer num;\n\n public DistributionOrder(StoreFlow storeFlow) {\n distributionOrderStatus = DistributionOrderStatusEnum.NO_COMPLETED.name();\n memberId = storeFlow.getMemberId();\n memberName = storeFlow.getMemberName();\n rebate = storeFlow.getDistributionRebate();\n storeId = storeFlow.getStoreId();\n storeName = storeFlow.getStoreName();\n orderSn = storeFlow.getOrderSn();\n orderItemSn = storeFlow.getOrderItemSn();\n goodsId = storeFlow.getGoodsId();\n goodsName = storeFlow.getGoodsName();\n skuId = storeFlow.getSkuId();\n specs = storeFlow.getSpecs();\n image = storeFlow.getImage();\n num = storeFlow.getNum();\n }\n\n}" }, { "identifier": "DistributionOrderSearchParams", "path": "framework/src/main/java/cn/lili/modules/distribution/entity/vos/DistributionOrderSearchParams.java", "snippet": "@Data\n@ApiModel(value = \"分销订单查询对象\")\npublic class DistributionOrderSearchParams extends PageVO {\n\n private static final long serialVersionUID = -8736018687663645064L;\n\n @ApiModelProperty(value = \"分销员名称\")\n private String distributionName;\n\n @ApiModelProperty(value = \"订单sn\")\n private String orderSn;\n\n @ApiModelProperty(value = \"分销员ID\", hidden = true)\n private String distributionId;\n\n @ApiModelProperty(value = \"分销订单状态\")\n private String distributionOrderStatus;\n\n @ApiModelProperty(value = \"店铺ID\")\n private String storeId;\n\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(value = \"开始时间\")\n private Date startTime;\n\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(value = \"结束时间\")\n private Date endTime;\n\n\n public <T> QueryWrapper<T> queryWrapper() {\n QueryWrapper<T> queryWrapper = Wrappers.query();\n queryWrapper.like(StringUtils.isNotBlank(distributionName), \"distribution_name\", distributionName);\n queryWrapper.eq(StringUtils.isNotBlank(distributionOrderStatus), \"distribution_order_status\", distributionOrderStatus);\n queryWrapper.eq(StringUtils.isNotBlank(orderSn), \"order_sn\", orderSn);\n queryWrapper.eq(StringUtils.isNotBlank(distributionId), \"distribution_id\", distributionId);\n queryWrapper.eq(StringUtils.isNotBlank(storeId), \"store_id\", storeId);\n if (endTime != null && startTime != null) {\n endTime = DateUtil.endOfDate(endTime);\n queryWrapper.between(\"create_time\", startTime, endTime);\n }\n return queryWrapper;\n }\n\n}" }, { "identifier": "AfterSale", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/dos/AfterSale.java", "snippet": "@Data\n@TableName(\"li_after_sale\")\n@ApiModel(value = \"售后\")\npublic class AfterSale extends BaseEntity {\n\n private static final long serialVersionUID = -5339221840646353416L;\n\n //基础信息\n\n @ApiModelProperty(value = \"售后服务单号\")\n private String sn;\n\n @ApiModelProperty(value = \"订单编号\")\n private String orderSn;\n\n @ApiModelProperty(value = \"订单货物编号\")\n private String orderItemSn;\n\n @ApiModelProperty(value = \"交易编号\")\n private String tradeSn;\n\n @ApiModelProperty(value = \"会员ID\")\n private String memberId;\n\n @ApiModelProperty(value = \"会员名称\")\n @Sensitive(strategy = SensitiveStrategy.PHONE)\n private String memberName;\n\n @ApiModelProperty(value = \"商家ID\")\n private String storeId;\n\n @ApiModelProperty(value = \"商家名称\")\n private String storeName;\n\n //商品信息\n\n @ApiModelProperty(value = \"商品ID\")\n private String goodsId;\n @ApiModelProperty(value = \"货品ID\")\n private String skuId;\n @ApiModelProperty(value = \"申请数量\")\n private Integer num;\n @ApiModelProperty(value = \"商品图片\")\n private String goodsImage;\n @ApiModelProperty(value = \"商品名称\")\n private String goodsName;\n\n @ApiModelProperty(value = \"规格json\")\n private String specs;\n @ApiModelProperty(value = \"实际金额\")\n private Double flowPrice;\n\n\n //交涉信息\n\n @ApiModelProperty(value = \"申请原因\")\n private String reason;\n\n @ApiModelProperty(value = \"问题描述\")\n private String problemDesc;\n\n @ApiModelProperty(value = \"评价图片\")\n private String afterSaleImage;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleTypeEnum\n */\n @ApiModelProperty(value = \"售后类型\", allowableValues = \"RETURN_GOODS,RETURN_MONEY\")\n private String serviceType;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleStatusEnum\n */\n @ApiModelProperty(value = \"售后单状态\", allowableValues = \"APPLY,PASS,REFUSE,BUYER_RETURN,SELLER_RE_DELIVERY,BUYER_CONFIRM,SELLER_CONFIRM,COMPLETE\")\n private String serviceStatus;\n\n //退款信息\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleRefundWayEnum\n */\n @ApiModelProperty(value = \"退款方式\", allowableValues = \"ORIGINAL,OFFLINE\")\n private String refundWay;\n\n @ApiModelProperty(value = \"账号类型\", allowableValues = \"ALIPAY,WECHATPAY,BANKTRANSFER\")\n private String accountType;\n\n @ApiModelProperty(value = \"银行账户\")\n private String bankAccountNumber;\n\n @ApiModelProperty(value = \"银行开户名\")\n private String bankAccountName;\n\n @ApiModelProperty(value = \"银行开户行\")\n private String bankDepositName;\n\n @ApiModelProperty(value = \"商家备注\")\n private String auditRemark;\n\n @ApiModelProperty(value = \"订单支付方式返回的交易号\")\n private String payOrderNo;\n\n @ApiModelProperty(value = \"申请退款金额\")\n private Double applyRefundPrice;\n\n @ApiModelProperty(value = \"实际退款金额\")\n private Double actualRefundPrice;\n\n @ApiModelProperty(value = \"退还积分\")\n private Integer refundPoint;\n\n @ApiModelProperty(value = \"退款时间\")\n private Date refundTime;\n\n /**\n * 买家物流信息\n */\n @ApiModelProperty(value = \"发货单号\")\n private String mLogisticsNo;\n\n @ApiModelProperty(value = \"物流公司CODE\")\n private String mLogisticsCode;\n\n @ApiModelProperty(value = \"物流公司名称\")\n private String mLogisticsName;\n\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd\")\n @ApiModelProperty(value = \"买家发货时间\")\n private Date mDeliverTime;\n\n}" }, { "identifier": "OrderItem", "path": "framework/src/main/java/cn/lili/modules/order/order/entity/dos/OrderItem.java", "snippet": "@Data\n@TableName(\"li_order_item\")\n@ApiModel(value = \"子订单\")\n@NoArgsConstructor\n@AllArgsConstructor\npublic class OrderItem extends BaseEntity {\n\n private static final long serialVersionUID = 2108971190191410182L;\n\n @ApiModelProperty(value = \"订单编号\")\n private String orderSn;\n\n @ApiModelProperty(value = \"子订单编号\")\n private String sn;\n\n @ApiModelProperty(value = \"单价\")\n private Double unitPrice;\n\n @ApiModelProperty(value = \"小记\")\n private Double subTotal;\n\n @ApiModelProperty(value = \"商品ID\")\n private String goodsId;\n\n @ApiModelProperty(value = \"货品ID\")\n private String skuId;\n\n @ApiModelProperty(value = \"销售量\")\n private Integer num;\n\n @ApiModelProperty(value = \"交易编号\")\n private String tradeSn;\n\n @ApiModelProperty(value = \"图片\")\n private String image;\n\n @ApiModelProperty(value = \"商品名称\")\n private String goodsName;\n\n @ApiModelProperty(value = \"分类ID\")\n private String categoryId;\n\n @ApiModelProperty(value = \"快照id\")\n private String snapshotId;\n\n @ApiModelProperty(value = \"规格json\")\n private String specs;\n\n @ApiModelProperty(value = \"促销类型\")\n private String promotionType;\n\n @ApiModelProperty(value = \"促销id\")\n private String promotionId;\n\n @ApiModelProperty(value = \"销售金额\")\n private Double goodsPrice;\n\n @ApiModelProperty(value = \"实际金额\")\n private Double flowPrice;\n\n /**\n * @see CommentStatusEnum\n */\n @ApiModelProperty(value = \"评论状态:未评论(UNFINISHED),待追评(WAIT_CHASE),评论完成(FINISHED),\")\n private String commentStatus;\n\n /**\n * @see OrderItemAfterSaleStatusEnum\n */\n @ApiModelProperty(value = \"售后状态\")\n private String afterSaleStatus;\n\n @ApiModelProperty(value = \"价格详情\")\n private String priceDetail;\n\n /**\n * @see OrderComplaintStatusEnum\n */\n @ApiModelProperty(value = \"投诉状态\")\n private String complainStatus;\n\n @ApiModelProperty(value = \"交易投诉id\")\n private String complainId;\n\n @ApiModelProperty(value = \"退货商品数量\")\n private Integer returnGoodsNumber;\n\n\n public OrderItem(CartSkuVO cartSkuVO, CartVO cartVO, TradeDTO tradeDTO) {\n String oldId = this.getId();\n BeanUtil.copyProperties(cartSkuVO.getGoodsSku(), this);\n BeanUtil.copyProperties(cartSkuVO.getPriceDetailDTO(), this);\n BeanUtil.copyProperties(cartSkuVO, this);\n this.setId(oldId);\n if (cartSkuVO.getPriceDetailDTO().getJoinPromotion() != null && !cartSkuVO.getPriceDetailDTO().getJoinPromotion().isEmpty()) {\n this.setPromotionType(CollUtil.join(cartSkuVO.getPriceDetailDTO().getJoinPromotion().stream().map(PromotionSkuVO::getPromotionType).collect(Collectors.toList()), \",\"));\n this.setPromotionId(CollUtil.join(cartSkuVO.getPriceDetailDTO().getJoinPromotion().stream().map(PromotionSkuVO::getActivityId).collect(Collectors.toList()), \",\"));\n }\n this.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.NEW.name());\n this.setCommentStatus(CommentStatusEnum.NEW.name());\n this.setComplainStatus(OrderComplaintStatusEnum.NEW.name());\n this.setPriceDetailDTO(cartSkuVO.getPriceDetailDTO());\n this.setOrderSn(cartVO.getSn());\n this.setTradeSn(tradeDTO.getSn());\n this.setImage(cartSkuVO.getGoodsSku().getThumbnail());\n this.setGoodsName(cartSkuVO.getGoodsSku().getGoodsName());\n this.setSkuId(cartSkuVO.getGoodsSku().getId());\n this.setCategoryId(cartSkuVO.getGoodsSku().getCategoryPath().substring(\n cartSkuVO.getGoodsSku().getCategoryPath().lastIndexOf(\",\") + 1\n ));\n this.setGoodsPrice(cartSkuVO.getGoodsSku().getPrice());\n this.setUnitPrice(cartSkuVO.getPurchasePrice());\n this.setSubTotal(cartSkuVO.getSubTotal());\n this.setSn(SnowFlake.createStr(\"OI\"));\n\n\n }\n\n public PriceDetailDTO getPriceDetailDTO() {\n return JSONUtil.toBean(priceDetail, PriceDetailDTO.class);\n }\n\n public void setPriceDetailDTO(PriceDetailDTO priceDetail) {\n this.priceDetail = JSONUtil.toJsonStr(priceDetail);\n }\n\n}" } ]
import cn.hutool.core.date.DateTime; import cn.lili.modules.distribution.entity.dos.DistributionOrder; import cn.lili.modules.distribution.entity.vos.DistributionOrderSearchParams; import cn.lili.modules.order.aftersale.entity.dos.AfterSale; import cn.lili.modules.order.order.entity.dos.OrderItem; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List;
3,757
package cn.lili.modules.distribution.service; /** * 分销订单业务层 * * @author pikachu * @since 2020-03-15 10:46:33 */ public interface DistributionOrderService extends IService<DistributionOrder> { /** * 获取分销订单分页 * @param distributionOrderSearchParams 分销订单搜索参数 * @return 分销订单分页 */ IPage<DistributionOrder> getDistributionOrderPage(DistributionOrderSearchParams distributionOrderSearchParams); /** * 支付订单 * 记录分销订单 * * @param orderSn 订单编号 */ void calculationDistribution(String orderSn); /** * 取消订单 * 记录分销订单 * * @param orderSn 订单编号 */ void cancelOrder(String orderSn); /** * 订单退款 * 记录分销订单 * * @param afterSaleSn 售后单号 */ void refundOrder(AfterSale afterSale); /** * 分销订单状态修改 * * @param orderItems */
package cn.lili.modules.distribution.service; /** * 分销订单业务层 * * @author pikachu * @since 2020-03-15 10:46:33 */ public interface DistributionOrderService extends IService<DistributionOrder> { /** * 获取分销订单分页 * @param distributionOrderSearchParams 分销订单搜索参数 * @return 分销订单分页 */ IPage<DistributionOrder> getDistributionOrderPage(DistributionOrderSearchParams distributionOrderSearchParams); /** * 支付订单 * 记录分销订单 * * @param orderSn 订单编号 */ void calculationDistribution(String orderSn); /** * 取消订单 * 记录分销订单 * * @param orderSn 订单编号 */ void cancelOrder(String orderSn); /** * 订单退款 * 记录分销订单 * * @param afterSaleSn 售后单号 */ void refundOrder(AfterSale afterSale); /** * 分销订单状态修改 * * @param orderItems */
void updateDistributionOrderStatus(List<OrderItem> orderItems);
3
2023-12-24 19:45:18+00:00
8k
SocialPanda3578/OnlineShop
shop/src/shop/Panel/MainPanel.java
[ { "identifier": "Admin", "path": "shop/src/shop/Admin.java", "snippet": "public class Admin extends User{\n public Admin(){\n\n }\n public Admin(String name,String pass){\n setUsername(name);\n setPassword(pass);\n }\n \n public void login(){\n if (isLogin()) {\n System.out.println(getUsername()+\"已登录,不能重复登录!\");\n } else {\n String username = \"\";\n String password = \"\";\n while (true) {\n System.out.print(\"请输入用户名:\");\n username = Main.sc.next();\n System.out.print(\"请输入密码:\");\n Console console = System.console();\n char[] pass = console.readPassword();\n password = String.valueOf(pass);\n if (password == null || username == null) {\n System.out.println(\"用户名或密码不能为空\");\n continue;\n }\n DBUtil db = new DBUtil();\n Object[] obj = { username, password };\n String sql = \"select * from admins where ad_name=? and ad_password=?\";\n ResultSet rs = db.select(sql, obj);\n try {\n if (!rs.next()) {\n System.out.println(\"用户名或密码错误!请重试!\");\n continue;\n } else {\n setUsername(username);\n setPassword(password);\n setStatus(true);\n System.out.println(\"管理员\" + username + \" 登录成功!\");\n AdminPanel ap = new AdminPanel();\n ap.FirstMenu();\n }\n } catch (Exception e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n break;\n }\n }\n }\n }\n\n public void printUsers(){\n DBUtil db=new DBUtil();\n Object[] objs={};\n ResultSet set = db.select(\"select * from users\", objs);\n System.out.println(\"用户名\"+\"\\t\\t密码\");\n try {\n while (set.next()){\n String u_name=set.getString(\"u_username\");\n String u_pass=set.getString(\"u_password\");\n System.out.println(String.format(\"%-16s\", u_name)+String.format(\"%-16s\",u_pass));\n }\n }\n catch (SQLException e1) {\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n public void updateUser() throws SQLException {\n DBUtil db=new DBUtil();\n System.out.println(\"***************************\");\n System.out.print(\"请输入需修改的用户名:\");\n String targetUser = Main.sc.next();\n if(checkUser(targetUser)) {\n System.out.print(\"请输入新用户名:\");\n String newName = Main.sc.next();\n System.out.print(\"请输入新的密码:\");\n String newPassword = Main.sc.next();\n\n Object[] obj = {newName, newPassword, targetUser};\n int i=db.update(\"update users set u_username=?,u_password=? where u_username=?\", obj);\n if(i!=0) System.out.println(\"用户修改成功\");\n else\n System.out.println(\"用户修改失败\");\n db.closeConnection();\n }\n else{\n System.out.println(\"用户不存在,请检查输入!\");\n }\n }\n public void addUser() throws SQLException {\n System.out.print(\"请输入用户名:\");\n String newName = Main.sc.next();\n DBUtil db=new DBUtil();\n if(checkUser(newName)) System.out.println(\"用户名已存在\");\n else\n {\n System.out.print(\"请输入密码:\");\n String newPassword=Main.sc.next();\n Object[] objs={newName,newPassword};\n int i=db.update(\"insert into users values(?,?)\",objs);\n if(i==0) System.out.println(\"用户创建失败\");\n else {\n System.out.println(\"用户创建成功\");\n String sql = \"CREATE TABLE \" + newName + \"_cart\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n sql = \"CREATE TABLE \" + newName + \"_history\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n }\n db.closeConnection();\n }\n }\n public void deleteUser() throws SQLException {\n System.out.print(\"请输入用户名:\");\n String newName = Main.sc.next();\n DBUtil db=new DBUtil();\n if(!checkUser(newName)) System.out.println(\"用户名不存在\");\n else\n {\n Object[] obj={newName};\n int i=db.update(\"delete from users where u_username=?\",obj);\n if(i==0) System.out.println(\"用户删除失败\");\n else {\n db.update(\"drop table \" + newName + \"_cart\", null);\n db.update(\"drop table \" + newName + \"_history\", null);\n System.out.println(\"用户删除成功\");\n }\n db.closeConnection();\n }\n }\n public void updateItems() throws SQLException {\n DBUtil db = new DBUtil();\n System.out.print(\"请输入需修改的商品编号:\");\n String targetItems = Main.sc.next();\n if (checkItems(targetItems)) {\n System.out.print(\"请输入新的商品名称\");\n String newName = Main.sc.next();\n System.out.print(\"请输入新的商品价格\");\n String newPrice = Main.sc.next();\n System.out.print(\"请输入新的商品数量\");\n String newNums = Main.sc.next();\n Object[] obj = { newName, newPrice, newNums ,targetItems};\n int i = db.update(\"update items set it_name=?,it_price=?,it_nums=? where it_id=?\", obj);\n if (i != 0)\n System.out.println(\"商品修改成功\");\n else\n System.out.println(\"商品修改失败\");\n db.closeConnection();\n }\n else {\n System.out.println(\"商品不存在,请检查输入!\");\n }\n }\n public void addItems() {\n System.out.println(\"请依次输入 编号 名称 价格 数量\");\n String id = Main.sc.next();\n String name = Main.sc.next();\n Double price = Main.sc.nextDouble();\n int nums = Main.sc.nextInt();\n DBUtil db = new DBUtil();\n Object obj[] = { id, name, price, nums };\n int i = db.update(\"insert into items values(?,?,?,?)\", obj);\n if (i == 1)\n System.out.println(\"商品上架成功\");\n else\n System.out.println(\"商品上架失败\");\n db.closeConnection();\n }\n public void deleteItems() {\n System.out.println(\"输入 要删除商品的编号\");\n String id = Main.sc.next();\n DBUtil db = new DBUtil();\n Object[] obj = { id };\n int i = db.update(\"delete from items where it_id=?\", obj);\n if (i == 0)\n System.out.println(\"商品删除失败\");\n else\n System.out.println(\"商品删除成功\");\n db.closeConnection();\n }\n public boolean checkUser(String name) throws SQLException {\n DBUtil db = new DBUtil();\n Object[] obj = { name };\n ResultSet rs = db.select(\"select * from users where u_username=?\", obj);\n if (rs.next())\n return true;\n else\n return false;\n }\n public boolean checkItems(String id) throws SQLException {\n DBUtil db = new DBUtil();\n Object[] obj = { id };\n ResultSet rs = db.select(\"select * from items where it_id=?\", obj);\n if (rs.next()) {\n return true;\n }\n else {\n return false;\n }\n }\n}" }, { "identifier": "History", "path": "shop/src/shop/History.java", "snippet": "public class History {\r\n public void PrintHistoryItems(User user) {\r\n if (user.isLogin()) {\r\n DBUtil db = new DBUtil();\r\n Object obj[] = {};\r\n String username = user.getUsername();\r\n ResultSet rs = db.select(\"select * from \" + username + \"_history\", obj);\r\n try {\r\n while (rs.next()) {\r\n String id = rs.getString(\"id\");\r\n String na = rs.getString(\"name\");\r\n Double price = rs.getDouble(\"price\");\r\n Integer num = rs.getInt(\"nums\");\r\n System.out.println(id + \"\\t\\t\" + na + \"\\t\\t\\t\" + price + \"\\t\\t\\t\" + num);\r\n }\r\n } catch (SQLException e1) {\r\n e1.printStackTrace();\r\n } finally {\r\n db.closeConnection();\r\n }\r\n } else {\r\n System.out.println(\"用户未登录\");\r\n }\r\n }\r\n\r\n public void addHistory(User user,Object obj[]/*id name price nums*/) {\r\n DBUtil db = new DBUtil();\r\n db.update(\"insert into \" + user.getUsername() + \"_history\", obj);\r\n }\r\n}\r" }, { "identifier": "Main", "path": "shop/src/shop/Main.java", "snippet": "public class Main\r\n{\r\n public static Scanner sc=new Scanner(System.in);\r\n\r\n public static void main(String[] args) throws SQLException, InterruptedException {\r\n MainPanel mainPanel = new MainPanel();\r\n mainPanel.showMainMenu();\r\n }\r\n}\r" }, { "identifier": "Shop", "path": "shop/src/shop/Shop.java", "snippet": "public class Shop {\n\n public void PrintItems()\n {\n System.out.println(\"商品编号\\t名称\\t\\t价格\\t\\t数量\");\n DBUtil db=new DBUtil();\n Object objs[]={};\n ResultSet rs=db.select(\"select * from items\",objs);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(String.format(\"%-16s\",id)+String.format(\"%-16s\",na)+String.format(\"%-16s\", price)+String.format(\"%-16s\", num));\n }\n }\n catch(SQLException e1){\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n\n public void ID_ASC_Order() {\n System.out.println(\"商品编号\\t名称\\t\\t价格\\t\\t数量\");\n DBUtil db=new DBUtil();\n Object objs[]={};\n ResultSet rs = db.select(\"select * from items order by it_id asc\", objs);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(String.format(\"%-16s\",id)+String.format(\"%-16s\",na)+String.format(\"%-16s\", price)+String.format(\"%-16s\", num));\n }\n }\n catch(SQLException e1){\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n\n public void Price_ASC_Order() {\n System.out.println(\"商品编号\\t名称\\t\\t价格\\t\\t数量\");\n DBUtil db=new DBUtil();\n Object objs[]={};\n ResultSet rs=db.select(\"select * from items order by it_price asc\",objs);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(String.format(\"%-16s\",id)+String.format(\"%-16s\",na)+String.format(\"%-16s\", price)+String.format(\"%-16s\", num));\n }\n }\n catch(SQLException e1){\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n\n public void Find(String s) {\n DBUtil db = new DBUtil();\n Object obj[] = { s };\n ResultSet rs = db.select(\"select * from items where ca_id=? or ca_name=?\", obj);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(id + ' ' + na + ' ' + price + ' ' + num);\n }\n } catch (SQLException e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n }\n // i = new Items(null, null, null, null);\n //return i;\n }\n\n public void buy(User user) throws SQLException {\n if (user.isLogin()) {\n System.out.println(\"想买点什么\");\n String name = Main.sc.next();\n System.out.println(\"想买多少\");\n int n = Main.sc.nextInt();\n\n Object obj[] = { name, name };\n DBUtil db = new DBUtil();\n ResultSet rs = db.select(\"select * from items where it_name=? or it_id=?\", obj);\n if (rs.next()) {\n if (rs.getInt(\"it_nums\") < n) {\n System.out.println(\"库存不够\");\n } else {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n db.update(\"insert into \" + user.getUsername() + \"_history values(?,?,?,?)\",\n new Object[] { id, na, price, n });\n db.update(\"update items set it_nums=it_nums-? where it_id=?\", new Object[] { n, id });\n db.update(\"delete from items where it_nums<=0\", new Object[] {});\n System.out.println(n+\"件 商品\" + na + \"购买成功\");\n }\n } else {\n System.out.println(\"商品不存在\");\n }\n db.closeConnection();\n }\n else {\n System.out.println(\"请登录后使用\");\n } \n }\n}" }, { "identifier": "User", "path": "shop/src/shop/User.java", "snippet": "public class User\n{\n private static String user_name;\n private static String pass_word;\n private static boolean status=false;\n\n public String getUsername()\n {\n return user_name;\n }\n public String getPassword()\n {\n return pass_word;\n }\n public void setPassword(String password)\n {\n pass_word = password;\n }\n public void setUsername(String username){user_name=username;}\n public static boolean isLogin()\n {\n return status;\n }\n public static void setStatus(boolean status) {\n User.status = status;\n }\n\n public void reg() //用户注册\n {\n if (!status) {\n String username = \"\";\n String password = \"\";\n while (true) {\n System.out.print(\"请输入用户名:\");\n username = Main.sc.next();\n boolean fg = true;\n\n DBUtil db = new DBUtil();\n Object[] objs = { username };\n String sql = \"select * from users where u_username=?\";\n ResultSet rs = db.select(sql, objs);\n try {\n if (rs.next()) {\n System.out.println(\"用户名重复\");\n continue;\n }\n } catch (Exception e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n }\n\n if (fg == false)\n continue;\n else if (username.length() < 3) {\n System.out.println(\"用户名长度至少大于3位!\");\n continue;\n } else\n break;\n }\n while (true) {\n System.out.print(\"请输入登录密码:\");\n password = Main.sc.next();\n if (password.length() < 6) {\n System.out.println(\"密码长度至少大于6位!\");\n continue;\n }\n int digit = 0;\n int letter = 0;\n for (int i = 0; i < password.length(); i++) {\n if (Character.isDigit(password.charAt(i)))\n digit++;\n if (Character.isLetter(password.charAt(i)))\n letter++;\n }\n if (digit == 0 || letter == 0) {\n System.out.println(\"密码至少含有一个字符和一个数字!\");\n continue;\n }\n System.out.print(\"请再次确认您的密码\");\n Console console = System.console();\n char[] repassword = console.readPassword();\n //String repassword = Main.sc.next();\n if (password.equals(String.valueOf(repassword)))//插入用户数据\n {\n DBUtil db = new DBUtil();\n Object[] obj = { username, password };\n //ResultSet set=db.select(\"select * from users\",obj);\n int i = db.update(\"insert into users values(?,?)\", obj);\n if (i != 0) {\n System.out.println(\"用户创建成功,已为您自动登录\");\n String sql = \"CREATE TABLE \" + username + \"_cart\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n sql = \"CREATE TABLE \" + username + \"_history\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n user_name = username;\n pass_word = password;\n status = true;\n System.out.println(\"普通用户\" + username + \" 登录成功!\");\n } else\n System.out.println(\"用户创建失败\");\n db.closeConnection();\n break;\n } else {\n System.out.println(\"两次输入的密码不一致!\");\n }\n }\n }\n else {\n System.out.println(\"您已登录!请退出登录后尝试注册\");\n }\n }\n\n public void login()\n {\n if (status) {\n System.out.println(user_name+\"已登录,不能重复登录!\");\n } else {\n String username = \"\";\n String password = \"\";\n while (true) {\n System.out.print(\"请输入用户名:\");\n username = Main.sc.next();\n System.out.print(\"请输入密码:\");\n Console console = System.console();\n char[] pass = console.readPassword();\n password = String.valueOf(pass);\n if (password == null || username == null) {\n System.out.println(\"用户名或密码不能为空\");\n continue;\n }\n DBUtil db = new DBUtil();\n Object[] obj = { username, password };\n String sql = \"select * from users where u_username=? and u_password=?\";\n ResultSet rs = db.select(sql, obj);\n try {\n if (!rs.next()) {\n System.out.println(\"用户名或密码错误!请重试!\");\n continue;\n } else {\n user_name = username;\n pass_word = password;\n status = true;\n System.out.println(\"普通用户\" + username + \" 登录成功!\");\n }\n } catch (Exception e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n break;\n }\n }\n }\n }\n\n public void exit() {\n if (status) {\n status = false;\n System.out.println(\"再见\" + user_name + \"!\");\n }\n }\n}" } ]
import shop.Admin; import shop.History; import shop.Main; import shop.Shop; import shop.User; import java.io.IOException; import java.sql.SQLException;
4,771
package shop.Panel; public class MainPanel { public void showMainMenu() throws SQLException, InterruptedException { System.out.println(" _ _ "); System.out.println(" | | / / "); System.out.println(" | /| / __ / __ __ _ _ __ "); System.out.println(" |/ |/ /___) / / ' / ) / / ) /___)"); System.out.println("_/__|___(___ _/___(___ _(___/_/_/__/_(___ _"); boolean flag = true; while (flag) { System.out.println("***************************"); System.out.println("\t1.注册"); System.out.println("\t2.登录"); System.out.println("\t3.退出登录"); System.out.println("\t4.查看商城"); System.out.println("\t5.查看我购买的商品"); System.out.println("\t6.管理员登录"); System.out.println("\t7.退出系统"); System.out.println("***************************"); System.out.print("请选择菜单:");
package shop.Panel; public class MainPanel { public void showMainMenu() throws SQLException, InterruptedException { System.out.println(" _ _ "); System.out.println(" | | / / "); System.out.println(" | /| / __ / __ __ _ _ __ "); System.out.println(" |/ |/ /___) / / ' / ) / / ) /___)"); System.out.println("_/__|___(___ _/___(___ _(___/_/_/__/_(___ _"); boolean flag = true; while (flag) { System.out.println("***************************"); System.out.println("\t1.注册"); System.out.println("\t2.登录"); System.out.println("\t3.退出登录"); System.out.println("\t4.查看商城"); System.out.println("\t5.查看我购买的商品"); System.out.println("\t6.管理员登录"); System.out.println("\t7.退出系统"); System.out.println("***************************"); System.out.print("请选择菜单:");
int choice = Main.sc.nextInt();
2
2023-12-28 04:26:15+00:00
8k
MuskStark/EasyECharts
src/main/java/com/github/muskstark/echart/model/bar/BarChart.java
[ { "identifier": "Legend", "path": "src/main/java/com/github/muskstark/echart/attribute/Legend.java", "snippet": "@Getter\npublic class Legend {\n\n private String type;\n private String id;\n private Boolean show;\n private Double zLevel;\n private Double z;\n private Object left;\n private Object top;\n private Object right;\n private Object bottom;\n private Object width;\n private Object height;\n private String orient;\n private String align;\n private Integer[] padding;\n private Double itemGap;\n private Double itemWidth;\n private Double itemHeight;\n// private ItemStyle itemStyle;\n private LineStyle lineStyle;\n private Object symbolRotate;\n private String formatter;\n private Boolean selectedMode;\n private String inactiveColor;\n private String inactiveBorderColor;\n private String inactiveBorderWidth;\n private Object selected;\n private TextStyle textStyle;\n private ToolTip tooltip;\n private String icon;\n private List<Object> data;\n private String backgroundColor;\n private String borderColor;\n private Double borderWidth;\n private Integer[] borderRadius;\n private Double shadowBlur;\n private String shadowColor;\n private Double shadowOffsetX;\n private Double shadowOffsetY;\n private Double scrollDataIndex;\n private Double pageButtonItemGap;\n private Double pageButtonGap;\n private String pageButtonPosition;\n private String pageFormatter;\n// private PageIcons pageIcons;\n private String pageIconColor;\n private String pageIconInactiveColor;\n private Integer[] pageIconSize;\n// private TextStyle pageTextStyle;\n private Boolean animation;\n private Double animationDurationUpdate;\n// private Object emphasis;\n private Boolean[] selector;\n// private SelectorLabel selectorLabel;\n private String selectorPosition;\n private Integer selectorItemGap;\n private Integer selectorButtonGap;\n\n public Legend type(String type){\n this.type = type;\n return this;\n }\n\n public Legend id(String id){\n this.id = id;\n return this;\n }\n\n public Legend show(Boolean show){\n this.show = show;\n return this;\n }\n\n public Legend zLevel(Double zLevel){\n this.zLevel = zLevel;\n return this;\n }\n\n public Legend z(Double z){\n this.z = z;\n return this;\n }\n\n public Legend left(Object left){\n if(left instanceof String || left instanceof Double){\n this.left = left;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend top(Object top){\n if(top instanceof String || top instanceof Double){\n this.top = top;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend right(Object right){\n if(right instanceof String || right instanceof Double){\n this.right = right;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend bottom(Object bottom){\n if(bottom instanceof String || bottom instanceof Double){\n this.bottom = bottom;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend width(Object width){\n if(width instanceof String || width instanceof Double){\n this.width = width;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend height(Object height){\n if(height instanceof String || height instanceof Double){\n this.height = height;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend orient(String orient){\n this.orient = orient;\n return this;\n }\n\n\n\n}" }, { "identifier": "Title", "path": "src/main/java/com/github/muskstark/echart/attribute/Title.java", "snippet": "@Getter\npublic class Title implements Serializable {\n private String id;\n private Boolean show;\n private String text;\n private String link;\n private String target;\n private TextStyle textStyle;\n private String subtext;\n private String subLink;\n private String subTarget;\n private TextStyle subtextStyle;\n private String textAlign;\n private String textVerticalAlign;\n private Boolean triggerEvent;\n private Integer[] padding;\n private Integer itemGap;\n private Integer zLevel;\n private Integer z;\n private String left;\n private String top;\n private String right;\n private String bottom;\n private String backgroundColor;\n private String borderColor;\n private Integer borderWidth;\n private Integer[] borderRadius;\n private Integer shadowBlur;\n private String shadowColor;\n private Integer shadowOffsetX;\n private Integer shadowOffsetY;\n\n public Title id(String id){\n this.id = id;\n return this;\n }\n\n public Title show(Boolean show){\n this.show = show;\n return this;\n }\n\n public Title text(String text){\n this.text = text;\n return this;\n }\n\n public Title link(String link){\n this.link = link;\n return this;\n }\n\n public Title target(String target){\n this.target = target;\n return this;\n }\n\n public Title textStyle(TextStyle textStyle){\n this.textStyle = textStyle;\n return this;\n }\n\n public Title subtext(String subtext){\n this.subtext = subtext;\n return this;\n }\n\n public Title subLink(String subLink){\n this.subLink = subLink;\n return this;\n }\n\n public Title subTarget(String subTarget){\n this.subTarget = subTarget;\n return this;\n }\n\n public Title subtextStyle(TextStyle subtextStyle){\n this.subtextStyle = subtextStyle;\n return this;\n }\n\n public Title textAlign(String textAlign){\n this.textAlign = textAlign;\n return this;\n }\n\n public Title textVerticalAlign(String textVerticalAlign){\n this.textVerticalAlign = textVerticalAlign;\n return this;\n }\n\n public Title triggerEvent(Boolean triggerEvent){\n this.triggerEvent = triggerEvent;\n return this;\n }\n\n public Title padding(Integer[] padding){\n this.padding = padding;\n return this;\n }\n\n public Title itemGap(Integer itemGap){\n this.itemGap = itemGap;\n return this;\n }\n\n public Title zLevel(Integer zLevel){\n this.zLevel = zLevel;\n return this;\n }\n\n public Title z(Integer z){\n this.z = z;\n return this;\n }\n\n public Title left(String left){\n this.left = left;\n return this;\n }\n\n public Title top(String top){\n this.top = top;\n return this;\n }\n\n public Title right(String right){\n this.right = right;\n return this;\n }\n\n public Title bottom(String bottom){\n this.bottom = bottom;\n return this;\n }\n\n public Title backgroundColor(String backgroundColor){\n this.backgroundColor = backgroundColor;\n return this;\n }\n\n public Title borderColor(String borderColor){\n this.borderColor = borderColor;\n return this;\n }\n\n public Title borderWidth(Integer borderWidth){\n this.borderWidth = borderWidth;\n return this;\n }\n\n public Title borderRadius(Integer[] borderRadius){\n this.borderRadius = borderRadius;\n return this;\n }\n\n public Title shadowBlur(Integer shadowBlur){\n this.shadowBlur = shadowBlur;\n return this;\n }\n\n public Title shadowColor(String shadowColor){\n this.shadowColor = shadowColor;\n return this;\n }\n\n public Title shadowOffsetX(Integer shadowOffsetX){\n this.shadowOffsetX = shadowOffsetX;\n return this;\n }\n\n public Title shadowOffsetY(Integer shadowOffsetY){\n this.shadowOffsetY = shadowOffsetY;\n return this;\n }\n\n\n}" }, { "identifier": "ToolTip", "path": "src/main/java/com/github/muskstark/echart/attribute/ToolTip.java", "snippet": "@Getter\npublic class ToolTip implements Serializable {\n\n private Boolean show;\n private String trigger;\n private AxisPointer axisPointer;\n private Boolean showContent;\n private Boolean alwaysShowContent;\n private String triggerOn;\n private Integer showDelay;\n private Integer hideDelay;\n private String rendererMode;\n private Boolean confine;\n private Boolean appendToBody;\n private String className;\n private Double transitionDuration;\n// private Object position;\n private String formatter;\n private String valueFormatter;\n// private Color backgroundColor;\n// private Color borderColor;\n// private Double borderWidth;\n// private Double padding;\n private TextStyle textStyle;\n private String extraCssText;\n private String order;\n\n public ToolTip show(Boolean show) {\n this.show = show;\n return this;\n }\n\n public ToolTip trigger(String trigger) {\n this.trigger = trigger;\n return this;\n }\n\n public ToolTip axisPointer(AxisPointer axisPointer) {\n this.axisPointer = axisPointer;\n return this;\n }\n\n public ToolTip showContent(Boolean showContent) {\n this.showContent = showContent;\n return this;\n }\n\n public ToolTip alwaysShowContent(Boolean alwaysShowContent) {\n this.alwaysShowContent = alwaysShowContent;\n return this;\n }\n\n public ToolTip triggerOn(String triggerOn) {\n this.triggerOn = triggerOn;\n return this;\n }\n\n public ToolTip showDelay(Integer showDelay) {\n this.showDelay = showDelay;\n return this;\n }\n\n public ToolTip hideDelay(Integer hideDelay) {\n this.hideDelay = hideDelay;\n return this;\n }\n\n public ToolTip rendererMode(String rendererMode) {\n this.rendererMode = rendererMode;\n return this;\n }\n\n public ToolTip confine(Boolean confine) {\n this.confine = confine;\n return this;\n }\n\n public ToolTip appendToBody(Boolean appendToBody) {\n this.appendToBody = appendToBody;\n return this;\n }\n\n public ToolTip className(String className) {\n this.className = className;\n return this;\n }\n\n public ToolTip transitionDuration(Double transitionDuration) {\n this.transitionDuration = transitionDuration;\n return this;\n }\n\n public ToolTip formatter(String formatter) {\n this.formatter = formatter;\n return this;\n }\n\n public ToolTip valueFormatter(String valueFormatter) {\n this.valueFormatter = valueFormatter;\n return this;\n }\n\n public ToolTip textStyle(TextStyle textStyle) {\n this.textStyle = textStyle;\n return this;\n }\n\n public ToolTip extraCssText(String extraCssText) {\n this.extraCssText = extraCssText;\n return this;\n }\n\n public ToolTip order(String order) {\n this.order = order;\n return this;\n }\n\n// public ToolTip position(Object position) {\n// this.position = position;\n// return this;\n// }\n//\n// public ToolTip backgroundColor(Color backgroundColor) {\n// this.backgroundColor = backgroundColor;\n// return this;\n// }\n//\n// public ToolTip borderColor(Color borderColor) {\n// this.borderColor = borderColor;\n// return this;\n// }\n//\n// public ToolTip borderWidth(Double borderWidth) {\n// this.borderWidth = borderWidth;\n// return this;\n// }\n//\n// public ToolTip padding(Double padding) {\n// this.padding = padding;\n// return this;\n// }\n\n\n\n\n\n}" }, { "identifier": "XAxis", "path": "src/main/java/com/github/muskstark/echart/attribute/axis/XAxis.java", "snippet": "@Getter\npublic class XAxis extends Axis {\n\n\n}" }, { "identifier": "YAxis", "path": "src/main/java/com/github/muskstark/echart/attribute/axis/YAxis.java", "snippet": "@Getter\npublic class YAxis extends Axis {\n\n\n}" }, { "identifier": "BarSeries", "path": "src/main/java/com/github/muskstark/echart/attribute/series/BarSeries.java", "snippet": "@Getter\npublic class BarSeries extends Series {\n\n private String barWidth;\n private String barMaxWidth;\n private Integer barMinWidth;\n private Integer barMinHeight;\n private Integer barMinAngle;\n private String barGap;\n private String barCategoryGap;\n\n public BarSeries defineBarWidth(String barWidth){\n this.barWidth = barWidth;\n return this;\n }\n\n public BarSeries defineBarMaxWidth(String barMaxWidth){\n this.barMaxWidth = barMaxWidth;\n return this;\n }\n public BarSeries defineBarMinWidth(Integer barMinWidth){\n this.barMinWidth = barMinWidth;\n return this;\n }\n\n public BarSeries defineBarMinHeight(Integer barMinHeight){\n this.barMinHeight = barMinHeight;\n return this;\n }\n\n public BarSeries defineBarMinAngle(Integer barMinAngle){\n this.barMinAngle = barMinAngle;\n return this;\n }\n\n public BarSeries defineBarGap(String barGap){\n this.barGap = barGap;\n return this;\n }\n\n public BarSeries defineBarCategoryGap(String barCategoryGap){\n this.barCategoryGap = barCategoryGap;\n return this;\n }\n\n\n\n\n\n\n\n}" }, { "identifier": "Charts", "path": "src/main/java/com/github/muskstark/echart/model/Charts.java", "snippet": "@Data\npublic abstract class Charts implements Serializable {\n\n private Title title;\n\n private ToolTip toolTip;\n\n private Legend legend;\n\n}" } ]
import com.alibaba.fastjson2.annotation.JSONField; import com.github.muskstark.echart.attribute.Legend; import com.github.muskstark.echart.attribute.Title; import com.github.muskstark.echart.attribute.ToolTip; import com.github.muskstark.echart.attribute.axis.XAxis; import com.github.muskstark.echart.attribute.axis.YAxis; import com.github.muskstark.echart.attribute.series.BarSeries; import com.github.muskstark.echart.model.Charts; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List;
3,643
package com.github.muskstark.echart.model.bar; @EqualsAndHashCode(callSuper = true) @Data public class BarChart extends Charts { @JSONField(name = "xAxis") private XAxis xAxis; @JSONField(name = "yAxis") private YAxis yAxis; private List<BarSeries> series; public Title defineTitle() { return this.getTitle(); } public XAxis defineXAxis() { return this.getXAxis(); } public YAxis defineYAxis() { return this.getYAxis(); }
package com.github.muskstark.echart.model.bar; @EqualsAndHashCode(callSuper = true) @Data public class BarChart extends Charts { @JSONField(name = "xAxis") private XAxis xAxis; @JSONField(name = "yAxis") private YAxis yAxis; private List<BarSeries> series; public Title defineTitle() { return this.getTitle(); } public XAxis defineXAxis() { return this.getXAxis(); } public YAxis defineYAxis() { return this.getYAxis(); }
public ToolTip defineToolTip() {
2
2023-12-25 08:03:42+00:00
8k
xyzell/OOP_UAS
Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/ManageRoomReceptionist.java
[ { "identifier": "ExitConfirmation", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/component/ExitConfirmation.java", "snippet": "public class ExitConfirmation extends javax.swing.JFrame {\n\n /**\n * Creates new form ExitConfirmation\n */\n public ExitConfirmation() {\n initComponents();\n }\n\n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n jPanel3 = new javax.swing.JPanel();\n jPanel1 = new javax.swing.JPanel();\n jPanel2 = new javax.swing.JPanel();\n jLabel1 = new javax.swing.JLabel();\n button1 = new com.itenas.oop.org.uashotel.swing.component.Button();\n Keluar = new com.itenas.oop.org.uashotel.swing.component.ButtonOutLine();\n\n setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);\n setUndecorated(true);\n\n jPanel3.setBackground(new Color(255, 255, 255, 88));\n jPanel3.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jPanel3MouseClicked(evt);\n }\n });\n\n jPanel1.setBackground(new java.awt.Color(255, 255, 255));\n jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(173, 151, 79)));\n jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jPanel1MouseClicked(evt);\n }\n });\n\n jPanel2.setBackground(new java.awt.Color(255, 255, 255));\n jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(173, 151, 79)));\n\n jLabel1.setFont(new java.awt.Font(\"Arial\", 0, 18)); // NOI18N\n jLabel1.setForeground(new java.awt.Color(173, 151, 79));\n jLabel1.setText(\"Apakah Anda yakin Akan Keluar?\");\n\n button1.setBackground(new java.awt.Color(173, 151, 79));\n button1.setForeground(new java.awt.Color(255, 255, 255));\n button1.setText(\"Batal\");\n button1.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n button1ActionPerformed(evt);\n }\n });\n\n Keluar.setBackground(new java.awt.Color(173, 151, 79));\n Keluar.setForeground(new java.awt.Color(173, 151, 79));\n Keluar.setText(\"Keluar\");\n Keluar.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n KeluarActionPerformed(evt);\n }\n });\n\n javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);\n jPanel2.setLayout(jPanel2Layout);\n jPanel2Layout.setHorizontalGroup(\n jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addGap(91, 91, 91)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(45, 45, 45)\n .addComponent(Keluar, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(8, 8, 8))\n .addComponent(jLabel1))\n .addContainerGap(90, Short.MAX_VALUE))\n );\n jPanel2Layout.setVerticalGroup(\n jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addGap(33, 33, 33)\n .addComponent(jLabel1)\n .addGap(40, 40, 40)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(Keluar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addContainerGap(40, Short.MAX_VALUE))\n );\n\n javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);\n jPanel1.setLayout(jPanel1Layout);\n jPanel1Layout.setHorizontalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n jPanel1Layout.setVerticalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n\n javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);\n jPanel3.setLayout(jPanel3Layout);\n jPanel3Layout.setHorizontalGroup(\n jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel3Layout.createSequentialGroup()\n .addGap(178, 178, 178)\n .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addContainerGap(178, Short.MAX_VALUE))\n );\n jPanel3Layout.setVerticalGroup(\n jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel3Layout.createSequentialGroup()\n .addGap(168, 168, 168)\n .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addContainerGap(169, Short.MAX_VALUE))\n );\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n getContentPane().setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n );\n\n pack();\n }// </editor-fold>//GEN-END:initComponents\n\n private void KeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_KeluarActionPerformed\n System.exit(0);\n }//GEN-LAST:event_KeluarActionPerformed\n\n private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed\n this.setVisible(false);\n }//GEN-LAST:event_button1ActionPerformed\n\n private void jPanel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MouseClicked\n this.setVisible(false);\n }//GEN-LAST:event_jPanel3MouseClicked\n\n private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked\n this.setVisible(true);\n }//GEN-LAST:event_jPanel1MouseClicked\n \n \n /**\n * @param args the command line arguments\n */\n public static void main(String args[]) {\n /* Set the Nimbus look and feel */\n //<editor-fold defaultstate=\"collapsed\" desc=\" Look and feel setting code (optional) \">\n /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.\n * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html \n */\n try {\n for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {\n if (\"Nimbus\".equals(info.getName())) {\n javax.swing.UIManager.setLookAndFeel(info.getClassName());\n break;\n }\n }\n } catch (ClassNotFoundException ex) {\n java.util.logging.Logger.getLogger(ExitConfirmation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (InstantiationException ex) {\n java.util.logging.Logger.getLogger(ExitConfirmation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (IllegalAccessException ex) {\n java.util.logging.Logger.getLogger(ExitConfirmation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (javax.swing.UnsupportedLookAndFeelException ex) {\n java.util.logging.Logger.getLogger(ExitConfirmation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n }\n //</editor-fold>\n\n /* Create and display the form */\n java.awt.EventQueue.invokeLater(new Runnable() {\n public void run() {\n new ExitConfirmation().setVisible(true);\n }\n }); \n }\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private com.itenas.oop.org.uashotel.swing.component.ButtonOutLine Keluar;\n private com.itenas.oop.org.uashotel.swing.component.Button button1;\n private javax.swing.JLabel jLabel1;\n private javax.swing.JPanel jPanel1;\n private javax.swing.JPanel jPanel2;\n private javax.swing.JPanel jPanel3;\n // End of variables declaration//GEN-END:variables\n}" }, { "identifier": "ConnectionManager", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/utilities/ConnectionManager.java", "snippet": "public class ConnectionManager {\n private String DB_URL = \"jdbc:mysql://localhost:3306/hotel1\";\n private String username;\n private String password;\n private Connection connection;\n\n \n\n public ConnectionManager() {\n this.username = \"root\";\n this.password = \"basdat2022\";\n }\n\n public String getDB_URL() {\n return DB_URL;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public Connection connect() {\n if (connection == null) {\n try {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(getDB_URL(), \n getUsername(), getPassword());\n } catch (ClassNotFoundException | SQLException ex) {\n Logger.getLogger(ConnectionManager.class.getName())\n .log(Level.SEVERE, null, ex);\n }\n }\n return connection;\n }\n \n public Connection disconnect() {\n try {\n connection.close();\n } catch (SQLException ex) {\n Logger.getLogger(ConnectionManager.class.getName())\n .log(Level.SEVERE, null, ex);\n }\n return connection;\n }\n}" } ]
import com.itenas.oop.org.uashotel.swing.component.ExitConfirmation; import com.itenas.oop.org.uashotel.utilities.ConnectionManager; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel;
5,630
jLabel6.setForeground(new java.awt.Color(173, 151, 79)); jLabel6.setText("___________________________________________________"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 300, -1)); jLabel7.setForeground(new java.awt.Color(173, 151, 79)); jLabel7.setText("________________________________________________________"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 290, 300, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtBadTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBadTotalActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtBadTotalActionPerformed private void ShowRooms() { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); st = con.createStatement(); rs = st.executeQuery("select * from hotel_room"); // Mendapatkan metadata dari ResultSet java.sql.ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // Mengosongkan model tabel DefaultTableModel model = (DefaultTableModel) tabelRoom.getModel(); model.setRowCount(0); // Menambahkan baris ke model while (rs.next()) { Object[] rowData = new Object[columnCount]; for (int i = 1; i <= columnCount; i++) { rowData[i - 1] = rs.getObject(i); } model.addRow(rowData); } } catch (Exception e) { e.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace } finally{ try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } } private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed if (txtIdRoom.getText().isEmpty() || cmbRoomType.getSelectedIndex() == -1 || txtRoomPrice.getText().isEmpty() || txtBadTotal.getText().isEmpty() || cmbStatus.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(this, "Missing Data"); } else { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); PreparedStatement Save = con.prepareStatement("INSERT INTO hotel_room VALUES(?, ?, ?, ?, ?)"); Save.setString(1, txtIdRoom.getText()); Save.setString(2, cmbRoomType.getSelectedItem().toString()); Save.setInt(3, Integer.valueOf(txtRoomPrice.getText())); Save.setInt(4, Integer.valueOf(txtBadTotal.getText())); Save.setString(5, cmbStatus.getSelectedItem().toString()); int row = Save.executeUpdate(); if (row > 0) { JOptionPane.showMessageDialog(this, "Room Added"); ShowRooms(); } else { JOptionPane.showMessageDialog(this, "Failed to add room"); } con.close(); } catch (SQLException ex) { ex.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage()); } } }//GEN-LAST:event_btnAddActionPerformed private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed txtIdRoom.setText(""); cmbRoomType.setSelectedIndex(-1); txtRoomPrice.setText(""); txtBadTotal.setText(""); cmbStatus.setSelectedIndex(-1); }//GEN-LAST:event_btnClearActionPerformed private void lblGuestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblGuestMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblGuestMouseClicked private void lblLogOut2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOut2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblLogOut2MouseClicked private void lblReservationMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblReservationMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblReservationMouseClicked private void lblLogOutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOutMouseClicked
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package com.itenas.oop.org.uashotel.swing; /** * * @author acer */ public class ManageRoomReceptionist extends javax.swing.JFrame { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; Statement st = null; public ManageRoomReceptionist() { initComponents(); setExtendedState(JFrame.MAXIMIZED_BOTH); txtIdRoom.setBackground(new java.awt.Color(0,0,0,1)); txtBadTotal.setBackground(new java.awt.Color(0,0,0,1)); txtRoomPrice.setBackground(new java.awt.Color(0,0,0,1)); cmbStatus.setBackground(new java.awt.Color(0,0,0,1)); ShowRooms(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); lblGuest = new javax.swing.JLabel(); lblLogOut2 = new javax.swing.JLabel(); lblReservation = new javax.swing.JLabel(); lblLogOut = new javax.swing.JLabel(); lblDashboard1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); txtRoomPrice = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); lblSearch = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtBadTotal = new javax.swing.JTextField(); cmbStatus = new javax.swing.JComboBox<>(); cmbRoomType = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); tabelRoom = new javax.swing.JTable(); btnAdd = new javax.swing.JButton(); btnClear = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); txtIdRoom = new javax.swing.JTextField(); btnSearch = new javax.swing.JButton(); btnDelete = new javax.swing.JButton(); btnEdit = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setForeground(new java.awt.Color(0, 0, 0)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setBackground(new java.awt.Color(173, 151, 79)); lblGuest.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblGuest.setForeground(new java.awt.Color(255, 255, 255)); lblGuest.setText("Guest"); lblGuest.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblGuest.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblGuestMouseClicked(evt); } }); lblLogOut2.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblLogOut2.setForeground(new java.awt.Color(255, 255, 255)); lblLogOut2.setText("Rooms"); lblLogOut2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblLogOut2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblLogOut2MouseClicked(evt); } }); lblReservation.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblReservation.setForeground(new java.awt.Color(255, 255, 255)); lblReservation.setText("Reservation"); lblReservation.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblReservation.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblReservationMouseClicked(evt); } }); lblLogOut.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblLogOut.setForeground(new java.awt.Color(255, 255, 255)); lblLogOut.setText("Log Out"); lblLogOut.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblLogOut.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblLogOutMouseClicked(evt); } }); lblDashboard1.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblDashboard1.setForeground(new java.awt.Color(255, 255, 255)); lblDashboard1.setText("Dashboard"); lblDashboard1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblDashboard1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblDashboard1MouseClicked(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblDashboard1) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblGuest) .addComponent(lblLogOut2) .addComponent(lblReservation) .addComponent(lblLogOut, javax.swing.GroupLayout.Alignment.TRAILING))) .addContainerGap(45, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(122, 122, 122) .addComponent(lblLogOut2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblGuest) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblReservation) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblDashboard1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 356, Short.MAX_VALUE) .addComponent(lblLogOut) .addGap(91, 91, 91)) ); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 150, 730)); jPanel3.setBackground(new java.awt.Color(190, 160, 90)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(182, 0, 1216, -1)); txtRoomPrice.setBackground(new java.awt.Color(204, 204, 204)); txtRoomPrice.setBorder(null); txtRoomPrice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtRoomPriceActionPerformed(evt); } }); jPanel1.add(txtRoomPrice, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 280, 300, 32)); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel2.setForeground(new java.awt.Color(173, 151, 79)); jLabel2.setText("ID Room"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 120, -1, -1)); lblSearch.setBackground(new java.awt.Color(204, 204, 204)); lblSearch.setBorder(null); lblSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lblSearchActionPerformed(evt); } }); jPanel1.add(lblSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(998, 79, 244, 32)); jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel3.setForeground(new java.awt.Color(173, 151, 79)); jLabel3.setText("Room Type"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 190, -1, -1)); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel4.setForeground(new java.awt.Color(173, 151, 79)); jLabel4.setText("Bed Total"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 320, -1, -1)); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel5.setForeground(new java.awt.Color(173, 151, 79)); jLabel5.setText("Status"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 380, -1, -1)); txtBadTotal.setBackground(new java.awt.Color(204, 204, 204)); txtBadTotal.setBorder(null); txtBadTotal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtBadTotalActionPerformed(evt); } }); jPanel1.add(txtBadTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 340, 300, 32)); cmbStatus.setBackground(new java.awt.Color(173, 151, 79)); cmbStatus.setForeground(new java.awt.Color(255, 255, 255)); cmbStatus.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Available", "Booked", " " })); jPanel1.add(cmbStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 410, 300, 34)); cmbRoomType.setBackground(new java.awt.Color(173, 151, 79)); cmbRoomType.setForeground(new java.awt.Color(255, 255, 255)); cmbRoomType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "VIP", "Double Bed", "Single Bad", "Family" })); cmbRoomType.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbRoomTypeActionPerformed(evt); } }); jPanel1.add(cmbRoomType, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 210, 300, 34)); tabelRoom.setBackground(new java.awt.Color(204, 204, 255)); tabelRoom.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "ID Room", "Room Type", "Room Price", "Bed Total", "Status" } )); tabelRoom.setGridColor(new java.awt.Color(190, 160, 90)); tabelRoom.setRowHeight(25); tabelRoom.setRowMargin(1); jScrollPane1.setViewportView(tabelRoom); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(521, 119, 843, 530)); btnAdd.setBackground(new java.awt.Color(0, 204, 0)); btnAdd.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnAdd.setForeground(new java.awt.Color(255, 255, 255)); btnAdd.setText("Add"); btnAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddActionPerformed(evt); } }); jPanel1.add(btnAdd, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 470, 300, 35)); btnClear.setBackground(new java.awt.Color(3, 45, 137)); btnClear.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnClear.setForeground(new java.awt.Color(255, 255, 255)); btnClear.setText("Clear"); btnClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearActionPerformed(evt); } }); jPanel1.add(btnClear, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 620, 300, 35)); jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel8.setForeground(new java.awt.Color(173, 151, 79)); jLabel8.setText("Hotel Management System"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(657, 20, -1, -1)); jLabel9.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel9.setForeground(new java.awt.Color(173, 151, 79)); jLabel9.setText("Room Price"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, -1, -1)); jLabel10.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jLabel10.setForeground(new java.awt.Color(173, 151, 79)); jLabel10.setText("Manage Room"); jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(711, 47, -1, -1)); txtIdRoom.setBackground(new java.awt.Color(204, 204, 204)); txtIdRoom.setBorder(null); txtIdRoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtIdRoomActionPerformed(evt); } }); jPanel1.add(txtIdRoom, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 140, 300, 30)); btnSearch.setBackground(new java.awt.Color(3, 45, 137)); btnSearch.setForeground(new java.awt.Color(255, 255, 255)); btnSearch.setText("Search"); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); jPanel1.add(btnSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(1260, 78, 104, 35)); btnDelete.setBackground(new java.awt.Color(255, 0, 0)); btnDelete.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnDelete.setForeground(new java.awt.Color(255, 255, 255)); btnDelete.setText("Delete"); btnDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteActionPerformed(evt); } }); jPanel1.add(btnDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 570, 300, 35)); btnEdit.setBackground(new java.awt.Color(3, 45, 137)); btnEdit.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnEdit.setForeground(new java.awt.Color(255, 255, 255)); btnEdit.setText("Edit"); btnEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditActionPerformed(evt); } }); jPanel1.add(btnEdit, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 520, 300, 35)); jLabel1.setForeground(new java.awt.Color(173, 151, 79)); jLabel1.setText("________________________________________________________"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 350, 300, -1)); jLabel6.setForeground(new java.awt.Color(173, 151, 79)); jLabel6.setText("___________________________________________________"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 300, -1)); jLabel7.setForeground(new java.awt.Color(173, 151, 79)); jLabel7.setText("________________________________________________________"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 290, 300, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtBadTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBadTotalActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtBadTotalActionPerformed private void ShowRooms() { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); st = con.createStatement(); rs = st.executeQuery("select * from hotel_room"); // Mendapatkan metadata dari ResultSet java.sql.ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // Mengosongkan model tabel DefaultTableModel model = (DefaultTableModel) tabelRoom.getModel(); model.setRowCount(0); // Menambahkan baris ke model while (rs.next()) { Object[] rowData = new Object[columnCount]; for (int i = 1; i <= columnCount; i++) { rowData[i - 1] = rs.getObject(i); } model.addRow(rowData); } } catch (Exception e) { e.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace } finally{ try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } } private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed if (txtIdRoom.getText().isEmpty() || cmbRoomType.getSelectedIndex() == -1 || txtRoomPrice.getText().isEmpty() || txtBadTotal.getText().isEmpty() || cmbStatus.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(this, "Missing Data"); } else { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); PreparedStatement Save = con.prepareStatement("INSERT INTO hotel_room VALUES(?, ?, ?, ?, ?)"); Save.setString(1, txtIdRoom.getText()); Save.setString(2, cmbRoomType.getSelectedItem().toString()); Save.setInt(3, Integer.valueOf(txtRoomPrice.getText())); Save.setInt(4, Integer.valueOf(txtBadTotal.getText())); Save.setString(5, cmbStatus.getSelectedItem().toString()); int row = Save.executeUpdate(); if (row > 0) { JOptionPane.showMessageDialog(this, "Room Added"); ShowRooms(); } else { JOptionPane.showMessageDialog(this, "Failed to add room"); } con.close(); } catch (SQLException ex) { ex.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage()); } } }//GEN-LAST:event_btnAddActionPerformed private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed txtIdRoom.setText(""); cmbRoomType.setSelectedIndex(-1); txtRoomPrice.setText(""); txtBadTotal.setText(""); cmbStatus.setSelectedIndex(-1); }//GEN-LAST:event_btnClearActionPerformed private void lblGuestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblGuestMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblGuestMouseClicked private void lblLogOut2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOut2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblLogOut2MouseClicked private void lblReservationMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblReservationMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblReservationMouseClicked private void lblLogOutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOutMouseClicked
new ExitConfirmation().setVisible(true);
0
2023-12-24 11:39:51+00:00
8k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/domain/member/member/service/MemberService.java
[ { "identifier": "GenFileService", "path": "src/main/java/com/multibook/bookorder/domain/base/genFile/service/GenFileService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class GenFileService {\n private final GenFileRepository genFileRepository;\n\n // 조회\n public Optional<GenFile> findBy(String relTypeCode, Long relId, String typeCode, String type2Code, long fileNo) {\n return genFileRepository.findByRelTypeCodeAndRelIdAndTypeCodeAndType2CodeAndFileNo(relTypeCode, relId, typeCode, type2Code, fileNo);\n }\n\n @Transactional\n public GenFile save(String relTypeCode, long relId, String typeCode, String type2Code, long fileNo, MultipartFile sourceFile) {\n String sourceFilePath = UtZip.file.toFile(sourceFile, AppConfig.getTempDirPath());\n return save(relTypeCode, relId, typeCode, type2Code, fileNo, sourceFilePath);\n }\n\n // 명령\n @Transactional\n public GenFile save(String relTypeCode, long relId, String typeCode, String type2Code, long fileNo, String sourceFile) {\n if (!UtZip.file.exists(sourceFile)) return null;\n\n // fileNo 가 0 이면, 이 파일은 로직상 무조건 새 파일이다.\n if (fileNo > 0) remove(relTypeCode, relId, typeCode, type2Code, fileNo);\n\n String originFileName = UtZip.file.getOriginFileName(sourceFile);\n String fileExt = UtZip.file.getExt(originFileName);\n String fileExtTypeCode = UtZip.file.getFileExtTypeCodeFromFileExt(fileExt);\n String fileExtType2Code = UtZip.file.getFileExtType2CodeFromFileExt(fileExt);\n long fileSize = new File(sourceFile).length();\n String fileDir = getCurrentDirName(relTypeCode);\n\n int maxTryCount = 3;\n\n GenFile genFile = null;\n\n for (int tryCount = 1; tryCount <= maxTryCount; tryCount++) {\n try {\n if (fileNo == 0) fileNo = genNextFileNo(relTypeCode, relId, typeCode, type2Code);\n\n genFile = GenFile.builder()\n .relTypeCode(relTypeCode)\n .relId(relId)\n .typeCode(typeCode)\n .type2Code(type2Code)\n .fileExtTypeCode(fileExtTypeCode)\n .fileExtType2Code(fileExtType2Code)\n .originFileName(originFileName)\n .fileSize(fileSize)\n .fileNo(fileNo)\n .fileExt(fileExt)\n .fileDir(fileDir)\n .build();\n\n genFileRepository.save(genFile);\n\n break;\n } catch (Exception ignored) {\n\n }\n }\n\n File file = new File(genFile.getFilePath());\n\n file.getParentFile().mkdirs();\n\n UtZip.file.moveFile(sourceFile, file);\n\n return genFile;\n }\n\n private long genNextFileNo(String relTypeCode, long relId, String typeCode, String type2Code) {\n return genFileRepository\n .findTop1ByRelTypeCodeAndRelIdAndTypeCodeAndType2CodeOrderByFileNoDesc(relTypeCode, relId, typeCode, type2Code)\n .map(genFile -> genFile.getFileNo() + 1)\n .orElse(1L);\n }\n\n private String getCurrentDirName(String relTypeCode) {\n return relTypeCode + \"/\" + UtZip.date.getCurrentDateFormatted(\"yyyy_MM_dd\");\n }\n\n public Map<String, GenFile> findGenFilesMapKeyByFileNo(String relTypeCode, long relId, String typeCode, String type2Code) {\n List<GenFile> genFiles = genFileRepository.findByRelTypeCodeAndRelIdAndTypeCodeAndType2CodeOrderByFileNoAsc(relTypeCode, relId, typeCode, type2Code);\n\n return genFiles\n .stream()\n .collect(Collectors.toMap(\n genFile -> String.valueOf(genFile.getFileNo()), // key\n genFile -> genFile // value\n ));\n }\n\n public Optional<GenFile> findById(long id) {\n return genFileRepository.findById(id);\n }\n\n @Transactional\n public void remove(String relTypeCode, long relId, String typeCode, String type2Code, long fileNo) {\n findBy(relTypeCode, relId, typeCode, type2Code, fileNo).ifPresent(this::remove);\n }\n\n @Transactional\n public void remove(GenFile genFile) {\n UtZip.file.remove(genFile.getFilePath());\n genFileRepository.delete(genFile);\n genFileRepository.flush();\n }\n\n public List<GenFile> findByRelId(String modelName, long relId) {\n return genFileRepository.findByRelTypeCodeAndRelId(modelName, relId);\n }\n\n @Transactional\n public GenFile saveTempFile(Member actor, MultipartFile file) {\n return save(\"temp_\" + actor.getModelName(), actor.getId(), \"common\", \"editorUpload\", 0, file);\n }\n\n @Transactional\n public GenFile tempToFile(String url, BaseEntity entity, String typeCode, String type2Code, long fileNo) {\n String fileName = UtZip.file.getFileNameFromUrl(url);\n String fileExt = UtZip.file.getFileExt(fileName);\n\n long genFileId = Long.parseLong(fileName.replace(\".\" + fileExt, \"\"));\n GenFile tempGenFile = findById(genFileId).get();\n\n GenFile newGenFile = save(entity.getModelName(), entity.getId(), typeCode, type2Code, fileNo, tempGenFile.getFilePath());\n\n remove(tempGenFile);\n\n return newGenFile;\n }\n\n public void removeOldTempFiles() {\n findOldTempFiles().forEach(this::remove);\n }\n\n private List<GenFile> findOldTempFiles() {\n LocalDateTime oneDayAgo = LocalDateTime.now().minusDays(1);\n return genFileRepository.findByRelTypeCodeAndCreateDateBefore(\"temp\", oneDayAgo);\n }\n}" }, { "identifier": "CashLog", "path": "src/main/java/com/multibook/bookorder/domain/cash/cash/entity/CashLog.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class CashLog extends BaseTime {\n @Enumerated(EnumType.STRING)\n private EvenType eventType;\n private String relTypeCode;\n private Long relId;\n @ManyToOne\n private Member member;\n private long price;\n\n public enum EvenType {\n 충전__무통장입금,\n 충전__토스페이먼츠,\n 출금__통장입금,\n 사용__토스페이먼츠_주문결제,\n 사용__예치금_주문결제,\n 환불__예치금_주문결제,\n 작가정산__예치금;\n }\n}" }, { "identifier": "CashService", "path": "src/main/java/com/multibook/bookorder/domain/cash/cash/service/CashService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class CashService {\n private final CashLogRepository cashLogRepository;\n\n @Transactional\n public CashLog addCash(Member member, long price, CashLog.EvenType eventType, BaseEntity relEntity) {\n CashLog cashLog = CashLog.builder()\n .member(member)\n .price(price)\n .relTypeCode(relEntity.getModelName())\n .relId(relEntity.getId())\n .eventType(eventType)\n .build();\n\n cashLogRepository.save(cashLog);\n\n return cashLog;\n }\n}" }, { "identifier": "Member", "path": "src/main/java/com/multibook/bookorder/domain/member/member/entity/Member.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true, exclude = {\"myBooks\", \"owner\"})\npublic class Member extends BaseTime {\n private String username;\n private String password;\n private String nickname;\n private long restCash;\n\n @OneToMany(mappedBy = \"owner\", cascade = ALL, orphanRemoval = true)\n @Builder.Default\n private List<MyBook> myBooks = new ArrayList<>();\n\n public void addMyBook(Book book) {\n MyBook myBook = MyBook.builder()\n .owner(this)\n .book(book)\n .build();\n\n myBooks.add(myBook);\n }\n\n public void removeMyBook(Book book) {\n myBooks.removeIf(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean hasBook(Book book) {\n return myBooks\n .stream()\n .anyMatch(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean has(Product product) {\n return switch (product.getRelTypeCode()) {\n case \"book\" -> hasBook(product.getBook());\n default -> false;\n };\n }\n\n @Transient\n public Collection<? extends GrantedAuthority> getAuthorities() {\n List<GrantedAuthority> authorities = new ArrayList<>();\n\n authorities.add(new SimpleGrantedAuthority(\"ROLE_MEMBER\"));\n\n if (List.of(\"system\", \"admin\").contains(username)) {\n authorities.add(new SimpleGrantedAuthority(\"ROLE_ADMIN\"));\n }\n\n return authorities;\n }\n\n public boolean isAdmin() {\n return getAuthorities().stream()\n .anyMatch(a -> a.getAuthority().equals(\"ROLE_ADMIN\"));\n }\n}" }, { "identifier": "MemberRepository", "path": "src/main/java/com/multibook/bookorder/domain/member/member/repository/MemberRepository.java", "snippet": "public interface MemberRepository extends JpaRepository<Member, Long> {\n Optional<Member> findByUsername(String username);\n}" }, { "identifier": "AppConfig", "path": "src/main/java/com/multibook/bookorder/global/app/AppConfig.java", "snippet": "@Configuration\n@RequiredArgsConstructor\npublic class AppConfig {\n private static String activeProfile;\n\n @Value(\"${spring.profiles.active}\")\n public void setActiveProfile(String value) {\n activeProfile = value;\n }\n\n public static boolean isNotProd() {\n return isProd() == false;\n }\n\n public static boolean isProd() {\n return activeProfile.equals(\"prod\");\n }\n\n @Getter\n private static String siteName;\n\n @Value(\"${custom.site.name}\")\n public void setSiteName(String siteName) {\n this.siteName = siteName;\n }\n\n @Getter\n private static EntityManager entityManager;\n\n @Autowired\n public void setEntityManager(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n\n @Getter\n private static String tempDirPath;\n\n @Value(\"${custom.temp.dirPath}\")\n public void setTempDirPath(String tempDirPath) {\n this.tempDirPath = tempDirPath;\n }\n\n @Getter\n private static String genFileDirPath;\n\n @Value(\"${custom.genFile.dirPath}\")\n public void setGenFileDirPath(String genFileDirPath) {\n this.genFileDirPath = genFileDirPath;\n }\n\n @Getter\n private static String tossPaymentsWidgetSecretKey;\n\n @Value(\"${custom.tossPayments.widget.secretKey}\")\n public void setTossPaymentsWidgetSecretKey(String tossPaymentsWidgetSecretKey) {\n this.tossPaymentsWidgetSecretKey = tossPaymentsWidgetSecretKey;\n }\n}" }, { "identifier": "BaseEntity", "path": "src/main/java/com/multibook/bookorder/global/jpa/BaseEntity.java", "snippet": "@MappedSuperclass\n@Getter\n@EqualsAndHashCode(onlyExplicitlyIncluded = true)\n@ToString\npublic abstract class BaseEntity {\n @Id\n @GeneratedValue(strategy = IDENTITY)\n @EqualsAndHashCode.Include\n private Long id;\n\n public String getModelName() {\n return UtZip.str.lcfirst(this.getClass().getSimpleName());\n }\n}" }, { "identifier": "RsData", "path": "src/main/java/com/multibook/bookorder/global/rsData/RsData.java", "snippet": "@AllArgsConstructor(access = PROTECTED)\n@Getter\npublic class RsData<T> {\n private final String resultCode;\n private final String msg;\n private final T data;\n private final int statusCode;\n\n public static <T> RsData<T> of(String resultCode, String msg, T data) {\n int statusCode = Integer.parseInt(resultCode.split(\"-\", 2)[0]);\n\n return new RsData<>(resultCode, msg, data, statusCode);\n }\n\n public static <T> RsData<T> of(String resultCode, String msg) {\n return of(resultCode, msg, null);\n }\n\n public boolean isSuccess() {\n return statusCode >= 200 && statusCode < 400;\n }\n\n public boolean isFail() {\n return !isSuccess();\n }\n\n public <T> RsData<T> of(T data) {\n return RsData.of(resultCode, msg, data);\n }\n}" }, { "identifier": "UtZip", "path": "src/main/java/com/multibook/bookorder/util/UtZip.java", "snippet": "public class UtZip {\n public static class exception {\n public static String toString(Exception e) {\n StringWriter sw = new StringWriter();\n e.printStackTrace(new PrintWriter(sw));\n String stackTrace = sw.toString();\n\n StringBuilder details = new StringBuilder();\n\n // 예외 메시지 추가\n details.append(\"Exception Message: \").append(e.getMessage()).append(\"\\n\");\n\n // 예외 원인 추가\n Throwable cause = e.getCause();\n if (cause != null) {\n details.append(\"Caused by: \").append(cause.toString()).append(\"\\n\");\n }\n\n // 스택 트레이스 추가\n details.append(\"Stack Trace:\\n\").append(stackTrace);\n\n return details.toString();\n }\n }\n\n public static class match {\n public static boolean isTrue(Boolean bool) {\n return bool != null && bool;\n }\n\n public static boolean isFalse(Boolean bool) {\n return bool != null && !bool;\n }\n }\n\n public static class date {\n private date() {\n }\n\n public static String getCurrentDateFormatted(String pattern) {\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);\n return simpleDateFormat.format(new Date());\n }\n }\n\n public static class file {\n private file() {\n }\n\n private static final String ORIGIN_FILE_NAME_SEPARATOR;\n\n static {\n ORIGIN_FILE_NAME_SEPARATOR = \"--originFileName_\";\n }\n\n public static String getOriginFileName(String file) {\n if (file.contains(ORIGIN_FILE_NAME_SEPARATOR)) {\n String[] fileInfos = file.split(ORIGIN_FILE_NAME_SEPARATOR);\n return fileInfos[fileInfos.length - 1];\n }\n\n return Paths.get(file).getFileName().toString();\n }\n\n public static String toFile(MultipartFile multipartFile, String tempDirPath) {\n if (multipartFile == null) return \"\";\n if (multipartFile.isEmpty()) return \"\";\n\n String filePath = tempDirPath + \"/\" + UUID.randomUUID() + ORIGIN_FILE_NAME_SEPARATOR + multipartFile.getOriginalFilename();\n\n try {\n multipartFile.transferTo(new File(filePath));\n } catch (IOException e) {\n return \"\";\n }\n\n return filePath;\n }\n\n public static void moveFile(String filePath, File file) {\n moveFile(filePath, file.getAbsolutePath());\n }\n\n public static boolean exists(String file) {\n return new File(file).exists();\n }\n\n public static boolean exists(MultipartFile file) {\n return file != null && !file.isEmpty();\n }\n\n public static String tempCopy(String file) {\n String tempPath = AppConfig.getTempDirPath() + \"/\" + getFileName(file);\n copy(file, tempPath);\n\n return tempPath;\n }\n\n private static String getFileName(String file) {\n return Paths.get(file).getFileName().toString();\n }\n\n private static void copy(String file, String tempDirPath) {\n try {\n Files.copy(Paths.get(file), Paths.get(tempDirPath), StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static class DownloadFileFailException extends RuntimeException {\n\n }\n\n private static String getFileExt(File file) {\n Tika tika = new Tika();\n String mimeType = \"\";\n\n try {\n mimeType = tika.detect(file);\n } catch (IOException e) {\n return null;\n }\n\n String ext = mimeType.replace(\"image/\", \"\");\n ext = ext.replace(\"jpeg\", \"jpg\");\n\n return ext.toLowerCase();\n }\n\n public static String getFileExt(String fileName) {\n int pos = fileName.lastIndexOf(\".\");\n\n if (pos == -1) {\n return \"\";\n }\n\n return fileName.substring(pos + 1).trim();\n }\n\n public static String getFileNameFromUrl(String fileUrl) {\n try {\n return Paths.get(new URI(fileUrl).getPath()).getFileName().toString();\n } catch (URISyntaxException e) {\n return \"\";\n }\n }\n\n public static String downloadFileByHttp(String fileUrl, String outputDir) {\n String originFileName = getFileNameFromUrl(fileUrl);\n String fileExt = getFileExt(originFileName);\n\n if (fileExt.isEmpty()) {\n fileExt = \"tmp\";\n }\n\n String tempFileName = UUID.randomUUID() + ORIGIN_FILE_NAME_SEPARATOR + originFileName + \".\" + fileExt;\n String filePath = outputDir + \"/\" + tempFileName;\n\n try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {\n ReadableByteChannel readableByteChannel = Channels.newChannel(new URI(fileUrl).toURL().openStream());\n FileChannel fileChannel = fileOutputStream.getChannel();\n fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);\n } catch (Exception e) {\n throw new DownloadFileFailException();\n }\n\n File file = new File(filePath);\n\n if (file.length() == 0) {\n throw new DownloadFileFailException();\n }\n\n if (fileExt.equals(\"tmp\")) {\n String ext = getFileExt(file);\n\n if (ext == null || ext.isEmpty()) {\n throw new DownloadFileFailException();\n }\n\n String newFilePath = filePath.replace(\".tmp\", \".\" + ext);\n moveFile(filePath, newFilePath);\n filePath = newFilePath;\n }\n\n return filePath;\n }\n\n public static void moveFile(String filePath, String destFilePath) {\n Path file = Paths.get(filePath);\n Path destFile = Paths.get(destFilePath);\n\n try {\n Files.move(file, destFile, StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException ignored) {\n\n }\n }\n\n public static String getExt(String filename) {\n return Optional.ofNullable(filename)\n .filter(f -> f.contains(\".\"))\n .map(f -> f.substring(filename.lastIndexOf(\".\") + 1).toLowerCase())\n .orElse(\"\");\n }\n\n public static String getFileExtTypeCodeFromFileExt(String ext) {\n return switch (ext) {\n case \"jpeg\", \"jpg\", \"gif\", \"png\" -> \"img\";\n case \"mp4\", \"avi\", \"mov\" -> \"video\";\n case \"mp3\" -> \"audio\";\n default -> \"etc\";\n };\n\n }\n\n public static String getFileExtType2CodeFromFileExt(String ext) {\n\n return switch (ext) {\n case \"jpeg\", \"jpg\" -> \"jpg\";\n case \"gif\", \"png\", \"mp4\", \"mov\", \"avi\", \"mp3\" -> ext;\n default -> \"etc\";\n };\n\n }\n\n public static void remove(String filePath) {\n File file = new File(filePath);\n if (file.exists()) {\n file.delete();\n }\n }\n }\n\n public static class str {\n\n public static String lcfirst(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n return str.substring(0, 1).toLowerCase() + str.substring(1);\n }\n\n public static boolean hasLength(String string) {\n return string != null && !string.trim().isEmpty();\n }\n\n public static boolean isBlank(String string) {\n return !hasLength(string);\n }\n }\n\n public static class url {\n public static String modifyQueryParam(String url, String paramName, String paramValue) {\n url = deleteQueryParam(url, paramName);\n url = addQueryParam(url, paramName, paramValue);\n\n return url;\n }\n\n public static String addQueryParam(String url, String paramName, String paramValue) {\n if (!url.contains(\"?\")) {\n url += \"?\";\n }\n\n if (!url.endsWith(\"?\") && !url.endsWith(\"&\")) {\n url += \"&\";\n }\n\n url += paramName + \"=\" + paramValue;\n\n return url;\n }\n\n public static String deleteQueryParam(String url, String paramName) {\n int startPoint = url.indexOf(paramName + \"=\");\n if (startPoint == -1) return url;\n\n int endPoint = url.substring(startPoint).indexOf(\"&\");\n\n if (endPoint == -1) {\n return url.substring(0, startPoint - 1);\n }\n\n String urlAfter = url.substring(startPoint + endPoint + 1);\n\n return url.substring(0, startPoint) + urlAfter;\n }\n\n public static String encode(String url) {\n return new URLEncoder().encode(url, StandardCharsets.UTF_8);\n }\n }\n}" }, { "identifier": "GenFile", "path": "src/main/java/com/multibook/bookorder/domain/base/genFile/entity/GenFile.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\n@Table(\n uniqueConstraints = @UniqueConstraint(\n columnNames = {\n \"relId\", \"relTypeCode\", \"typeCode\", \"type2Code\", \"fileNo\"\n }\n ),\n indexes = {\n // 특정 그룹의 데이터들을 불러올 때\n @Index(name = \"GenFile_idx2\", columnList = \"relTypeCode, typeCode, type2Code\")\n }\n)\npublic class GenFile extends BaseTime {\n private String relTypeCode;\n private long relId;\n private String typeCode;\n private String type2Code;\n private String fileExtTypeCode;\n private String fileExtType2Code;\n private long fileSize;\n private long fileNo;\n private String fileExt;\n private String fileDir;\n private String originFileName;\n\n public String getFileName() {\n return getId() + \".\" + getFileExt();\n }\n\n public String getUrl() {\n return \"/gen/\" + getFileDir() + \"/\" + getFileName();\n }\n\n public String getDownloadUrl() {\n return \"/domain/genFile/download/\" + getId();\n }\n\n public String getFilePath() {\n return AppConfig.getGenFileDirPath() + \"/\" + getFileDir() + \"/\" + getFileName();\n }\n}" } ]
import com.multibook.bookorder.domain.base.genFile.service.GenFileService; import com.multibook.bookorder.domain.cash.cash.entity.CashLog; import com.multibook.bookorder.domain.cash.cash.service.CashService; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.domain.member.member.repository.MemberRepository; import com.multibook.bookorder.global.app.AppConfig; import com.multibook.bookorder.global.jpa.BaseEntity; import com.multibook.bookorder.global.rsData.RsData; import com.multibook.bookorder.util.UtZip; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import com.multibook.bookorder.domain.base.genFile.entity.GenFile; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.util.Optional;
6,248
package com.multibook.bookorder.domain.member.member.service; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class MemberService { private final MemberRepository memberRepository; private final PasswordEncoder passwordEncoder; private final CashService cashService; private final GenFileService genFileService; @Transactional public RsData<Member> join(String username, String password, String nickname) { return join(username, password, nickname, ""); } @Transactional public RsData<Member> join(String username, String password, String nickname, MultipartFile profileImg) { String profileImgFilePath = UtZip.file.toFile(profileImg, AppConfig.getTempDirPath()); return join(username, password, nickname, profileImgFilePath); } @Transactional public RsData<Member> join(String username, String password, String nickname, String profileImgFilePath) { if (findByUsername(username).isPresent()) { return RsData.of("400-2", "이미 존재하는 회원입니다."); } Member member = Member.builder() .username(username) .password(passwordEncoder.encode(password)) .nickname(nickname) .build(); memberRepository.save(member); if (UtZip.str.hasLength(profileImgFilePath)) { saveProfileImg(member, profileImgFilePath); } return RsData.of("200", "%s님 환영합니다. 회원가입이 완료되었습니다. 로그인 후 이용해주세요.".formatted(member.getUsername()), member); } private void saveProfileImg(Member member, String profileImgFilePath) { genFileService.save(member.getModelName(), member.getId(), "common", "profileImg", 1, profileImgFilePath); } public Optional<Member> findByUsername(String username) { return memberRepository.findByUsername(username); } @Transactional
package com.multibook.bookorder.domain.member.member.service; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class MemberService { private final MemberRepository memberRepository; private final PasswordEncoder passwordEncoder; private final CashService cashService; private final GenFileService genFileService; @Transactional public RsData<Member> join(String username, String password, String nickname) { return join(username, password, nickname, ""); } @Transactional public RsData<Member> join(String username, String password, String nickname, MultipartFile profileImg) { String profileImgFilePath = UtZip.file.toFile(profileImg, AppConfig.getTempDirPath()); return join(username, password, nickname, profileImgFilePath); } @Transactional public RsData<Member> join(String username, String password, String nickname, String profileImgFilePath) { if (findByUsername(username).isPresent()) { return RsData.of("400-2", "이미 존재하는 회원입니다."); } Member member = Member.builder() .username(username) .password(passwordEncoder.encode(password)) .nickname(nickname) .build(); memberRepository.save(member); if (UtZip.str.hasLength(profileImgFilePath)) { saveProfileImg(member, profileImgFilePath); } return RsData.of("200", "%s님 환영합니다. 회원가입이 완료되었습니다. 로그인 후 이용해주세요.".formatted(member.getUsername()), member); } private void saveProfileImg(Member member, String profileImgFilePath) { genFileService.save(member.getModelName(), member.getId(), "common", "profileImg", 1, profileImgFilePath); } public Optional<Member> findByUsername(String username) { return memberRepository.findByUsername(username); } @Transactional
public void addCash(Member member, long price, CashLog.EvenType eventType, BaseEntity relEntity) {
6
2023-12-26 14:58:59+00:00
8k
huidongyin/kafka-2.7.2
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/WorkerMetricsGroup.java
[ { "identifier": "MetricName", "path": "clients/src/main/java/org/apache/kafka/common/MetricName.java", "snippet": "public final class MetricName {\n\n private final String name;\n private final String group;\n private final String description;\n private Map<String, String> tags;\n private int hash = 0;\n\n /**\n * Please create MetricName by method {@link org.apache.kafka.common.metrics.Metrics#metricName(String, String, String, Map)}\n *\n * @param name The name of the metric\n * @param group logical group name of the metrics to which this metric belongs\n * @param description A human-readable description to include in the metric\n * @param tags additional key/value attributes of the metric\n */\n public MetricName(String name, String group, String description, Map<String, String> tags) {\n this.name = Objects.requireNonNull(name);\n this.group = Objects.requireNonNull(group);\n this.description = Objects.requireNonNull(description);\n this.tags = Objects.requireNonNull(tags);\n }\n\n public String name() {\n return this.name;\n }\n\n public String group() {\n return this.group;\n }\n\n public Map<String, String> tags() {\n return this.tags;\n }\n\n public String description() {\n return this.description;\n }\n\n @Override\n public int hashCode() {\n if (hash != 0)\n return hash;\n final int prime = 31;\n int result = 1;\n result = prime * result + group.hashCode();\n result = prime * result + name.hashCode();\n result = prime * result + tags.hashCode();\n this.hash = result;\n return result;\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 MetricName other = (MetricName) obj;\n return group.equals(other.group) && name.equals(other.name) && tags.equals(other.tags);\n }\n\n @Override\n public String toString() {\n return \"MetricName [name=\" + name + \", group=\" + group + \", description=\"\n + description + \", tags=\" + tags + \"]\";\n }\n}" }, { "identifier": "Sensor", "path": "clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java", "snippet": "public final class Sensor {\n\n private final Metrics registry;\n private final String name;\n private final Sensor[] parents;\n private final List<StatAndConfig> stats;\n private final Map<MetricName, KafkaMetric> metrics;\n private final MetricConfig config;\n private final Time time;\n private volatile long lastRecordTime;\n private final long inactiveSensorExpirationTimeMs;\n private final Object metricLock;\n\n private static class StatAndConfig {\n private final Stat stat;\n private final Supplier<MetricConfig> configSupplier;\n\n StatAndConfig(Stat stat, Supplier<MetricConfig> configSupplier) {\n this.stat = stat;\n this.configSupplier = configSupplier;\n }\n\n public Stat stat() {\n return stat;\n }\n\n public MetricConfig config() {\n return configSupplier.get();\n }\n }\n\n public enum RecordingLevel {\n INFO(0, \"INFO\"), DEBUG(1, \"DEBUG\"), TRACE(2, \"TRACE\");\n\n private static final RecordingLevel[] ID_TO_TYPE;\n private static final int MIN_RECORDING_LEVEL_KEY = 0;\n public static final int MAX_RECORDING_LEVEL_KEY;\n\n static {\n int maxRL = -1;\n for (RecordingLevel level : RecordingLevel.values()) {\n maxRL = Math.max(maxRL, level.id);\n }\n RecordingLevel[] idToName = new RecordingLevel[maxRL + 1];\n for (RecordingLevel level : RecordingLevel.values()) {\n idToName[level.id] = level;\n }\n ID_TO_TYPE = idToName;\n MAX_RECORDING_LEVEL_KEY = maxRL;\n }\n\n /** an english description of the api--this is for debugging and can change */\n public final String name;\n\n /** the permanent and immutable id of an API--this can't change ever */\n public final short id;\n\n RecordingLevel(int id, String name) {\n this.id = (short) id;\n this.name = name;\n }\n\n public static RecordingLevel forId(int id) {\n if (id < MIN_RECORDING_LEVEL_KEY || id > MAX_RECORDING_LEVEL_KEY)\n throw new IllegalArgumentException(String.format(\"Unexpected RecordLevel id `%d`, it should be between `%d` \" +\n \"and `%d` (inclusive)\", id, MIN_RECORDING_LEVEL_KEY, MAX_RECORDING_LEVEL_KEY));\n return ID_TO_TYPE[id];\n }\n\n /** Case insensitive lookup by protocol name */\n public static RecordingLevel forName(String name) {\n return RecordingLevel.valueOf(name.toUpperCase(Locale.ROOT));\n }\n\n public boolean shouldRecord(final int configId) {\n if (configId == INFO.id) {\n return this.id == INFO.id;\n } else if (configId == DEBUG.id) {\n return this.id == INFO.id || this.id == DEBUG.id;\n } else if (configId == TRACE.id) {\n return true;\n } else {\n throw new IllegalStateException(\"Did not recognize recording level \" + configId);\n }\n }\n }\n\n private final RecordingLevel recordingLevel;\n\n Sensor(Metrics registry, String name, Sensor[] parents, MetricConfig config, Time time,\n long inactiveSensorExpirationTimeSeconds, RecordingLevel recordingLevel) {\n super();\n this.registry = registry;\n this.name = Objects.requireNonNull(name);\n this.parents = parents == null ? new Sensor[0] : parents;\n this.metrics = new LinkedHashMap<>();\n this.stats = new ArrayList<>();\n this.config = config;\n this.time = time;\n this.inactiveSensorExpirationTimeMs = TimeUnit.MILLISECONDS.convert(inactiveSensorExpirationTimeSeconds, TimeUnit.SECONDS);\n this.lastRecordTime = time.milliseconds();\n this.recordingLevel = recordingLevel;\n this.metricLock = new Object();\n checkForest(new HashSet<>());\n }\n\n /* Validate that this sensor doesn't end up referencing itself */\n private void checkForest(Set<Sensor> sensors) {\n if (!sensors.add(this))\n throw new IllegalArgumentException(\"Circular dependency in sensors: \" + name() + \" is its own parent.\");\n for (Sensor parent : parents)\n parent.checkForest(sensors);\n }\n\n /**\n * The name this sensor is registered with. This name will be unique among all registered sensors.\n */\n public String name() {\n return this.name;\n }\n\n List<Sensor> parents() {\n return unmodifiableList(asList(parents));\n }\n\n /**\n * @return true if the sensor's record level indicates that the metric will be recorded, false otherwise\n */\n public boolean shouldRecord() {\n return this.recordingLevel.shouldRecord(config.recordLevel().id);\n }\n\n /**\n * Record an occurrence, this is just short-hand for {@link #record(double) record(1.0)}\n */\n public void record() {\n if (shouldRecord()) {\n recordInternal(1.0d, time.milliseconds(), true);\n }\n }\n\n /**\n * Record a value with this sensor\n * @param value The value to record\n * @throws QuotaViolationException if recording this value moves a metric beyond its configured maximum or minimum\n * bound\n */\n public void record(double value) {\n if (shouldRecord()) {\n recordInternal(value, time.milliseconds(), true);\n }\n }\n\n /**\n * Record a value at a known time. This method is slightly faster than {@link #record(double)} since it will reuse\n * the time stamp.\n * @param value The value we are recording\n * @param timeMs The current POSIX time in milliseconds\n * @throws QuotaViolationException if recording this value moves a metric beyond its configured maximum or minimum\n * bound\n */\n public void record(double value, long timeMs) {\n if (shouldRecord()) {\n recordInternal(value, timeMs, true);\n }\n }\n\n /**\n * Record a value at a known time. This method is slightly faster than {@link #record(double)} since it will reuse\n * the time stamp.\n * @param value The value we are recording\n * @param timeMs The current POSIX time in milliseconds\n * @param checkQuotas Indicate if quota must be enforced or not\n * @throws QuotaViolationException if recording this value moves a metric beyond its configured maximum or minimum\n * bound\n */\n public void record(double value, long timeMs, boolean checkQuotas) {\n if (shouldRecord()) {\n recordInternal(value, timeMs, checkQuotas);\n }\n }\n\n private void recordInternal(double value, long timeMs, boolean checkQuotas) {\n this.lastRecordTime = timeMs;\n synchronized (this) {\n synchronized (metricLock()) {\n // increment all the stats\n for (StatAndConfig statAndConfig : this.stats) {\n statAndConfig.stat.record(statAndConfig.config(), value, timeMs);\n }\n }\n if (checkQuotas)\n checkQuotas(timeMs);\n }\n for (Sensor parent : parents)\n parent.record(value, timeMs, checkQuotas);\n }\n\n /**\n * Check if we have violated our quota for any metric that has a configured quota\n */\n public void checkQuotas() {\n checkQuotas(time.milliseconds());\n }\n\n public void checkQuotas(long timeMs) {\n for (KafkaMetric metric : this.metrics.values()) {\n MetricConfig config = metric.config();\n if (config != null) {\n Quota quota = config.quota();\n if (quota != null) {\n double value = metric.measurableValue(timeMs);\n if (metric.measurable() instanceof TokenBucket) {\n if (value < 0) {\n throw new QuotaViolationException(metric, value, quota.bound());\n }\n } else {\n if (!quota.acceptable(value)) {\n throw new QuotaViolationException(metric, value, quota.bound());\n }\n }\n }\n }\n }\n }\n\n /**\n * Register a compound statistic with this sensor with no config override\n * @param stat The stat to register\n * @return true if stat is added to sensor, false if sensor is expired\n */\n public boolean add(CompoundStat stat) {\n return add(stat, null);\n }\n\n /**\n * Register a compound statistic with this sensor which yields multiple measurable quantities (like a histogram)\n * @param stat The stat to register\n * @param config The configuration for this stat. If null then the stat will use the default configuration for this\n * sensor.\n * @return true if stat is added to sensor, false if sensor is expired\n */\n public synchronized boolean add(CompoundStat stat, MetricConfig config) {\n if (hasExpired())\n return false;\n\n final MetricConfig statConfig = config == null ? this.config : config;\n stats.add(new StatAndConfig(Objects.requireNonNull(stat), () -> statConfig));\n Object lock = metricLock();\n for (NamedMeasurable m : stat.stats()) {\n final KafkaMetric metric = new KafkaMetric(lock, m.name(), m.stat(), statConfig, time);\n if (!metrics.containsKey(metric.metricName())) {\n registry.registerMetric(metric);\n metrics.put(metric.metricName(), metric);\n }\n }\n return true;\n }\n\n /**\n * Register a metric with this sensor\n * @param metricName The name of the metric\n * @param stat The statistic to keep\n * @return true if metric is added to sensor, false if sensor is expired\n */\n public boolean add(MetricName metricName, MeasurableStat stat) {\n return add(metricName, stat, null);\n }\n\n /**\n * Register a metric with this sensor\n *\n * @param metricName The name of the metric\n * @param stat The statistic to keep\n * @param config A special configuration for this metric. If null use the sensor default configuration.\n * @return true if metric is added to sensor, false if sensor is expired\n */\n public synchronized boolean add(final MetricName metricName, final MeasurableStat stat, final MetricConfig config) {\n if (hasExpired()) {\n return false;\n } else if (metrics.containsKey(metricName)) {\n return true;\n } else {\n final MetricConfig statConfig = config == null ? this.config : config;\n final KafkaMetric metric = new KafkaMetric(\n metricLock(),\n Objects.requireNonNull(metricName),\n Objects.requireNonNull(stat),\n statConfig,\n time\n );\n registry.registerMetric(metric);\n metrics.put(metric.metricName(), metric);\n stats.add(new StatAndConfig(Objects.requireNonNull(stat), metric::config));\n return true;\n }\n }\n\n /**\n * Return if metrics were registered with this sensor.\n *\n * @return true if metrics were registered, false otherwise\n */\n public synchronized boolean hasMetrics() {\n return !metrics.isEmpty();\n }\n\n /**\n * Return true if the Sensor is eligible for removal due to inactivity.\n * false otherwise\n */\n public boolean hasExpired() {\n return (time.milliseconds() - this.lastRecordTime) > this.inactiveSensorExpirationTimeMs;\n }\n\n synchronized List<KafkaMetric> metrics() {\n return unmodifiableList(new ArrayList<>(this.metrics.values()));\n }\n\n /**\n * KafkaMetrics of sensors which use SampledStat should be synchronized on the same lock\n * for sensor record and metric value read to allow concurrent reads and updates. For simplicity,\n * all sensors are synchronized on this object.\n * <p>\n * Sensor object is not used as a lock for reading metric value since metrics reporter is\n * invoked while holding Sensor and Metrics locks to report addition and removal of metrics\n * and synchronized reporters may deadlock if Sensor lock is used for reading metrics values.\n * Note that Sensor object itself is used as a lock to protect the access to stats and metrics\n * while recording metric values, adding and deleting sensors.\n * </p><p>\n * Locking order (assume all MetricsReporter methods may be synchronized):\n * <ul>\n * <li>Sensor#add: Sensor -> Metrics -> MetricsReporter</li>\n * <li>Metrics#removeSensor: Sensor -> Metrics -> MetricsReporter</li>\n * <li>KafkaMetric#metricValue: MetricsReporter -> Sensor#metricLock</li>\n * <li>Sensor#record: Sensor -> Sensor#metricLock</li>\n * </ul>\n * </p>\n */\n private Object metricLock() {\n return metricLock;\n }\n}" }, { "identifier": "CumulativeSum", "path": "clients/src/main/java/org/apache/kafka/common/metrics/stats/CumulativeSum.java", "snippet": "public class CumulativeSum implements MeasurableStat {\n\n private double total;\n\n public CumulativeSum() {\n total = 0.0;\n }\n\n public CumulativeSum(double value) {\n total = value;\n }\n\n @Override\n public void record(MetricConfig config, double value, long now) {\n total += value;\n }\n\n @Override\n public double measure(MetricConfig config, long now) {\n return total;\n }\n\n}" }, { "identifier": "Frequencies", "path": "clients/src/main/java/org/apache/kafka/common/metrics/stats/Frequencies.java", "snippet": "public class Frequencies extends SampledStat implements CompoundStat {\n\n /**\n * Create a Frequencies instance with metrics for the frequency of a boolean sensor that records 0.0 for\n * false and 1.0 for true.\n *\n * @param falseMetricName the name of the metric capturing the frequency of failures; may be null if not needed\n * @param trueMetricName the name of the metric capturing the frequency of successes; may be null if not needed\n * @return the Frequencies instance; never null\n * @throws IllegalArgumentException if both {@code falseMetricName} and {@code trueMetricName} are null\n */\n public static Frequencies forBooleanValues(MetricName falseMetricName, MetricName trueMetricName) {\n List<Frequency> frequencies = new ArrayList<>();\n if (falseMetricName != null) {\n frequencies.add(new Frequency(falseMetricName, 0.0));\n }\n if (trueMetricName != null) {\n frequencies.add(new Frequency(trueMetricName, 1.0));\n }\n if (frequencies.isEmpty()) {\n throw new IllegalArgumentException(\"Must specify at least one metric name\");\n }\n Frequency[] frequencyArray = frequencies.toArray(new Frequency[frequencies.size()]);\n return new Frequencies(2, 0.0, 1.0, frequencyArray);\n }\n\n private final Frequency[] frequencies;\n private final BinScheme binScheme;\n\n /**\n * Create a Frequencies that captures the values in the specified range into the given number of buckets,\n * where the buckets are centered around the minimum, maximum, and intermediate values.\n *\n * @param buckets the number of buckets; must be at least 1\n * @param min the minimum value to be captured\n * @param max the maximum value to be captured\n * @param frequencies the list of {@link Frequency} metrics, which at most should be one per bucket centered\n * on the bucket's value, though not every bucket need to correspond to a metric if the\n * value is not needed\n * @throws IllegalArgumentException if any of the {@link Frequency} objects do not have a\n * {@link Frequency#centerValue() center value} within the specified range\n */\n public Frequencies(int buckets, double min, double max, Frequency... frequencies) {\n super(0.0); // initial value is unused by this implementation\n if (max < min) {\n throw new IllegalArgumentException(\"The maximum value \" + max\n + \" must be greater than the minimum value \" + min);\n }\n if (buckets < 1) {\n throw new IllegalArgumentException(\"Must be at least 1 bucket\");\n }\n if (buckets < frequencies.length) {\n throw new IllegalArgumentException(\"More frequencies than buckets\");\n }\n this.frequencies = frequencies;\n for (Frequency freq : frequencies) {\n if (min > freq.centerValue() || max < freq.centerValue()) {\n throw new IllegalArgumentException(\"The frequency centered at '\" + freq.centerValue()\n + \"' is not within the range [\" + min + \",\" + max + \"]\");\n }\n }\n double halfBucketWidth = (max - min) / (buckets - 1) / 2.0;\n this.binScheme = new ConstantBinScheme(buckets, min - halfBucketWidth, max + halfBucketWidth);\n }\n\n @Override\n public List<NamedMeasurable> stats() {\n List<NamedMeasurable> ms = new ArrayList<>(frequencies.length);\n for (Frequency frequency : frequencies) {\n final double center = frequency.centerValue();\n ms.add(new NamedMeasurable(frequency.name(), new Measurable() {\n public double measure(MetricConfig config, long now) {\n return frequency(config, now, center);\n }\n }));\n }\n return ms;\n }\n\n /**\n * Return the computed frequency describing the number of occurrences of the values in the bucket for the given\n * center point, relative to the total number of occurrences in the samples.\n *\n * @param config the metric configuration\n * @param now the current time in milliseconds\n * @param centerValue the value corresponding to the center point of the bucket\n * @return the frequency of the values in the bucket relative to the total number of samples\n */\n public double frequency(MetricConfig config, long now, double centerValue) {\n purgeObsoleteSamples(config, now);\n long totalCount = 0;\n for (Sample sample : samples) {\n totalCount += sample.eventCount;\n }\n if (totalCount == 0) {\n return 0.0d;\n }\n // Add up all of the counts in the bin corresponding to the center value\n float count = 0.0f;\n int binNum = binScheme.toBin(centerValue);\n for (Sample s : samples) {\n HistogramSample sample = (HistogramSample) s;\n float[] hist = sample.histogram.counts();\n count += hist[binNum];\n }\n // Compute the ratio of counts to total counts\n return count / (double) totalCount;\n }\n\n double totalCount() {\n long count = 0;\n for (Sample sample : samples) {\n count += sample.eventCount;\n }\n return count;\n }\n\n @Override\n public double combine(List<Sample> samples, MetricConfig config, long now) {\n return totalCount();\n }\n\n @Override\n protected HistogramSample newSample(long timeMs) {\n return new HistogramSample(binScheme, timeMs);\n }\n\n @Override\n protected void update(Sample sample, MetricConfig config, double value, long timeMs) {\n HistogramSample hist = (HistogramSample) sample;\n hist.histogram.record(value);\n }\n\n private static class HistogramSample extends SampledStat.Sample {\n\n private final Histogram histogram;\n\n private HistogramSample(BinScheme scheme, long now) {\n super(0.0, now);\n histogram = new Histogram(scheme);\n }\n\n @Override\n public void reset(long now) {\n super.reset(now);\n histogram.clear();\n }\n }\n}" }, { "identifier": "ConnectorTaskId", "path": "connect/runtime/src/main/java/org/apache/kafka/connect/util/ConnectorTaskId.java", "snippet": "public class ConnectorTaskId implements Serializable, Comparable<ConnectorTaskId> {\n private final String connector;\n private final int task;\n\n @JsonCreator\n public ConnectorTaskId(@JsonProperty(\"connector\") String connector, @JsonProperty(\"task\") int task) {\n this.connector = connector;\n this.task = task;\n }\n\n @JsonProperty\n public String connector() {\n return connector;\n }\n\n @JsonProperty\n public int task() {\n return task;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n\n ConnectorTaskId that = (ConnectorTaskId) o;\n\n if (task != that.task)\n return false;\n\n return Objects.equals(connector, that.connector);\n }\n\n @Override\n public int hashCode() {\n int result = connector != null ? connector.hashCode() : 0;\n result = 31 * result + task;\n return result;\n }\n\n @Override\n public String toString() {\n return connector + '-' + task;\n }\n\n @Override\n public int compareTo(ConnectorTaskId o) {\n int connectorCmp = connector.compareTo(o.connector);\n if (connectorCmp != 0)\n return connectorCmp;\n return Integer.compare(task, o.task);\n }\n}" } ]
import org.apache.kafka.common.MetricName; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.stats.CumulativeSum; import org.apache.kafka.common.metrics.stats.Frequencies; import org.apache.kafka.connect.util.ConnectorTaskId; import java.util.Map;
6,051
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime; class WorkerMetricsGroup { private final ConnectMetrics.MetricGroup metricGroup; private final Sensor connectorStartupAttempts; private final Sensor connectorStartupSuccesses; private final Sensor connectorStartupFailures; private final Sensor connectorStartupResults; private final Sensor taskStartupAttempts; private final Sensor taskStartupSuccesses; private final Sensor taskStartupFailures; private final Sensor taskStartupResults; public WorkerMetricsGroup(final Map<String, WorkerConnector> connectors, Map<ConnectorTaskId, WorkerTask> tasks, ConnectMetrics connectMetrics) { ConnectMetricsRegistry registry = connectMetrics.registry(); metricGroup = connectMetrics.group(registry.workerGroupName()); metricGroup.addValueMetric(registry.connectorCount, now -> (double) connectors.size()); metricGroup.addValueMetric(registry.taskCount, now -> (double) tasks.size()); MetricName connectorFailurePct = metricGroup.metricName(registry.connectorStartupFailurePercentage); MetricName connectorSuccessPct = metricGroup.metricName(registry.connectorStartupSuccessPercentage);
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime; class WorkerMetricsGroup { private final ConnectMetrics.MetricGroup metricGroup; private final Sensor connectorStartupAttempts; private final Sensor connectorStartupSuccesses; private final Sensor connectorStartupFailures; private final Sensor connectorStartupResults; private final Sensor taskStartupAttempts; private final Sensor taskStartupSuccesses; private final Sensor taskStartupFailures; private final Sensor taskStartupResults; public WorkerMetricsGroup(final Map<String, WorkerConnector> connectors, Map<ConnectorTaskId, WorkerTask> tasks, ConnectMetrics connectMetrics) { ConnectMetricsRegistry registry = connectMetrics.registry(); metricGroup = connectMetrics.group(registry.workerGroupName()); metricGroup.addValueMetric(registry.connectorCount, now -> (double) connectors.size()); metricGroup.addValueMetric(registry.taskCount, now -> (double) tasks.size()); MetricName connectorFailurePct = metricGroup.metricName(registry.connectorStartupFailurePercentage); MetricName connectorSuccessPct = metricGroup.metricName(registry.connectorStartupSuccessPercentage);
Frequencies connectorStartupResultFrequencies = Frequencies.forBooleanValues(connectorFailurePct, connectorSuccessPct);
3
2023-12-23 07:12:18+00:00
8k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/entity/client/EmperorPenguinModel.java
[ { "identifier": "EmperorPenguinAnimationDefinitions", "path": "src/main/java/com/sdevuyst/pingyswaddles/animations/EmperorPenguinAnimationDefinitions.java", "snippet": "public class EmperorPenguinAnimationDefinitions\n{\n public static final AnimationDefinition WINGING = AnimationDefinition.Builder.withLength(2.0F)\n .addAnimation(\"rightwing\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(1.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, -27.5F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(2.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .addAnimation(\"emperor_penguin\", new AnimationChannel(AnimationChannel.Targets.POSITION,\n new Keyframe(0.0F, KeyframeAnimations.posVec(1.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR)\n ))\n .addAnimation(\"leftwing\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(1.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 27.5F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(2.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .build();\n\n public static final AnimationDefinition WALKING = AnimationDefinition.Builder.withLength(1.0F).looping()\n .addAnimation(\"emperor_penguin\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(0.0F, -7.0F, -10.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.5F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.75F, KeyframeAnimations.degreeVec(0.0F, 7.0F, 10.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(1.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR)\n ))\n //.addAnimation(\"body\", new AnimationChannel(AnimationChannel.Targets.POSITION,\n // new Keyframe(0.0F, KeyframeAnimations.posVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n // new Keyframe(0.5F, KeyframeAnimations.posVec(5.0F, 10.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n // new Keyframe(1.0F, KeyframeAnimations.posVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n // new Keyframe(1.5F, KeyframeAnimations.posVec(5.0F, 10.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n // new Keyframe(2.0F, KeyframeAnimations.posVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR)\n //))\n .addAnimation(\"top\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(0.0F, 10.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.5F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.75F, KeyframeAnimations.degreeVec(0.0F, -10.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(1.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR)\n ))\n .addAnimation(\"rightwing\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(0.0F, 0.0F, -7.5F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(0.5F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(0.75F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(1.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .addAnimation(\"leftwing\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(0.50F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(0.75F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 7.5F), AnimationChannel.Interpolations.CATMULLROM),\n new Keyframe(1.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .build();\n\n public static final AnimationDefinition FALLING = AnimationDefinition.Builder.withLength(0.25F)\n .addAnimation(\"rightwing\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(0.0F, 0.0F, -130.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .addAnimation(\"leftwing\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 130.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .addAnimation(\"tail\", new AnimationChannel(AnimationChannel.Targets.ROTATION,\n new Keyframe(0.0F, KeyframeAnimations.degreeVec(0.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.LINEAR),\n new Keyframe(0.25F, KeyframeAnimations.degreeVec(-10.0F, 0.0F, 0.0F), AnimationChannel.Interpolations.CATMULLROM)\n ))\n .build();\n\n}" }, { "identifier": "EmperorPenguinEntity", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/custom/EmperorPenguinEntity.java", "snippet": "public class EmperorPenguinEntity extends AbstractPenguin {\n\n public EmperorPenguinEntity(EntityType<? extends Animal> pEntityType, Level pLevel) {\n super(pEntityType, pLevel);\n }\n\n @Nullable\n @Override\n public AgeableMob getBreedOffspring(ServerLevel serverLevel, AgeableMob ageableMob) {\n return ModEntities.EMPEROR_PENGUIN.get().create(serverLevel);\n }\n\n static {\n NORMAL_DIMENSIONS = EntityDimensions.fixed(1.0F, 1.9F);\n BABY_DIMENSIONS = EntityDimensions.fixed(0.5F, 0.9F);\n }\n}" } ]
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.sdevuyst.pingyswaddles.animations.EmperorPenguinAnimationDefinitions; import com.sdevuyst.pingyswaddles.entity.custom.EmperorPenguinEntity; import net.minecraft.client.model.HierarchicalModel; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.PartPose; import net.minecraft.client.model.geom.builders.*; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity;
3,948
package com.sdevuyst.pingyswaddles.entity.client; public class EmperorPenguinModel<T extends Entity> extends HierarchicalModel<T> { private final ModelPart root; private final ModelPart head; public EmperorPenguinModel(ModelPart root) { this.root = root; this.head = root.getChild("emperor_penguin").getChild("top"); } public static LayerDefinition createBodyLayer() { MeshDefinition meshdefinition = new MeshDefinition(); PartDefinition partdefinition = meshdefinition.getRoot(); PartDefinition emperor_penguin = partdefinition.addOrReplaceChild("emperor_penguin", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 135F, 0.0F)); PartDefinition top = emperor_penguin.addOrReplaceChild("top", CubeListBuilder.create(), PartPose.offsetAndRotation(2.0F, -11.5F, 0.0F, -0.0349F, 0.0F, 0.0F)); PartDefinition head = top.addOrReplaceChild("head", CubeListBuilder.create().texOffs(2, 38).addBox(-7.0F, -18.5009F, -6.9477F, 14.0F, 10.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition beak = top.addOrReplaceChild("beak", CubeListBuilder.create().texOffs(50, 2).addBox(-1.0F, -12.5009F, 6.0523F, 2.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition body = emperor_penguin.addOrReplaceChild("body", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -20.0F, -8.0F, 16.0F, 20.0F, 16.0F, new CubeDeformation(0.0F)), PartPose.offset(2.0F, 0.0F, 0.0F)); PartDefinition wings = emperor_penguin.addOrReplaceChild("wings", CubeListBuilder.create(), PartPose.offset(2.0F, -1.5F, 0.0F)); PartDefinition rightwing = wings.addOrReplaceChild("rightwing", CubeListBuilder.create(), PartPose.offset(7.0F, -17.0F, 0.0F)); PartDefinition cube_r1 = rightwing.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(60, 58).addBox(15.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-12.7747F, 14.9515F, -13.0F, 0.0F, 0.0F, -0.1309F)); PartDefinition leftwing = wings.addOrReplaceChild("leftwing", CubeListBuilder.create(), PartPose.offset(-7.0F, -17.0F, 0.0F)); PartDefinition cube_r2 = leftwing.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(60, 32).addBox(-17.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(12.2192F, 15.1698F, -13.0F, 0.0F, 0.0F, 0.1309F)); PartDefinition feet = emperor_penguin.addOrReplaceChild("feet", CubeListBuilder.create(), PartPose.offset(2.0F, -2.0F, 0.0F)); PartDefinition rightfoot = feet.addOrReplaceChild("rightfoot", CubeListBuilder.create().texOffs(0, 7).addBox(2.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition leftfoot = feet.addOrReplaceChild("leftfoot", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition tail = emperor_penguin.addOrReplaceChild("tail", CubeListBuilder.create(), PartPose.offset(8.25F, -1.75F, 0.75F)); PartDefinition part1 = tail.addOrReplaceChild("part1", CubeListBuilder.create().texOffs(0, 36).addBox(-7.25F, 0.5F, -10.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition part2 = tail.addOrReplaceChild("part2", CubeListBuilder.create(), PartPose.offset(-6.25F, 0.25F, -0.75F)); PartDefinition cube_r3 = part2.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(0.5F, -1.0F, -13.0F, 1.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 1.25F, 2.75F, 0.0349F, 0.0F, 0.0F)); return LayerDefinition.create(meshdefinition, 128, 128); } @Override public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { this.root().getAllParts().forEach(ModelPart::resetPose); this.applyHeadRotation(entity, netHeadYaw, headPitch, ageInTicks); this.animateWalk(EmperorPenguinAnimationDefinitions.WALKING, limbSwing, limbSwingAmount, 2f, 2.5f);
package com.sdevuyst.pingyswaddles.entity.client; public class EmperorPenguinModel<T extends Entity> extends HierarchicalModel<T> { private final ModelPart root; private final ModelPart head; public EmperorPenguinModel(ModelPart root) { this.root = root; this.head = root.getChild("emperor_penguin").getChild("top"); } public static LayerDefinition createBodyLayer() { MeshDefinition meshdefinition = new MeshDefinition(); PartDefinition partdefinition = meshdefinition.getRoot(); PartDefinition emperor_penguin = partdefinition.addOrReplaceChild("emperor_penguin", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 135F, 0.0F)); PartDefinition top = emperor_penguin.addOrReplaceChild("top", CubeListBuilder.create(), PartPose.offsetAndRotation(2.0F, -11.5F, 0.0F, -0.0349F, 0.0F, 0.0F)); PartDefinition head = top.addOrReplaceChild("head", CubeListBuilder.create().texOffs(2, 38).addBox(-7.0F, -18.5009F, -6.9477F, 14.0F, 10.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition beak = top.addOrReplaceChild("beak", CubeListBuilder.create().texOffs(50, 2).addBox(-1.0F, -12.5009F, 6.0523F, 2.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition body = emperor_penguin.addOrReplaceChild("body", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -20.0F, -8.0F, 16.0F, 20.0F, 16.0F, new CubeDeformation(0.0F)), PartPose.offset(2.0F, 0.0F, 0.0F)); PartDefinition wings = emperor_penguin.addOrReplaceChild("wings", CubeListBuilder.create(), PartPose.offset(2.0F, -1.5F, 0.0F)); PartDefinition rightwing = wings.addOrReplaceChild("rightwing", CubeListBuilder.create(), PartPose.offset(7.0F, -17.0F, 0.0F)); PartDefinition cube_r1 = rightwing.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(60, 58).addBox(15.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-12.7747F, 14.9515F, -13.0F, 0.0F, 0.0F, -0.1309F)); PartDefinition leftwing = wings.addOrReplaceChild("leftwing", CubeListBuilder.create(), PartPose.offset(-7.0F, -17.0F, 0.0F)); PartDefinition cube_r2 = leftwing.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(60, 32).addBox(-17.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(12.2192F, 15.1698F, -13.0F, 0.0F, 0.0F, 0.1309F)); PartDefinition feet = emperor_penguin.addOrReplaceChild("feet", CubeListBuilder.create(), PartPose.offset(2.0F, -2.0F, 0.0F)); PartDefinition rightfoot = feet.addOrReplaceChild("rightfoot", CubeListBuilder.create().texOffs(0, 7).addBox(2.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition leftfoot = feet.addOrReplaceChild("leftfoot", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition tail = emperor_penguin.addOrReplaceChild("tail", CubeListBuilder.create(), PartPose.offset(8.25F, -1.75F, 0.75F)); PartDefinition part1 = tail.addOrReplaceChild("part1", CubeListBuilder.create().texOffs(0, 36).addBox(-7.25F, 0.5F, -10.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition part2 = tail.addOrReplaceChild("part2", CubeListBuilder.create(), PartPose.offset(-6.25F, 0.25F, -0.75F)); PartDefinition cube_r3 = part2.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(0.5F, -1.0F, -13.0F, 1.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 1.25F, 2.75F, 0.0349F, 0.0F, 0.0F)); return LayerDefinition.create(meshdefinition, 128, 128); } @Override public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { this.root().getAllParts().forEach(ModelPart::resetPose); this.applyHeadRotation(entity, netHeadYaw, headPitch, ageInTicks); this.animateWalk(EmperorPenguinAnimationDefinitions.WALKING, limbSwing, limbSwingAmount, 2f, 2.5f);
this.animate(((EmperorPenguinEntity) entity).idleAnimationState, EmperorPenguinAnimationDefinitions.WINGING, ageInTicks, 1f);
1
2023-12-31 09:54:03+00:00
8k
IGinX-THU/Parquet
src/main/java/org/apache/parquet/local/ParquetFileReader.java
[ { "identifier": "ColumnChunkPageReader", "path": "src/main/java/org/apache/parquet/local/ColumnChunkPageReadStore.java", "snippet": "static final class ColumnChunkPageReader implements PageReader {\n\n private final BytesInputDecompressor decompressor;\n private final long valueCount;\n private final Queue<DataPage> compressedPages;\n private final DictionaryPage compressedDictionaryPage;\n // null means no page synchronization is required; firstRowIndex will not be returned by the\n // pages\n private final OffsetIndex offsetIndex;\n private final long rowCount;\n private int pageIndex = 0;\n\n private final BlockCipher.Decryptor blockDecryptor;\n private final byte[] dataPageAAD;\n private final byte[] dictionaryPageAAD;\n\n ColumnChunkPageReader(\n BytesInputDecompressor decompressor,\n List<DataPage> compressedPages,\n DictionaryPage compressedDictionaryPage,\n OffsetIndex offsetIndex,\n long rowCount,\n BlockCipher.Decryptor blockDecryptor,\n byte[] fileAAD,\n int rowGroupOrdinal,\n int columnOrdinal) {\n this.decompressor = decompressor;\n this.compressedPages = new ArrayDeque<DataPage>(compressedPages);\n this.compressedDictionaryPage = compressedDictionaryPage;\n long count = 0;\n for (DataPage p : compressedPages) {\n count += p.getValueCount();\n }\n this.valueCount = count;\n this.offsetIndex = offsetIndex;\n this.rowCount = rowCount;\n\n this.blockDecryptor = blockDecryptor;\n\n if (null != blockDecryptor) {\n dataPageAAD =\n AesCipher.createModuleAAD(\n fileAAD, ModuleType.DataPage, rowGroupOrdinal, columnOrdinal, 0);\n dictionaryPageAAD =\n AesCipher.createModuleAAD(\n fileAAD, ModuleType.DictionaryPage, rowGroupOrdinal, columnOrdinal, -1);\n } else {\n dataPageAAD = null;\n dictionaryPageAAD = null;\n }\n }\n\n private int getPageOrdinal(int currentPageIndex) {\n if (null == offsetIndex) {\n return currentPageIndex;\n }\n\n return offsetIndex.getPageOrdinal(currentPageIndex);\n }\n\n @Override\n public long getTotalValueCount() {\n return valueCount;\n }\n\n @Override\n public DataPage readPage() {\n final DataPage compressedPage = compressedPages.poll();\n if (compressedPage == null) {\n return null;\n }\n final int currentPageIndex = pageIndex++;\n\n if (null != blockDecryptor) {\n AesCipher.quickUpdatePageAAD(dataPageAAD, getPageOrdinal(currentPageIndex));\n }\n\n return compressedPage.accept(\n new DataPage.Visitor<DataPage>() {\n @Override\n public DataPage visit(DataPageV1 dataPageV1) {\n try {\n BytesInput bytes = dataPageV1.getBytes();\n if (null != blockDecryptor) {\n bytes = BytesInput.from(blockDecryptor.decrypt(bytes.toByteArray(), dataPageAAD));\n }\n BytesInput decompressed =\n decompressor.decompress(bytes, dataPageV1.getUncompressedSize());\n\n final DataPageV1 decompressedPage;\n if (offsetIndex == null) {\n decompressedPage =\n new DataPageV1(\n decompressed,\n dataPageV1.getValueCount(),\n dataPageV1.getUncompressedSize(),\n dataPageV1.getStatistics(),\n dataPageV1.getRlEncoding(),\n dataPageV1.getDlEncoding(),\n dataPageV1.getValueEncoding());\n } else {\n long firstRowIndex = offsetIndex.getFirstRowIndex(currentPageIndex);\n decompressedPage =\n new DataPageV1(\n decompressed,\n dataPageV1.getValueCount(),\n dataPageV1.getUncompressedSize(),\n firstRowIndex,\n Math.toIntExact(\n offsetIndex.getLastRowIndex(currentPageIndex, rowCount)\n - firstRowIndex\n + 1),\n dataPageV1.getStatistics(),\n dataPageV1.getRlEncoding(),\n dataPageV1.getDlEncoding(),\n dataPageV1.getValueEncoding());\n }\n if (dataPageV1.getCrc().isPresent()) {\n decompressedPage.setCrc(dataPageV1.getCrc().getAsInt());\n }\n return decompressedPage;\n } catch (IOException e) {\n throw new ParquetDecodingException(\"could not decompress page\", e);\n }\n }\n\n @Override\n public DataPage visit(DataPageV2 dataPageV2) {\n if (!dataPageV2.isCompressed() && offsetIndex == null && null == blockDecryptor) {\n return dataPageV2;\n }\n BytesInput pageBytes = dataPageV2.getData();\n\n if (null != blockDecryptor) {\n try {\n pageBytes =\n BytesInput.from(blockDecryptor.decrypt(pageBytes.toByteArray(), dataPageAAD));\n } catch (IOException e) {\n throw new ParquetDecodingException(\n \"could not convert page ByteInput to byte array\", e);\n }\n }\n if (dataPageV2.isCompressed()) {\n int uncompressedSize =\n Math.toIntExact(\n dataPageV2.getUncompressedSize()\n - dataPageV2.getDefinitionLevels().size()\n - dataPageV2.getRepetitionLevels().size());\n try {\n pageBytes = decompressor.decompress(pageBytes, uncompressedSize);\n } catch (IOException e) {\n throw new ParquetDecodingException(\"could not decompress page\", e);\n }\n }\n\n if (offsetIndex == null) {\n return DataPageV2.uncompressed(\n dataPageV2.getRowCount(),\n dataPageV2.getNullCount(),\n dataPageV2.getValueCount(),\n dataPageV2.getRepetitionLevels(),\n dataPageV2.getDefinitionLevels(),\n dataPageV2.getDataEncoding(),\n pageBytes,\n dataPageV2.getStatistics());\n } else {\n return DataPageV2.uncompressed(\n dataPageV2.getRowCount(),\n dataPageV2.getNullCount(),\n dataPageV2.getValueCount(),\n offsetIndex.getFirstRowIndex(currentPageIndex),\n dataPageV2.getRepetitionLevels(),\n dataPageV2.getDefinitionLevels(),\n dataPageV2.getDataEncoding(),\n pageBytes,\n dataPageV2.getStatistics());\n }\n }\n });\n }\n\n @Override\n public DictionaryPage readDictionaryPage() {\n if (compressedDictionaryPage == null) {\n return null;\n }\n try {\n BytesInput bytes = compressedDictionaryPage.getBytes();\n if (null != blockDecryptor) {\n bytes = BytesInput.from(blockDecryptor.decrypt(bytes.toByteArray(), dictionaryPageAAD));\n }\n DictionaryPage decompressedPage =\n new DictionaryPage(\n decompressor.decompress(bytes, compressedDictionaryPage.getUncompressedSize()),\n compressedDictionaryPage.getDictionarySize(),\n compressedDictionaryPage.getEncoding());\n if (compressedDictionaryPage.getCrc().isPresent()) {\n decompressedPage.setCrc(compressedDictionaryPage.getCrc().getAsInt());\n }\n return decompressedPage;\n } catch (IOException e) {\n throw new ParquetDecodingException(\"Could not decompress dictionary page\", e);\n }\n }\n}" }, { "identifier": "OffsetRange", "path": "src/main/java/org/apache/parquet/local/ColumnIndexFilterUtils.java", "snippet": "static class OffsetRange {\n private final long offset;\n private long length;\n\n private OffsetRange(long offset, int length) {\n this.offset = offset;\n this.length = length;\n }\n\n long getOffset() {\n return offset;\n }\n\n long getLength() {\n return length;\n }\n\n private boolean extend(long offset, int length) {\n if (this.offset + this.length == offset) {\n this.length += length;\n return true;\n } else {\n return false;\n }\n }\n}" }, { "identifier": "RowGroupFilter", "path": "src/main/java/org/apache/parquet/local/filter2/compat/RowGroupFilter.java", "snippet": "public class RowGroupFilter implements Visitor<List<BlockMetaData>> {\n private final List<BlockMetaData> blocks;\n private final MessageType schema;\n private final List<FilterLevel> levels;\n private final ParquetFileReader reader;\n\n public enum FilterLevel {\n STATISTICS,\n DICTIONARY,\n BLOOMFILTER\n }\n\n public static List<BlockMetaData> filterRowGroups(\n List<FilterLevel> levels,\n Filter filter,\n List<BlockMetaData> blocks,\n ParquetFileReader reader) {\n Objects.requireNonNull(filter, \"filter cannot be null\");\n return filter.accept(new RowGroupFilter(levels, blocks, reader));\n }\n\n private RowGroupFilter(\n List<FilterLevel> levels, List<BlockMetaData> blocks, ParquetFileReader reader) {\n this.blocks = Objects.requireNonNull(blocks, \"blocks cannnot be null\");\n this.reader = Objects.requireNonNull(reader, \"reader cannnot be null\");\n this.schema = reader.getFileMetaData().getSchema();\n this.levels = levels;\n }\n\n @Override\n public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) {\n FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate();\n\n // check that the schema of the filter matches the schema of the file\n SchemaCompatibilityValidator.validate(filterPredicate, schema);\n\n List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>();\n\n for (BlockMetaData block : blocks) {\n boolean drop = false;\n\n if (levels.contains(FilterLevel.STATISTICS)) {\n drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns());\n }\n\n if (!drop && levels.contains(FilterLevel.DICTIONARY)) {\n drop =\n DictionaryFilter.canDrop(\n filterPredicate, block.getColumns(), reader.getDictionaryReader(block));\n }\n\n if (!drop && levels.contains(FilterLevel.BLOOMFILTER)) {\n drop =\n BloomFilterImpl.canDrop(\n filterPredicate, block.getColumns(), reader.getBloomFilterDataReader(block));\n }\n\n if (!drop) {\n filteredBlocks.add(block);\n }\n }\n\n return filteredBlocks;\n }\n\n @Override\n public List<BlockMetaData> visit(\n FilterCompat.UnboundRecordFilterCompat unboundRecordFilterCompat) {\n return blocks;\n }\n\n @Override\n public List<BlockMetaData> visit(NoOpFilter noOpFilter) {\n return blocks;\n }\n}" }, { "identifier": "calculateOffsetRanges", "path": "src/main/java/org/apache/parquet/local/ColumnIndexFilterUtils.java", "snippet": "static List<OffsetRange> calculateOffsetRanges(\n OffsetIndex offsetIndex, ColumnChunkMetaData cm, long firstPageOffset) {\n List<OffsetRange> ranges = new ArrayList<>();\n int n = offsetIndex.getPageCount();\n if (n > 0) {\n OffsetRange currentRange = null;\n\n // Add a range for the dictionary page if required\n long rowGroupOffset = cm.getStartingPos();\n if (rowGroupOffset < firstPageOffset) {\n currentRange = new OffsetRange(rowGroupOffset, (int) (firstPageOffset - rowGroupOffset));\n ranges.add(currentRange);\n }\n\n for (int i = 0; i < n; ++i) {\n long offset = offsetIndex.getOffset(i);\n int length = offsetIndex.getCompressedPageSize(i);\n if (currentRange == null || !currentRange.extend(offset, length)) {\n currentRange = new OffsetRange(offset, length);\n ranges.add(currentRange);\n }\n }\n }\n return ranges;\n}" }, { "identifier": "filterOffsetIndex", "path": "src/main/java/org/apache/parquet/local/ColumnIndexFilterUtils.java", "snippet": "static OffsetIndex filterOffsetIndex(\n OffsetIndex offsetIndex, RowRanges rowRanges, long totalRowCount) {\n int[] result = new int[offsetIndex.getPageCount()];\n int count = 0;\n for (int i = 0, n = offsetIndex.getPageCount(); i < n; ++i) {\n long from = offsetIndex.getFirstRowIndex(i);\n if (rowRanges.isOverlapping(from, offsetIndex.getLastRowIndex(i, totalRowCount))) {\n result[count++] = i;\n }\n }\n return new FilteredOffsetIndex(offsetIndex, Arrays.copyOfRange(result, 0, count));\n}" }, { "identifier": "EFMAGIC", "path": "src/main/java/org/apache/parquet/local/ParquetFileWriter.java", "snippet": "public static final byte[] EFMAGIC = EF_MAGIC_STR.getBytes(StandardCharsets.US_ASCII);" }, { "identifier": "MAGIC", "path": "src/main/java/org/apache/parquet/local/ParquetFileWriter.java", "snippet": "public static final byte[] MAGIC = MAGIC_STR.getBytes(StandardCharsets.US_ASCII);" } ]
import org.apache.parquet.bytes.ByteBufferInputStream; import org.apache.parquet.bytes.BytesInput; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.column.page.*; import org.apache.parquet.column.values.bloomfilter.BlockSplitBloomFilter; import org.apache.parquet.column.values.bloomfilter.BloomFilter; import org.apache.parquet.compression.CompressionCodecFactory.BytesInputDecompressor; import org.apache.parquet.crypto.*; import org.apache.parquet.crypto.ModuleCipherFactory.ModuleType; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.format.*; import org.apache.parquet.hadoop.ParquetEmptyBlockException; import org.apache.parquet.hadoop.metadata.*; import org.apache.parquet.hadoop.metadata.FileMetaData; import org.apache.parquet.internal.column.columnindex.ColumnIndex; import org.apache.parquet.internal.column.columnindex.OffsetIndex; import org.apache.parquet.internal.filter2.columnindex.ColumnIndexFilter; import org.apache.parquet.internal.filter2.columnindex.ColumnIndexStore; import org.apache.parquet.internal.filter2.columnindex.RowRanges; import org.apache.parquet.internal.hadoop.metadata.IndexReference; import org.apache.parquet.io.InputFile; import org.apache.parquet.io.ParquetDecodingException; import org.apache.parquet.io.SeekableInputStream; import org.apache.parquet.local.ColumnChunkPageReadStore.ColumnChunkPageReader; import org.apache.parquet.local.ColumnIndexFilterUtils.OffsetRange; import org.apache.parquet.local.filter2.compat.RowGroupFilter; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.PrimitiveType; import org.apache.yetus.audience.InterfaceAudience.Private; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.nio.ByteBuffer; import java.util.*; import java.util.Map.Entry; import java.util.zip.CRC32; import static org.apache.parquet.bytes.BytesUtils.readIntLittleEndian; import static org.apache.parquet.format.Util.readFileCryptoMetaData; import static org.apache.parquet.local.ColumnIndexFilterUtils.calculateOffsetRanges; import static org.apache.parquet.local.ColumnIndexFilterUtils.filterOffsetIndex; import static org.apache.parquet.local.ParquetFileWriter.EFMAGIC; import static org.apache.parquet.local.ParquetFileWriter.MAGIC;
5,717
columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetOffsetIndex( Util.readOffsetIndex(f, offsetIndexDecryptor, offsetIndexAAD)); } @Override public void close() throws IOException { try { if (f != null) { f.close(); } } finally { options.getCodecFactory().release(); } } public ParquetMetadata getFooter() { return footer; } /* * Builder to concatenate the buffers of the discontinuous parts for the same column. These parts are generated as a * result of the column-index based filtering when some pages might be skipped at reading. */ private class ChunkListBuilder { private class ChunkData { final List<ByteBuffer> buffers = new ArrayList<>(); OffsetIndex offsetIndex; } private final Map<ChunkDescriptor, ChunkData> map = new HashMap<>(); private ChunkDescriptor lastDescriptor; private final long rowCount; private SeekableInputStream f; public ChunkListBuilder(long rowCount) { this.rowCount = rowCount; } void add(ChunkDescriptor descriptor, List<ByteBuffer> buffers, SeekableInputStream f) { map.computeIfAbsent(descriptor, d -> new ChunkData()).buffers.addAll(buffers); lastDescriptor = descriptor; this.f = f; } void setOffsetIndex(ChunkDescriptor descriptor, OffsetIndex offsetIndex) { map.computeIfAbsent(descriptor, d -> new ChunkData()).offsetIndex = offsetIndex; } List<Chunk> build() { Set<Entry<ChunkDescriptor, ChunkData>> entries = map.entrySet(); List<Chunk> chunks = new ArrayList<>(entries.size()); for (Entry<ChunkDescriptor, ChunkData> entry : entries) { ChunkDescriptor descriptor = entry.getKey(); ChunkData data = entry.getValue(); if (descriptor.equals(lastDescriptor)) { // because of a bug, the last chunk might be larger than descriptor.size chunks.add( new WorkaroundChunk(lastDescriptor, data.buffers, f, data.offsetIndex, rowCount)); } else { chunks.add(new Chunk(descriptor, data.buffers, data.offsetIndex, rowCount)); } } return chunks; } } /** The data for a column chunk */ private class Chunk { protected final ChunkDescriptor descriptor; protected final ByteBufferInputStream stream; final OffsetIndex offsetIndex; final long rowCount; /** * @param descriptor descriptor for the chunk * @param buffers ByteBuffers that contain the chunk * @param offsetIndex the offset index for this column; might be null */ public Chunk( ChunkDescriptor descriptor, List<ByteBuffer> buffers, OffsetIndex offsetIndex, long rowCount) { this.descriptor = descriptor; this.stream = ByteBufferInputStream.wrap(buffers); this.offsetIndex = offsetIndex; this.rowCount = rowCount; } protected PageHeader readPageHeader() throws IOException { return readPageHeader(null, null); } protected PageHeader readPageHeader(BlockCipher.Decryptor blockDecryptor, byte[] pageHeaderAAD) throws IOException { return Util.readPageHeader(stream, blockDecryptor, pageHeaderAAD); } /** * Calculate checksum of input bytes, throw decoding exception if it does not match the provided * reference crc */ private void verifyCrc(int referenceCrc, byte[] bytes, String exceptionMsg) { crc.reset(); crc.update(bytes); if (crc.getValue() != ((long) referenceCrc & 0xffffffffL)) { throw new ParquetDecodingException(exceptionMsg); } } /** * Read all of the pages in a given column chunk. * * @return the list of pages */
/* * 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. */ /* * copied from parquet-mr, updated by An Qi */ package org.apache.parquet.local; /** Internal implementation of the Parquet file reader as a block container */ public class ParquetFileReader implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(ParquetFileReader.class); private final ParquetMetadataConverter converter; private final CRC32 crc; public static ParquetMetadata readFooter( InputFile file, ParquetReadOptions options, SeekableInputStream f) throws IOException { ParquetMetadataConverter converter = new ParquetMetadataConverter(options); return readFooter(file, options, f, converter); } private static ParquetMetadata readFooter( InputFile file, ParquetReadOptions options, SeekableInputStream f, ParquetMetadataConverter converter) throws IOException { long fileLen = file.getLength(); String filePath = file.toString(); LOG.debug("File length {}", fileLen); int FOOTER_LENGTH_SIZE = 4; if (fileLen < MAGIC.length + FOOTER_LENGTH_SIZE + MAGIC.length) { // MAGIC + data + footer + footerIndex + MAGIC throw new RuntimeException( filePath + " is not a Parquet file (length is too low: " + fileLen + ")"); } // Read footer length and magic string - with a single seek byte[] magic = new byte[MAGIC.length]; long fileMetadataLengthIndex = fileLen - magic.length - FOOTER_LENGTH_SIZE; LOG.debug("reading footer index at {}", fileMetadataLengthIndex); f.seek(fileMetadataLengthIndex); int fileMetadataLength = readIntLittleEndian(f); f.readFully(magic); boolean encryptedFooterMode; if (Arrays.equals(MAGIC, magic)) { encryptedFooterMode = false; } else if (Arrays.equals(EFMAGIC, magic)) { encryptedFooterMode = true; } else { throw new RuntimeException( filePath + " is not a Parquet file. Expected magic number at tail, but found " + Arrays.toString(magic)); } long fileMetadataIndex = fileMetadataLengthIndex - fileMetadataLength; LOG.debug("read footer length: {}, footer index: {}", fileMetadataLength, fileMetadataIndex); if (fileMetadataIndex < magic.length || fileMetadataIndex >= fileMetadataLengthIndex) { throw new RuntimeException( "corrupted file: the footer index is not within the file: " + fileMetadataIndex); } f.seek(fileMetadataIndex); FileDecryptionProperties fileDecryptionProperties = options.getDecryptionProperties(); InternalFileDecryptor fileDecryptor = null; if (null != fileDecryptionProperties) { fileDecryptor = new InternalFileDecryptor(fileDecryptionProperties); } // Read all the footer bytes in one time to avoid multiple read operations, // since it can be pretty time consuming for a single read operation in HDFS. ByteBuffer footerBytesBuffer = ByteBuffer.allocate(fileMetadataLength); f.readFully(footerBytesBuffer); LOG.debug("Finished to read all footer bytes."); footerBytesBuffer.flip(); InputStream footerBytesStream = ByteBufferInputStream.wrap(footerBytesBuffer); // Regular file, or encrypted file with plaintext footer if (!encryptedFooterMode) { return converter.readParquetMetadata( footerBytesStream, options.getMetadataFilter(), fileDecryptor, false, fileMetadataLength); } // Encrypted file with encrypted footer if (null == fileDecryptor) { throw new ParquetCryptoRuntimeException( "Trying to read file with encrypted footer. No keys available"); } FileCryptoMetaData fileCryptoMetaData = readFileCryptoMetaData(footerBytesStream); fileDecryptor.setFileCryptoMetaData( fileCryptoMetaData.getEncryption_algorithm(), true, fileCryptoMetaData.getKey_metadata()); // footer length is required only for signed plaintext footers return converter.readParquetMetadata( footerBytesStream, options.getMetadataFilter(), fileDecryptor, true, 0); } protected final SeekableInputStream f; private final InputFile file; private final ParquetReadOptions options; private final Map<ColumnPath, ColumnDescriptor> paths = new HashMap<>(); private final FileMetaData fileMetaData; // may be null private final List<BlockMetaData> blocks; private final List<ColumnIndexStore> blockIndexStores; private final List<RowRanges> blockRowRanges; // not final. in some cases, this may be lazily loaded for backward-compat. private final ParquetMetadata footer; private int currentBlock = 0; private ColumnChunkPageReadStore currentRowGroup = null; private DictionaryPageReader nextDictionaryReader = null; private InternalFileDecryptor fileDecryptor = null; public ParquetFileReader(InputFile file, ParquetMetadata footer, ParquetReadOptions options) throws IOException { this.converter = new ParquetMetadataConverter(options); this.file = file; this.options = options; this.f = file.newStream(); try { this.footer = footer; this.fileMetaData = footer.getFileMetaData(); this.fileDecryptor = fileMetaData.getFileDecryptor(); // must be called before filterRowGroups! if (null != fileDecryptor && fileDecryptor.plaintextFile()) { this.fileDecryptor = null; // Plaintext file. No need in decryptor } this.blocks = filterRowGroups(footer.getBlocks()); this.blockIndexStores = listWithNulls(this.blocks.size()); this.blockRowRanges = listWithNulls(this.blocks.size()); for (ColumnDescriptor col : footer.getFileMetaData().getSchema().getColumns()) { paths.put(ColumnPath.get(col.getPath()), col); } this.crc = options.usePageChecksumVerification() ? new CRC32() : null; } catch (Exception e) { f.close(); throw e; } } private static <T> List<T> listWithNulls(int size) { return new ArrayList<>(Collections.nCopies(size, null)); } public FileMetaData getFileMetaData() { return fileMetaData; } public long getRecordCount() { long total = 0L; for (BlockMetaData block : blocks) { total += block.getRowCount(); } return total; } public long getFilteredRecordCount() { if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return getRecordCount(); } long total = 0L; for (int i = 0, n = blocks.size(); i < n; ++i) { total += getRowRanges(i).rowCount(); } return total; } public String getFile() { return file.toString(); } public List<BlockMetaData> filterRowGroups(List<BlockMetaData> blocks) throws IOException { FilterCompat.Filter recordFilter = options.getRecordFilter(); if (FilterCompat.isFilteringRequired(recordFilter)) { // set up data filters based on configured levels List<RowGroupFilter.FilterLevel> levels = new ArrayList<>(); if (options.useStatsFilter()) { levels.add(RowGroupFilter.FilterLevel.STATISTICS); } if (options.useDictionaryFilter()) { levels.add(RowGroupFilter.FilterLevel.DICTIONARY); } if (options.useBloomFilter()) { levels.add(RowGroupFilter.FilterLevel.BLOOMFILTER); } return RowGroupFilter.filterRowGroups(levels, recordFilter, blocks, this); } return blocks; } public List<BlockMetaData> getRowGroups() { return blocks; } private MessageType requestedSchema = null; public void setRequestedSchema(MessageType projection) { requestedSchema = projection; paths.clear(); for (ColumnDescriptor col : projection.getColumns()) { paths.put(ColumnPath.get(col.getPath()), col); } } public MessageType getRequestedSchema() { if (requestedSchema == null) { return fileMetaData.getSchema(); } return requestedSchema; } /** * Reads all the columns requested from the row group at the specified block. * * @param blockIndex the index of the requested block * @return the PageReadStore which can provide PageReaders for each column. * @throws IOException if an error occurs while reading */ public PageReadStore readRowGroup(int blockIndex) throws IOException { return internalReadRowGroup(blockIndex); } /** * Reads all the columns requested from the row group at the current file position. * * @return the PageReadStore which can provide PageReaders for each column. * @throws IOException if an error occurs while reading */ public PageReadStore readNextRowGroup() throws IOException { ColumnChunkPageReadStore rowGroup = null; try { rowGroup = internalReadRowGroup(currentBlock); } catch (ParquetEmptyBlockException e) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); advanceToNextBlock(); return readNextRowGroup(); } if (rowGroup == null) { return null; } this.currentRowGroup = rowGroup; // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return currentRowGroup; } private ColumnChunkPageReadStore internalReadRowGroup(int blockIndex) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } org.apache.parquet.local.ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(block.getRowCount(), block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan List<ConsecutivePartList> allParts = new ArrayList<ConsecutivePartList>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { long startingPos = mc.getStartingPos(); // first part or not consecutive => new list if (currentParts == null || currentParts.endPos() != startingPos) { currentParts = new ConsecutivePartList(startingPos); allParts.add(currentParts); } currentParts.addChunk( new ChunkDescriptor(columnDescriptor, mc, startingPos, mc.getTotalSize())); } } // actually read all the chunks ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); for (ConsecutivePartList consecutiveChunks : allParts) { consecutiveChunks.readAll(f, builder); } for (Chunk chunk : builder.build()) { readChunkPages(chunk, block, rowGroup); } return rowGroup; } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the column indexes according to the actual filter. As the rows are not aligned among the * pages of the different columns row synchronization might be required. See the documentation of * the class SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading */ public PageReadStore readFilteredRowGroup(int blockIndex) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return internalReadRowGroup(blockIndex); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } RowRanges rowRanges = getRowRanges(blockIndex); return readFilteredRowGroup(blockIndex, rowRanges); } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the {@code rowRanges} passed in. As the rows are not aligned among the pages of the * different columns row synchronization might be required. See the documentation of the class * SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @param rowRanges the row ranges to be read from the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading * @throws IllegalArgumentException if the {@code blockIndex} is invalid or the {@code rowRanges} * is null */ public ColumnChunkPageReadStore readFilteredRowGroup(int blockIndex, RowRanges rowRanges) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { throw new IllegalArgumentException( String.format( "Invalid block index %s, the valid block index range are: " + "[%s, %s]", blockIndex, 0, blocks.size() - 1)); } if (Objects.isNull(rowRanges)) { throw new IllegalArgumentException("RowRanges must not be null"); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0L) { return null; } long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> returning null return null; } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return internalReadRowGroup(blockIndex); } return internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(blockIndex)); } /** * Reads all the columns requested from the row group at the current file position. It may skip * specific pages based on the column indexes according to the actual filter. As the rows are not * aligned among the pages of the different columns row synchronization might be required. See the * documentation of the class SynchronizingColumnReader for details. * * @return the PageReadStore which can provide PageReaders for each column * @throws IOException if an error occurs while reading */ public PageReadStore readNextFilteredRowGroup() throws IOException { if (currentBlock == blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return readNextRowGroup(); } BlockMetaData block = blocks.get(currentBlock); if (block.getRowCount() == 0L) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); // Skip the empty block advanceToNextBlock(); return readNextFilteredRowGroup(); } RowRanges rowRanges = getRowRanges(currentBlock); long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> skipping this row-group advanceToNextBlock(); return readNextFilteredRowGroup(); } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return readNextRowGroup(); } this.currentRowGroup = internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(currentBlock)); // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return this.currentRowGroup; } private ColumnChunkPageReadStore internalReadFilteredRowGroup( BlockMetaData block, RowRanges rowRanges, ColumnIndexStore ciStore) throws IOException { ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(rowRanges, block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); List<ConsecutivePartList> allParts = new ArrayList<>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { OffsetIndex offsetIndex = ciStore.getOffsetIndex(mc.getPath()); OffsetIndex filteredOffsetIndex = filterOffsetIndex(offsetIndex, rowRanges, block.getRowCount()); for (OffsetRange range : calculateOffsetRanges(filteredOffsetIndex, mc, offsetIndex.getOffset(0))) { long startingPos = range.getOffset(); // first part or not consecutive => new list if (currentParts == null || currentParts.endPos() != startingPos) { currentParts = new ConsecutivePartList(startingPos); allParts.add(currentParts); } ChunkDescriptor chunkDescriptor = new ChunkDescriptor(columnDescriptor, mc, startingPos, range.getLength()); currentParts.addChunk(chunkDescriptor); builder.setOffsetIndex(chunkDescriptor, filteredOffsetIndex); } } } // actually read all the chunks for (ConsecutivePartList consecutiveChunks : allParts) { consecutiveChunks.readAll(f, builder); } for (Chunk chunk : builder.build()) { readChunkPages(chunk, block, rowGroup); } return rowGroup; } private void readChunkPages(Chunk chunk, BlockMetaData block, ColumnChunkPageReadStore rowGroup) throws IOException { if (null == fileDecryptor || fileDecryptor.plaintextFile()) { rowGroup.addColumn(chunk.descriptor.col, chunk.readAllPages()); return; } // Encrypted file ColumnPath columnPath = ColumnPath.get(chunk.descriptor.col.getPath()); InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(columnPath); if (!columnDecryptionSetup.isEncrypted()) { // plaintext column rowGroup.addColumn(chunk.descriptor.col, chunk.readAllPages()); } else { // encrypted column rowGroup.addColumn( chunk.descriptor.col, chunk.readAllPages( columnDecryptionSetup.getMetaDataDecryptor(), columnDecryptionSetup.getDataDecryptor(), fileDecryptor.getFileAAD(), block.getOrdinal(), columnDecryptionSetup.getOrdinal())); } } public ColumnIndexStore getColumnIndexStore(int blockIndex) { ColumnIndexStore ciStore = blockIndexStores.get(blockIndex); if (ciStore == null) { ciStore = org.apache.parquet.local.ColumnIndexStoreImpl.create( this, blocks.get(blockIndex), paths.keySet()); blockIndexStores.set(blockIndex, ciStore); } return ciStore; } private RowRanges getRowRanges(int blockIndex) { assert FilterCompat.isFilteringRequired(options.getRecordFilter()) : "Should not be invoked if filter is null or NOOP"; RowRanges rowRanges = blockRowRanges.get(blockIndex); if (rowRanges == null) { rowRanges = ColumnIndexFilter.calculateRowRanges( options.getRecordFilter(), getColumnIndexStore(blockIndex), paths.keySet(), blocks.get(blockIndex).getRowCount()); blockRowRanges.set(blockIndex, rowRanges); } return rowRanges; } public boolean skipNextRowGroup() { return advanceToNextBlock(); } private boolean advanceToNextBlock() { if (currentBlock == blocks.size()) { return false; } // update the current block and instantiate a dictionary reader for it ++currentBlock; this.nextDictionaryReader = null; return true; } /** * Returns a {@link DictionaryPageReadStore} for the row group that would be returned by calling * {@link #readNextRowGroup()} or skipped by calling {@link #skipNextRowGroup()}. * * @return a DictionaryPageReadStore for the next row group */ public DictionaryPageReadStore getNextDictionaryReader() { if (nextDictionaryReader == null) { this.nextDictionaryReader = getDictionaryReader(currentBlock); } return nextDictionaryReader; } public DictionaryPageReader getDictionaryReader(int blockIndex) { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } return new DictionaryPageReader(this, blocks.get(blockIndex)); } public DictionaryPageReader getDictionaryReader(BlockMetaData block) { return new DictionaryPageReader(this, block); } /** * Reads and decompresses a dictionary page for the given column chunk. * * <p>Returns null if the given column chunk has no dictionary page. * * @param meta a column's ColumnChunkMetaData to read the dictionary from * @return an uncompressed DictionaryPage or null * @throws IOException if there is an error while reading the dictionary */ DictionaryPage readDictionary(ColumnChunkMetaData meta) throws IOException { if (!meta.hasDictionaryPage()) { return null; } // TODO: this should use getDictionaryPageOffset() but it isn't reliable. if (f.getPos() != meta.getStartingPos()) { f.seek(meta.getStartingPos()); } boolean encryptedColumn = false; InternalColumnDecryptionSetup columnDecryptionSetup = null; byte[] dictionaryPageAAD = null; BlockCipher.Decryptor pageDecryptor = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { columnDecryptionSetup = fileDecryptor.getColumnSetup(meta.getPath()); if (columnDecryptionSetup.isEncrypted()) { encryptedColumn = true; } } PageHeader pageHeader; if (!encryptedColumn) { pageHeader = Util.readPageHeader(f); } else { byte[] dictionaryPageHeaderAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.DictionaryPageHeader, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); pageHeader = Util.readPageHeader( f, columnDecryptionSetup.getMetaDataDecryptor(), dictionaryPageHeaderAAD); dictionaryPageAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.DictionaryPage, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); pageDecryptor = columnDecryptionSetup.getDataDecryptor(); } if (!pageHeader.isSetDictionary_page_header()) { return null; // TODO: should this complain? } DictionaryPage compressedPage = readCompressedDictionary(pageHeader, f, pageDecryptor, dictionaryPageAAD); BytesInputDecompressor decompressor = options.getCodecFactory().getDecompressor(meta.getCodec()); return new DictionaryPage( decompressor.decompress(compressedPage.getBytes(), compressedPage.getUncompressedSize()), compressedPage.getDictionarySize(), compressedPage.getEncoding()); } private DictionaryPage readCompressedDictionary( PageHeader pageHeader, SeekableInputStream fin, BlockCipher.Decryptor pageDecryptor, byte[] dictionaryPageAAD) throws IOException { DictionaryPageHeader dictHeader = pageHeader.getDictionary_page_header(); int uncompressedPageSize = pageHeader.getUncompressed_page_size(); int compressedPageSize = pageHeader.getCompressed_page_size(); byte[] dictPageBytes = new byte[compressedPageSize]; fin.readFully(dictPageBytes); BytesInput bin = BytesInput.from(dictPageBytes); if (null != pageDecryptor) { bin = BytesInput.from(pageDecryptor.decrypt(bin.toByteArray(), dictionaryPageAAD)); } return new DictionaryPage( bin, uncompressedPageSize, dictHeader.getNum_values(), converter.getEncoding(dictHeader.getEncoding())); } public BloomFilterReader getBloomFilterDataReader(int blockIndex) { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } return new BloomFilterReader(this, blocks.get(blockIndex)); } public BloomFilterReader getBloomFilterDataReader(BlockMetaData block) { return new BloomFilterReader(this, block); } /** * Reads Bloom filter data for the given column chunk. * * @param meta a column's ColumnChunkMetaData to read the dictionary from * @return an BloomFilter object. * @throws IOException if there is an error while reading the Bloom filter. */ public BloomFilter readBloomFilter(ColumnChunkMetaData meta) throws IOException { long bloomFilterOffset = meta.getBloomFilterOffset(); if (bloomFilterOffset < 0) { return null; } // Prepare to decrypt Bloom filter (for encrypted columns) BlockCipher.Decryptor bloomFilterDecryptor = null; byte[] bloomFilterHeaderAAD = null; byte[] bloomFilterBitsetAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(meta.getPath()); if (columnDecryptionSetup.isEncrypted()) { bloomFilterDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); bloomFilterHeaderAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.BloomFilterHeader, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); bloomFilterBitsetAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.BloomFilterBitset, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } // Read Bloom filter data header. f.seek(bloomFilterOffset); BloomFilterHeader bloomFilterHeader; try { bloomFilterHeader = Util.readBloomFilterHeader(f, bloomFilterDecryptor, bloomFilterHeaderAAD); } catch (IOException e) { LOG.warn("read no bloom filter"); return null; } int numBytes = bloomFilterHeader.getNumBytes(); if (numBytes <= 0 || numBytes > BlockSplitBloomFilter.UPPER_BOUND_BYTES) { LOG.warn("the read bloom filter size is wrong, size is {}", bloomFilterHeader.getNumBytes()); return null; } if (!bloomFilterHeader.getHash().isSetXXHASH() || !bloomFilterHeader.getAlgorithm().isSetBLOCK() || !bloomFilterHeader.getCompression().isSetUNCOMPRESSED()) { LOG.warn( "the read bloom filter is not supported yet, algorithm = {}, hash = {}, compression = {}", bloomFilterHeader.getAlgorithm(), bloomFilterHeader.getHash(), bloomFilterHeader.getCompression()); return null; } byte[] bitset; if (null == bloomFilterDecryptor) { bitset = new byte[numBytes]; f.readFully(bitset); } else { bitset = bloomFilterDecryptor.decrypt(f, bloomFilterBitsetAAD); if (bitset.length != numBytes) { throw new ParquetCryptoRuntimeException("Wrong length of decrypted bloom filter bitset"); } } return new BlockSplitBloomFilter(bitset); } /** * @param column the column chunk which the column index is to be returned for * @return the column index for the specified column chunk or {@code null} if there is no index * @throws IOException if any I/O error occurs during reading the file */ @Private public ColumnIndex readColumnIndex(ColumnChunkMetaData column) throws IOException { IndexReference ref = column.getColumnIndexReference(); if (ref == null) { return null; } f.seek(ref.getOffset()); BlockCipher.Decryptor columnIndexDecryptor = null; byte[] columnIndexAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(column.getPath()); if (columnDecryptionSetup.isEncrypted()) { columnIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); columnIndexAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.ColumnIndex, column.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetColumnIndex( column.getPrimitiveType(), Util.readColumnIndex(f, columnIndexDecryptor, columnIndexAAD)); } /** * @param column the column chunk which the offset index is to be returned for * @return the offset index for the specified column chunk or {@code null} if there is no index * @throws IOException if any I/O error occurs during reading the file */ @Private public OffsetIndex readOffsetIndex(ColumnChunkMetaData column) throws IOException { IndexReference ref = column.getOffsetIndexReference(); if (ref == null) { return null; } f.seek(ref.getOffset()); BlockCipher.Decryptor offsetIndexDecryptor = null; byte[] offsetIndexAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(column.getPath()); if (columnDecryptionSetup.isEncrypted()) { offsetIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); offsetIndexAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.OffsetIndex, column.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetOffsetIndex( Util.readOffsetIndex(f, offsetIndexDecryptor, offsetIndexAAD)); } @Override public void close() throws IOException { try { if (f != null) { f.close(); } } finally { options.getCodecFactory().release(); } } public ParquetMetadata getFooter() { return footer; } /* * Builder to concatenate the buffers of the discontinuous parts for the same column. These parts are generated as a * result of the column-index based filtering when some pages might be skipped at reading. */ private class ChunkListBuilder { private class ChunkData { final List<ByteBuffer> buffers = new ArrayList<>(); OffsetIndex offsetIndex; } private final Map<ChunkDescriptor, ChunkData> map = new HashMap<>(); private ChunkDescriptor lastDescriptor; private final long rowCount; private SeekableInputStream f; public ChunkListBuilder(long rowCount) { this.rowCount = rowCount; } void add(ChunkDescriptor descriptor, List<ByteBuffer> buffers, SeekableInputStream f) { map.computeIfAbsent(descriptor, d -> new ChunkData()).buffers.addAll(buffers); lastDescriptor = descriptor; this.f = f; } void setOffsetIndex(ChunkDescriptor descriptor, OffsetIndex offsetIndex) { map.computeIfAbsent(descriptor, d -> new ChunkData()).offsetIndex = offsetIndex; } List<Chunk> build() { Set<Entry<ChunkDescriptor, ChunkData>> entries = map.entrySet(); List<Chunk> chunks = new ArrayList<>(entries.size()); for (Entry<ChunkDescriptor, ChunkData> entry : entries) { ChunkDescriptor descriptor = entry.getKey(); ChunkData data = entry.getValue(); if (descriptor.equals(lastDescriptor)) { // because of a bug, the last chunk might be larger than descriptor.size chunks.add( new WorkaroundChunk(lastDescriptor, data.buffers, f, data.offsetIndex, rowCount)); } else { chunks.add(new Chunk(descriptor, data.buffers, data.offsetIndex, rowCount)); } } return chunks; } } /** The data for a column chunk */ private class Chunk { protected final ChunkDescriptor descriptor; protected final ByteBufferInputStream stream; final OffsetIndex offsetIndex; final long rowCount; /** * @param descriptor descriptor for the chunk * @param buffers ByteBuffers that contain the chunk * @param offsetIndex the offset index for this column; might be null */ public Chunk( ChunkDescriptor descriptor, List<ByteBuffer> buffers, OffsetIndex offsetIndex, long rowCount) { this.descriptor = descriptor; this.stream = ByteBufferInputStream.wrap(buffers); this.offsetIndex = offsetIndex; this.rowCount = rowCount; } protected PageHeader readPageHeader() throws IOException { return readPageHeader(null, null); } protected PageHeader readPageHeader(BlockCipher.Decryptor blockDecryptor, byte[] pageHeaderAAD) throws IOException { return Util.readPageHeader(stream, blockDecryptor, pageHeaderAAD); } /** * Calculate checksum of input bytes, throw decoding exception if it does not match the provided * reference crc */ private void verifyCrc(int referenceCrc, byte[] bytes, String exceptionMsg) { crc.reset(); crc.update(bytes); if (crc.getValue() != ((long) referenceCrc & 0xffffffffL)) { throw new ParquetDecodingException(exceptionMsg); } } /** * Read all of the pages in a given column chunk. * * @return the list of pages */
public ColumnChunkPageReader readAllPages() throws IOException {
0
2023-12-29 01:48:28+00:00
8k
iamamritpalrandhawa/JChess
Engines/InitEngine.java
[ { "identifier": "ChessBoard", "path": "Chess/ChessBoard.java", "snippet": "public class ChessBoard {\r\n private JFrame frame;\r\n DbEngine db = new DbEngine();\r\n private BoardPanel boardPanel;\r\n private ChessEngine gameState;\r\n private static final int SQ_SIZE = 90;\r\n private Pair<Integer, Integer> selectedTile;\r\n private List<Pair<Integer, Integer>> playerClicks;\r\n private boolean GameOver = false, inProgress = true;\r\n private boolean playerone, playertwo;\r\n InfoBoard info;\r\n String whitePlayer, blackPlayer;\r\n\r\n public ChessBoard(boolean p1, boolean p2, InfoBoard info, String whitePlayer, String blackPlayer) {\r\n frame = new JFrame(\"Chess Game\");\r\n frame.setLayout(new BorderLayout());\r\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n frame.setSize(736, 758);\r\n frame.setResizable(false);\r\n gameState = new ChessEngine();\r\n boardPanel = new BoardPanel();\r\n selectedTile = null;\r\n playerClicks = new ArrayList<>();\r\n // boolean playerone = p1, playertwo = p2;\r\n this.playerone = p1;\r\n this.playertwo = p2;\r\n this.info = info;\r\n this.whitePlayer = whitePlayer;\r\n this.blackPlayer = blackPlayer;\r\n frame.add(boardPanel, BorderLayout.CENTER);\r\n frame.setVisible(true);\r\n\r\n frame.addKeyListener(new KeyListener() {\r\n\r\n @Override\r\n public void keyPressed(KeyEvent e) {\r\n if (e.getKeyChar() == 'z') {\r\n gameState.undoMove();\r\n info.UpdateMoves(gameState.moveLog);\r\n boardPanel.repaint();\r\n } else if (e.getKeyChar() == 'r') {\r\n inProgress = false;\r\n info.dispose();\r\n frame.dispose();\r\n new InitEngine();\r\n }\r\n }\r\n\r\n @Override\r\n public void keyTyped(KeyEvent e) {\r\n if (e.getKeyChar() == 'z') {\r\n gameState.undoMove();\r\n info.UpdateMoves(gameState.moveLog);\r\n boardPanel.repaint();\r\n } else if (e.getKeyChar() == 'r') {\r\n new Thread(() -> {\r\n info.dispose();\r\n frame.dispose();\r\n }).start();\r\n new Thread(() -> {\r\n new InitEngine();\r\n }).start();\r\n }\r\n }\r\n\r\n @Override\r\n public void keyReleased(KeyEvent e) {\r\n }\r\n\r\n });\r\n\r\n boardPanel.addMouseListener(new MouseListener() {\r\n\r\n @Override\r\n public void mouseClicked(MouseEvent e) {\r\n handleMouseClick(e);\r\n }\r\n\r\n @Override\r\n public void mousePressed(MouseEvent e) {\r\n }\r\n\r\n @Override\r\n public void mouseReleased(MouseEvent e) {\r\n }\r\n\r\n @Override\r\n public void mouseEntered(MouseEvent e) {\r\n }\r\n\r\n @Override\r\n public void mouseExited(MouseEvent e) {\r\n }\r\n });\r\n startGame();\r\n }\r\n\r\n private void handleMouseClick(MouseEvent e) {\r\n boolean humanTurn = (gameState.whiteToMove && playerone) || (!gameState.whiteToMove && playertwo);\r\n\r\n // Ensure it's the player's turn and the game isn't over\r\n if (!GameOver && humanTurn) {\r\n int x = e.getY() / (758 / 8);\r\n int y = e.getX() / (736 / 8);\r\n\r\n // If no tile is selected, select the current tile\r\n if (selectedTile == null) {\r\n selectedTile = new Pair<>(x, y);\r\n playerClicks.add(selectedTile);\r\n } else {\r\n // If a tile is already selected, make the move\r\n playerClicks.add(new Pair<>(x, y));\r\n Pair<Integer, Integer> startTile = playerClicks.get(0);\r\n Pair<Integer, Integer> endTile = playerClicks.get(1);\r\n Move move = new Move(startTile.getFirst(), startTile.getSecond(), endTile.getFirst(),\r\n endTile.getSecond(), gameState.board, false);\r\n\r\n if (gameState.getValidMoves().contains(move)) {\r\n gameState.makeMove(move, true);\r\n info.UpdateMoves(gameState.moveLog);\r\n\r\n // Print the board state after the move\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.print(gameState.board[i][j] + \" \");\r\n }\r\n System.out.println(); // Move to the next row\r\n }\r\n System.out.println(\"################################################\");\r\n }\r\n\r\n // Reset selected tile and clicks\r\n selectedTile = null;\r\n playerClicks.clear();\r\n }\r\n }\r\n\r\n // Check for game over conditions and repaint the board\r\n decide(info, gameState, whitePlayer, blackPlayer);\r\n boardPanel.repaint();\r\n\r\n // Highlight valid moves after a short delay for better visualization\r\n new Thread(() -> {\r\n try {\r\n Thread.sleep(40);\r\n } catch (InterruptedException ex) {\r\n ex.printStackTrace();\r\n }\r\n boardPanel.highlightSquares(gameState, gameState.getValidMoves(), selectedTile);\r\n }).start();\r\n }\r\n\r\n private void makeAIMove() {\r\n Move aiMove = AiEngine.bestMove(gameState, gameState.getValidMoves());\r\n if (aiMove == null)\r\n aiMove = AiEngine.randomMove(gameState.getValidMoves());\r\n gameState.makeMove(aiMove, true);\r\n info.UpdateMoves(gameState.moveLog);\r\n\r\n // Check for game over conditions and repaint the board after AI's move\r\n decide(info, gameState, whitePlayer, blackPlayer);\r\n boardPanel.repaint();\r\n }\r\n\r\n public void startGame() {\r\n // Start a new thread to continuously check and make AI moves\r\n new Thread(() -> {\r\n while (!GameOver && inProgress) {\r\n decide(info, gameState, whitePlayer, blackPlayer);\r\n boolean humanTurn = (gameState.whiteToMove && playerone) || (!gameState.whiteToMove && playertwo);\r\n if (!GameOver && !humanTurn) {\r\n makeAIMove();\r\n }\r\n try {\r\n // Adjust the delay between AI moves (in milliseconds) as needed\r\n Thread.sleep(1000);\r\n } catch (InterruptedException ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n }).start();\r\n }\r\n\r\n void decide(InfoBoard info, ChessEngine gameState, String whitePlayer, String blackPlayer) {\r\n String s = new String();\r\n for (Move move : gameState.moveLog) {\r\n s += move.getChessNotation() + \",\";\r\n }\r\n if (gameState.checkMate) {\r\n GameOver = true;\r\n String winner = gameState.whiteToMove ? \"Black\" : \"White\";\r\n JOptionPane.showMessageDialog(null, winner + \" Wins\", \"Game Over\",\r\n JOptionPane.INFORMATION_MESSAGE);\r\n db.run(\"INSERT INTO `matches`( `Player1Name`, `Player2Name`, `Result`, `MoveLogs`) VALUES ('\"\r\n + whitePlayer + \"','\" + blackPlayer + \"','\" + winner + \" wins','\" + s + \"')\");\r\n info.dispose();\r\n frame.dispose();\r\n new InitEngine();\r\n } else if (gameState.staleMate) {\r\n GameOver = true;\r\n JOptionPane.showMessageDialog(null, \"Stalemate\", \"Game Over\", JOptionPane.INFORMATION_MESSAGE);\r\n db.run(\"INSERT INTO `matches`( `Player1Name`, `Player2Name`, `Result`, `MoveLogs`) VALUES ('\"\r\n + whitePlayer + \"','\" + blackPlayer + \"','Stalemate','\" + s + \"')\");\r\n info.dispose();\r\n frame.dispose();\r\n new InitEngine();\r\n }\r\n }\r\n\r\n private class BoardPanel extends JPanel {\r\n private static final int TILE_SIZE = 90;\r\n private static final int BOARD_SIZE = 8;\r\n\r\n private HashMap<String, ImageIcon> images;\r\n\r\n private void loadImages() {\r\n images = new HashMap<>();\r\n\r\n String[] pieces = { \"wp\", \"wR\", \"wN\", \"wB\", \"wK\", \"wQ\", \"bp\", \"bR\", \"bN\", \"bB\", \"bK\", \"bQ\" };\r\n\r\n for (String piece : pieces) {\r\n ImageIcon imageIcon = new ImageIcon(\"Resources/Images/\" + piece + \".png\");\r\n Image image = imageIcon.getImage().getScaledInstance(SQ_SIZE, SQ_SIZE, Image.SCALE_SMOOTH);\r\n images.put(piece, new ImageIcon(image));\r\n }\r\n }\r\n\r\n @Override\r\n protected void paintComponent(Graphics g) {\r\n super.paintComponent(g);\r\n Graphics2D g2d = (Graphics2D) g;\r\n loadImages();\r\n for (int row = 0; row < BOARD_SIZE; row++) {\r\n for (int col = 0; col < BOARD_SIZE; col++) {\r\n Color color = (row + col) % 2 == 0 ? new Color(183, 152, 115) : new Color(115, 83, 58);\r\n g.setColor(color);\r\n g.fillRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE);\r\n String piece = gameState.board[row][col];\r\n if (!piece.equals(\"--\")) {\r\n ImageIcon pieceImage = images.get(piece);\r\n pieceImage.paintIcon(this, g, col * TILE_SIZE, row * TILE_SIZE);\r\n }\r\n }\r\n }\r\n\r\n if (selectedTile != null) {\r\n g2d.setColor(Color.BLUE);\r\n Stroke oldStroke = g2d.getStroke();\r\n float borderWidth = 4.0f;\r\n g2d.setStroke(new BasicStroke(borderWidth));\r\n int x = selectedTile.getSecond() * TILE_SIZE;\r\n int y = selectedTile.getFirst() * TILE_SIZE;\r\n g2d.drawRect(x, y, TILE_SIZE, TILE_SIZE);\r\n g2d.setStroke(oldStroke);\r\n }\r\n\r\n }\r\n\r\n private void highlightSquares(ChessEngine gs, List<Move> validMoves,\r\n Pair<Integer, Integer> sqSelected) {\r\n Graphics g = getGraphics();\r\n if (sqSelected != null) {\r\n int r = sqSelected.getFirst();\r\n int c = sqSelected.getSecond();\r\n\r\n if (gs.board[r][c].charAt(0) == (gs.whiteToMove ? 'w' : 'b')) {\r\n\r\n g.setColor(new Color(0, 0, 255, 100));\r\n g.fillRect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE);\r\n\r\n g.setColor(new Color(255, 255, 0, 100));\r\n for (Move move : validMoves) {\r\n if (move.startRow == r && move.startCol == c) {\r\n g.fillRect(move.endCol * SQ_SIZE, move.endRow * SQ_SIZE, SQ_SIZE, SQ_SIZE);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "InfoBoard", "path": "Chess/InfoBoard.java", "snippet": "public class InfoBoard extends JFrame {\r\n static JScrollPane scrollPane1;\r\n static JScrollPane scrollPane2;\r\n\r\n public InfoBoard(String p1, String p2) {\r\n setTitle(\"Chess\");\r\n setSize(400, 700);\r\n setResizable(false);\r\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n setLocationRelativeTo(null); // Center the window\r\n setLocation(1000, 0); // Set the location to the top right corner\r\n\r\n setLayout(new GridLayout(2, 1)); // Use a 1x2 grid layout\r\n setVisible(true);\r\n\r\n JPanel mp1 = new JPanel();\r\n mp1.setLayout(new GridLayout(1, 2)); // 2 rows, 1 column for mp1\r\n\r\n JLabel p1_label = new JLabel(p1, JLabel.CENTER);\r\n p1_label.setHorizontalAlignment(SwingConstants.CENTER);\r\n p1_label.setFont(new Font(\"New Times Roman\", Font.BOLD, 20));\r\n p1_label.setSize(200, 100);\r\n mp1.add(p1_label);\r\n\r\n JLabel p2_label = new JLabel(p2, JLabel.CENTER);\r\n p2_label.setHorizontalAlignment(SwingConstants.CENTER);\r\n p2_label.setFont(new Font(\"New Times Roman\", Font.BOLD, 20));\r\n p2_label.setForeground(Color.WHITE);\r\n p2_label.setBackground(Color.BLACK);\r\n p2_label.setSize(200, 100);\r\n p2_label.setOpaque(true);\r\n\r\n mp1.add(p2_label);\r\n\r\n JPanel mp2 = new JPanel();\r\n mp2.setLayout(new GridLayout(1, 2));\r\n\r\n String[] data = {};\r\n\r\n JList<String> list1 = new JList<String>(data);\r\n scrollPane1 = new JScrollPane(list1);\r\n scrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);\r\n\r\n mp2.add(scrollPane1);\r\n\r\n JList<String> list2 = new JList<String>(data);\r\n scrollPane2 = new JScrollPane(list2);\r\n mp2.add(scrollPane2);\r\n scrollPane1.getVerticalScrollBar().setModel(scrollPane2.getVerticalScrollBar().getModel());\r\n\r\n add(mp1);\r\n add(mp2);\r\n\r\n }\r\n\r\n public void UpdateMoves(List<Move> moves) {\r\n DefaultListModel<String> listModel1 = new DefaultListModel<String>();\r\n DefaultListModel<String> listModel2 = new DefaultListModel<String>();\r\n\r\n for (int i = 0; i < moves.size(); i++) {\r\n Move move = moves.get(i);\r\n String moveString = move.getChessNotation();\r\n\r\n if (i % 2 == 0) {\r\n listModel1.addElement(moveString);\r\n } else {\r\n listModel2.addElement(moveString);\r\n }\r\n }\r\n\r\n JList<String> list1 = new JList<>(listModel1);\r\n JList<String> list2 = new JList<>(listModel2);\r\n\r\n scrollPane1.setViewportView(list1);\r\n scrollPane2.setViewportView(list2);\r\n\r\n // Sync both scrollable lists together with one scrollable\r\n scrollPane1.getVerticalScrollBar().setModel(scrollPane2.getVerticalScrollBar().getModel());\r\n }\r\n}\r" } ]
import Chess.ChessBoard; import Chess.InfoBoard; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane;
4,104
package Engines; public class InitEngine extends JFrame implements ActionListener { JButton startButton; public InitEngine() { setTitle("Start a Chess Game"); ImageIcon logo = new ImageIcon("Resources/Icons/logo-b.png"); setIconImage(logo.getImage()); setSize(600, 400); setResizable(false); getContentPane().setBackground(new Color(27, 27, 27)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); JLabel mainHeading = new JLabel("Chess", JLabel.CENTER); mainHeading.setForeground(Color.WHITE); mainHeading.setFont(new Font("OLD ENGLISH TEXT MT", Font.BOLD, 55)); mainHeading.setBounds(210, 60, 160, 39); add(mainHeading); String[] menuItems = { "Human", "Magnus (AI)" }; JComboBox<String> dropdown_w = new JComboBox<>(menuItems); dropdown_w.setBounds(80, 185, 100, 30); ImageIcon versus = new ImageIcon("Resources/Icons/vs.png"); JLabel versusLabel = new JLabel(versus); versusLabel.setBounds(180, 120, versus.getIconWidth(), versus.getIconHeight()); add(versusLabel); JComboBox<String> dropdown_b = new JComboBox<>(menuItems); dropdown_b.setBounds(410, 185, 100, 30); add(dropdown_w); add(dropdown_b); JLabel whiteLabel = new JLabel("White"); whiteLabel.setForeground(Color.WHITE); whiteLabel.setBounds(110, 225, 100, 30); add(whiteLabel); JLabel blackLabel = new JLabel("Black"); blackLabel.setForeground(Color.WHITE); blackLabel.setBounds(440, 225, 100, 30); add(blackLabel); startButton = new JButton("Start"); startButton.setBounds(245, 295, 100, 30); startButton.setFocusPainted(false); startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); startButton.setFont(new Font("Arial", Font.BOLD, 14)); startButton.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(27, 27, 27), 2), BorderFactory.createEmptyBorder(5, 10, 5, 10))); startButton.setOpaque(true); startButton.setBorderPainted(false); startButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(27, 27, 27)); startButton.setForeground(new Color(255, 255, 255)); } public void mouseExited(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); } }); startButton.addActionListener(this); add(startButton); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { boolean p1 = false, p2 = false; String whitePlayer = (String) ((JComboBox<?>) getContentPane().getComponent(2)).getSelectedItem(); String blackPlayer = (String) ((JComboBox<?>) getContentPane().getComponent(3)).getSelectedItem(); if (whitePlayer.length() == 5 && whitePlayer.substring(0, 5).equals("Human")) { p1 = true; } if (blackPlayer.length() == 5 && blackPlayer.substring(0, 5).equals("Human")) { p2 = true; }
package Engines; public class InitEngine extends JFrame implements ActionListener { JButton startButton; public InitEngine() { setTitle("Start a Chess Game"); ImageIcon logo = new ImageIcon("Resources/Icons/logo-b.png"); setIconImage(logo.getImage()); setSize(600, 400); setResizable(false); getContentPane().setBackground(new Color(27, 27, 27)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); JLabel mainHeading = new JLabel("Chess", JLabel.CENTER); mainHeading.setForeground(Color.WHITE); mainHeading.setFont(new Font("OLD ENGLISH TEXT MT", Font.BOLD, 55)); mainHeading.setBounds(210, 60, 160, 39); add(mainHeading); String[] menuItems = { "Human", "Magnus (AI)" }; JComboBox<String> dropdown_w = new JComboBox<>(menuItems); dropdown_w.setBounds(80, 185, 100, 30); ImageIcon versus = new ImageIcon("Resources/Icons/vs.png"); JLabel versusLabel = new JLabel(versus); versusLabel.setBounds(180, 120, versus.getIconWidth(), versus.getIconHeight()); add(versusLabel); JComboBox<String> dropdown_b = new JComboBox<>(menuItems); dropdown_b.setBounds(410, 185, 100, 30); add(dropdown_w); add(dropdown_b); JLabel whiteLabel = new JLabel("White"); whiteLabel.setForeground(Color.WHITE); whiteLabel.setBounds(110, 225, 100, 30); add(whiteLabel); JLabel blackLabel = new JLabel("Black"); blackLabel.setForeground(Color.WHITE); blackLabel.setBounds(440, 225, 100, 30); add(blackLabel); startButton = new JButton("Start"); startButton.setBounds(245, 295, 100, 30); startButton.setFocusPainted(false); startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); startButton.setFont(new Font("Arial", Font.BOLD, 14)); startButton.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(27, 27, 27), 2), BorderFactory.createEmptyBorder(5, 10, 5, 10))); startButton.setOpaque(true); startButton.setBorderPainted(false); startButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(27, 27, 27)); startButton.setForeground(new Color(255, 255, 255)); } public void mouseExited(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); } }); startButton.addActionListener(this); add(startButton); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { boolean p1 = false, p2 = false; String whitePlayer = (String) ((JComboBox<?>) getContentPane().getComponent(2)).getSelectedItem(); String blackPlayer = (String) ((JComboBox<?>) getContentPane().getComponent(3)).getSelectedItem(); if (whitePlayer.length() == 5 && whitePlayer.substring(0, 5).equals("Human")) { p1 = true; } if (blackPlayer.length() == 5 && blackPlayer.substring(0, 5).equals("Human")) { p2 = true; }
InfoBoard info = null;
1
2023-12-28 13:53:01+00:00
8k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/poolServiceImpl.java
[ { "identifier": "poolToken", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/poolToken.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class poolToken {\n /**\n * pool_token 专属名(文件唯一)\n */\n private String poolName;\n\n /**\n * pool_token 值\n */\n private String poolToken;\n\n /**\n * pool_token 的分享token名数组\n */\n private List<String> shareTokens;\n\n /**\n * pool_token 注册时间\n */\n private String poolTime;\n\n /**\n * token 检查checkPool是否过期\n */\n private boolean checkPool;\n\n /**\n * 是否添加到oneApi里面\n */\n private boolean intoOneApi;\n\n /**\n * 接入oneAPI是否开启gpt4模型\n */\n private boolean pandoraNextGpt4;\n\n /**\n * 接入oneApi自定义PandoraNext地址\n */\n private String oneApi_pandoraUrl;\n\n /**\n * 接入oneApi的组别\n */\n private String groupChecked;\n\n /**\n * 接入oneApi的优先级\n */\n private Integer priority;\n}" }, { "identifier": "systemSetting", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n private Integer timeout;\n /**\n * 部署服务流量走代理\n */\n private String proxy_url;\n /**\n * GPT中创建的对话分享\n */\n private Boolean public_share;\n /**\n * 访问网站密码\n */\n private String site_password;\n /**\n * 重载服务密码\n */\n private String setup_password;\n /**\n * 白名单(null则不限制,为空数组[]则限制所有账号)\n */\n private String whitelist;\n\n /**\n * pandoraNext验证license_id\n */\n private String license_id;\n\n /**\n * tokensTool登录Username\n */\n private String loginUsername;\n\n /**\n * tokensTool密码Password\n */\n private String loginPassword;\n\n /**\n * tokensTool 验证信息\n */\n private validation validation;\n\n /**\n * tokensTool 更新token网址\n * 为\"default\"则调用本机的,不为“default\"则自定义\n */\n private String autoToken_url;\n\n /**\n * 是否开启拿tokensTool的后台token\n */\n private Boolean isGetToken;\n /**\n * tokensTool 拿到getTokenPassword\n * 为\"getTokenPassword\" 默认:123456\n * 默认拿getTokenPassword\n */\n private String getTokenPassword;\n\n /**\n * tokensTool 更新containerName(容器名)\n * 通过容器名实现开启,关闭,重新启动容器\n */\n private String containerName;\n\n\n /**\n * PandoraNext tls证书\n */\n private tls tls;\n\n /**\n * PandoraNext config.json位置\n */\n private String configPosition;\n\n /**\n * PandoraNext 接口地址添加前缀\n */\n private String isolated_conv_title;\n\n /**\n * PandoraNext 会话标题\n */\n private String proxy_api_prefix;\n\n /**\n * 禁用注册账号功能,true或false\n */\n private Boolean disable_signup;\n\n /**\n * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码,使用消耗为4+10。\n */\n private Boolean auto_conv_arkose;\n\n /**\n * 在proxy模式是否使用PandoraNext的文件代理服务,避免官方文件服务的墙。\n */\n private Boolean proxy_file_service;\n\n /**\n * 配置自定义的DoH主机名,建议使用IP形式。默认在+8区使用223.6.6.6,其余地区使用1.1.1.1。\n */\n private String custom_doh_host;\n\n /**\n * 自动刷新session的开关\n */\n private Boolean auto_updateSession;\n\n /**\n * 自动刷新session的时间 (天为单位)\n */\n private Integer auto_updateTime;\n\n /**\n * 自动刷新session的个数 (个)\n */\n private Integer auto_updateNumber;\n\n /**\n * PadoraNext的公网访问地址\n */\n private String pandoraNext_outUrl;\n\n /**\n * oneAPi的公网访问地址\n */\n private String oneAPi_outUrl;\n\n /**\n * oneApi访问令牌\n */\n private String oneAPi_intoToken;\n}" }, { "identifier": "token", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/token.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class token {\n\n /**\n * token 名称\n */\n private String name;\n\n /**\n * token 值\n */\n private String token;\n\n /**\n * token openai账号用户名\n */\n private String username;\n\n /**\n * token openai账号用户密码\n */\n private String userPassword;\n\n /**\n * token 是否分享\n */\n private boolean shared;\n\n /**\n * token 是否分享聊天信息\n */\n private boolean show_user_info;\n\n /**\n * token 是否显示金光\n */\n private boolean plus;\n\n /**\n * token 是否合成pool_token\n */\n private boolean setPoolToken;\n\n /**\n * token 进去token的密码\n */\n private String password;\n\n /**\n * token share_token的值\n */\n private String share_token;\n\n /**\n * token access_token的值\n */\n private String access_token;\n\n /**\n * token session_token或者refresh_token获取的时间\n */\n private String updateTime;\n\n /**\n * token 是否使用refresh_token\n */\n private boolean useRefreshToken;\n\n /**\n * token 检查session是否过期\n */\n private boolean checkSession;\n}" }, { "identifier": "poolService", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/service/poolService.java", "snippet": "public interface poolService {\n\n String addPoolToken(poolToken poolToken);\n\n String deletePoolToken(poolToken poolToken);\n\n String refreshSimplyToken(poolToken poolToken);\n\n String changePoolToken(poolToken poolToken);\n\n List<poolToken> selectPoolToken(String name);\n\n String refreshAllTokens();\n\n String verifySimplyPoolToken(poolToken poolToken);\n\n String verifyAllPoolToken();\n\n String toRequirePoolToken(poolToken poolToken);\n}" } ]
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.tokensTool.pandoraNext.pojo.poolToken; import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.poolService; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.regex.Pattern;
4,845
boolean b = addKey(poolToken, strings); if (b && poolToken.getPriority() != 0) { boolean b1 = getPriority(poolToken, strings); if (b1) { log.info("修改优先级成功!"); } } if (b) { log.info("pool_token进one-Api成功!"); } else { return "pool_token添加进one-api失败!"; } } String parent = selectFile(); File jsonFile = new File(parent); Path jsonFilePath = Paths.get(parent); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode rootNode; // 如果 JSON 文件不存在,创建一个新的 JSON 对象 if (!jsonFile.exists()) { // 创建文件 Files.createFile(jsonFilePath); System.out.println("pool.json创建完成: " + jsonFilePath); rootNode = objectMapper.createObjectNode(); } else { if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) { rootNode = objectMapper.readTree(jsonFile).deepCopy(); } else { rootNode = objectMapper.createObjectNode(); } } // 创建要添加的新数据 ObjectNode newData = objectMapper.createObjectNode(); newData.put("poolToken", resPoolToken); List<String> shareTokensList = poolToken.getShareTokens(); ArrayNode arrayNode = objectMapper.createArrayNode(); for (String value : shareTokensList) { arrayNode.add(value); } newData.set("shareTokens", arrayNode); //0.5.0 newData.put("checkPool", true); newData.put("intoOneApi", poolToken.isIntoOneApi()); newData.put("pandoraNextGpt4", poolToken.isPandoraNextGpt4()); newData.put("oneApi_pandoraUrl", poolToken.getOneApi_pandoraUrl()); LocalDateTime now = LocalDateTime.now(); newData.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 将新数据添加到 JSON 树中 rootNode.put(poolToken.getPoolName(), newData); // 将修改后的数据写回到文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode); log.info("数据成功添加到 JSON 文件中。"); return "pool_token数据添加成功"; } catch (IOException e) { e.printStackTrace(); return "添加失败!"; } } /** * 删除通过poolToken里的poolName删除poolToken * * @param poolToken * @return */ public String deletePoolToken(poolToken poolToken) { try { String name = poolToken.getPoolName(); String parent = selectFile(); String deletePoolToken = poolToken.getPoolToken(); //确保注销成功! if (deletePoolToken != null && deletePoolToken.contains("pk")) { String s = apiService.deletePoolToken(deletePoolToken); if (s == null) { log.info("删除失败,看看自己的poolToken是否合法"); } } if (poolToken.isIntoOneApi()) { String[] strings = systemService.selectOneAPi(); boolean b = deleteKeyId(poolToken, strings); if (!b) { return "删除oneApi中的poolToken失败!"; } } ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 检查要删除的节点是否存在 JsonNode nodeToRemove = rootNode.get(name); if (nodeToRemove != null) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 删除节点 newObjectNode.remove(name); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); log.info("删除成功"); return "删除成功!"; } else { System.out.println("Node not found: " + name); return "节点未找到!"; } } catch (IOException e) { e.printStackTrace(); } return "删除失败"; } /** * 从poolToken里拿到share_tokens的集合,传参给share_token * * @param shareName * @return */ public String getShareTokens(List<String> shareName) { try { StringBuffer resToken = new StringBuffer();
package com.tokensTool.pandoraNext.service.impl; /** * @author Yangyang * @create 2023-12-10 11:59 */ @Service @Slf4j public class poolServiceImpl implements poolService { private static final String gpt3Models = "gpt-3.5-turbo"; private static final String gpt4Models = "gpt-3.5-turbo,gpt-4"; private static final String openAiChat = "/v1/chat/completions"; private static final String oneApiSelect = "api/channel/?p=0"; private static final String oneAPiChannel = "api/channel/"; private final String deploy = "default"; @Value("${deployPosition}") private String deployPosition; @Autowired private apiServiceImpl apiService; @Autowired private systemServiceImpl systemService; /** * 遍历文件 * * @return */ public String selectFile() { String projectRoot; if (deploy.equals(deployPosition)) { projectRoot = System.getProperty("user.dir"); } else { projectRoot = deployPosition; } String parent = projectRoot + File.separator + "pool.json"; File jsonFile = new File(parent); Path jsonFilePath = Paths.get(parent); // 如果 JSON 文件不存在,创建一个新的 JSON 对象 if (!jsonFile.exists()) { try { // 创建文件pool.json Files.createFile(jsonFilePath); // 往 pool.json 文件中添加一个空数组,防止重启报错 Files.writeString(jsonFilePath, "{}"); log.info("新建pool.json,并初始化pool.json成功!"); } catch (IOException e) { throw new RuntimeException(e); } } return parent; } /** * 初始化pool.json * 添加checkPool变量,初始化为true * 启动的时候自动全部添加 */ public String initializeCheckPool() { try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 遍历根节点的所有子节点 if (rootNode.isObject()) { ObjectNode rootObjectNode = (ObjectNode) rootNode; // 遍历所有子节点 Iterator<Map.Entry<String, JsonNode>> fields = rootObjectNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); // 获取子节点的名称 String nodeName = entry.getKey(); // 获取子节点 JsonNode nodeToModify = entry.getValue(); if (nodeToModify != null && nodeToModify.isObject()) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll(rootObjectNode); // 获取要修改的节点 ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName); // 初始化checkSession的值为true if (!nodeToModifyInNew.has("checkPool")) { nodeToModifyInNew.put("checkPool", true); log.info("为节点 " + nodeName + " 添加 checkPool 变量成功!"); } // 初始化intoOneApi的值为false if (!nodeToModifyInNew.has("intoOneApi")) { nodeToModifyInNew.put("intoOneApi", false); log.info("为节点 " + nodeName + " 添加 intoOneApi 变量成功!"); } // 初始化pandoraNextGpt4的值为false if (!nodeToModifyInNew.has("pandoraNextGpt4")) { nodeToModifyInNew.put("pandoraNextGpt4", false); log.info("为节点 " + nodeName + " 添加 pandoraNextGpt4 变量成功!"); } // 初始化oneApi_pandoraUrl的值为"" if (!nodeToModifyInNew.has("oneApi_pandoraUrl")) { nodeToModifyInNew.put("oneApi_pandoraUrl", ""); log.info("为节点 " + nodeName + " 添加 oneApi_pandoraUrl 变量成功!"); } // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); } } return "为所有子节点添加 checkPool 变量成功!"; } } catch (IOException e) { e.printStackTrace(); } return "为所有子节点添加 checkPool 变量失败!"; } /** * 通过name遍历poolToken * * @param name * @return */ public List<poolToken> selectPoolToken(String name) { List<poolToken> res = new ArrayList<>(); try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 遍历所有字段 Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String nodeName = entry.getKey(); if (nodeName.contains(name)) { poolToken temRes = new poolToken(); temRes.setPoolName(nodeName); // 获取对应的节点 JsonNode temNode = rootNode.get(nodeName); temRes.setPoolToken(temNode.has("poolToken") ? temNode.get("poolToken").asText() : ""); temRes.setPoolTime(temNode.has("poolTime") ? temNode.get("poolTime").asText() : ""); // 将 JsonNode 转换为 List<String> List<String> sharedTokens = new ArrayList<>(); if (temNode.has("shareTokens") && temNode.get("shareTokens").isArray()) { for (JsonNode tokenNode : temNode.get("shareTokens")) { sharedTokens.add(tokenNode.asText()); } } temRes.setShareTokens(sharedTokens); temRes.setCheckPool(!temNode.has("checkPool") || temNode.get("checkPool").asBoolean()); //0.5.0 temRes.setIntoOneApi(temNode.has("intoOneApi") && temNode.get("intoOneApi").asBoolean()); temRes.setPandoraNextGpt4(temNode.has("pandoraNextGpt4") && temNode.get("pandoraNextGpt4").asBoolean()); temRes.setOneApi_pandoraUrl(temNode.has("oneApi_pandoraUrl") ? temNode.get("oneApi_pandoraUrl").asText() : ""); temRes.setPriority(temNode.has("priority") ? temNode.get("priority").asInt() : 0); res.add(temRes); } } } catch (Exception e) { e.printStackTrace(); return null; } return res; } /** * 仅支持修改poolToken的时间和值 * 修改poolToken的时间 * 修改poolToken的值 * * @param poolToken * @return 修改成功!or 节点未找到或不是对象! * @throws Exception */ public String requirePoolToken(poolToken poolToken) { try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 要修改的节点名称 String nodeNameToModify = poolToken.getPoolName(); // 获取要修改的节点 JsonNode nodeToModify = rootNode.get(nodeNameToModify); if (nodeToModify != null && nodeToModify.isObject()) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 获取要修改的节点 ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify); //仅支持修改poolToken的时间和值 LocalDateTime now = LocalDateTime.now(); nodeToModifyInNew.put("checkPool", poolToken.isCheckPool()); nodeToModifyInNew.put("poolToken", poolToken.getPoolToken()); nodeToModifyInNew.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); log.info("修改成功!"); return "修改成功!"; } else { log.info("节点未找到或不是对象,请检查pool.json! " + nodeNameToModify); return "节点未找到或不是对象!"; } } catch (Exception e) { throw new RuntimeException(e); } } public String requireCheckPoolToken(poolToken poolToken) { try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 要修改的节点名称 String nodeNameToModify = poolToken.getPoolName(); // 获取要修改的节点 JsonNode nodeToModify = rootNode.get(nodeNameToModify); if (nodeToModify != null && nodeToModify.isObject()) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 获取要修改的节点 ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify); //仅支持修改poolToken的时间和值 LocalDateTime now = LocalDateTime.now(); nodeToModifyInNew.put("checkPool", poolToken.isCheckPool()); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); return "修改成功!"; } else { log.info("节点未找到或不是对象,请检查pool.json! " + nodeNameToModify); return "节点未找到或不是对象!"; } } catch (Exception e) { throw new RuntimeException(e); } } /** * 通过poolToken添加PoolToken * * @param poolToken * @return */ public String addPoolToken(poolToken poolToken) { String resPoolToken; try { String shareTokens = getShareTokens(poolToken.getShareTokens()); String temPoolToken = poolToken.getPoolToken(); if (temPoolToken != null && temPoolToken.contains("pk")) { resPoolToken = apiService.getPoolToken(temPoolToken, shareTokens); } else { resPoolToken = apiService.getPoolToken("", shareTokens); } } catch (Exception ex) { throw new RuntimeException(ex); } try { if (resPoolToken == null) { return "pool_token数据添加失败,请先按全部选择并生成,并确保url配对正确!"; } poolToken.setPoolToken(resPoolToken); if (poolToken.isIntoOneApi()) { String[] strings = systemService.selectOneAPi(); boolean b = addKey(poolToken, strings); if (b && poolToken.getPriority() != 0) { boolean b1 = getPriority(poolToken, strings); if (b1) { log.info("修改优先级成功!"); } } if (b) { log.info("pool_token进one-Api成功!"); } else { return "pool_token添加进one-api失败!"; } } String parent = selectFile(); File jsonFile = new File(parent); Path jsonFilePath = Paths.get(parent); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode rootNode; // 如果 JSON 文件不存在,创建一个新的 JSON 对象 if (!jsonFile.exists()) { // 创建文件 Files.createFile(jsonFilePath); System.out.println("pool.json创建完成: " + jsonFilePath); rootNode = objectMapper.createObjectNode(); } else { if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) { rootNode = objectMapper.readTree(jsonFile).deepCopy(); } else { rootNode = objectMapper.createObjectNode(); } } // 创建要添加的新数据 ObjectNode newData = objectMapper.createObjectNode(); newData.put("poolToken", resPoolToken); List<String> shareTokensList = poolToken.getShareTokens(); ArrayNode arrayNode = objectMapper.createArrayNode(); for (String value : shareTokensList) { arrayNode.add(value); } newData.set("shareTokens", arrayNode); //0.5.0 newData.put("checkPool", true); newData.put("intoOneApi", poolToken.isIntoOneApi()); newData.put("pandoraNextGpt4", poolToken.isPandoraNextGpt4()); newData.put("oneApi_pandoraUrl", poolToken.getOneApi_pandoraUrl()); LocalDateTime now = LocalDateTime.now(); newData.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 将新数据添加到 JSON 树中 rootNode.put(poolToken.getPoolName(), newData); // 将修改后的数据写回到文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode); log.info("数据成功添加到 JSON 文件中。"); return "pool_token数据添加成功"; } catch (IOException e) { e.printStackTrace(); return "添加失败!"; } } /** * 删除通过poolToken里的poolName删除poolToken * * @param poolToken * @return */ public String deletePoolToken(poolToken poolToken) { try { String name = poolToken.getPoolName(); String parent = selectFile(); String deletePoolToken = poolToken.getPoolToken(); //确保注销成功! if (deletePoolToken != null && deletePoolToken.contains("pk")) { String s = apiService.deletePoolToken(deletePoolToken); if (s == null) { log.info("删除失败,看看自己的poolToken是否合法"); } } if (poolToken.isIntoOneApi()) { String[] strings = systemService.selectOneAPi(); boolean b = deleteKeyId(poolToken, strings); if (!b) { return "删除oneApi中的poolToken失败!"; } } ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 检查要删除的节点是否存在 JsonNode nodeToRemove = rootNode.get(name); if (nodeToRemove != null) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 删除节点 newObjectNode.remove(name); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); log.info("删除成功"); return "删除成功!"; } else { System.out.println("Node not found: " + name); return "节点未找到!"; } } catch (IOException e) { e.printStackTrace(); } return "删除失败"; } /** * 从poolToken里拿到share_tokens的集合,传参给share_token * * @param shareName * @return */ public String getShareTokens(List<String> shareName) { try { StringBuffer resToken = new StringBuffer();
List<token> tokens = apiService.selectToken("");
2
2023-11-17 11:37:37+00:00
8k
bryan31/Akali
src/main/java/org/dromara/akali/proxy/AkaliByteBuddyProxy.java
[ { "identifier": "AkaliStrategyEnum", "path": "src/main/java/org/dromara/akali/enums/AkaliStrategyEnum.java", "snippet": "public enum AkaliStrategyEnum {\n\n FALLBACK, HOT_METHOD\n}" }, { "identifier": "AkaliMethodManager", "path": "src/main/java/org/dromara/akali/manager/AkaliMethodManager.java", "snippet": "public class AkaliMethodManager {\n\n private static final Logger log = LoggerFactory.getLogger(AkaliMethodManager.class);\n\n private static final Map<String, Tuple2<AkaliStrategyEnum, Annotation>> akaliMethodMap = new HashMap<>();\n\n public static void addMethodStr(String methodStr, Tuple2<AkaliStrategyEnum, Annotation> tuple){\n log.info(\"[AKALI] Register akali method:[{}][{}]\", tuple.r1.name(), methodStr);\n akaliMethodMap.put(methodStr, tuple);\n }\n\n public static Tuple2<AkaliStrategyEnum, Annotation> getAnnoInfo(String methodStr){\n return akaliMethodMap.get(methodStr);\n }\n\n public static boolean contain(String methodStr){\n return akaliMethodMap.containsKey(methodStr);\n }\n}" }, { "identifier": "AkaliRuleManager", "path": "src/main/java/org/dromara/akali/manager/AkaliRuleManager.java", "snippet": "public class AkaliRuleManager {\n private static final Logger log = LoggerFactory.getLogger(AkaliRuleManager.class);\n\n public static void registerFallbackRule(AkaliFallback akaliFallback, Method method){\n String resourceKey = MethodUtil.resolveMethodName(method);\n\n if (!FlowRuleManager.hasConfig(resourceKey)){\n FlowRule rule = new FlowRule();\n\n rule.setResource(resourceKey);\n rule.setGrade(akaliFallback.grade().getGrade());\n rule.setCount(akaliFallback.count());\n rule.setLimitApp(\"default\");\n\n FlowRuleManager.loadRules(ListUtil.toList(rule));\n log.info(\"[AKALI] Add Fallback Rule [{}]\", resourceKey);\n }\n }\n\n public static void registerHotRule(AkaliHot akaliHot, Method method){\n String resourceKey = MethodUtil.resolveMethodName(method);\n\n if (!ParamFlowRuleManager.hasRules(resourceKey)){\n ParamFlowRule rule = new ParamFlowRule();\n\n rule.setResource(MethodUtil.resolveMethodName(method));\n rule.setGrade(akaliHot.grade().getGrade());\n rule.setCount(akaliHot.count());\n rule.setDurationInSec(akaliHot.duration());\n rule.setParamIdx(0);\n\n ParamFlowRuleManager.loadRules(ListUtil.toList(rule));\n log.info(\"[AKALI] Add Hot Rule [{}]\", rule.getResource());\n }\n }\n}" }, { "identifier": "SphEngine", "path": "src/main/java/org/dromara/akali/sph/SphEngine.java", "snippet": "public class SphEngine {\n\n private static final Logger log = LoggerFactory.getLogger(SphEngine.class);\n\n public static Object process(Object bean, Method method, Object[] args, String methodStr, AkaliStrategyEnum akaliStrategyEnum) throws Throwable{\n switch (akaliStrategyEnum){\n case FALLBACK:\n if (SphO.entry(methodStr)){\n try{\n return method.invoke(bean, args);\n }finally {\n SphO.exit();\n }\n }else{\n log.info(\"[AKALI]Trigger fallback strategy for [{}]\", methodStr);\n return AkaliStrategyManager.getStrategy(akaliStrategyEnum).process(bean, method, args);\n }\n case HOT_METHOD:\n String convertParam = DigestUtil.md5Hex(JSON.toJSONString(args));\n Entry entry = null;\n try{\n entry = SphU.entry(methodStr, EntryType.IN, 1, convertParam);\n return method.invoke(bean, args);\n }catch (BlockException e){\n log.info(\"[AKALI]Trigger hotspot strategy for [{}]\", methodStr);\n return AkaliStrategyManager.getStrategy(akaliStrategyEnum).process(bean, method, args);\n }finally {\n if (entry != null){\n entry.exit(1, convertParam);\n }\n }\n default:\n throw new Exception(\"[AKALI] Strategy error!\");\n }\n }\n}" }, { "identifier": "SerialsUtil", "path": "src/main/java/org/dromara/akali/util/SerialsUtil.java", "snippet": "public class SerialsUtil {\n\n\tpublic static int serialInt = 1;\n\n\tprivate static final DecimalFormat format8 = new DecimalFormat(\"00000000\");\n\n\tprivate static final DecimalFormat format12 = new DecimalFormat(\"000000000000\");\n\n\tprivate static final BigInteger divisor;\n\n\tprivate static final BigInteger divisor12;\n\n\tstatic {\n\t\tdivisor = BigInteger.valueOf(19999999L).multiply(BigInteger.valueOf(5));\n\t\tdivisor12 = BigInteger.valueOf(190000000097L).multiply(BigInteger.valueOf(5));\n\t}\n\n\tpublic static String genSerialNo() {\n\t\tSimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmss\");\n\t\tString strNow = sdf.format(new Date());\n\n\t\t// 生成3位随机数\n\t\tRandom random = new Random();\n\t\tint intRandom = random.nextInt(999);\n\n\t\tString strRandom = String.valueOf(intRandom);\n\t\tint len = strRandom.length();\n\t\tfor (int i = 0; i < (3 - len); i++) {\n\t\t\tstrRandom = \"0\" + strRandom;\n\t\t}\n\t\tString serialStr = SerialsUtil.nextSerial();\n\t\treturn (strNow + strRandom + serialStr);\n\t}\n\n\tpublic static synchronized String nextSerial() {\n\t\tint serial = serialInt++;\n\t\tif (serial > 999) {\n\t\t\tserialInt = 1;\n\t\t\tserial = 1;\n\t\t}\n\t\tString serialStr = serial + \"\";\n\t\tint len = serialStr.length();\n\t\tfor (int i = 0; i < (3 - len); i++) {\n\t\t\tserialStr = \"0\" + serialStr;\n\t\t}\n\n\t\treturn serialStr;\n\t}\n\n\t/**\n\t * 生成一个12位随机数\n\t * @param seed 种子值\n\t * @return String 随机数\n\t */\n\tpublic static String randomNum12(long seed) {\n\t\t// 被除数\n\t\tBigInteger dividend = BigDecimal.valueOf(seed).pow(5).toBigInteger();\n\t\treturn format12.format(dividend.remainder(divisor12));\n\t}\n\n\t/**\n\t * 生成一个8位随机数\n\t * @param seed 种子值\n\t * @return String 随机数\n\t */\n\tpublic static String randomNum8(long seed) {\n\t\t// 被除数\n\t\tBigInteger dividend = BigDecimal.valueOf(seed).pow(5).toBigInteger();\n\t\treturn format8.format(dividend.remainder(divisor));\n\t}\n\n\t/*\n\t * 10进制转32进制(去除0,O,1,I)\n\t */\n\tpublic static String from10To32(String numStr, int size) {\n\t\tlong to = 32;\n\t\tlong num = Long.parseLong(numStr);\n\t\tString jg = \"\";\n\t\twhile (num != 0) {\n\t\t\tswitch (new Long(num % to).intValue()) {\n\t\t\t\tcase 0:\n\t\t\t\t\tjg = \"B\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tjg = \"R\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tjg = \"6\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tjg = \"U\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tjg = \"M\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tjg = \"E\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\t\tjg = \"H\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tjg = \"C\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tjg = \"G\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tjg = \"Q\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tjg = \"A\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\t\tjg = \"8\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\tjg = \"3\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 13:\n\t\t\t\t\tjg = \"S\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 14:\n\t\t\t\t\tjg = \"J\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tjg = \"Y\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\t\tjg = \"7\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 17:\n\t\t\t\t\tjg = \"5\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 18:\n\t\t\t\t\tjg = \"W\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 19:\n\t\t\t\t\tjg = \"9\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tjg = \"F\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tjg = \"T\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 22:\n\t\t\t\t\tjg = \"D\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tjg = \"2\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 24:\n\t\t\t\t\tjg = \"P\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tjg = \"Z\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\t\tjg = \"N\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 27:\n\t\t\t\t\tjg = \"K\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 28:\n\t\t\t\t\tjg = \"V\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 29:\n\t\t\t\t\tjg = \"X\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tjg = \"L\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tjg = \"4\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tjg = String.valueOf(num % to) + jg;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnum = num / to;\n\t\t}\n\t\tif (jg.length() < size) {\n\t\t\tint loop = size - jg.length();\n\t\t\tfor (int i = 0; i < loop; i++) {\n\t\t\t\tjg = \"2\" + jg;\n\t\t\t}\n\t\t}\n\t\treturn jg;\n\t}\n\n\t/*\n\t * 10进制转32进制(去除0,O,1,I)\n\t */\n\tpublic static String from10To24(String numStr, int size) {\n\t\tlong to = 24;\n\t\tlong num = Long.parseLong(numStr);\n\t\tString jg = \"\";\n\t\twhile (num != 0) {\n\t\t\tswitch (new Long(num % to).intValue()) {\n\t\t\t\tcase 0:\n\t\t\t\t\tjg = \"B\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tjg = \"R\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tjg = \"U\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tjg = \"M\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tjg = \"E\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tjg = \"H\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\t\tjg = \"C\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tjg = \"G\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tjg = \"Q\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tjg = \"A\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tjg = \"S\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\t\tjg = \"J\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\tjg = \"Y\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 13:\n\t\t\t\t\tjg = \"W\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 14:\n\t\t\t\t\tjg = \"F\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tjg = \"T\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\t\tjg = \"D\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 17:\n\t\t\t\t\tjg = \"P\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 18:\n\t\t\t\t\tjg = \"Z\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 19:\n\t\t\t\t\tjg = \"N\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tjg = \"K\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tjg = \"V\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 22:\n\t\t\t\t\tjg = \"X\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tjg = \"L\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tjg = String.valueOf(num % to) + jg;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnum = num / to;\n\t\t}\n\t\tif (jg.length() < size) {\n\t\t\tint loop = size - jg.length();\n\t\t\tfor (int i = 0; i < loop; i++) {\n\t\t\t\tjg = \"B\" + jg;\n\t\t\t}\n\t\t}\n\t\treturn jg;\n\t}\n\n\tpublic static String getUUID() {\n\t\tUUID uuid = UUID.randomUUID();\n\t\tString str = uuid.toString();\n\t\t// 去掉\"-\"符号\n\t\tString temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23)\n\t\t\t\t+ str.substring(24);\n\t\treturn temp;\n\t}\n\n\tpublic static String generateShortUUID() {\n\t\tString str = randomNum8(System.nanoTime());\n\t\treturn from10To24(str, 6);\n\t}\n\n\tpublic static String generateFileUUID() {\n\t\tString str = randomNum12(System.nanoTime());\n\t\treturn from10To32(str, 8);\n\t}\n\n\tpublic static String genToken() {\n\t\treturn from10To32(randomNum12(System.currentTimeMillis()), 8) + from10To32(randomNum12(System.nanoTime()), 8);\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSet set = new HashSet();\n\t\tString str;\n\t\tfor (int i = 0; i < 300; i++) {\n\t\t\tstr = generateShortUUID();\n\t\t\tSystem.out.println(str);\n\t\t\tset.add(str);\n\t\t}\n\t\tSystem.out.println(set.size());\n\t}\n\n}" } ]
import cn.hutool.core.util.StrUtil; import com.alibaba.csp.sentinel.util.MethodUtil; import net.bytebuddy.implementation.attribute.MethodAttributeAppender; import org.dromara.akali.annotation.AkaliFallback; import org.dromara.akali.annotation.AkaliHot; import org.dromara.akali.enums.AkaliStrategyEnum; import org.dromara.akali.manager.AkaliMethodManager; import org.dromara.akali.manager.AkaliRuleManager; import org.dromara.akali.sph.SphEngine; import org.dromara.akali.util.SerialsUtil; import net.bytebuddy.ByteBuddy; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.implementation.InvocationHandlerAdapter; import net.bytebuddy.matcher.ElementMatchers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
4,111
package org.dromara.akali.proxy; public class AkaliByteBuddyProxy { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Object bean; private final Class<?> originalClazz; public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) { this.bean = bean; this.originalClazz = originalClazz; } public Object proxy() throws Exception{ return new ByteBuddy().subclass(originalClazz) .name(StrUtil.format("{}$ByteBuddy${}", bean.getClass().getName(), SerialsUtil.generateShortUUID())) .method(ElementMatchers.any()) .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler())) .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) .annotateType(bean.getClass().getAnnotations()) .make() .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); } public class AopInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodStr = MethodUtil.resolveMethodName(method); if (AkaliMethodManager.contain(methodStr)){ AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1; Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2; if (anno instanceof AkaliFallback){ AkaliRuleManager.registerFallbackRule((AkaliFallback) anno, method); }else if (anno instanceof AkaliHot){ AkaliRuleManager.registerHotRule((AkaliHot) anno, method); }else{ throw new RuntimeException("annotation type error"); }
package org.dromara.akali.proxy; public class AkaliByteBuddyProxy { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Object bean; private final Class<?> originalClazz; public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) { this.bean = bean; this.originalClazz = originalClazz; } public Object proxy() throws Exception{ return new ByteBuddy().subclass(originalClazz) .name(StrUtil.format("{}$ByteBuddy${}", bean.getClass().getName(), SerialsUtil.generateShortUUID())) .method(ElementMatchers.any()) .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler())) .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) .annotateType(bean.getClass().getAnnotations()) .make() .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); } public class AopInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodStr = MethodUtil.resolveMethodName(method); if (AkaliMethodManager.contain(methodStr)){ AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1; Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2; if (anno instanceof AkaliFallback){ AkaliRuleManager.registerFallbackRule((AkaliFallback) anno, method); }else if (anno instanceof AkaliHot){ AkaliRuleManager.registerHotRule((AkaliHot) anno, method); }else{ throw new RuntimeException("annotation type error"); }
return SphEngine.process(bean, method, args, methodStr, akaliStrategyEnum);
3
2023-11-10 07:28:38+00:00
8k
quarkiverse/quarkus-langchain4j
hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/runtime/HuggingFaceRecorder.java
[ { "identifier": "firstOrDefault", "path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java", "snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) {\n return o.get();\n }\n }\n return defaultValue;\n}" }, { "identifier": "QuarkusHuggingFaceChatModel", "path": "hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/QuarkusHuggingFaceChatModel.java", "snippet": "public class QuarkusHuggingFaceChatModel implements ChatLanguageModel {\n\n public static final QuarkusHuggingFaceClientFactory CLIENT_FACTORY = new QuarkusHuggingFaceClientFactory();\n private final HuggingFaceClient client;\n private final Double temperature;\n private final Integer maxNewTokens;\n private final Boolean returnFullText;\n private final Boolean waitForModel;\n private final Optional<Boolean> doSample;\n private final OptionalDouble topP;\n private final OptionalInt topK;\n private final OptionalDouble repetitionPenalty;\n\n private QuarkusHuggingFaceChatModel(Builder builder) {\n this.client = CLIENT_FACTORY.create(builder, new HuggingFaceClientFactory.Input() {\n @Override\n public String apiKey() {\n return builder.accessToken;\n }\n\n @Override\n public String modelId() {\n throw new UnsupportedOperationException(\"Should not be called\");\n }\n\n @Override\n public Duration timeout() {\n return builder.timeout;\n }\n }, builder.url);\n this.temperature = builder.temperature;\n this.maxNewTokens = builder.maxNewTokens;\n this.returnFullText = builder.returnFullText;\n this.waitForModel = builder.waitForModel;\n this.doSample = builder.doSample;\n this.topP = builder.topP;\n this.topK = builder.topK;\n this.repetitionPenalty = builder.repetitionPenalty;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n @Override\n public Response<AiMessage> generate(List<ChatMessage> messages) {\n\n Parameters.Builder builder = Parameters.builder()\n .temperature(temperature)\n .maxNewTokens(maxNewTokens)\n .returnFullText(returnFullText);\n\n doSample.ifPresent(builder::doSample);\n topK.ifPresent(builder::topK);\n topP.ifPresent(builder::topP);\n repetitionPenalty.ifPresent(builder::repetitionPenalty);\n\n Parameters parameters = builder\n .build();\n TextGenerationRequest request = TextGenerationRequest.builder()\n .inputs(messages.stream()\n .map(ChatMessage::text)\n .collect(joining(\"\\n\")))\n .parameters(parameters)\n .options(Options.builder()\n .waitForModel(waitForModel)\n .build())\n .build();\n\n TextGenerationResponse textGenerationResponse = client.chat(request);\n\n return Response.from(AiMessage.from(textGenerationResponse.generatedText()));\n }\n\n @Override\n public Response<AiMessage> generate(List<ChatMessage> messages, List<ToolSpecification> toolSpecifications) {\n throw new IllegalArgumentException(\"Tools are currently not supported for HuggingFace models\");\n }\n\n @Override\n public Response<AiMessage> generate(List<ChatMessage> messages, ToolSpecification toolSpecification) {\n throw new IllegalArgumentException(\"Tools are currently not supported for HuggingFace models\");\n }\n\n public static final class Builder {\n\n private String accessToken;\n private Duration timeout = Duration.ofSeconds(15);\n private Double temperature;\n private Integer maxNewTokens;\n private Boolean returnFullText;\n private Boolean waitForModel = true;\n private URI url;\n private Optional<Boolean> doSample;\n\n private OptionalInt topK;\n private OptionalDouble topP;\n\n private OptionalDouble repetitionPenalty;\n public boolean logResponses;\n public boolean logRequests;\n\n public Builder accessToken(String accessToken) {\n this.accessToken = accessToken;\n return this;\n }\n\n public Builder url(URL url) {\n try {\n this.url = url.toURI();\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n public Builder timeout(Duration timeout) {\n this.timeout = timeout;\n return this;\n }\n\n public Builder temperature(Double temperature) {\n this.temperature = temperature;\n return this;\n }\n\n public Builder maxNewTokens(Integer maxNewTokens) {\n this.maxNewTokens = maxNewTokens;\n return this;\n }\n\n public Builder returnFullText(Boolean returnFullText) {\n this.returnFullText = returnFullText;\n return this;\n }\n\n public Builder waitForModel(Boolean waitForModel) {\n this.waitForModel = waitForModel;\n return this;\n }\n\n public Builder doSample(Optional<Boolean> doSample) {\n this.doSample = doSample;\n return this;\n }\n\n public Builder topK(OptionalInt topK) {\n this.topK = topK;\n return this;\n }\n\n public Builder topP(OptionalDouble topP) {\n this.topP = topP;\n return this;\n }\n\n public Builder repetitionPenalty(OptionalDouble repetitionPenalty) {\n this.repetitionPenalty = repetitionPenalty;\n return this;\n }\n\n public QuarkusHuggingFaceChatModel build() {\n return new QuarkusHuggingFaceChatModel(this);\n }\n\n public Builder logRequests(boolean logRequests) {\n this.logRequests = logRequests;\n return this;\n }\n\n public Builder logResponses(boolean logResponses) {\n this.logResponses = logResponses;\n return this;\n }\n }\n}" }, { "identifier": "QuarkusHuggingFaceEmbeddingModel", "path": "hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/QuarkusHuggingFaceEmbeddingModel.java", "snippet": "public class QuarkusHuggingFaceEmbeddingModel implements EmbeddingModel {\n\n public static final QuarkusHuggingFaceClientFactory CLIENT_FACTORY = new QuarkusHuggingFaceClientFactory();\n\n private final HuggingFaceClient client;\n private final boolean waitForModel;\n\n private QuarkusHuggingFaceEmbeddingModel(Builder builder) {\n this.client = CLIENT_FACTORY.create(null, new HuggingFaceClientFactory.Input() {\n @Override\n public String apiKey() {\n return builder.accessToken;\n }\n\n @Override\n public String modelId() {\n throw new UnsupportedOperationException(\"Should not be called\");\n }\n\n @Override\n public Duration timeout() {\n return builder.timeout;\n }\n }, builder.url);\n this.waitForModel = builder.waitForModel;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n @Override\n public Response<List<Embedding>> embedAll(List<TextSegment> textSegments) {\n\n List<String> texts = textSegments.stream()\n .map(TextSegment::text)\n .collect(toList());\n\n return embedTexts(texts);\n }\n\n private Response<List<Embedding>> embedTexts(List<String> texts) {\n\n EmbeddingRequest request = new EmbeddingRequest(texts, waitForModel);\n\n List<float[]> response = client.embed(request);\n\n List<Embedding> embeddings = response.stream()\n .map(Embedding::from)\n .collect(toList());\n\n return Response.from(embeddings);\n }\n\n public static final class Builder {\n\n private String accessToken;\n private Duration timeout = Duration.ofSeconds(15);\n private Boolean waitForModel = true;\n private URI url;\n\n public Builder accessToken(String accessToken) {\n this.accessToken = accessToken;\n return this;\n }\n\n public Builder url(URL url) {\n try {\n this.url = url.toURI();\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n public Builder timeout(Duration timeout) {\n this.timeout = timeout;\n return this;\n }\n\n public Builder waitForModel(Boolean waitForModel) {\n this.waitForModel = waitForModel;\n return this;\n }\n\n public QuarkusHuggingFaceEmbeddingModel build() {\n return new QuarkusHuggingFaceEmbeddingModel(this);\n }\n }\n}" }, { "identifier": "ChatModelConfig", "path": "hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/runtime/config/ChatModelConfig.java", "snippet": "@ConfigGroup\npublic interface ChatModelConfig {\n\n String DEFAULT_INFERENCE_ENDPOINT = \"https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct\";\n\n /**\n * The URL of the inference endpoint for the chat model.\n * <p>\n * When using Hugging Face with the inference API, the URL is\n * {@code https://api-inference.huggingface.co/models/<model-id>},\n * for example {@code https://api-inference.huggingface.co/models/google/flan-t5-small}.\n * <p>\n * When using a deployed inference endpoint, the URL is the URL of the endpoint.\n * When using a local hugging face model, the URL is the URL of the local model.\n */\n @WithDefault(DEFAULT_INFERENCE_ENDPOINT)\n URL inferenceEndpointUrl();\n\n /**\n * Float (0.0-100.0). The temperature of the sampling operation. 1 means regular sampling, 0 means always take the highest\n * score, 100.0 is getting closer to uniform probability\n */\n @WithDefault(\"1.0\")\n Double temperature();\n\n /**\n * Int (0-250). The amount of new tokens to be generated, this does not include the input length it is a estimate of the\n * size of generated text you want. Each new tokens slows down the request, so look for balance between response times and\n * length of text generated\n */\n Optional<Integer> maxNewTokens();\n\n /**\n * If set to {@code false}, the return results will not contain the original query making it easier for prompting\n */\n Optional<Boolean> returnFullText();\n\n /**\n * If the model is not ready, wait for it instead of receiving 503. It limits the number of requests required to get your\n * inference done. It is advised to only set this flag to true after receiving a 503 error as it will limit hanging in your\n * application to known places\n */\n @WithDefault(\"true\")\n Boolean waitForModel();\n\n /**\n * Whether or not to use sampling ; use greedy decoding otherwise.\n */\n Optional<Boolean> doSample();\n\n /**\n * The number of highest probability vocabulary tokens to keep for top-k-filtering.\n */\n OptionalInt topK();\n\n /**\n * If set to less than {@code 1}, only the most probable tokens with probabilities that add up to {@code top_p} or\n * higher are kept for generation.\n */\n OptionalDouble topP();\n\n /**\n * The parameter for repetition penalty. 1.0 means no penalty.\n * See <a href=\"https://arxiv.org/pdf/1909.05858.pdf\">this paper</a> for more details.\n */\n OptionalDouble repetitionPenalty();\n\n /**\n * Whether chat model requests should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether chat model responses should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n\n}" }, { "identifier": "EmbeddingModelConfig", "path": "hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/runtime/config/EmbeddingModelConfig.java", "snippet": "@ConfigGroup\npublic interface EmbeddingModelConfig {\n\n String DEFAULT_INFERENCE_ENDPOINT_EMBEDDING = \"https://api-inference.huggingface.co/pipeline/feature-extraction/sentence-transformers/all-MiniLM-L6-v2\";\n\n /**\n * The URL of the inference endpoint for the embedding.\n * <p>\n * When using Hugging Face with the inference API, the URL is\n * {@code https://api-inference.huggingface.co/pipeline/feature-extraction/<model-id>},\n * for example\n * {@code https://api-inference.huggingface.co/pipeline/feature-extraction/sentence-transformers/all-mpnet-base-v2}.\n * <p>\n * When using a deployed inference endpoint, the URL is the URL of the endpoint.\n * When using a local hugging face model, the URL is the URL of the local model.\n */\n @WithDefault(DEFAULT_INFERENCE_ENDPOINT_EMBEDDING)\n Optional<URL> inferenceEndpointUrl();\n\n /**\n * If the model is not ready, wait for it instead of receiving 503. It limits the number of requests required to get your\n * inference done. It is advised to only set this flag to true after receiving a 503 error as it will limit hanging in your\n * application to known places\n */\n @WithDefault(\"true\")\n Boolean waitForModel();\n}" }, { "identifier": "Langchain4jHuggingFaceConfig", "path": "hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/runtime/config/Langchain4jHuggingFaceConfig.java", "snippet": "@ConfigRoot(phase = RUN_TIME)\n@ConfigMapping(prefix = \"quarkus.langchain4j.huggingface\")\npublic interface Langchain4jHuggingFaceConfig {\n\n /**\n * HuggingFace API key\n */\n Optional<String> apiKey();\n\n /**\n * Timeout for HuggingFace calls\n */\n @WithDefault(\"10s\")\n Duration timeout();\n\n /**\n * Chat model related settings\n */\n ChatModelConfig chatModel();\n\n /**\n * Embedding model related settings\n */\n EmbeddingModelConfig embeddingModel();\n\n /**\n * Whether the HuggingFace client should log requests\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether the HuggingFace client should log responses\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n}" } ]
import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault; import java.net.URL; import java.util.Optional; import java.util.function.Supplier; import io.quarkiverse.langchain4j.huggingface.QuarkusHuggingFaceChatModel; import io.quarkiverse.langchain4j.huggingface.QuarkusHuggingFaceEmbeddingModel; import io.quarkiverse.langchain4j.huggingface.runtime.config.ChatModelConfig; import io.quarkiverse.langchain4j.huggingface.runtime.config.EmbeddingModelConfig; import io.quarkiverse.langchain4j.huggingface.runtime.config.Langchain4jHuggingFaceConfig; import io.quarkus.runtime.annotations.Recorder; import io.smallrye.config.ConfigValidationException;
3,699
package io.quarkiverse.langchain4j.huggingface.runtime; @Recorder public class HuggingFaceRecorder { public Supplier<?> chatModel(Langchain4jHuggingFaceConfig runtimeConfig) { Optional<String> apiKeyOpt = runtimeConfig.apiKey(); URL url = runtimeConfig.chatModel().inferenceEndpointUrl(); if (apiKeyOpt.isEmpty() && url.toExternalForm().contains("api-inference.huggingface.co")) { // when using the default base URL an API key is required throw new ConfigValidationException(createApiKeyConfigProblems()); }
package io.quarkiverse.langchain4j.huggingface.runtime; @Recorder public class HuggingFaceRecorder { public Supplier<?> chatModel(Langchain4jHuggingFaceConfig runtimeConfig) { Optional<String> apiKeyOpt = runtimeConfig.apiKey(); URL url = runtimeConfig.chatModel().inferenceEndpointUrl(); if (apiKeyOpt.isEmpty() && url.toExternalForm().contains("api-inference.huggingface.co")) { // when using the default base URL an API key is required throw new ConfigValidationException(createApiKeyConfigProblems()); }
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
3
2023-11-13 09:10:27+00:00
8k
qiusunshine/xiu
VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/factory/HttpDefaultDataSourceFactory.java
[ { "identifier": "DefaultDataSource", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultDataSource.java", "snippet": "public final class DefaultDataSource implements DataSource {\n\n private static final String TAG = \"DefaultDataSource\";\n\n private static final String SCHEME_ASSET = \"asset\";\n private static final String SCHEME_CONTENT = \"content\";\n private static final String SCHEME_RTMP = \"rtmp\";\n private static final String SCHEME_UDP = \"udp\";\n private static final String SCHEME_DATA = DataSchemeDataSource.SCHEME_DATA;\n private static final String SCHEME_RAW = RawResourceDataSource.RAW_RESOURCE_SCHEME;\n private static final String SCHEME_ANDROID_RESOURCE = ContentResolver.SCHEME_ANDROID_RESOURCE;\n\n private final Context context;\n private final List<TransferListener> transferListeners;\n private final DataSource baseDataSource;\n\n // Lazily initialized.\n @Nullable private DataSource fileDataSource;\n @Nullable private DataSource assetDataSource;\n @Nullable private DataSource contentDataSource;\n @Nullable private DataSource rtmpDataSource;\n @Nullable private DataSource udpDataSource;\n @Nullable private DataSource dataSchemeDataSource;\n @Nullable private DataSource rawResourceDataSource;\n\n @Nullable private DataSource dataSource;\n\n /**\n * Constructs a new instance, optionally configured to follow cross-protocol redirects.\n *\n * @param context A context.\n */\n public DefaultDataSource(Context context, boolean allowCrossProtocolRedirects) {\n this(\n context,\n /* userAgent= */ null,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,\n allowCrossProtocolRedirects);\n }\n\n /**\n * Constructs a new instance, optionally configured to follow cross-protocol redirects.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n * @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP\n * to HTTPS and vice versa) are enabled when fetching remote data.\n */\n public DefaultDataSource(\n Context context, @Nullable String userAgent, boolean allowCrossProtocolRedirects) {\n this(\n context,\n userAgent,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,\n allowCrossProtocolRedirects);\n }\n\n /**\n * Constructs a new instance, optionally configured to follow cross-protocol redirects.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n * @param connectTimeoutMillis The connection timeout that should be used when requesting remote\n * data, in milliseconds. A timeout of zero is interpreted as an infinite timeout.\n * @param readTimeoutMillis The read timeout that should be used when requesting remote data, in\n * milliseconds. A timeout of zero is interpreted as an infinite timeout.\n * @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP\n * to HTTPS and vice versa) are enabled when fetching remote data.\n */\n public DefaultDataSource(\n Context context,\n @Nullable String userAgent,\n int connectTimeoutMillis,\n int readTimeoutMillis,\n boolean allowCrossProtocolRedirects) {\n this(\n context,\n new DefaultHttpDataSource.Factory()\n .setUserAgent(userAgent)\n .setConnectTimeoutMs(connectTimeoutMillis)\n .setReadTimeoutMs(readTimeoutMillis)\n .setAllowCrossProtocolRedirects(allowCrossProtocolRedirects)\n .createDataSource());\n }\n\n /**\n * Constructs a new instance that delegates to a provided {@link DataSource} for URI schemes other\n * than file, asset and content.\n *\n * @param context A context.\n * @param baseDataSource A {@link DataSource} to use for URI schemes other than file, asset and\n * content. This {@link DataSource} should normally support at least http(s).\n */\n public DefaultDataSource(Context context, DataSource baseDataSource) {\n this.context = context.getApplicationContext();\n this.baseDataSource = Assertions.checkNotNull(baseDataSource);\n transferListeners = new ArrayList<>();\n }\n\n @Override\n public void addTransferListener(TransferListener transferListener) {\n Assertions.checkNotNull(transferListener);\n baseDataSource.addTransferListener(transferListener);\n transferListeners.add(transferListener);\n maybeAddListenerToDataSource(fileDataSource, transferListener);\n maybeAddListenerToDataSource(assetDataSource, transferListener);\n maybeAddListenerToDataSource(contentDataSource, transferListener);\n maybeAddListenerToDataSource(rtmpDataSource, transferListener);\n maybeAddListenerToDataSource(udpDataSource, transferListener);\n maybeAddListenerToDataSource(dataSchemeDataSource, transferListener);\n maybeAddListenerToDataSource(rawResourceDataSource, transferListener);\n }\n\n @Override\n public long open(DataSpec dataSpec) throws IOException {\n Assertions.checkState(dataSource == null);\n // Choose the correct source for the scheme.\n String scheme = dataSpec.uri.getScheme();\n if (Util.isLocalFileUri(dataSpec.uri)) {\n String uriPath = dataSpec.uri.getPath();\n if (uriPath != null && uriPath.startsWith(\"/android_asset/\")) {\n dataSource = getAssetDataSource();\n } else {\n dataSource = getFileDataSource();\n }\n } else if (SCHEME_ASSET.equals(scheme)) {\n dataSource = getAssetDataSource();\n } else if (SCHEME_CONTENT.equals(scheme)) {\n dataSource = getContentDataSource();\n } else if (SCHEME_RTMP.equals(scheme)) {\n dataSource = getRtmpDataSource();\n } else if (SCHEME_UDP.equals(scheme)) {\n dataSource = getUdpDataSource();\n } else if (SCHEME_DATA.equals(scheme)) {\n dataSource = getDataSchemeDataSource();\n } else if (SCHEME_RAW.equals(scheme) || SCHEME_ANDROID_RESOURCE.equals(scheme)) {\n dataSource = getRawResourceDataSource();\n } else {\n dataSource = baseDataSource;\n }\n // Open the source and return.\n return dataSource.open(dataSpec);\n }\n\n @Override\n public int read(byte[] buffer, int offset, int length) throws IOException {\n return Assertions.checkNotNull(dataSource).read(buffer, offset, length);\n }\n\n @Override\n @Nullable\n public Uri getUri() {\n return dataSource == null ? null : dataSource.getUri();\n }\n\n @Override\n public Map<String, List<String>> getResponseHeaders() {\n return dataSource == null ? new HashMap<String, List<String>>() : dataSource.getResponseHeaders();\n }\n\n @Override\n public void close() throws IOException {\n if (dataSource != null) {\n try {\n dataSource.close();\n } finally {\n dataSource = null;\n }\n }\n }\n\n private DataSource getUdpDataSource() {\n if (udpDataSource == null) {\n udpDataSource = new UdpDataSource();\n addListenersToDataSource(udpDataSource);\n }\n return udpDataSource;\n }\n\n private DataSource getFileDataSource() {\n if (fileDataSource == null) {\n fileDataSource = new FileDataSource();\n addListenersToDataSource(fileDataSource);\n }\n return fileDataSource;\n }\n\n private DataSource getAssetDataSource() {\n if (assetDataSource == null) {\n assetDataSource = new AssetDataSource(context);\n addListenersToDataSource(assetDataSource);\n }\n return assetDataSource;\n }\n\n private DataSource getContentDataSource() {\n if (contentDataSource == null) {\n contentDataSource = new ContentDataSource(context);\n addListenersToDataSource(contentDataSource);\n }\n return contentDataSource;\n }\n\n private DataSource getRtmpDataSource() {\n if (rtmpDataSource == null) {\n try {\n Class<?> clazz = Class.forName(\"com.google.android.exoplayer2.ext.rtmp.RtmpDataSource\");\n rtmpDataSource = (DataSource) clazz.getConstructor().newInstance();\n addListenersToDataSource(rtmpDataSource);\n } catch (ClassNotFoundException e) {\n // Expected if the app was built without the RTMP extension.\n Log.w(TAG, \"Attempting to play RTMP stream without depending on the RTMP extension\");\n } catch (Exception e) {\n // The RTMP extension is present, but instantiation failed.\n throw new RuntimeException(\"Error instantiating RTMP extension\", e);\n }\n if (rtmpDataSource == null) {\n rtmpDataSource = baseDataSource;\n }\n }\n return rtmpDataSource;\n }\n\n private DataSource getDataSchemeDataSource() {\n if (dataSchemeDataSource == null) {\n dataSchemeDataSource = new DataSchemeDataSource();\n addListenersToDataSource(dataSchemeDataSource);\n }\n return dataSchemeDataSource;\n }\n\n private DataSource getRawResourceDataSource() {\n if (rawResourceDataSource == null) {\n rawResourceDataSource = new RawResourceDataSource(context);\n addListenersToDataSource(rawResourceDataSource);\n }\n return rawResourceDataSource;\n }\n\n private void addListenersToDataSource(DataSource dataSource) {\n for (int i = 0; i < transferListeners.size(); i++) {\n dataSource.addTransferListener(transferListeners.get(i));\n }\n }\n\n private void maybeAddListenerToDataSource(\n @Nullable DataSource dataSource, TransferListener listener) {\n if (dataSource != null) {\n dataSource.addTransferListener(listener);\n }\n }\n}" }, { "identifier": "DefaultDataSourceFactory", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultDataSourceFactory.java", "snippet": "public final class DefaultDataSourceFactory implements Factory {\n\n private final Context context;\n @Nullable private final TransferListener listener;\n private final Factory baseDataSourceFactory;\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n */\n public DefaultDataSourceFactory(Context context) {\n this(context, /* userAgent= */ (String) null, /* listener= */ null);\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n */\n public DefaultDataSourceFactory(Context context, @Nullable String userAgent) {\n this(context, userAgent, /* listener= */ null);\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n * @param listener An optional listener.\n */\n public DefaultDataSourceFactory(\n Context context, @Nullable String userAgent, @Nullable TransferListener listener) {\n this(context, listener, new DefaultHttpDataSource.Factory().setUserAgent(userAgent));\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param baseDataSourceFactory A {@link Factory} to be used to create a base {@link DataSource}\n * for {@link com.google.android.exoplayer2.upstream.DefaultDataSource}.\n * @see com.google.android.exoplayer2.upstream.DefaultDataSource#DefaultDataSource(Context, DataSource)\n */\n public DefaultDataSourceFactory(Context context, Factory baseDataSourceFactory) {\n this(context, /* listener= */ null, baseDataSourceFactory);\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param listener An optional listener.\n * @param baseDataSourceFactory A {@link Factory} to be used to create a base {@link DataSource}\n * for {@link com.google.android.exoplayer2.upstream.DefaultDataSource}.\n * @see com.google.android.exoplayer2.upstream.DefaultDataSource#DefaultDataSource(Context, DataSource)\n */\n public DefaultDataSourceFactory(\n Context context,\n @Nullable TransferListener listener,\n Factory baseDataSourceFactory) {\n this.context = context.getApplicationContext();\n this.listener = listener;\n this.baseDataSourceFactory = baseDataSourceFactory;\n }\n\n @Override\n public com.google.android.exoplayer2.upstream.DefaultDataSource createDataSource() {\n com.google.android.exoplayer2.upstream.DefaultDataSource dataSource =\n new DefaultDataSource(context, baseDataSourceFactory.createDataSource());\n if (listener != null) {\n dataSource.addTransferListener(listener);\n }\n return dataSource;\n }\n}" }, { "identifier": "HttpsUtils", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/HttpsUtils.java", "snippet": "public class HttpsUtils {\n public static X509TrustManager UnSafeTrustManager = new X509TrustManager() {\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n public static HostnameVerifier UnSafeHostnameVerifier = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n\n public HttpsUtils() {\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory() {\n return getSslSocketFactoryBase((X509TrustManager)null, (InputStream)null, (String)null);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(X509TrustManager trustManager) {\n return getSslSocketFactoryBase(trustManager, (InputStream)null, (String)null);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(InputStream... certificates) {\n return getSslSocketFactoryBase((X509TrustManager)null, (InputStream)null, (String)null, certificates);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(InputStream bksFile, String password, InputStream... certificates) {\n return getSslSocketFactoryBase((X509TrustManager)null, bksFile, password, certificates);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(InputStream bksFile, String password, X509TrustManager trustManager) {\n return getSslSocketFactoryBase(trustManager, bksFile, password);\n }\n\n private static HttpsUtils.SSLParams getSslSocketFactoryBase(X509TrustManager trustManager, InputStream bksFile, String password, InputStream... certificates) {\n HttpsUtils.SSLParams sslParams = new HttpsUtils.SSLParams();\n\n try {\n KeyManager[] keyManagers = prepareKeyManager(bksFile, password);\n TrustManager[] trustManagers = prepareTrustManager(certificates);\n X509TrustManager manager;\n if (trustManager != null) {\n manager = trustManager;\n } else if (trustManagers != null) {\n manager = chooseTrustManager(trustManagers);\n } else {\n manager = UnSafeTrustManager;\n }\n\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(keyManagers, new TrustManager[]{manager}, (SecureRandom)null);\n sslParams.sSLSocketFactory = sslContext.getSocketFactory();\n sslParams.trustManager = manager;\n return sslParams;\n } catch (NoSuchAlgorithmException var9) {\n throw new AssertionError(var9);\n } catch (KeyManagementException var10) {\n throw new AssertionError(var10);\n }\n }\n\n private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {\n try {\n if (bksFile != null && password != null) {\n KeyStore clientKeyStore = KeyStore.getInstance(\"BKS\");\n clientKeyStore.load(bksFile, password.toCharArray());\n KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\n kmf.init(clientKeyStore, password.toCharArray());\n return kmf.getKeyManagers();\n } else {\n return null;\n }\n } catch (Exception var4) {\n var4.printStackTrace();\n return null;\n }\n }\n\n private static TrustManager[] prepareTrustManager(InputStream... certificates) {\n if (certificates != null && certificates.length > 0) {\n try {\n CertificateFactory certificateFactory = CertificateFactory.getInstance(\"X.509\");\n KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());\n keyStore.load((LoadStoreParameter)null);\n int index = 0;\n InputStream[] var4 = certificates;\n int var5 = certificates.length;\n\n for(int var6 = 0; var6 < var5; ++var6) {\n InputStream certStream = var4[var6];\n String certificateAlias = Integer.toString(index++);\n Certificate cert = certificateFactory.generateCertificate(certStream);\n keyStore.setCertificateEntry(certificateAlias, cert);\n\n try {\n if (certStream != null) {\n certStream.close();\n }\n } catch (IOException var11) {\n var11.printStackTrace();\n }\n }\n\n TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n tmf.init(keyStore);\n return tmf.getTrustManagers();\n } catch (Exception var12) {\n var12.printStackTrace();\n return null;\n }\n } else {\n return null;\n }\n }\n\n private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {\n TrustManager[] var1 = trustManagers;\n int var2 = trustManagers.length;\n\n for(int var3 = 0; var3 < var2; ++var3) {\n TrustManager trustManager = var1[var3];\n if (trustManager instanceof X509TrustManager) {\n return (X509TrustManager)trustManager;\n }\n }\n\n return null;\n }\n\n public static class SSLParams {\n public SSLSocketFactory sSLSocketFactory;\n public X509TrustManager trustManager;\n\n public SSLParams() {\n }\n }\n}" }, { "identifier": "DEFAULT_READ_TIMEOUT_MILLIS", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultHttpDataSource.java", "snippet": "public static final int DEFAULT_READ_TIMEOUT_MILLIS = 8 * 1000;" } ]
import android.content.Context; import android.net.Uri; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.util.Util; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import chuangyuan.ycj.videolibrary.upstream.DefaultDataSource; import chuangyuan.ycj.videolibrary.upstream.DefaultDataSourceFactory; import chuangyuan.ycj.videolibrary.upstream.HttpsUtils; import okhttp3.OkHttpClient; import okhttp3.brotli.BrotliInterceptor; import static chuangyuan.ycj.videolibrary.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS;
4,972
package chuangyuan.ycj.videolibrary.factory; /** * 作者:By 15968 * 日期:On 2020/6/1 * 时间:At 23:08 */ public class HttpDefaultDataSourceFactory implements DataSource.Factory { private final Context context; private final DataSource.Factory baseDataSourceFactory; public static String DEFAULT_UA = "Mozilla/5.0 (Linux; Android 11; Mi 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Mobile Safari/537.36"; /** * Instantiates a new J default data source factory. * * @param context A context. for {@link DefaultDataSource}. */ public HttpDefaultDataSourceFactory(Context context) { String userAgent = Util.getUserAgent(context, context.getPackageName()); Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", userAgent); this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, null); } public HttpDefaultDataSourceFactory(Context context, Map<String, String> headers, Uri uri) { this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, uri); } private DataSource.Factory init(Context context, Map<String, String> headers, Uri uri) { // String userAgent = Util.getUserAgent(context, context.getPackageName()); String userAgent = DEFAULT_UA; if (headers != null) { if (headers.containsKey("User-Agent")) { userAgent = headers.get("User-Agent"); } else if (headers.containsKey("user-agent")) { userAgent = headers.get("user-agent"); } else if (headers.containsKey("user-Agent")) { userAgent = headers.get("user-Agent"); } headers = new HashMap<>(headers); headers.remove("User-Agent"); } if (headers == null) { headers = new HashMap<>(); } //方法一:信任所有证书,不安全有风险
package chuangyuan.ycj.videolibrary.factory; /** * 作者:By 15968 * 日期:On 2020/6/1 * 时间:At 23:08 */ public class HttpDefaultDataSourceFactory implements DataSource.Factory { private final Context context; private final DataSource.Factory baseDataSourceFactory; public static String DEFAULT_UA = "Mozilla/5.0 (Linux; Android 11; Mi 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Mobile Safari/537.36"; /** * Instantiates a new J default data source factory. * * @param context A context. for {@link DefaultDataSource}. */ public HttpDefaultDataSourceFactory(Context context) { String userAgent = Util.getUserAgent(context, context.getPackageName()); Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", userAgent); this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, null); } public HttpDefaultDataSourceFactory(Context context, Map<String, String> headers, Uri uri) { this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, uri); } private DataSource.Factory init(Context context, Map<String, String> headers, Uri uri) { // String userAgent = Util.getUserAgent(context, context.getPackageName()); String userAgent = DEFAULT_UA; if (headers != null) { if (headers.containsKey("User-Agent")) { userAgent = headers.get("User-Agent"); } else if (headers.containsKey("user-agent")) { userAgent = headers.get("user-agent"); } else if (headers.containsKey("user-Agent")) { userAgent = headers.get("user-Agent"); } headers = new HashMap<>(headers); headers.remove("User-Agent"); } if (headers == null) { headers = new HashMap<>(); } //方法一:信任所有证书,不安全有风险
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
2
2023-11-10 14:28:40+00:00
8k
noear/folkmq
folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/AdminController.java
[ { "identifier": "LicenceUtils", "path": "folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/dso/LicenceUtils.java", "snippet": "public class LicenceUtils {\n private static String licence = null;\n private static int isAuthorized = 0;\n private static String subscribeDate;\n private static int subscribeMonths;\n private static String consumer;\n\n public static String getLicence() {\n if (licence == null) {\n licence = Solon.cfg().get(ConfigNames.folkmq_licence, \"\");\n }\n\n return licence;\n }\n\n public static String getLicence2() {\n StringBuilder buf = new StringBuilder();\n String[] ary = getLicence().split(\"-\");\n for (String s : ary) {\n if (s.length() > 8) {\n buf.append(s.substring(0, s.length() - 6) + \"******\");\n } else if (s.length() > 6) {\n buf.append(s.substring(0, s.length() - 4) + \"****\");\n } else {\n buf.append(s.substring(0, s.length() - 2) + \"**\");\n }\n buf.append(\"-\");\n }\n buf.setLength(buf.length() - 1);\n return buf.toString();\n }\n\n public static boolean isValid() {\n if (Utils.isEmpty(getLicence()) || getLicence().length() != 36) {\n return false;\n } else {\n return true;\n }\n }\n\n public static int isAuthorized() {\n return isAuthorized;\n }\n\n public static int getSubscribeMonths() {\n return subscribeMonths;\n }\n\n public static String getSubscribeDate() {\n return subscribeDate;\n }\n\n public static String getConsumer() {\n return consumer;\n }\n\n public static Result auth() {\n try {\n String json = HttpUtils.http(\"https://folkmq.noear.org/licence/auth\")\n .data(\"licence\", LicenceUtils.getLicence())\n .data(\"version\", FolkMQ.version())\n .post();\n\n ONode oNode = ONode.loadStr(json);\n int code = oNode.get(\"code\").getInt();\n String description = oNode.get(\"description\").getString();\n\n if (code == 200) {\n isAuthorized = 1;\n subscribeDate = oNode.get(\"data\").get(\"subscribe_date\").getString();\n subscribeMonths = oNode.get(\"data\").get(\"subscribe_months\").getInt();\n consumer = oNode.get(\"data\").get(\"consumer\").getString();\n\n return Result.succeed(description);\n } else {\n if (code == 401) {\n isAuthorized = -1;\n } else {\n isAuthorized = 0;\n }\n\n\n return Result.failure(code, description);\n }\n } catch (Exception e) {\n isAuthorized = 0;\n return Result.failure(400, \"检测出错:\" + e.getMessage());\n }\n }\n}" }, { "identifier": "ViewQueueService", "path": "folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/dso/ViewQueueService.java", "snippet": "@Component\npublic class ViewQueueService implements LifecycleBean {\n private static final Logger log = LoggerFactory.getLogger(ViewQueueService.class);\n\n @Inject\n private BrokerListenerFolkmq brokerListener;\n\n private Set<String> queueSet = Collections.newSetFromMap(new ConcurrentHashMap<>());\n private Map<String, QueueVo> queueVoMap = new ConcurrentHashMap<>();\n private Map<String, QueueVo> queueVoMapTmp = new ConcurrentHashMap<>();\n private Object QUEUE_LOCK = new Object();\n\n private ScheduledFuture<?> scheduledFuture;\n\n public List<QueueVo> getQueueListVo() {\n List<QueueVo> list = new ArrayList<>();\n\n for (String queueName : new ArrayList<>(queueSet)) {\n QueueVo queueVo = queueVoMap.get(queueName);\n if (queueVo == null) {\n queueVo = new QueueVo();//初始化\n queueVo.queue = queueName;\n }\n\n //随时刷新\n queueVo.sessionCount = brokerListener.getPlayerNum(queueName);\n list.add(queueVo);\n }\n\n return list;\n }\n\n public QueueVo getQueueVo(String queueName) {\n QueueVo queueVo = queueVoMap.get(queueName);\n if (queueVo != null) {\n queueVo.sessionCount = brokerListener.getPlayerNum(queueName);\n }\n\n return queueVo;\n }\n\n public void removeQueueVo(String queueName){\n queueVoMap.remove(queueName);\n queueVoMapTmp.remove(queueName);\n queueSet.remove(queueName);\n }\n\n @Override\n public void start() throws Throwable {\n delay();\n }\n\n /**\n * 延时处理\n * */\n private void delay() {\n long sync_time_millis = Integer.parseInt(Solon.cfg().get(\n ConfigNames.folkmq_view_queue_syncInterval,\n ConfigNames.folkmq_view_queue_syncInterval_def));\n\n if (sync_time_millis > 0) {\n scheduledFuture = RunUtil.delay(this::delayDo, sync_time_millis);\n }\n }\n\n\n private void delayDo() {\n try {\n Collection<Session> tmp = brokerListener.getPlayerAll(MqConstants.BROKER_AT_SERVER);\n if (tmp == null) {\n return;\n }\n\n //一种切换效果。把上次收集的效果切换给当前的。然后重新开始收集\n queueVoMap.clear();\n queueVoMap.putAll(queueVoMapTmp);\n queueVoMapTmp.clear();\n\n List<Session> sessions = new ArrayList<>(tmp);\n for (Session session : sessions) {\n try {\n session.sendAndRequest(MqConstants.ADMIN_VIEW_QUEUE, new StringEntity(\"\"), -1).thenReply(r -> {\n String json = r.dataAsString();\n List<QueueVo> list = ONode.loadStr(json).toObjectList(QueueVo.class);\n addQueueVo(list, queueVoMapTmp);\n });\n } catch (Throwable e) {\n log.warn(\"Cmd 'admin.view.queue' call error\", e);\n }\n }\n }finally {\n delay();\n }\n }\n\n private void addQueueVo(List<QueueVo> list, Map<String, QueueVo> coll) {\n synchronized (QUEUE_LOCK) {\n for (QueueVo queueVo : list) {\n if (Utils.isEmpty(queueVo.queue)) {\n continue;\n }\n\n queueSet.add(queueVo.queue);\n\n QueueVo stat = coll.computeIfAbsent(queueVo.queue, n -> new QueueVo());\n\n stat.queue = queueVo.queue;\n stat.messageCount += queueVo.messageCount;\n stat.messageDelayedCount1 += queueVo.messageDelayedCount1;\n stat.messageDelayedCount2 += queueVo.messageDelayedCount2;\n stat.messageDelayedCount3 += queueVo.messageDelayedCount3;\n stat.messageDelayedCount4 += queueVo.messageDelayedCount4;\n stat.messageDelayedCount5 += queueVo.messageDelayedCount5;\n stat.messageDelayedCount6 += queueVo.messageDelayedCount6;\n stat.messageDelayedCount7 += queueVo.messageDelayedCount7;\n stat.messageDelayedCount8 += queueVo.messageDelayedCount8;\n\n String topic = queueVo.queue.split(MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP)[0];\n brokerListener.subscribeDo(null, topic, queueVo.queue);\n }\n }\n }\n\n @Override\n public void stop() throws Throwable {\n if (scheduledFuture != null) {\n scheduledFuture.cancel(false);\n }\n }\n}" }, { "identifier": "ServerVo", "path": "folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/model/ServerVo.java", "snippet": "public class ServerVo {\n public String sid;\n public String addree;\n public String adminUrl;\n\n public String getSid() {\n return sid;\n }\n\n public String getAddree() {\n return addree;\n }\n\n public String getAdminUrl() {\n return adminUrl;\n }\n}" }, { "identifier": "TopicVo", "path": "folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/model/TopicVo.java", "snippet": "public class TopicVo {\n private String topic;\n private int queueCount;\n private String queueList;\n\n public void setTopic(String topic) {\n this.topic = topic;\n }\n\n public void setQueueCount(int queueCount) {\n this.queueCount = queueCount;\n }\n\n public void setQueueList(String queueList) {\n this.queueList = queueList;\n }\n\n public String getTopic() {\n return topic;\n }\n\n public int getQueueCount() {\n return queueCount;\n }\n\n public String getQueueList() {\n return queueList;\n }\n}" }, { "identifier": "BrokerListenerFolkmq", "path": "folkmq-broker/src/main/java/org/noear/folkmq/broker/mq/BrokerListenerFolkmq.java", "snippet": "public class BrokerListenerFolkmq extends BrokerListener {\n //访问账号\n private Map<String, String> accessMap = new HashMap<>();\n\n //订阅关系表(topic=>topicConsumerGroup[])\n private Map<String, Set<String>> subscribeMap = new ConcurrentHashMap<>();\n private Object SUBSCRIBE_LOCK = new Object();\n\n public Map<String, Set<String>> getSubscribeMap() {\n return subscribeMap;\n }\n\n public void removeSubscribe(String topic, String queueName) {\n Set<String> tmp = subscribeMap.get(topic);\n if (tmp != null) {\n tmp.remove(queueName);\n }\n }\n\n /**\n * 配置访问账号\n *\n * @param accessKey 访问者身份\n * @param accessSecretKey 访问者密钥\n */\n public BrokerListenerFolkmq addAccess(String accessKey, String accessSecretKey) {\n accessMap.put(accessKey, accessSecretKey);\n return this;\n }\n\n /**\n * 配置访问账号\n *\n * @param accessMap 访问账号集合\n */\n public BrokerListenerFolkmq addAccessAll(Map<String, String> accessMap) {\n if (accessMap != null) {\n this.accessMap.putAll(accessMap);\n }\n return this;\n }\n\n @Override\n public void onOpen(Session session) throws IOException {\n if (accessMap.size() > 0) {\n //如果有 ak/sk 配置,则进行鉴权\n String accessKey = session.param(MqConstants.PARAM_ACCESS_KEY);\n String accessSecretKey = session.param(MqConstants.PARAM_ACCESS_SECRET_KEY);\n\n if (accessKey == null || accessSecretKey == null) {\n session.close();\n return;\n }\n\n if (accessSecretKey.equals(accessMap.get(accessKey)) == false) {\n session.close();\n return;\n }\n }\n\n if(MqConstants.BROKER_AT_SERVER.equals(session.name()) == false) {\n //如果不是 server,直接添加为 player\n super.onOpen(session);\n }\n\n log.info(\"Player channel opened, sessionId={}, ip={}\",\n session.sessionId(),\n session.remoteAddress());\n }\n\n @Override\n public void onClose(Session session) {\n super.onClose(session);\n\n log.info(\"Player channel closed, sessionId={}\", session.sessionId());\n\n Collection<String> atList = session.attrMap().keySet();\n if (atList.size() > 0) {\n for (String at : atList) {\n //注销玩家\n removePlayer(at, session);\n }\n }\n }\n\n @Override\n public void onMessage(Session requester, Message message) throws IOException {\n if (MqConstants.MQ_EVENT_SUBSCRIBE.equals(message.event())) {\n onSubscribe(requester, message);\n } else if (MqConstants.MQ_EVENT_UNSUBSCRIBE.equals(message.event())) {\n //取消订阅,注销玩家\n String topic = message.meta(MqConstants.MQ_META_TOPIC);\n String consumerGroup = message.meta(MqConstants.MQ_META_CONSUMER_GROUP);\n String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup;\n\n removePlayer(queueName, requester);\n } else if (MqConstants.MQ_EVENT_DISTRIBUTE.equals(message.event())) {\n String atName = message.atName();\n\n //单发模式(给同名的某个玩家,轮询负截均衡)\n Session responder = getPlayerOne(atName);\n if (responder != null && responder.isValid()) {\n //转发消息\n try {\n forwardToSession(requester, message, responder);\n } catch (Throwable e) {\n acknowledgeAsNo(requester, message);\n }\n } else {\n acknowledgeAsNo(requester, message);\n }\n\n //结束处理\n return;\n } else if (MqConstants.MQ_EVENT_JOIN.equals(message.event())) {\n //同步订阅\n if (subscribeMap.size() > 0) {\n String json = ONode.stringify(subscribeMap);\n Entity entity = new StringEntity(json).metaPut(MqConstants.MQ_META_BATCH, \"1\");\n requester.sendAndRequest(MqConstants.MQ_EVENT_SUBSCRIBE, entity, 30_000).await();\n }\n\n //注册服务\n String name = requester.name();\n if (StrUtils.isNotEmpty(name)) {\n addPlayer(name, requester);\n }\n\n log.info(\"Player channel joined, sessionId={}, ip={}\",\n requester.sessionId(),\n requester.remoteAddress());\n\n //结束处理\n return;\n }\n\n if (message.event().startsWith(MqConstants.ADMIN_PREFIX)) {\n log.warn(\"Player channel admin events are not allowed, sessionId={}, ip={}\",\n requester.sessionId(),\n requester.remoteAddress());\n return;\n }\n\n super.onMessage(requester, message);\n }\n\n private void onSubscribe(Session requester, Message message) {\n String is_batch = message.meta(MqConstants.MQ_META_BATCH);\n if (\"1\".equals(is_batch)) {\n ONode oNode = ONode.loadStr(message.dataAsString());\n Map<String, Collection<String>> subscribeData = oNode.toObject();\n if (subscribeData != null) {\n for (Map.Entry<String, Collection<String>> kv : subscribeData.entrySet()) {\n for (String queueName : kv.getValue()) {\n //执行订阅\n subscribeDo(requester, kv.getKey(), queueName);\n }\n }\n }\n } else {\n //订阅,注册玩家\n String topic = message.meta(MqConstants.MQ_META_TOPIC);\n String consumerGroup = message.meta(MqConstants.MQ_META_CONSUMER_GROUP);\n String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup;\n\n\n subscribeDo(requester, topic, queueName);\n }\n }\n\n public void subscribeDo(Session requester, String topic, String queueName) {\n if (requester != null) {\n requester.attrPut(queueName, \"1\");\n addPlayer(queueName, requester);\n }\n\n synchronized (SUBSCRIBE_LOCK) {\n //以身份进行订阅(topic=>[topicConsumerGroup])\n Set<String> topicConsumerSet = subscribeMap.computeIfAbsent(topic, n -> Collections.newSetFromMap(new ConcurrentHashMap<>()));\n topicConsumerSet.add(queueName);\n }\n }\n\n public boolean publishDo(String topic, IMqMessage message) throws IOException {\n Message routingMessage = MqUtils.routingMessageBuild(topic, message);\n\n Session responder = this.getPlayerOne(MqConstants.BROKER_AT_SERVER);\n if (responder != null) {\n if (message.getQos() > 0) {\n responder.sendAndRequest(MqConstants.MQ_EVENT_PUBLISH, routingMessage).await();\n } else {\n responder.send(MqConstants.MQ_EVENT_PUBLISH, routingMessage);\n }\n\n return true;\n } else {\n return false;\n }\n }\n\n\n\n private void acknowledgeAsNo(Session requester, Message message) throws IOException {\n //如果没有会话,自动转为ACK失败\n if (message.isSubscribe() || message.isRequest()) {\n requester.replyEnd(message, new StringEntity(\"\")\n .metaPut(MqConstants.MQ_META_ACK, \"0\"));\n }\n }\n}" }, { "identifier": "MqMessage", "path": "folkmq/src/main/java/org/noear/folkmq/client/MqMessage.java", "snippet": "public class MqMessage implements IMqMessage {\n private String tid;\n private String content;\n private Date scheduled;\n private Date expiration;\n private int qos = 1;\n\n public MqMessage(String content){\n this.tid = StrUtils.guid();\n this.content = content;\n }\n\n @Override\n public String getTid() {\n return tid;\n }\n\n public String getContent() {\n return content;\n }\n\n public Date getScheduled() {\n return scheduled;\n }\n\n @Override\n public Date getExpiration() {\n return expiration;\n }\n\n public int getQos() {\n return qos;\n }\n\n public MqMessage scheduled(Date scheduled) {\n this.scheduled = scheduled;\n return this;\n }\n\n public MqMessage expiration(Date expiration){\n this.expiration = expiration;\n return this;\n }\n\n public MqMessage qos(int qos) {\n this.qos = qos;\n return this;\n }\n}" }, { "identifier": "MqConstants", "path": "folkmq/src/main/java/org/noear/folkmq/common/MqConstants.java", "snippet": "public interface MqConstants {\n /**\n * 元信息:消息事务Id\n */\n String MQ_META_TID = \"mq.tid\";\n /**\n * 元信息:消息主题\n */\n String MQ_META_TOPIC = \"mq.topic\";\n /**\n * 元信息:消息调度时间\n */\n String MQ_META_SCHEDULED = \"mq.scheduled\";\n /**\n * 元信息:消息过期时间\n */\n String MQ_META_EXPIRATION = \"mq.expiration\";\n /**\n * 元信息:消息质量等级\n */\n String MQ_META_QOS = \"mq.qos\";\n /**\n * 元信息:消费者组\n */\n String MQ_META_CONSUMER_GROUP = \"mq.consumer\"; //此处不改动,算历史痕迹。保持向下兼容\n /**\n * 元信息:派发次数\n */\n String MQ_META_TIMES = \"mq.times\";\n /**\n * 元信息:消费回执\n */\n String MQ_META_ACK = \"mq.ack\";\n /**\n * 元信息:执行确认\n */\n String MQ_META_CONFIRM = \"mq.confirm\";\n /**\n * 元信息:批量处理\n */\n String MQ_META_BATCH = \"mq.batch\";\n\n /**\n * 事件:订阅\n */\n String MQ_EVENT_SUBSCRIBE = \"mq.event.subscribe\";\n /**\n * 事件:取消订阅\n */\n String MQ_EVENT_UNSUBSCRIBE = \"mq.event.unsubscribe\";\n /**\n * 事件:发布\n */\n String MQ_EVENT_PUBLISH = \"mq.event.publish\";\n /**\n * 事件:取消发布\n */\n String MQ_EVENT_UNPUBLISH = \"mq.event.unpublish\";\n /**\n * 事件:派发\n */\n String MQ_EVENT_DISTRIBUTE = \"mq.event.distribute\";\n /**\n * 事件:保存快照\n */\n String MQ_EVENT_SAVE = \"mq.event.save\";\n\n /**\n * 事件:加入集群\n * */\n String MQ_EVENT_JOIN = \"mq.event.join\";\n\n /**\n * 管理指令\n */\n String ADMIN_PREFIX = \"admin.\";\n\n /**\n * 管理视图-队列\n */\n String ADMIN_VIEW_QUEUE = \"admin.view.queue\";\n\n /**\n * 管理队列-强制删除\n */\n String ADMIN_QUEUE_FORCE_DELETE = \"admin.queue.force.delete\";\n /**\n * 管理队列-强制派发\n */\n String ADMIN_QUEUE_FORCE_DISTRIBUTE = \"admin.queue.force.distribute\";\n\n /**\n * 连接参数:ak\n */\n String PARAM_ACCESS_KEY = \"ak\";\n /**\n * 连接参数: sk\n */\n String PARAM_ACCESS_SECRET_KEY = \"sk\";\n\n /**\n * 主题与消息者间隔符\n */\n String SEPARATOR_TOPIC_CONSUMER_GROUP = \"#\";\n\n /**\n * 经理人服务\n */\n String BROKER_AT_SERVER = \"folkmq-server\";\n\n /**\n * 经理人所有服务\n */\n String BROKER_AT_SERVER_ALL = \"folkmq-server*\";\n\n /**\n * 最大分片大小(1m)\n */\n int MAX_FRAGMENT_SIZE = 1024 * 1024;\n}" } ]
import org.noear.folkmq.broker.admin.dso.LicenceUtils; import org.noear.folkmq.broker.admin.dso.ViewQueueService; import org.noear.folkmq.broker.admin.model.ServerVo; import org.noear.folkmq.broker.admin.model.TopicVo; import org.noear.folkmq.broker.mq.BrokerListenerFolkmq; import org.noear.folkmq.client.MqMessage; import org.noear.folkmq.common.MqConstants; import org.noear.snack.core.utils.DateUtil; import org.noear.socketd.transport.core.Session; import org.noear.socketd.transport.core.entity.StringEntity; import org.noear.solon.annotation.Controller; import org.noear.solon.annotation.Inject; import org.noear.solon.annotation.Mapping; import org.noear.solon.core.handle.ModelAndView; import org.noear.solon.core.handle.Result; import org.noear.solon.validation.annotation.Logined; import org.noear.solon.validation.annotation.NotEmpty; import org.noear.solon.validation.annotation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.*;
6,057
package org.noear.folkmq.broker.admin; /** * 管理控制器 * * @author noear * @since 1.0 */ @Logined @Valid @Controller public class AdminController extends BaseController { static final Logger log = LoggerFactory.getLogger(AdminController.class); @Inject BrokerListenerFolkmq brokerListener; @Inject ViewQueueService viewQueueService; @Mapping("/admin") public ModelAndView admin() { ModelAndView vm = view("admin"); vm.put("isValid", LicenceUtils.isValid()); if (LicenceUtils.isValid()) { switch (LicenceUtils.isAuthorized()) { case -1: vm.put("licenceBtn", "非法授权"); break; case 1: vm.put("licenceBtn", "正版授权"); break; default: vm.put("licenceBtn", "授权检测"); break; } } else { vm.put("licenceBtn", "非法授权"); } return vm; } @Mapping("/admin/licence") public ModelAndView licence() { ModelAndView vm = view("admin_licence"); vm.put("isAuthorized", false); if (LicenceUtils.isValid() == false) { vm.put("licence", "无效许可证(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); vm.put("checkBtnShow", false); } else { vm.put("licence", LicenceUtils.getLicence2()); if (LicenceUtils.isAuthorized() == 0) { vm.put("checkBtnShow", true); } else { vm.put("checkBtnShow", false); if (LicenceUtils.isAuthorized() == 1) { vm.put("isAuthorized", true); vm.put("subscribeDate", LicenceUtils.getSubscribeDate()); vm.put("subscribeMonths", LicenceUtils.getSubscribeMonths()); vm.put("consumer", LicenceUtils.getConsumer()); } else { vm.put("licence", "非法授权(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); } } } return vm; } @Mapping("/admin/licence/ajax/check") public Result licence_check() { if (LicenceUtils.isValid() == false) { return Result.failure(400, "无效许可证"); } return LicenceUtils.auth(); } @Mapping("/admin/topic") public ModelAndView topic() { Map<String, Set<String>> subscribeMap = brokerListener.getSubscribeMap();
package org.noear.folkmq.broker.admin; /** * 管理控制器 * * @author noear * @since 1.0 */ @Logined @Valid @Controller public class AdminController extends BaseController { static final Logger log = LoggerFactory.getLogger(AdminController.class); @Inject BrokerListenerFolkmq brokerListener; @Inject ViewQueueService viewQueueService; @Mapping("/admin") public ModelAndView admin() { ModelAndView vm = view("admin"); vm.put("isValid", LicenceUtils.isValid()); if (LicenceUtils.isValid()) { switch (LicenceUtils.isAuthorized()) { case -1: vm.put("licenceBtn", "非法授权"); break; case 1: vm.put("licenceBtn", "正版授权"); break; default: vm.put("licenceBtn", "授权检测"); break; } } else { vm.put("licenceBtn", "非法授权"); } return vm; } @Mapping("/admin/licence") public ModelAndView licence() { ModelAndView vm = view("admin_licence"); vm.put("isAuthorized", false); if (LicenceUtils.isValid() == false) { vm.put("licence", "无效许可证(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); vm.put("checkBtnShow", false); } else { vm.put("licence", LicenceUtils.getLicence2()); if (LicenceUtils.isAuthorized() == 0) { vm.put("checkBtnShow", true); } else { vm.put("checkBtnShow", false); if (LicenceUtils.isAuthorized() == 1) { vm.put("isAuthorized", true); vm.put("subscribeDate", LicenceUtils.getSubscribeDate()); vm.put("subscribeMonths", LicenceUtils.getSubscribeMonths()); vm.put("consumer", LicenceUtils.getConsumer()); } else { vm.put("licence", "非法授权(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); } } } return vm; } @Mapping("/admin/licence/ajax/check") public Result licence_check() { if (LicenceUtils.isValid() == false) { return Result.failure(400, "无效许可证"); } return LicenceUtils.auth(); } @Mapping("/admin/topic") public ModelAndView topic() { Map<String, Set<String>> subscribeMap = brokerListener.getSubscribeMap();
List<TopicVo> list = new ArrayList<>();
3
2023-11-18 19:09:28+00:00
8k
leluque/java2uml
src/main/java/br/com/luque/java2uml/plantuml/writer/classdiagram/PlantUMLWriter.java
[ { "identifier": "Rules", "path": "src/main/java/br/com/luque/java2uml/Rules.java", "snippet": "public class Rules {\n private final Set<String> packages;\n private final Set<String> classes;\n private final Set<String> ignorePackages;\n private final Set<String> ignoreClasses;\n\n public Rules() {\n this.packages = new HashSet<>();\n this.classes = new HashSet<>();\n this.ignorePackages = new HashSet<>();\n this.ignoreClasses = new HashSet<>();\n }\n\n public Rules addPackages(String... packagesName) {\n Objects.requireNonNull(packagesName);\n this.packages.addAll(Stream.of(packagesName).filter(p -> !p.isEmpty()).toList());\n return this;\n }\n\n public Rules addClasses(String... classesName) {\n Objects.requireNonNull(classesName);\n this.classes.addAll(Stream.of(classesName).filter(c -> !c.isEmpty()).toList());\n return this;\n }\n\n public Rules ignorePackages(String... packagesName) {\n Objects.requireNonNull(packagesName);\n this.ignorePackages.addAll(Stream.of(packagesName).filter(p -> !p.isEmpty()).toList());\n return this;\n }\n\n public Rules ignoreClasses(String... classesName) {\n Objects.requireNonNull(classesName);\n this.ignoreClasses.addAll(Stream.of(classesName).filter(c -> !c.isEmpty()).toList());\n return this;\n }\n\n public Set<String> getPackages() {\n return packages;\n }\n\n public Set<String> getClasses() {\n return classes;\n }\n\n public Set<String> getIgnorePackages() {\n return ignorePackages;\n }\n\n public Set<String> getIgnoreClasses() {\n return ignoreClasses;\n }\n\n public boolean includes(Class<?> originalClass) {\n return\n (\n packages.stream().anyMatch(p -> originalClass.getPackageName().startsWith(p)) ||\n classes.stream().anyMatch(c -> originalClass.getName().equals(c))\n ) &&\n (\n ignorePackages.stream().noneMatch(p -> originalClass.getPackageName().startsWith(p)) &&\n ignoreClasses.stream().noneMatch(c -> originalClass.getName().equals(c))\n );\n }\n}" }, { "identifier": "ClasspathSearcher", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/classsearch/ClasspathSearcher.java", "snippet": "public class ClasspathSearcher {\n private static final Logger logger = Logger.getLogger(ClasspathSearcher.class.getName());\n private final Rules rules;\n\n public ClasspathSearcher(Rules rules) {\n this.rules = Objects.requireNonNull(rules);\n }\n\n public Class<?>[] search() {\n return searchClasses();\n }\n\n private Class<?>[] searchClasses() {\n Set<Class<?>> classes = new HashSet<>();\n\n for (String qualifiedClassName : rules.getClasses()) {\n try {\n classes.add(Class.forName(qualifiedClassName));\n } catch (ClassNotFoundException e) {\n logger.warning(\"Class not found: \" + qualifiedClassName);\n }\n }\n\n for (String packageName : rules.getPackages()) {\n try {\n Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', '/'));\n while (resources.hasMoreElements()) {\n URL resource = resources.nextElement();\n\n classes.addAll(searchClassesRecursively(new File(resource.getPath()), packageName));\n }\n } catch (IOException e) {\n logger.warning(\"Package not found: \" + packageName);\n }\n }\n\n return classes.toArray(Class<?>[]::new);\n }\n\n private Collection<Class<?>> searchClassesRecursively(File folder, String packageName) {\n Objects.requireNonNull(folder);\n if (!folder.exists()) {\n return Collections.emptyList();\n } else if (!folder.isDirectory()) {\n throw new IllegalArgumentException(\"The folder must be a directory!\");\n }\n\n Set<Class<?>> classes = new HashSet<>();\n for (File child : Objects.requireNonNull(folder.listFiles())) {\n if (child.isDirectory()) {\n if (rules.getIgnorePackages().contains(packageName + \".\" + child.getName())) {\n continue;\n }\n\n classes.addAll(searchClassesRecursively(child, packageName + \".\" + child.getName()));\n } else if (child.getName().endsWith(\".class\")) {\n String qualifiedClassName = packageName + \".\" + child.getName().substring(0, child.getName().length() - \".class\".length());\n\n if (rules.getIgnoreClasses().contains(packageName + \".\" + qualifiedClassName)) {\n continue;\n }\n\n try {\n classes.add(Class.forName(qualifiedClassName));\n } catch (ClassNotFoundException e) {\n logger.warning(\"Class not found: \" + qualifiedClassName);\n }\n }\n }\n return classes;\n }\n}" }, { "identifier": "Clazz", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/Clazz.java", "snippet": "public abstract class Clazz extends BaseItem {\n private final Class<?> javaClass;\n private final boolean abstract_;\n private boolean interface_;\n\n public Clazz(Class<?> javaClass, ClazzPool clazzPool) {\n super(Objects.requireNonNull(javaClass).getSimpleName(), clazzPool);\n this.javaClass = javaClass;\n this.abstract_ = Modifier.isAbstract(javaClass.getModifiers());\n this.interface_ = javaClass.isInterface();\n }\n\n public Class<?> getJavaClass() {\n return javaClass;\n }\n\n public boolean isAbstract() {\n return abstract_;\n }\n\n public boolean isInterface() {\n return interface_;\n }\n\n public void setInterface(boolean interface_) {\n this.interface_ = interface_;\n }\n\n public void extractClassInfo() {\n }\n}" }, { "identifier": "ClazzPool", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/ClazzPool.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class ClazzPool {\n private final Rules rules;\n private final Map<Class<?>, Clazz> clazzMap;\n\n public ClazzPool(Rules rules) {\n this.rules = Objects.requireNonNull(rules);\n this.clazzMap = new HashMap<>();\n }\n\n public Clazz getFor(Class<?> originalClass) {\n Objects.requireNonNull(originalClass);\n if (clazzMap.containsKey(originalClass)) {\n return clazzMap.get(originalClass);\n }\n Clazz clazz;\n if (rules.includes(originalClass)) {\n clazz = new ScopedClazz(originalClass, this);\n } else {\n clazz = new UnscopedClazz(originalClass, this);\n }\n clazzMap.put(originalClass, clazz);\n clazz.extractClassInfo();\n return clazzMap.get(originalClass);\n }\n\n\n public Rules getRules() {\n return rules;\n }\n\n public Clazz[] getClazzes() {\n return clazzMap.values().toArray(new Clazz[0]);\n }\n\n public Clazz[] getScopedClazzes() {\n return clazzMap.values().stream().filter(c -> c instanceof ScopedClazz).toArray(Clazz[]::new);\n }\n}" }, { "identifier": "RelationshipField", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/RelationshipField.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class RelationshipField extends Field {\n public enum Cardinalities {\n ONE, N\n }\n\n private Cardinalities cardinality;\n\n public enum Variations {\n ASSOCIATION, AGGREGATION, COMPOSITION\n }\n\n private Variations variation;\n\n private Clazz otherSide;\n private String mappedBy;\n\n public RelationshipField(Clazz clazz, java.lang.reflect.Field field, ClazzPool clazzPool) {\n super(clazz, field, clazzPool);\n extractRelationshipInfo();\n }\n\n public Cardinalities getCardinality() {\n return cardinality;\n }\n\n public Variations getVariation() {\n return variation;\n }\n\n public void setVariation(Variations variation) {\n this.variation = Objects.requireNonNull(variation);\n }\n\n public Clazz getOtherSide() {\n return otherSide;\n }\n\n public String getMappedBy() {\n return mappedBy;\n }\n\n public boolean isMappedBy() {\n return null != mappedBy;\n }\n\n public boolean isAssociation() {\n return Variations.ASSOCIATION.equals(getVariation());\n }\n\n public boolean isAggregation() {\n return Variations.AGGREGATION.equals(getVariation());\n }\n\n public boolean isComposition() {\n return Variations.COMPOSITION.equals(getVariation());\n }\n\n public static boolean isRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (isOneRelationship(field, clazzPool)) {\n return true;\n }\n if (isPureArrayRelationship(field, clazzPool)) {\n return true;\n }\n return isGenericRelationship(field, clazzPool);\n }\n\n private static boolean isOneRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n return clazzPool.getRules().includes(field.getType());\n }\n\n private static boolean isPureArrayRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (!field.getType().isArray()) {\n return false;\n }\n\n return clazzPool.getRules().includes(extractArrayType(field, clazzPool));\n }\n\n private static boolean isCollectionRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n return field.getType().getPackageName().startsWith(\"java.util\");\n }\n\n private static boolean isGenericRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (!field.getType().getPackageName().startsWith(\"java.util\")) {\n return false;\n }\n\n return extractScopedGenerics(field, clazzPool).length > 0;\n }\n\n private static Class<?> extractArrayType(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (!field.getType().isArray()) {\n return null;\n }\n\n // Handle the case of arrays of arrays ...\n Class<?> componentType = field.getType().getComponentType();\n while (componentType.isArray()) {\n componentType = componentType.getComponentType();\n }\n return componentType;\n }\n\n private static Class<?>[] extractScopedGenerics(java.lang.reflect.Field field, ClazzPool clazzPool) {\n // Handle the case of arrays of arrays of collections ...\n Type genericFieldType = field.getGenericType();\n while (genericFieldType instanceof GenericArrayType) {\n genericFieldType = ((GenericArrayType) genericFieldType).getGenericComponentType();\n }\n\n List<Class<?>> scopedGenerics = new ArrayList<>();\n if (genericFieldType instanceof ParameterizedType) {\n ParameterizedType generics = (ParameterizedType) genericFieldType;\n Type[] typeArguments = generics.getActualTypeArguments();\n for (Type typeArgument : typeArguments) {\n if (typeArgument instanceof Class<?> originalClass\n && clazzPool.getRules().includes(originalClass)) {\n scopedGenerics.add(originalClass);\n }\n }\n }\n return scopedGenerics.toArray(new Class<?>[0]);\n }\n\n private void extractRelationshipInfo() {\n if (isPureArrayRelationship(getField(), getClazzPool())) {\n cardinality = Cardinalities.N;\n otherSide = getClazzPool().getFor(extractArrayType(getField(), getClazzPool()));\n } else if (isGenericRelationship(getField(), getClazzPool())) {\n cardinality = isCollectionRelationship(getField(), getClazzPool()) ? Cardinalities.N : Cardinalities.ONE;\n\n // TODO: handle multiple relationships (more than one generic in the scope).\n Class<?>[] scopedGenerics = extractScopedGenerics(getField(), getClazzPool());\n if (scopedGenerics.length > 0) {\n otherSide = getClazzPool().getFor(scopedGenerics[0]);\n }\n } else if (isOneRelationship(getField(), getClazzPool())) { // This one must go last because it doesn't check if it is array nor collection to avoid double check.\n cardinality = Cardinalities.ONE;\n otherSide = getClazzPool().getFor(getField().getType());\n }\n\n MappedBy mappedByAnnotation = getField().getAnnotation(MappedBy.class);\n if (null != mappedByAnnotation) {\n mappedBy = mappedByAnnotation.value();\n }\n\n setVariation(Variations.ASSOCIATION);\n Aggregation aggregationAnnotation = getField().getAnnotation(Aggregation.class);\n if (null != aggregationAnnotation) {\n setVariation(Variations.AGGREGATION);\n }\n Composition compositionAnnotation = getField().getAnnotation(Composition.class);\n if (null != compositionAnnotation) {\n setVariation(Variations.COMPOSITION);\n }\n }\n}" }, { "identifier": "ScopedClazz", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/ScopedClazz.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class ScopedClazz extends Clazz {\n private Clazz superclass;\n private Clazz[] interfaces;\n private Field[] fields;\n private Method[] methods;\n\n public ScopedClazz(Class<?> javaClass, ClazzPool clazzPool) {\n super(javaClass, clazzPool);\n }\n\n public void extractClassInfo() {\n extractSuperclass();\n extractInterfaces();\n fields = Stream.of(getJavaClass().getDeclaredFields()).map(f -> Field.from(this, f, getClazzPool())).toArray(Field[]::new);\n methods = Stream.concat(Stream.of(getJavaClass().getDeclaredMethods()).map(m -> new Method(m, getClazzPool())),\n Stream.of(getJavaClass().getDeclaredConstructors()).map(m -> new Method(m, getClazzPool()))).toArray(Method[]::new);\n }\n\n public void extractSuperclass() {\n if (null != getJavaClass().getSuperclass() && getClazzPool().getRules().includes(getJavaClass().getSuperclass())) {\n superclass = getClazzPool().getFor(getJavaClass().getSuperclass());\n }\n }\n\n public int countSuperclasses() {\n return hasSuperclass() ? 1 : 0;\n }\n\n public boolean hasSuperclass() {\n return superclass != null;\n }\n\n public Clazz getSuperclass() {\n return superclass;\n }\n\n\n public int countInterfaces() {\n return interfaces.length;\n }\n\n public void extractInterfaces() {\n interfaces = Stream.of(getJavaClass().getInterfaces()).filter(i -> getClazzPool().getRules().includes(i)).map(i -> getClazzPool().getFor(i)).toArray(Clazz[]::new);\n }\n\n public boolean hasInterfaces() {\n return getInterfaces() != null && getInterfaces().length > 0;\n }\n\n public Clazz[] getInterfaces() {\n return interfaces;\n }\n\n public int countFields() {\n return fields.length;\n }\n\n public int countMethods() {\n return methods.length;\n }\n\n public int countConstructors() {\n return Stream.of(methods).filter(Method::isConstructor).toArray().length;\n }\n\n public int countNonConstructorMethods() {\n return Stream.of(methods).filter(m -> !m.isConstructor()).toArray().length;\n }\n\n public int countRelationshipFields() {\n return Stream.of(fields).filter(f -> f instanceof RelationshipField).toArray().length;\n }\n\n public int countNonRelationshipFields() {\n return Stream.of(fields).filter(f -> !(f instanceof RelationshipField)).toArray().length;\n }\n\n public RelationshipField[] getRelationshipFields() {\n return Stream.of(fields).filter(f -> f instanceof RelationshipField).toArray(RelationshipField[]::new);\n }\n\n public Optional<RelationshipField> getRelationshipField(String fieldName) {\n if (null == fields) {\n return Optional.empty();\n }\n return Stream.of(fields).filter(f -> f instanceof RelationshipField).map(RelationshipField.class::cast).filter(f -> f.getName().equals(fieldName)).findFirst();\n }\n\n public Field[] getNonRelationshipFields() {\n return Stream.of(fields).filter(f -> !(f instanceof RelationshipField)).toArray(Field[]::new);\n }\n\n public Method[] getConstructors() {\n return Stream.of(methods).filter(Method::isConstructor).toArray(Method[]::new);\n }\n\n public Method[] getNonConstructorMethods() {\n return Stream.of(methods).filter(m -> !m.isConstructor()).toArray(Method[]::new);\n }\n\n public boolean hasConstructors() {\n return getNonConstructorMethods().length > 0;\n }\n\n public Clazz[] getDependencies() {\n return Stream.of(methods).flatMap(method -> Stream.of(method.getDependencies())).toArray(Clazz[]::new);\n }\n\n public boolean hasAssociationOfAnyTypeWith(Clazz other) {\n return Stream.of(getRelationshipFields()).anyMatch(f -> f.getOtherSide().equals(other));\n }\n\n}" } ]
import br.com.luque.java2uml.Rules; import br.com.luque.java2uml.core.classdiagram.classsearch.ClasspathSearcher; import br.com.luque.java2uml.core.classdiagram.reflection.model.Clazz; import br.com.luque.java2uml.core.classdiagram.reflection.model.ClazzPool; import br.com.luque.java2uml.core.classdiagram.reflection.model.RelationshipField; import br.com.luque.java2uml.core.classdiagram.reflection.model.ScopedClazz; import java.util.Objects;
4,154
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLWriter { public static String generateClassDiagramUsing(PlantUMLClassWriter classWriter, PlantUMLRelationshipWriter relationshipWriter, Rules rules) { Objects.requireNonNull(classWriter); Objects.requireNonNull(relationshipWriter); Objects.requireNonNull(rules);
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLWriter { public static String generateClassDiagramUsing(PlantUMLClassWriter classWriter, PlantUMLRelationshipWriter relationshipWriter, Rules rules) { Objects.requireNonNull(classWriter); Objects.requireNonNull(relationshipWriter); Objects.requireNonNull(rules);
ClasspathSearcher searcher = new ClasspathSearcher(rules);
1
2023-11-10 16:49:58+00:00
8k
javpower/JavaVision
src/main/java/com/github/javpower/javavision/detect/Yolov8sOnnxRuntimeDetect.java
[ { "identifier": "AbstractOnnxRuntimeTranslator", "path": "src/main/java/com/github/javpower/javavision/detect/translator/AbstractOnnxRuntimeTranslator.java", "snippet": "public abstract class AbstractOnnxRuntimeTranslator {\n\n public OrtEnvironment environment;\n public OrtSession session;\n public String[] labels;\n public float confThreshold;\n public float nmsThreshold;\n\n static {\n // 加载opencv动态库,\n //System.load(ClassLoader.getSystemResource(\"lib/opencv_java470-无用.dll\").getPath());\n nu.pattern.OpenCV.loadLocally();\n }\n\n\n public AbstractOnnxRuntimeTranslator(String modelPath, String[] labels, float confThreshold, float nmsThreshold) throws OrtException {\n this.environment = OrtEnvironment.getEnvironment();\n OrtSession.SessionOptions sessionOptions = new OrtSession.SessionOptions();\n this.session = environment.createSession(modelPath, sessionOptions);\n this.labels = labels;\n this.confThreshold = confThreshold;\n this.nmsThreshold = nmsThreshold;\n }\n\n public List<Detection> runOcr(String imagePath) throws OrtException {\n Mat image = loadImage(imagePath);\n preprocessImage(image);\n float[][] outputData = runInference(image);\n Map<Integer, List<float[]>> class2Bbox = postprocessOutput(outputData);\n return convertDetections(class2Bbox);\n }\n // 实现加载图像的逻辑\n protected abstract Mat loadImage(String imagePath);\n // 实现图像预处理的逻辑\n protected abstract void preprocessImage(Mat image);\n // 实现推理的逻辑\n protected abstract float[][] runInference(Mat image) throws OrtException;\n // 实现输出后处理的逻辑\n protected abstract Map<Integer, List<float[]>> postprocessOutput(float[][] outputData);\n\n protected float[][] transposeMatrix(float[][] m) {\n float[][] temp = new float[m[0].length][m.length];\n for (int i = 0; i < m.length; i++)\n for (int j = 0; j < m[0].length; j++)\n temp[j][i] = m[i][j];\n return temp;\n }\n\n protected List<Detection> convertDetections(Map<Integer, List<float[]>> class2Bbox) {\n // 将边界框信息转换为 Detection 对象的逻辑\n List<Detection> detections = new ArrayList<>();\n for (Map.Entry<Integer, List<float[]>> entry : class2Bbox.entrySet()) {\n int label = entry.getKey();\n List<float[]> bboxes = entry.getValue();\n bboxes = nonMaxSuppression(bboxes, nmsThreshold);\n for (float[] bbox : bboxes) {\n String labelString = labels[label];\n detections.add(new Detection(labelString,entry.getKey(), Arrays.copyOfRange(bbox, 0, 4), bbox[4]));\n }\n }\n return detections;\n }\n public static List<float[]> nonMaxSuppression(List<float[]> bboxes, float iouThreshold) {\n\n List<float[]> bestBboxes = new ArrayList<>();\n\n bboxes.sort(Comparator.comparing(a -> a[4]));\n\n while (!bboxes.isEmpty()) {\n float[] bestBbox = bboxes.remove(bboxes.size() - 1);\n bestBboxes.add(bestBbox);\n bboxes = bboxes.stream().filter(a -> computeIOU(a, bestBbox) < iouThreshold).collect(Collectors.toList());\n }\n\n return bestBboxes;\n }\n public static float computeIOU(float[] box1, float[] box2) {\n\n float area1 = (box1[2] - box1[0]) * (box1[3] - box1[1]);\n float area2 = (box2[2] - box2[0]) * (box2[3] - box2[1]);\n\n float left = Math.max(box1[0], box2[0]);\n float top = Math.max(box1[1], box2[1]);\n float right = Math.min(box1[2], box2[2]);\n float bottom = Math.min(box1[3], box2[3]);\n\n float interArea = Math.max(right - left, 0) * Math.max(bottom - top, 0);\n float unionArea = area1 + area2 - interArea;\n return Math.max(interArea / unionArea, 1e-8f);\n\n }\n}" }, { "identifier": "Letterbox", "path": "src/main/java/com/github/javpower/javavision/entity/Letterbox.java", "snippet": "public class Letterbox {\n\n private Size newShape = new Size(640, 640);\n private final double[] color = new double[]{114,114,114};\n private final Boolean auto = false;\n private final Boolean scaleUp = true;\n private Integer stride = 32;\n\n private double ratio;\n private double dw;\n private double dh;\n\n public double getRatio() {\n return ratio;\n }\n\n public double getDw() {\n return dw;\n }\n\n public Integer getWidth() {\n return (int) this.newShape.width;\n }\n\n public Integer getHeight() {\n return (int) this.newShape.height;\n }\n\n public double getDh() {\n return dh;\n }\n\n public void setNewShape(Size newShape) {\n this.newShape = newShape;\n }\n\n public void setStride(Integer stride) {\n this.stride = stride;\n }\n\n public Mat letterbox(Mat im) { // 调整图像大小和填充图像,使满足步长约束,并记录参数\n\n int[] shape = {im.rows(), im.cols()}; // 当前形状 [height, width]\n // Scale ratio (new / old)\n double r = Math.min(this.newShape.height / shape[0], this.newShape.width / shape[1]);\n if (!this.scaleUp) { // 仅缩小,不扩大(一且为了mAP)\n r = Math.min(r, 1.0);\n }\n // Compute padding\n Size newUnpad = new Size(Math.round(shape[1] * r), Math.round(shape[0] * r));\n double dw = this.newShape.width - newUnpad.width, dh = this.newShape.height - newUnpad.height; // wh 填充\n if (this.auto) { // 最小矩形\n dw = dw % this.stride;\n dh = dh % this.stride;\n }\n dw /= 2; // 填充的时候两边都填充一半,使图像居于中心\n dh /= 2;\n if (shape[1] != newUnpad.width || shape[0] != newUnpad.height) { // resize\n Imgproc.resize(im, im, newUnpad, 0, 0, Imgproc.INTER_LINEAR);\n }\n int top = (int) Math.round(dh - 0.1), bottom = (int) Math.round(dh + 0.1);\n int left = (int) Math.round(dw - 0.1), right = (int) Math.round(dw + 0.1);\n // 将图像填充为正方形\n Core.copyMakeBorder(im, im, top, bottom, left, right, Core.BORDER_CONSTANT, new org.opencv.core.Scalar(this.color));\n this.ratio = r;\n this.dh = dh;\n this.dw = dw;\n return im;\n }\n}" }, { "identifier": "JarFileUtils", "path": "src/main/java/com/github/javpower/javavision/util/JarFileUtils.java", "snippet": "public class JarFileUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(JarFileUtils.class);\n\n /**\n * 文件前缀的最小长度\n */\n private static final int MIN_PREFIX_LENGTH = 3;\n\n /**\n * 临时文件\n */\n private static File temporaryDir;\n\n private JarFileUtils() {\n }\n\n /**\n * 从jar包中复制文件\n * 先将jar包中的动态库复制到系统临时文件夹,如果需要加载会进行加载,并且在JVM退出时自动删除。\n *\n * @param path 要复制文件的路径,必须以'/'开始,比如 /lib/monster.so,必须以'/'开始\n * @param dirName 保存的文件夹名称,必须以'/'开始,可为null\n * @param loadClass 用于提供{@link ClassLoader}加载动态库的类,如果为null,则使用JarFileUtils.class\n * @param load 是否加载,有些文件只需要复制到临时文件夹,不需要加载\n * @param deleteOnExit 是否在JVM退出时删除临时文件\n * @throws IOException 动态库读写错误\n * @throws FileNotFoundException 没有在jar包中找到指定的文件\n */\n public static synchronized void copyFileFromJar(String path, String dirName, Class<?> loadClass, boolean load, boolean deleteOnExit) throws IOException {\n\n String filename = checkFileName(path);\n\n // 创建临时文件夹\n if (temporaryDir == null) {\n temporaryDir = createTempDirectory(dirName);\n temporaryDir.deleteOnExit();\n }\n // 临时文件夹下的动态库名\n File temp = new File(temporaryDir, filename);\n if (!temp.exists()) {\n Class<?> clazz = loadClass == null ? JarFileUtils.class : loadClass;\n // 从jar包中复制文件到系统临时文件夹\n try (InputStream is = clazz.getResourceAsStream(path)) {\n if (is != null) {\n Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);\n } else {\n throw new NullPointerException(\"文件 \" + path + \" 在JAR中未找到.\");\n }\n } catch (IOException e) {\n Files.delete(temp.toPath());\n throw e;\n } catch (NullPointerException e) {\n Files.delete(temp.toPath());\n throw new FileNotFoundException(\"文件 \" + path + \" 在JAR中未找到.\");\n }\n }\n // 加载临时文件夹中的动态库\n if (load) {\n System.load(temp.getAbsolutePath());\n }\n if (deleteOnExit) {\n // 设置在JVM结束时删除临时文件\n temp.deleteOnExit();\n }\n logger.debug(\"将文件{}复制到{},加载此文件:{},JVM退出时删除此文件:{}\", path, dirName, load, deleteOnExit);\n }\n\n /**\n * 检查文件名是否正确\n *\n * @param path 文件路径\n * @return 文件名\n * @throws IllegalArgumentException 路径必须以'/'开始、文件名必须至少有3个字符长\n */\n private static String checkFileName(String path) {\n if (null == path || !path.startsWith(\"/\")) {\n throw new IllegalArgumentException(\"路径必须以文件分隔符开始.\");\n }\n\n // 从路径获取文件名\n String[] parts = path.split(\"/\");\n String filename = (parts.length > 1) ? parts[parts.length - 1] : null;\n\n // 检查文件名是否正确\n if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {\n throw new IllegalArgumentException(\"文件名必须至少有3个字符长.\");\n }\n return filename;\n }\n\n /**\n * 从jar包中复制models文件夹下的内容\n *\n * @param modelPath 文件夹路径\n */\n public static void copyModelsFromJar(String modelPath, boolean isDelOnExit) throws IOException {\n String base = modelPath.endsWith(\"/\") ? modelPath : modelPath + \"/\";\n if (modelPath.contains(PathConstants.ONNX)) {\n for (final String path : PathConstants.MODEL_ONNX_FILE_ARRAY) {\n copyFileFromJar(base + path, PathConstants.ONNX, null, Boolean.FALSE, isDelOnExit);\n }\n } else {\n for (final String path : PathConstants.MODEL_NCNN_FILE_ARRAY) {\n copyFileFromJar(base + path, PathConstants.NCNN, null, Boolean.FALSE, isDelOnExit);\n }\n }\n\n }\n\n /**\n * 在系统临时文件夹下创建临时文件夹\n */\n private static File createTempDirectory(String dirName) throws IOException {\n File dir = new File(PathConstants.TEMP_DIR, dirName);\n if (!dir.exists() && !dir.mkdirs()) {\n throw new IOException(\"无法在临时目录创建文件\" + dir);\n }\n return dir;\n }\n}" }, { "identifier": "PathConstants", "path": "src/main/java/com/github/javpower/javavision/util/PathConstants.java", "snippet": "public class PathConstants {\n\n private PathConstants() {\n }\n\n public static final String TEMP_DIR = System.getProperty(\"java.io.tmpdir\") + \"ocrJava\";\n\n /**\n * 推理引擎\n */\n public static final String NCNN = \"/ncnn\";\n public static final String ONNX = \"/onnx\";\n\n /**\n * 模型相关\n **/\n public static final String MODEL_NCNN_PATH = NCNN + \"/models\";\n public static final String MODEL_ONNX_PATH = ONNX + \"/models\";\n public static final String MODEL_SUFFIX_BIN = \".bin\";\n public static final String MODEL_SUFFIX_PARAM = \".param\";\n public static final String MODEL_SUFFIX_ONNX = \".onnx\";\n /**\n * 文本检测模型,可选版本v3、v4,默认v4版本\n */\n public static final String MODEL_DET_NAME_V3 = \"ch_PP-OCRv3_det_infer\";\n public static final String MODEL_DET_NAME_V4 = \"ch_PP-OCRv4_det_infer\";\n /**\n * 文本识别模型,可选版本v3、v4,默认v4版本\n */\n public static final String MODEL_REC_NAME_V3= \"ch_PP-OCRv3_rec_infer\";\n public static final String MODEL_REC_NAME_V4 = \"ch_PP-OCRv4_rec_infer\";\n public static final String MODEL_CLS_NAME = \"ch_ppocr_mobile_v2.0_cls_infer\";\n public static final String MODEL_KEYS_NAME = \"ppocr_keys_v1.txt\";\n public static final String[] MODEL_NCNN_FILE_ARRAY = new String[]{\n MODEL_DET_NAME_V3 + MODEL_SUFFIX_BIN, MODEL_DET_NAME_V3 + MODEL_SUFFIX_PARAM, MODEL_REC_NAME_V3 + MODEL_SUFFIX_BIN,\n MODEL_REC_NAME_V3 + MODEL_SUFFIX_PARAM, MODEL_CLS_NAME + MODEL_SUFFIX_BIN, MODEL_CLS_NAME + MODEL_SUFFIX_PARAM,\n MODEL_KEYS_NAME\n };\n public static final String[] MODEL_ONNX_FILE_ARRAY = new String[]{\n MODEL_DET_NAME_V3 + MODEL_SUFFIX_ONNX, MODEL_REC_NAME_V4 + MODEL_SUFFIX_ONNX,\n MODEL_CLS_NAME + MODEL_SUFFIX_ONNX, MODEL_KEYS_NAME\n };\n\n /**\n * 动态库\n **/\n public static final String OS_WINDOWS_32 = \"/win/win32/RapidOcr.dll\";\n public static final String OS_WINDOWS_64 = \"/win/x86_64/RapidOcr.dll\";\n public static final String OS_MAC_SILICON = \"/mac/arm64/libRapidOcr.dylib\";\n public static final String OS_MAC_INTEL = \"/mac/x86_64/libRapidOcr.dylib\";\n public static final String OS_LINUX = \"/linux/libRapidOcr.so\";\n\n\n}" } ]
import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtSession; import com.github.javpower.javavision.detect.translator.AbstractOnnxRuntimeTranslator; import com.github.javpower.javavision.entity.Letterbox; import com.github.javpower.javavision.util.JarFileUtils; import com.github.javpower.javavision.util.PathConstants; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import java.io.IOException; import java.nio.FloatBuffer; import java.util.*;
4,115
package com.github.javpower.javavision.detect; public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator { public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException { super(modelPath, labels,confThreshold,nmsThreshold); } // 实现加载图像的逻辑 @Override protected Mat loadImage(String imagePath) { return Imgcodecs.imread(imagePath); } // 实现图像预处理的逻辑 @Override protected void preprocessImage(Mat image) { Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB); // 更改 image 尺寸及其他预处理逻辑 } // 实现推理的逻辑 @Override protected float[][] runInference(Mat image) throws OrtException {
package com.github.javpower.javavision.detect; public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator { public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException { super(modelPath, labels,confThreshold,nmsThreshold); } // 实现加载图像的逻辑 @Override protected Mat loadImage(String imagePath) { return Imgcodecs.imread(imagePath); } // 实现图像预处理的逻辑 @Override protected void preprocessImage(Mat image) { Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB); // 更改 image 尺寸及其他预处理逻辑 } // 实现推理的逻辑 @Override protected float[][] runInference(Mat image) throws OrtException {
Letterbox letterbox = new Letterbox();
1
2023-11-10 01:57:37+00:00
8k
feiniaojin/graceful-response-boot2
src/main/java/com/feiniaojin/gracefulresponse/AutoConfig.java
[ { "identifier": "GlobalExceptionAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/GlobalExceptionAdvice.java", "snippet": "@ControllerAdvice\n@Order(200)\npublic class GlobalExceptionAdvice implements ApplicationContextAware {\n\n private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);\n\n @Resource\n private ResponseStatusFactory responseStatusFactory;\n\n @Resource\n private ResponseFactory responseFactory;\n\n private ExceptionAliasRegister exceptionAliasRegister;\n\n @Resource\n private GracefulResponseProperties gracefulResponseProperties;\n\n @Resource\n private GracefulResponseProperties properties;\n\n /**\n * 异常处理逻辑.\n *\n * @param throwable 业务逻辑抛出的异常\n * @return 统一返回包装后的结果\n */\n @ExceptionHandler({Throwable.class})\n @ResponseBody\n public Response exceptionHandler(Throwable throwable) {\n if (gracefulResponseProperties.isPrintExceptionInGlobalAdvice()) {\n logger.error(\"Graceful Response:GlobalExceptionAdvice捕获到异常,message=[{}]\", throwable.getMessage(), throwable);\n }\n ResponseStatus statusLine;\n if (throwable instanceof GracefulResponseException) {\n statusLine = fromGracefulResponseExceptionInstance((GracefulResponseException) throwable);\n } else {\n //校验异常转自定义异常\n statusLine = fromExceptionInstance(throwable);\n }\n return responseFactory.newInstance(statusLine);\n }\n\n private ResponseStatus fromGracefulResponseExceptionInstance(GracefulResponseException exception) {\n String code = exception.getCode();\n if (code == null) {\n code = properties.getDefaultErrorCode();\n }\n return responseStatusFactory.newInstance(code,\n exception.getMsg());\n }\n\n private ResponseStatus fromExceptionInstance(Throwable throwable) {\n\n Class<? extends Throwable> clazz = throwable.getClass();\n\n ExceptionMapper exceptionMapper = clazz.getAnnotation(ExceptionMapper.class);\n\n //1.有@ExceptionMapper注解,直接设置结果的状态\n if (exceptionMapper != null) {\n boolean msgReplaceable = exceptionMapper.msgReplaceable();\n //异常提示可替换+抛出来的异常有自定义的异常信息\n if (msgReplaceable) {\n String throwableMessage = throwable.getMessage();\n if (throwableMessage != null) {\n return responseStatusFactory.newInstance(exceptionMapper.code(), throwableMessage);\n }\n }\n return responseStatusFactory.newInstance(exceptionMapper.code(),\n exceptionMapper.msg());\n }\n\n //2.有@ExceptionAliasFor异常别名注解,获取已注册的别名信息\n if (exceptionAliasRegister != null) {\n ExceptionAliasFor exceptionAliasFor = exceptionAliasRegister.getExceptionAliasFor(clazz);\n if (exceptionAliasFor != null) {\n return responseStatusFactory.newInstance(exceptionAliasFor.code(),\n exceptionAliasFor.msg());\n }\n }\n ResponseStatus defaultError = responseStatusFactory.defaultError();\n\n //3. 原生异常+originExceptionUsingDetailMessage=true\n //如果有自定义的异常信息,原生异常将直接使用异常信息进行返回,不再返回默认错误提示\n if (properties.getOriginExceptionUsingDetailMessage()) {\n String throwableMessage = throwable.getMessage();\n if (throwableMessage != null) {\n defaultError.setMsg(throwableMessage);\n }\n }\n return defaultError;\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.exceptionAliasRegister = applicationContext.getBean(ExceptionAliasRegister.class);\n }\n}" }, { "identifier": "NotVoidResponseBodyAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/NotVoidResponseBodyAdvice.java", "snippet": "@ControllerAdvice\n@Order(value = 1000)\npublic class NotVoidResponseBodyAdvice implements ResponseBodyAdvice<Object> {\n\n private final Logger logger = LoggerFactory.getLogger(NotVoidResponseBodyAdvice.class);\n\n @Resource\n private ResponseFactory responseFactory;\n @Resource\n private GracefulResponseProperties properties;\n\n /**\n * 路径过滤器\n */\n private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();\n\n /**\n * 只处理不返回void的,并且MappingJackson2HttpMessageConverter支持的类型.\n *\n * @param methodParameter 方法参数\n * @param clazz 处理器\n * @return 是否支持\n */\n @Override\n public boolean supports(MethodParameter methodParameter,\n Class<? extends HttpMessageConverter<?>> clazz) {\n Method method = methodParameter.getMethod();\n\n //method为空、返回值为void、非JSON,直接跳过\n if (Objects.isNull(method)\n || method.getReturnType().equals(Void.TYPE)\n || !MappingJackson2HttpMessageConverter.class.isAssignableFrom(clazz)) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Graceful Response:method为空、返回值为void、非JSON,跳过\");\n }\n return false;\n }\n\n //有ExcludeFromGracefulResponse注解修饰的,也跳过\n if (method.isAnnotationPresent(ExcludeFromGracefulResponse.class)) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Graceful Response:方法被@ExcludeFromGracefulResponse注解修饰,跳过:methodName={}\", method.getName());\n }\n return false;\n }\n\n //配置了例外包路径,则该路径下的controller都不再处理\n List<String> excludePackages = properties.getExcludePackages();\n if (!CollectionUtils.isEmpty(excludePackages)) {\n // 获取请求所在类的的包名\n String packageName = method.getDeclaringClass().getPackage().getName();\n if (excludePackages.stream().anyMatch(item -> ANT_PATH_MATCHER.match(item, packageName))) {\n logger.debug(\"Graceful Response:匹配到excludePackages例外配置,跳过:packageName={},\", packageName);\n return false;\n }\n }\n logger.debug(\"Graceful Response:非空返回值,需要进行封装\");\n return true;\n }\n\n @Override\n public Object beforeBodyWrite(Object body,\n MethodParameter methodParameter,\n MediaType mediaType,\n Class<? extends HttpMessageConverter<?>> clazz,\n ServerHttpRequest serverHttpRequest,\n ServerHttpResponse serverHttpResponse) {\n if (body == null) {\n return responseFactory.newSuccessInstance();\n } else if (body instanceof Response) {\n return body;\n } else {\n if (logger.isDebugEnabled()) {\n String path = serverHttpRequest.getURI().getPath();\n logger.debug(\"Graceful Response:非空返回值,执行封装:path={}\", path);\n }\n return responseFactory.newSuccessInstance(body);\n }\n }\n\n}" }, { "identifier": "ValidationExceptionAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/ValidationExceptionAdvice.java", "snippet": "@ControllerAdvice\n@Order(100)\npublic class ValidationExceptionAdvice {\n\n private final Logger logger = LoggerFactory.getLogger(ValidationExceptionAdvice.class);\n @Resource\n private RequestMappingHandlerMapping requestMappingHandlerMapping;\n\n @Resource\n private ResponseStatusFactory responseStatusFactory;\n\n @Resource\n private ResponseFactory responseFactory;\n\n @Resource\n private GracefulResponseProperties gracefulResponseProperties;\n\n @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})\n @ResponseBody\n public Response exceptionHandler(Exception e) throws Exception {\n\n if (e instanceof MethodArgumentNotValidException\n || e instanceof BindException) {\n ResponseStatus responseStatus = this.handleBindException((BindException) e);\n return responseFactory.newInstance(responseStatus);\n }\n\n if (e instanceof ConstraintViolationException) {\n ResponseStatus responseStatus = this.handleConstraintViolationException(e);\n return responseFactory.newInstance(responseStatus);\n }\n\n return responseFactory.newFailInstance();\n }\n\n //Controller方法的参数校验码\n //Controller方法>Controller类>DTO入参属性>DTO入参类>配置文件默认参数码>默认错误码\n private ResponseStatus handleBindException(BindException e) throws Exception {\n List<ObjectError> allErrors = e.getBindingResult().getAllErrors();\n String msg = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(\";\"));\n String code;\n //Controller方法上的注解\n ValidationStatusCode validateStatusCode = this.findValidationStatusCodeInController();\n if (validateStatusCode != null) {\n code = validateStatusCode.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n //属性校验上的注解,只会取第一个属性上的注解,因此要配置\n //hibernate.validator.fail_fast=true\n List<FieldError> fieldErrors = e.getFieldErrors();\n if (!CollectionUtils.isEmpty(fieldErrors)) {\n FieldError fieldError = fieldErrors.get(0);\n String fieldName = fieldError.getField();\n Object target = e.getTarget();\n Field field = null;\n Class<?> clazz = null;\n Object obj = target;\n if (fieldName.contains(\".\")) {\n String[] strings = fieldName.split(\"\\\\.\");\n for (String fName : strings) {\n clazz = obj.getClass();\n field = obj.getClass().getDeclaredField(fName);\n field.setAccessible(true);\n obj = field.get(obj);\n }\n } else {\n clazz = target.getClass();\n field = target.getClass().getDeclaredField(fieldName);\n }\n\n ValidationStatusCode annotation = field.getAnnotation(ValidationStatusCode.class);\n //属性上找到注解\n if (annotation != null) {\n code = annotation.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n //类上面找到注解\n annotation = clazz.getAnnotation(ValidationStatusCode.class);\n if (annotation != null) {\n code = annotation.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n }\n //默认的参数异常码\n code = gracefulResponseProperties.getDefaultValidateErrorCode();\n if (StringUtils.hasLength(code)) {\n return responseStatusFactory.newInstance(code, msg);\n }\n //默认的异常码\n code = gracefulResponseProperties.getDefaultErrorCode();\n return responseStatusFactory.newInstance(code, msg);\n }\n\n /**\n * 当前Controller方法\n *\n * @return\n * @throws Exception\n */\n private Method currentControllerMethod() throws Exception {\n RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();\n ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;\n HandlerExecutionChain handlerChain = requestMappingHandlerMapping.getHandler(sra.getRequest());\n assert handlerChain != null;\n HandlerMethod handler = (HandlerMethod) handlerChain.getHandler();\n return handler.getMethod();\n }\n\n private ResponseStatus handleConstraintViolationException(Exception e) throws Exception {\n\n ConstraintViolationException exception = (ConstraintViolationException) e;\n Set<ConstraintViolation<?>> violationSet = exception.getConstraintViolations();\n String msg = violationSet.stream().map(s -> s.getConstraintDescriptor().getMessageTemplate()).collect(Collectors.joining(\";\"));\n String code;\n ValidationStatusCode validationStatusCode = this.findValidationStatusCodeInController();\n if (validationStatusCode != null) {\n code = validationStatusCode.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n //默认的参数异常码\n code = gracefulResponseProperties.getDefaultValidateErrorCode();\n if (StringUtils.hasLength(code)) {\n return responseStatusFactory.newInstance(code, msg);\n }\n //默认的异常码\n code = gracefulResponseProperties.getDefaultErrorCode();\n return responseStatusFactory.newInstance(code, msg);\n }\n\n /**\n * 找Controller中的ValidationStatusCode注解\n * 当前方法->当前Controller类\n *\n * @return\n * @throws Exception\n */\n private ValidationStatusCode findValidationStatusCodeInController() throws Exception {\n Method method = this.currentControllerMethod();\n //Controller方法上的注解\n ValidationStatusCode validateStatusCode = method.getAnnotation(ValidationStatusCode.class);\n //Controller类上的注解\n if (validateStatusCode == null) {\n validateStatusCode = method.getDeclaringClass().getAnnotation(ValidationStatusCode.class);\n }\n return validateStatusCode;\n }\n}" }, { "identifier": "VoidResponseBodyAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/VoidResponseBodyAdvice.java", "snippet": "@ControllerAdvice\n@Order(value = 1000)\npublic class VoidResponseBodyAdvice implements ResponseBodyAdvice<Object> {\n\n private final Logger logger = LoggerFactory.getLogger(VoidResponseBodyAdvice.class);\n\n @Resource\n private ResponseFactory responseFactory;\n\n /**\n * 只处理返回空的Controller方法.\n *\n * @param methodParameter 返回类型\n * @param clazz 消息转换器\n * @return 是否对这种返回值进行处理\n */\n @Override\n public boolean supports(MethodParameter methodParameter,\n Class<? extends HttpMessageConverter<?>> clazz) {\n\n return Objects.requireNonNull(methodParameter.getMethod()).getReturnType().equals(Void.TYPE)\n && MappingJackson2HttpMessageConverter.class.isAssignableFrom(clazz);\n }\n\n @Override\n public Object beforeBodyWrite(Object body,\n MethodParameter returnType,\n MediaType selectedContentType,\n Class<? extends HttpMessageConverter<?>> selectedConverterType,\n ServerHttpRequest request,\n ServerHttpResponse response) {\n return responseFactory.newSuccessInstance();\n }\n}" }, { "identifier": "ResponseFactory", "path": "src/main/java/com/feiniaojin/gracefulresponse/api/ResponseFactory.java", "snippet": "public interface ResponseFactory {\n\n\n /**\n * 创建新的空响应.\n *\n * @return\n */\n Response newEmptyInstance();\n\n /**\n * 创建新的空响应.\n *\n * @param statusLine 响应行信息.\n * @return\n */\n Response newInstance(ResponseStatus statusLine);\n\n /**\n * 创建新的响应.\n *\n * @return\n */\n Response newSuccessInstance();\n\n /**\n * 从数据中创建成功响应.\n *\n * @param data 响应数据.\n * @return\n */\n Response newSuccessInstance(Object data);\n\n /**\n * 创建新的失败响应.\n *\n * @return\n */\n Response newFailInstance();\n\n}" }, { "identifier": "ResponseStatusFactory", "path": "src/main/java/com/feiniaojin/gracefulresponse/api/ResponseStatusFactory.java", "snippet": "public interface ResponseStatusFactory {\n /**\n * 获得响应成功的ResponseMeta.\n *\n * @return\n */\n ResponseStatus defaultSuccess();\n\n /**\n * 获得失败的ResponseMeta.\n *\n * @return\n */\n ResponseStatus defaultError();\n\n\n /**\n * 从code和msg创建ResponseStatus\n * @param code\n * @param msg\n * @return\n */\n ResponseStatus newInstance(String code,String msg);\n\n}" }, { "identifier": "DefaultResponseFactory", "path": "src/main/java/com/feiniaojin/gracefulresponse/defaults/DefaultResponseFactory.java", "snippet": "public class DefaultResponseFactory implements ResponseFactory {\n\n private final Logger logger = LoggerFactory.getLogger(DefaultResponseFactory.class);\n\n private static final Integer RESPONSE_STYLE_0 = 0;\n\n private static final Integer RESPONSE_STYLE_1 = 1;\n\n @Resource\n private ResponseStatusFactory responseStatusFactory;\n\n @Resource\n private GracefulResponseProperties properties;\n\n @Override\n public Response newEmptyInstance() {\n try {\n String responseClassFullName = properties.getResponseClassFullName();\n\n //配置了Response的全限定名,即自定义了Response,用配置的进行返回\n if (StringUtils.hasLength(responseClassFullName)) {\n Object newInstance = Class.forName(responseClassFullName).newInstance();\n return (Response) newInstance;\n } else {\n //没有配Response的全限定名,则创建DefaultResponse\n return generateDefaultResponse();\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private Response generateDefaultResponse() {\n Integer responseStyle = properties.getResponseStyle();\n if (Objects.isNull(responseStyle) || RESPONSE_STYLE_0.equals(responseStyle)) {\n return new DefaultResponseImplStyle0();\n } else if (RESPONSE_STYLE_1.equals(responseStyle)) {\n return new DefaultResponseImplStyle1();\n } else {\n logger.error(\"不支持的Response style类型,responseStyle={}\", responseStyle);\n throw new IllegalArgumentException(\"不支持的Response style类型\");\n }\n }\n\n @Override\n public Response newInstance(ResponseStatus responseStatus) {\n Response bean = this.newEmptyInstance();\n bean.setStatus(responseStatus);\n return bean;\n }\n\n @Override\n public Response newSuccessInstance() {\n Response emptyInstance = this.newEmptyInstance();\n emptyInstance.setStatus(responseStatusFactory.defaultSuccess());\n return emptyInstance;\n }\n\n @Override\n public Response newSuccessInstance(Object payload) {\n Response bean = this.newSuccessInstance();\n bean.setPayload(payload);\n return bean;\n }\n\n @Override\n public Response newFailInstance() {\n Response bean = this.newEmptyInstance();\n bean.setStatus(responseStatusFactory.defaultError());\n return bean;\n }\n\n}" }, { "identifier": "DefaultResponseStatusFactoryImpl", "path": "src/main/java/com/feiniaojin/gracefulresponse/defaults/DefaultResponseStatusFactoryImpl.java", "snippet": "public class DefaultResponseStatusFactoryImpl implements ResponseStatusFactory {\n\n @Resource\n private GracefulResponseProperties properties;\n\n @Override\n public ResponseStatus defaultSuccess() {\n\n DefaultResponseStatus defaultResponseStatus = new DefaultResponseStatus();\n defaultResponseStatus.setCode(properties.getDefaultSuccessCode());\n defaultResponseStatus.setMsg(properties.getDefaultSuccessMsg());\n return defaultResponseStatus;\n }\n\n @Override\n public ResponseStatus defaultError() {\n DefaultResponseStatus defaultResponseStatus = new DefaultResponseStatus();\n defaultResponseStatus.setCode(properties.getDefaultErrorCode());\n defaultResponseStatus.setMsg(properties.getDefaultErrorMsg());\n return defaultResponseStatus;\n }\n\n @Override\n public ResponseStatus newInstance(String code, String msg) {\n return new DefaultResponseStatus(code, msg);\n }\n}" } ]
import com.feiniaojin.gracefulresponse.advice.GlobalExceptionAdvice; import com.feiniaojin.gracefulresponse.advice.NotVoidResponseBodyAdvice; import com.feiniaojin.gracefulresponse.advice.ValidationExceptionAdvice; import com.feiniaojin.gracefulresponse.advice.VoidResponseBodyAdvice; import com.feiniaojin.gracefulresponse.api.ResponseFactory; import com.feiniaojin.gracefulresponse.api.ResponseStatusFactory; import com.feiniaojin.gracefulresponse.defaults.DefaultResponseFactory; import com.feiniaojin.gracefulresponse.defaults.DefaultResponseStatusFactoryImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
4,677
package com.feiniaojin.gracefulresponse; /** * 全局返回值处理的自动配置. * * @author <a href="mailto:[email protected]">Yujie</a> * @version 0.1 * @since 0.1 */ @Configuration @EnableConfigurationProperties(GracefulResponseProperties.class) public class AutoConfig { @Bean @ConditionalOnMissingBean(value = GlobalExceptionAdvice.class) public GlobalExceptionAdvice globalExceptionAdvice() { return new GlobalExceptionAdvice(); } @Bean @ConditionalOnMissingBean(value = ValidationExceptionAdvice.class) public ValidationExceptionAdvice validationExceptionAdvice() { return new ValidationExceptionAdvice(); } @Bean
package com.feiniaojin.gracefulresponse; /** * 全局返回值处理的自动配置. * * @author <a href="mailto:[email protected]">Yujie</a> * @version 0.1 * @since 0.1 */ @Configuration @EnableConfigurationProperties(GracefulResponseProperties.class) public class AutoConfig { @Bean @ConditionalOnMissingBean(value = GlobalExceptionAdvice.class) public GlobalExceptionAdvice globalExceptionAdvice() { return new GlobalExceptionAdvice(); } @Bean @ConditionalOnMissingBean(value = ValidationExceptionAdvice.class) public ValidationExceptionAdvice validationExceptionAdvice() { return new ValidationExceptionAdvice(); } @Bean
@ConditionalOnMissingBean(NotVoidResponseBodyAdvice.class)
1
2023-11-15 10:54:19+00:00
8k
innogames/flink-real-time-crm
src/main/java/com/innogames/analytics/rtcrm/App.java
[ { "identifier": "Config", "path": "src/main/java/com/innogames/analytics/rtcrm/config/Config.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Config {\n\n\tprivate int defaultParallelism;\n\tprivate int checkpointInterval;\n\tprivate String checkpointDir;\n\tprivate String kafkaBootstrapServers;\n\tprivate String kafkaGroupId;\n\tprivate String eventTopic;\n\tprivate String campaignTopic;\n\tprivate String triggerTopic;\n\n\tpublic Config() {\n\t}\n\n\tpublic int getDefaultParallelism() {\n\t\treturn defaultParallelism;\n\t}\n\n\tpublic void setDefaultParallelism(final int defaultParallelism) {\n\t\tthis.defaultParallelism = defaultParallelism;\n\t}\n\n\tpublic int getCheckpointInterval() {\n\t\treturn checkpointInterval;\n\t}\n\n\tpublic void setCheckpointInterval(final int checkpointInterval) {\n\t\tthis.checkpointInterval = checkpointInterval;\n\t}\n\n\tpublic String getCheckpointDir() {\n\t\treturn checkpointDir;\n\t}\n\n\tpublic void setCheckpointDir(final String checkpointDir) {\n\t\tthis.checkpointDir = checkpointDir;\n\t}\n\n\tpublic String getKafkaBootstrapServers() {\n\t\treturn kafkaBootstrapServers;\n\t}\n\n\tpublic void setKafkaBootstrapServers(final String kafkaBootstrapServers) {\n\t\tthis.kafkaBootstrapServers = kafkaBootstrapServers;\n\t}\n\n\tpublic String getEventTopic() {\n\t\treturn eventTopic;\n\t}\n\n\tpublic void setEventTopic(final String eventTopic) {\n\t\tthis.eventTopic = eventTopic;\n\t}\n\n\tpublic String getKafkaGroupId() {\n\t\treturn kafkaGroupId;\n\t}\n\n\tpublic void setKafkaGroupId(final String kafkaGroupId) {\n\t\tthis.kafkaGroupId = kafkaGroupId;\n\t}\n\n\tpublic String getCampaignTopic() {\n\t\treturn campaignTopic;\n\t}\n\n\tpublic void setCampaignTopic(final String campaignTopic) {\n\t\tthis.campaignTopic = campaignTopic;\n\t}\n\n\tpublic String getTriggerTopic() {\n\t\treturn triggerTopic;\n\t}\n\n\tpublic void setTriggerTopic(final String triggerTopic) {\n\t\tthis.triggerTopic = triggerTopic;\n\t}\n\n}" }, { "identifier": "Campaign", "path": "src/main/java/com/innogames/analytics/rtcrm/entity/Campaign.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Campaign {\n\n\tprivate int campaignId;\n\tprivate boolean enabled;\n\tprivate String game;\n\tprivate String eventName;\n\tprivate String startDate;\n\tprivate String endDate;\n\tprivate String filter;\n\n\t@JsonIgnore\n\tprivate transient JSObject filterFunction;\n\n\tpublic Campaign() {\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\n\tpublic void setEnabled(final boolean enabled) {\n\t\tthis.enabled = enabled;\n\t}\n\n\tpublic int getCampaignId() {\n\t\treturn campaignId;\n\t}\n\n\tpublic void setCampaignId(final int campaignId) {\n\t\tthis.campaignId = campaignId;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tpublic void setStartDate(final String startDate) {\n\t\tthis.startDate = startDate;\n\t}\n\n\tpublic String getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tpublic void setEndDate(final String endDate) {\n\t\tthis.endDate = endDate;\n\t}\n\n\tpublic String getFilter() {\n\t\treturn filter;\n\t}\n\n\tpublic void setFilter(final String filter) {\n\t\tthis.filter = filter;\n\t}\n\n\tpublic JSObject getFilterFunction() throws ScriptException {\n\t\tif (filterFunction == null) {\n\t\t\tfilterFunction = (JSObject) NashornEngine.getInstance().eval(getFilter());\n\t\t}\n\n\t\treturn filterFunction;\n\t}\n\n}" }, { "identifier": "TrackingEvent", "path": "src/main/java/com/innogames/analytics/rtcrm/entity/TrackingEvent.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class TrackingEvent {\n\n\tprivate String schemaVersion;\n\tprivate String eventId;\n\tprivate String systemType;\n\tprivate String systemName;\n\tprivate String game;\n\tprivate String market;\n\tprivate Integer playerId;\n\tprivate String eventType;\n\tprivate String eventName;\n\tprivate String eventScope;\n\tprivate String createdAt;\n\tprivate String receivedAt;\n\tprivate String hostname;\n\n\tprivate Map<String, Object> context;\n\n\tprivate Map<String, Object> data;\n\n\tpublic TrackingEvent() {\n\t}\n\n\tpublic String getSchemaVersion() {\n\t\treturn schemaVersion;\n\t}\n\n\tpublic void setSchemaVersion(final String schemaVersion) {\n\t\tthis.schemaVersion = schemaVersion;\n\t}\n\n\tpublic String getEventId() {\n\t\treturn eventId;\n\t}\n\n\tpublic void setEventId(final String eventId) {\n\t\tthis.eventId = eventId;\n\t}\n\n\tpublic String getSystemType() {\n\t\treturn systemType;\n\t}\n\n\tpublic void setSystemType(final String systemType) {\n\t\tthis.systemType = systemType;\n\t}\n\n\tpublic String getSystemName() {\n\t\treturn systemName;\n\t}\n\n\tpublic void setSystemName(final String systemName) {\n\t\tthis.systemName = systemName;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getMarket() {\n\t\treturn market;\n\t}\n\n\tpublic void setMarket(final String market) {\n\t\tthis.market = market;\n\t}\n\n\tpublic Integer getPlayerId() {\n\t\treturn playerId;\n\t}\n\n\tpublic void setPlayerId(final Integer playerId) {\n\t\tthis.playerId = playerId;\n\t}\n\n\tpublic String getEventType() {\n\t\treturn eventType;\n\t}\n\n\tpublic void setEventType(final String eventType) {\n\t\tthis.eventType = eventType;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getEventScope() {\n\t\treturn eventScope;\n\t}\n\n\tpublic void setEventScope(final String eventScope) {\n\t\tthis.eventScope = eventScope;\n\t}\n\n\tpublic String getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(final String createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic String getReceivedAt() {\n\t\treturn receivedAt;\n\t}\n\n\tpublic void setReceivedAt(final String receivedAt) {\n\t\tthis.receivedAt = receivedAt;\n\t}\n\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic void setHostname(final String hostname) {\n\t\tthis.hostname = hostname;\n\t}\n\n\tpublic Map<String, Object> getContext() {\n\t\treturn context;\n\t}\n\n\tpublic void setContext(final Map<String, Object> context) {\n\t\tthis.context = context;\n\t}\n\n\tpublic Map<String, Object> getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(final Map<String, Object> data) {\n\t\tthis.data = data;\n\t}\n\n}" }, { "identifier": "EvaluateFilter", "path": "src/main/java/com/innogames/analytics/rtcrm/function/EvaluateFilter.java", "snippet": "public class EvaluateFilter extends BroadcastProcessFunction<TrackingEvent, Campaign, Tuple2<TrackingEvent, Campaign>> {\n\n\t@Override\n\tpublic void processElement(\n\t\tfinal TrackingEvent event,\n\t\tfinal ReadOnlyContext readOnlyContext,\n\t\tfinal Collector<Tuple2<TrackingEvent, Campaign>> collector\n\t) throws Exception {\n\t\tif (event == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfinal Instant now = Instant.now();\n\t\tfinal Iterable<Map.Entry<Integer, Campaign>> campaignState = readOnlyContext.getBroadcastState(App.CAMPAIGN_STATE_DESCRIPTOR).immutableEntries();\n\t\tfinal Stream<Campaign> campaigns = StreamSupport.stream(\n\t\t\tcampaignState.spliterator(),\n\t\t\tfalse\n\t\t).map(Map.Entry::getValue);\n\n\t\tcampaigns\n\t\t\t.filter(Campaign::isEnabled)\n\t\t\t.filter(crmCampaign -> crmCampaign.getGame().equals(event.getGame()))\n\t\t\t.filter(crmCampaign -> crmCampaign.getEventName().equals(event.getEventName()))\n\t\t\t.filter(crmCampaign -> crmCampaign.getStartDate() != null && now.isAfter(Instant.parse(crmCampaign.getStartDate())))\n\t\t\t.filter(crmCampaign -> crmCampaign.getEndDate() != null && now.isBefore(Instant.parse(crmCampaign.getEndDate())))\n\t\t\t.filter(crmCampaign -> evaluateScriptResult(evaluateScript(crmCampaign, event)))\n\t\t\t.map(crmCampaign -> new Tuple2<>(event, crmCampaign))\n\t\t\t.forEach(collector::collect);\n\t}\n\n\t@Override\n\tpublic void processBroadcastElement(\n\t\tfinal Campaign campaign,\n\t\tfinal Context context,\n\t\tfinal Collector<Tuple2<TrackingEvent, Campaign>> collector\n\t) throws Exception {\n\t\tif (campaign == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tcontext.getBroadcastState(App.CAMPAIGN_STATE_DESCRIPTOR).put(campaign.getCampaignId(), campaign);\n\t}\n\n\tprivate Object evaluateScript(final Campaign campaign, final TrackingEvent event) {\n\t\ttry {\n\t\t\tfinal JSObject filterFunction = campaign.getFilterFunction();\n\t\t\treturn filterFunction.call(null, event);\n\t\t} catch (final Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate boolean evaluateScriptResult(final Object result) {\n\t\tif (result instanceof Boolean) {\n\t\t\treturn (boolean) result;\n\t\t} else if (ScriptObjectMirror.isUndefined(result)) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n}" }, { "identifier": "StringToCampaign", "path": "src/main/java/com/innogames/analytics/rtcrm/map/StringToCampaign.java", "snippet": "public class StringToCampaign implements MapFunction<String, Campaign> {\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\t@Override\n\tpublic Campaign map(final String campaignString) {\n\t\ttry {\n\t\t\treturn objectMapper.readValue(campaignString, Campaign.class);\n\t\t} catch (final JsonProcessingException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" }, { "identifier": "StringToTrackingEvent", "path": "src/main/java/com/innogames/analytics/rtcrm/map/StringToTrackingEvent.java", "snippet": "public class StringToTrackingEvent implements MapFunction<String, TrackingEvent> {\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\t@Override\n\tpublic TrackingEvent map(final String eventString) {\n\t\ttry {\n\t\t\treturn objectMapper.readValue(eventString, TrackingEvent.class);\n\t\t} catch (final JsonProcessingException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" }, { "identifier": "TriggerCampaignSink", "path": "src/main/java/com/innogames/analytics/rtcrm/sink/TriggerCampaignSink.java", "snippet": "public class TriggerCampaignSink extends RichSinkFunction<Tuple2<TrackingEvent, Campaign>> {\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\tprivate transient StringProducer stringProducer;\n\tprivate String triggerTopic;\n\n\t@Override\n\tpublic void open(Configuration configuration) {\n\t\tfinal ParameterTool parameters = (ParameterTool) getRuntimeContext().getExecutionConfig().getGlobalJobParameters();\n\n\t\ttriggerTopic = parameters.getRequired(\"trigger_topic\");\n\n\t\tfinal String kafkaBootstrapServers = parameters.getRequired(\"kafka_bootstrap_servers\");\n\t\tfinal Properties properties = new Properties();\n\t\tproperties.put(\"bootstrap.servers\", kafkaBootstrapServers);\n\n\t\tstringProducer = new StringProducer(properties);\n\t\tstringProducer.start();\n\t}\n\n\t@Override\n\tpublic void invoke(final Tuple2<TrackingEvent, Campaign> tuple, final Context context) throws Exception {\n\t\tfinal TrackingEvent event = tuple.f0;\n\t\tfinal Campaign campaign = tuple.f1;\n\n\t\tstringProducer.send(triggerTopic, objectMapper.writeValueAsString(new Trigger(campaign, event)));\n\t\tstringProducer.flush();\n\t}\n\n\t@Override\n\tpublic void close() throws Exception {\n\t\tsuper.close();\n\t\tstringProducer.stop();\n\t}\n\n}" } ]
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.innogames.analytics.rtcrm.config.Config; import com.innogames.analytics.rtcrm.entity.Campaign; import com.innogames.analytics.rtcrm.entity.TrackingEvent; import com.innogames.analytics.rtcrm.function.EvaluateFilter; import com.innogames.analytics.rtcrm.map.StringToCampaign; import com.innogames.analytics.rtcrm.map.StringToTrackingEvent; import com.innogames.analytics.rtcrm.sink.TriggerCampaignSink; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.common.state.MapStateDescriptor; import org.apache.flink.api.common.time.Time; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; 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.BroadcastStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
4,104
package com.innogames.analytics.rtcrm; public class App { // pass config path via parameter or use config from resources as default private static final String configParameter = "config"; private static final String configResource = "config.json"; // state key: campaign ID // state value: campaign definition public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>( "CampaignState", BasicTypeInfo.INT_TYPE_INFO, TypeInformation.of(new TypeHint<>() {}) ); public static void main(String[] args) throws Exception { // 1 - parse config final ParameterTool parameterTool = ParameterTool.fromArgs(args); final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); // 2 - create local env with web UI enabled, use StreamExecutionEnvironment.getExecutionEnvironment() for deployment final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration()); // 3 - make config variables available to functions env.getConfig().setGlobalJobParameters(ParameterTool.fromMap(Map.of( "kafka_bootstrap_servers", config.getKafkaBootstrapServers(), "trigger_topic", config.getTriggerTopic() ))); // 4 - configure env env.setParallelism(config.getDefaultParallelism()); env.setRestartStrategy(RestartStrategies.fixedDelayRestart( 6, // number of restart attempts Time.of(10, TimeUnit.SECONDS) // delay )); // Checkpoints are a mechanism to recover from failures only(!) env.enableCheckpointing(config.getCheckpointInterval()); // If a checkpoint directory is configured FileSystemCheckpointStorage will be used, // otherwise the system will use the JobManagerCheckpointStorage env.getCheckpointConfig().setCheckpointStorage(config.getCheckpointDir()); // Checkpoint state is kept when the owning job is cancelled or fails env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); // 5 - create and prepare streams final String kafkaBootstrapServers = config.getKafkaBootstrapServers(); final String kafkaGroupId = config.getKafkaGroupId(); final String eventTopic = config.getEventTopic(); final String campaignTopic = config.getCampaignTopic(); // 5.1 - broadcast stream for campaigns, without group ID to always consume all data from topic final KafkaSource<String> campaignSource = buildKafkaSource(kafkaBootstrapServers, campaignTopic, OffsetsInitializer.earliest()); final BroadcastStream<Campaign> campaignStream = env.fromSource(campaignSource, WatermarkStrategy.noWatermarks(), campaignTopic) .setParallelism(1).name("campaign-stream") .map(new StringToCampaign()).setParallelism(1).name("parse-campaign") .broadcast(CAMPAIGN_STATE_DESCRIPTOR); // 5.2 - main stream for events, use group ID to resume reading from topic final KafkaSource<String> eventSource = buildKafkaSource(kafkaBootstrapServers, eventTopic, kafkaGroupId); final SingleOutputStreamOperator<TrackingEvent> eventStream = env.fromSource(eventSource, WatermarkStrategy.noWatermarks(), eventTopic) .map(new StringToTrackingEvent()).name("parse-event"); // 6 - create and run pipeline eventStream .connect(campaignStream) .process(new EvaluateFilter()).name("evaluate-filter")
package com.innogames.analytics.rtcrm; public class App { // pass config path via parameter or use config from resources as default private static final String configParameter = "config"; private static final String configResource = "config.json"; // state key: campaign ID // state value: campaign definition public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>( "CampaignState", BasicTypeInfo.INT_TYPE_INFO, TypeInformation.of(new TypeHint<>() {}) ); public static void main(String[] args) throws Exception { // 1 - parse config final ParameterTool parameterTool = ParameterTool.fromArgs(args); final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); // 2 - create local env with web UI enabled, use StreamExecutionEnvironment.getExecutionEnvironment() for deployment final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration()); // 3 - make config variables available to functions env.getConfig().setGlobalJobParameters(ParameterTool.fromMap(Map.of( "kafka_bootstrap_servers", config.getKafkaBootstrapServers(), "trigger_topic", config.getTriggerTopic() ))); // 4 - configure env env.setParallelism(config.getDefaultParallelism()); env.setRestartStrategy(RestartStrategies.fixedDelayRestart( 6, // number of restart attempts Time.of(10, TimeUnit.SECONDS) // delay )); // Checkpoints are a mechanism to recover from failures only(!) env.enableCheckpointing(config.getCheckpointInterval()); // If a checkpoint directory is configured FileSystemCheckpointStorage will be used, // otherwise the system will use the JobManagerCheckpointStorage env.getCheckpointConfig().setCheckpointStorage(config.getCheckpointDir()); // Checkpoint state is kept when the owning job is cancelled or fails env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); // 5 - create and prepare streams final String kafkaBootstrapServers = config.getKafkaBootstrapServers(); final String kafkaGroupId = config.getKafkaGroupId(); final String eventTopic = config.getEventTopic(); final String campaignTopic = config.getCampaignTopic(); // 5.1 - broadcast stream for campaigns, without group ID to always consume all data from topic final KafkaSource<String> campaignSource = buildKafkaSource(kafkaBootstrapServers, campaignTopic, OffsetsInitializer.earliest()); final BroadcastStream<Campaign> campaignStream = env.fromSource(campaignSource, WatermarkStrategy.noWatermarks(), campaignTopic) .setParallelism(1).name("campaign-stream") .map(new StringToCampaign()).setParallelism(1).name("parse-campaign") .broadcast(CAMPAIGN_STATE_DESCRIPTOR); // 5.2 - main stream for events, use group ID to resume reading from topic final KafkaSource<String> eventSource = buildKafkaSource(kafkaBootstrapServers, eventTopic, kafkaGroupId); final SingleOutputStreamOperator<TrackingEvent> eventStream = env.fromSource(eventSource, WatermarkStrategy.noWatermarks(), eventTopic) .map(new StringToTrackingEvent()).name("parse-event"); // 6 - create and run pipeline eventStream .connect(campaignStream) .process(new EvaluateFilter()).name("evaluate-filter")
.addSink(new TriggerCampaignSink()).name("trigger-campaign");
6
2023-11-12 17:52:45+00:00
8k
BlyznytsiaOrg/bring
core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/BeanCreator.java
[ { "identifier": "ClassPathScannerFactory", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/scaner/ClassPathScannerFactory.java", "snippet": "@Slf4j\npublic class ClassPathScannerFactory {\n\n private final List<ClassPathScanner> classPathScanners;\n private final List<AnnotationResolver> annotationResolvers;\n\n // List of annotations indicating beans created by the scanning process.\n @Getter\n private final List<Class<? extends Annotation>> createdBeanAnnotations;\n\n /**\n * Constructs the ClassPathScannerFactory with reflections for initializing scanners and resolvers.\n *\n * @param reflections The Reflections instance used for scanning and resolving annotations.\n */\n public ClassPathScannerFactory(Reflections reflections) {\n // Retrieve and initialize ClassPathScanner implementations.\n this.classPathScanners = reflections.getSubTypesOf(ClassPathScanner.class)\n .stream()\n .filter(clazz -> clazz.isAnnotationPresent(BeanProcessor.class))\n .sorted(ORDER_COMPARATOR)\n .map(clazz -> clazz.cast(getConstructorWithOneParameter(clazz, Reflections.class, reflections)))\n .collect(Collectors.toList());\n\n // Retrieve and initialize AnnotationResolver implementations.\n this.annotationResolvers = reflections.getSubTypesOf(AnnotationResolver.class)\n .stream()\n .filter(clazz -> clazz.isAnnotationPresent(BeanProcessor.class))\n .map(clazz -> clazz.cast(getConstructorWithOutParameters(clazz)))\n .collect(Collectors.toList());\n\n // Collect annotations used to identify created beans during scanning.\n this.createdBeanAnnotations = classPathScanners.stream()\n .map(ClassPathScanner::getAnnotation)\n .collect(Collectors.toList());\n\n log.info(\"Register ClassPathScannerFactory {}\", Arrays.toString(classPathScanners.toArray()));\n }\n\n /**\n * Retrieves a set of classes identified as beans to be created by the registered scanners.\n *\n * @return A set of classes to be created based on scanning.\n */\n public Set<Class<?>> getBeansToCreate() {\n return classPathScanners.stream()\n .flatMap(classPathScanner -> classPathScanner.scan().stream())\n .collect(Collectors.toSet());\n }\n\n /**\n * Resolves the bean name for a given class using registered AnnotationResolvers.\n *\n * @param clazz The class for which the bean name is to be resolved.\n * @return The resolved name of the bean.\n */\n public String resolveBeanName(Class<?> clazz) {\n log.info(\"Resolving bean name for class [{}]\", clazz.getName());\n return annotationResolvers.stream()\n .filter(resolver -> resolver.isSupported(clazz))\n .findFirst()\n .map(annotationResolver -> annotationResolver.resolve(clazz))\n .orElse(null);\n }\n\n}" }, { "identifier": "BeanDefinition", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/domain/BeanDefinition.java", "snippet": "@Getter\n@Builder\npublic class BeanDefinition {\n\n private Class<?> beanClass;\n\n private BeanTypeEnum beanType;\n\n private BeanScope scope;\n\n private ProxyMode proxyMode;\n\n private Method method;\n\n private String factoryBeanName;\n\n private boolean isPrimary;\n\n /**\n * Checks if the bean is of type Configuration.\n *\n * @return True if the bean is of type Configuration, otherwise false\n */\n public boolean isConfiguration() {\n return this.beanType == BeanTypeEnum.CONFIGURATION;\n }\n\n /**\n * Checks if the bean is a configuration bean.\n *\n * @return True if the bean is a configuration bean, otherwise false\n */\n public boolean isConfigurationBean() {\n return Objects.nonNull(method);\n }\n\n /**\n * Checks if the bean's scope is set to Prototype.\n *\n * @return True if the bean's scope is Prototype, otherwise false\n */\n public boolean isPrototype() {\n return scope == BeanScope.PROTOTYPE;\n }\n\n /**\n * Checks if the bean is configured for proxying.\n *\n * @return True if the bean is configured for proxying, otherwise false\n */\n public boolean isProxy() {\n return proxyMode == ProxyMode.ON;\n }\n\n}" }, { "identifier": "NoSuchBeanException", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/exception/NoSuchBeanException.java", "snippet": "public class NoSuchBeanException extends RuntimeException{\n\n private static final String MESSAGE = \"Not such bean found exception %s\";\n\n /**\n * Constructs a new NoSuchBeanException with a message indicating the absence of a bean of the specified type.\n *\n * @param clazz The class type for which the bean is not found\n * @param <T> The class type\n */\n public <T> NoSuchBeanException(Class<T> clazz) {\n super(String.format(MESSAGE, clazz));\n }\n\n /**\n * Constructs a new NoSuchBeanException with a custom detail message.\n *\n * @param message The custom message explaining the exception\n */\n public NoSuchBeanException(String message) {\n super(message);\n }\n}" }, { "identifier": "ReflectionUtils", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/utils/ReflectionUtils.java", "snippet": "@UtilityClass\n@Slf4j\npublic final class ReflectionUtils {\n private static final String BEAN_SHOULD_HAVE_MESSAGE = \"BeanProcessor '%s' should have \";\n private static final String BEAN_SHOULD_HAVE_DEFAULT_CONSTRUCTOR_MESSAGE =\n BEAN_SHOULD_HAVE_MESSAGE + \"only default constructor without params\";\n private static final String BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_ONE_PARAMETER_MESSAGE =\n BEAN_SHOULD_HAVE_MESSAGE + \"constructor with one parameter '%s'.\";\n private static final String BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_PARAMETERS_MESSAGE =\n BEAN_SHOULD_HAVE_MESSAGE + \"constructor with parameters '%s'.\";\n private static final String DELIMITER = \", \";\n\n public static final OrderComparator ORDER_COMPARATOR = new OrderComparator();\n private static final Paranamer info = new CachingParanamer(new QualifierAnnotationParanamer(new BytecodeReadingParanamer()));\n private static final String ARG = \"arg\";\n\n private static final String SET_METHOD_START_PREFIX = \"set\";\n\n /**\n * Checks if the given method is an autowired setter method.\n *\n * @param method The method to be checked\n * @return True if the method is an autowired setter method, otherwise false\n */\n public static boolean isAutowiredSetterMethod(Method method) {\n return method.isAnnotationPresent(Autowired.class) && method.getName().startsWith(SET_METHOD_START_PREFIX);\n }\n\n /**\n * Retrieves the instance of a class by invoking the default (parameterless) constructor.\n *\n * @param clazz The class for which an instance should be created\n * @return An instance of the specified class\n * @throws BeanPostProcessorConstructionLimitationException If the default constructor is not present or accessible\n */\n public static Object getConstructorWithOutParameters(Class<?> clazz) {\n try {\n Constructor<?> constructor = clazz.getConstructor();\n return constructor.newInstance();\n } catch (Exception ex) {\n throw new BeanPostProcessorConstructionLimitationException(\n String.format(BEAN_SHOULD_HAVE_DEFAULT_CONSTRUCTOR_MESSAGE, clazz.getSimpleName()));\n }\n }\n\n /**\n * Retrieves the instance of a class by invoking a constructor with a single parameter.\n *\n * @param clazz The class for which an instance should be created\n * @param parameterType The type of the constructor's single parameter\n * @param instance The instance to be passed as the constructor's argument\n * @return An instance of the specified class created using the provided parameter\n * @throws BeanPostProcessorConstructionLimitationException If the constructor with a single parameter is not present or accessible\n */\n public static Object getConstructorWithOneParameter(Class<?> clazz, Class<?> parameterType, Object instance) {\n try {\n Constructor<?> constructor = clazz.getConstructor(parameterType);\n return constructor.newInstance(instance);\n } catch (Exception ex) {\n throw new BeanPostProcessorConstructionLimitationException(\n String.format(BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_ONE_PARAMETER_MESSAGE,\n clazz.getSimpleName(),\n parameterType.getSimpleName()));\n }\n }\n\n /**\n * Retrieves the instance of a class by invoking a constructor with multiple parameters.\n *\n * @param clazz The class for which an instance should be created\n * @param parameterTypesToInstance A map containing parameter types and their corresponding instances\n * @return An instance of the specified class created using the provided parameters\n * @throws BeanPostProcessorConstructionLimitationException If the constructor with specified parameters is not present or accessible\n */\n public static Object getConstructorWithParameters(Class<?> clazz, Map<Class<?>, Object> parameterTypesToInstance) {\n try {\n Constructor<?> constructor = clazz.getConstructor(parameterTypesToInstance.keySet().toArray(new Class[0]));\n return constructor.newInstance(parameterTypesToInstance.values().toArray());\n } catch (Exception ex) {\n throw new BeanPostProcessorConstructionLimitationException(\n String.format(BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_PARAMETERS_MESSAGE,\n clazz.getSimpleName(),\n parameterTypesToInstance.keySet().stream()\n .map(Class::getSimpleName)\n .collect(Collectors.joining(DELIMITER))));\n }\n }\n\n /**\n * Sets a field's value within an object.\n *\n * @param field The field to be modified\n * @param obj The object containing the field\n * @param value The value to be set in the field\n */\n @SneakyThrows\n public static void setField(Field field, Object obj, Object value) {\n log.trace(\"Setting into field \\\"{}\\\" of {} the value {}\", field.getName(), obj, value);\n try {\n field.setAccessible(true);\n field.set(obj, value);\n } catch (Exception e) {\n throw new BringGeneralException(e);\n }\n }\n\n /**\n * Retrieves parameter names of a method or constructor.\n *\n * @param methodOrConstructor The method or constructor to retrieve parameter names from\n * @return A list of parameter names\n */\n public static List<String> getParameterNames(AccessibleObject methodOrConstructor) {\n return Arrays.stream(info.lookupParameterNames(methodOrConstructor)).toList();\n }\n\n /**\n * Extracts the position of a parameter.\n *\n * @param parameter The parameter to extract the position from\n * @return The position of the parameter\n */\n public static int extractParameterPosition(Parameter parameter) {\n String name = parameter.getName();\n return Integer.parseInt(name.substring(name.indexOf(ARG) + ARG.length()));\n }\n\n /**\n * Extracts implementation classes of a generic type.\n *\n * @param genericType The generic type\n * @param reflections The Reflections object to query types\n * @param createdBeanAnnotations List of annotations indicating created beans\n * @return A list of implementation classes\n */\n @SneakyThrows\n public static List<Class<?>> extractImplClasses(ParameterizedType genericType, Reflections reflections,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n Type actualTypeArgument = genericType.getActualTypeArguments()[0];\n if (actualTypeArgument instanceof Class actualTypeArgumentClass) {\n String name = actualTypeArgumentClass.getName();\n Class<?> interfaceClass = Class.forName(name);\n log.trace(\"Extracting implementations of {} for injection\", interfaceClass.getName());\n\n return reflections.getSubTypesOf(interfaceClass)\n .stream()\n .filter(implementation -> isImplementationAnnotated(implementation, createdBeanAnnotations))\n .sorted(ORDER_COMPARATOR)\n .collect(Collectors.toList());\n }\n return Collections.emptyList();\n }\n\n /**\n * Extracts implementation classes of a given type.\n *\n * @param type The type to extract implementations for\n * @param reflections The Reflections object to query types\n * @param createdBeanAnnotations List of annotations indicating created beans\n * @return A list of implementation classes\n */\n public static List<Class<?>> extractImplClasses(Class<?> type, Reflections reflections,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n return (List<Class<?>>)reflections.getSubTypesOf(type)\n .stream()\n .filter(implementation -> isImplementationAnnotated(implementation, createdBeanAnnotations))\n .toList();\n }\n\n /**\n * Checks if an implementation class is annotated with any of the specified annotations.\n *\n * @param implementation The implementation class to check\n * @param createdBeanAnnotations List of annotations indicating created beans\n * @return True if the implementation is annotated, otherwise false\n */\n private static boolean isImplementationAnnotated(Class<?> implementation,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n return Arrays.stream(implementation.getAnnotations())\n .map(Annotation::annotationType)\n .anyMatch(createdBeanAnnotations::contains);\n }\n\n /**\n * Invokes a method on an object and returns a Supplier for its result.\n *\n * @param method The method to invoke\n * @param obj The object to invoke the method on\n * @param params The parameters to pass to the method\n * @return A Supplier representing the method invocation\n */\n public static Supplier<Object> invokeBeanMethod(Method method, Object obj, Object[] params) {\n return () -> {\n try {\n return method.invoke(obj, params);\n } catch (Exception e) {\n throw new BringGeneralException(e);\n }\n };\n }\n\n /**\n * Creates a new instance using the given constructor and arguments and returns a Supplier for it.\n *\n * @param constructor The constructor to create the instance\n * @param args The arguments to pass to the constructor\n * @param clazz The class of the instance to be created\n * @param proxy Boolean flag indicating whether to use proxy creation\n * @return A Supplier representing the new instance creation\n */\n public static Supplier<Object> createNewInstance(Constructor<?> constructor, Object[] args, Class<?> clazz,\n boolean proxy) {\n return () -> {\n try {\n if (proxy) {\n return ProxyUtils.createProxy(clazz, constructor, args);\n } else {\n return constructor.newInstance(args);\n }\n } catch (Exception e) {\n throw new BringGeneralException(e);\n }\n };\n }\n\n /**\n * Processes the annotations on the methods of a bean.\n *\n * @param bean The bean object\n * @param declaredMethods The methods of the bean to process\n * @param annotation The annotation to process\n * @throws ReflectiveOperationException If an error occurs during reflective operations\n */\n public static void processBeanPostProcessorAnnotation(Object bean,\n Method[] declaredMethods,\n Class<? extends Annotation> annotation)\n throws ReflectiveOperationException {\n for (Method declaredMethod : declaredMethods) {\n if (declaredMethod.isAnnotationPresent(annotation)) {\n declaredMethod.invoke(bean);\n }\n }\n }\n\n /**\n * Inner class extending AnnotationParanamer to handle Qualifier annotations.\n */\n private static class QualifierAnnotationParanamer extends AnnotationParanamer {\n\n public QualifierAnnotationParanamer(Paranamer fallback) {\n super(fallback);\n }\n\n @Override\n protected String getNamedValue(Annotation ann) {\n if (Objects.equals(Qualifier.class, ann.annotationType())) {\n Qualifier qualifier = (Qualifier) ann;\n return qualifier.value();\n } else {\n return null;\n }\n }\n\n @Override\n protected boolean isNamed(Annotation ann) {\n return Objects.equals(Qualifier.class, ann.annotationType());\n }\n }\n}" } ]
import io.github.blyznytsiaorg.bring.core.context.scaner.ClassPathScannerFactory; import io.github.blyznytsiaorg.bring.core.domain.BeanDefinition; import io.github.blyznytsiaorg.bring.core.exception.NoSuchBeanException; import io.github.blyznytsiaorg.bring.core.utils.ReflectionUtils; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier;
4,419
package io.github.blyznytsiaorg.bring.core.context.impl; /** * Responsible for creating beans and injecting dependencies into these beans based on provided definitions. * * @author Blyzhnytsia Team * @since 1.0 */ @Slf4j public class BeanCreator { private final AnnotationBringBeanRegistry beanRegistry; private final ConstructorBeanInjection createBeanUsingConstructor; private final FieldBeanInjection fieldBeanInjection; private final SetterBeanInjection setterBeanInjection; /** * Constructs a BeanCreator. * * @param beanRegistry The registry storing beans and their definitions. * @param classPathScannerFactory The factory for creating class path scanners. */ public BeanCreator(AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { this.beanRegistry = beanRegistry; this.createBeanUsingConstructor = new ConstructorBeanInjection(beanRegistry, classPathScannerFactory); this.fieldBeanInjection = new FieldBeanInjection(beanRegistry, classPathScannerFactory); this.setterBeanInjection = new SetterBeanInjection(beanRegistry, classPathScannerFactory); } /** * Creates a bean of the specified class and injects dependencies into it. * * @param clazz The class of the bean to be created. * @param beanName The name of the bean being created. * @param beanDefinition The definition of the bean being created. * @return The created bean object. */ public Object create(Class<?> clazz, String beanName, BeanDefinition beanDefinition) { log.debug("Creating Bean \"{}\" of [{}]", beanName, clazz.getName()); Object bean = createBeanUsingConstructor.create(clazz, beanName, beanDefinition); log.debug("Injecting dependencies to Bean \"{}\"", beanName); injectDependencies(clazz, bean); return bean; } /** * Registers a configuration bean in the context based on the provided bean name and definition. * Resolves dependencies and instantiates the configuration bean within the context. * * @param beanName The name of the configuration bean to be registered. * @param beanDefinition The definition of the configuration bean. * @return The registered configuration bean. */ public Object registerConfigurationBean(String beanName, BeanDefinition beanDefinition) { Object configObj = Optional.ofNullable(beanRegistry.getSingletonObjects().get(beanDefinition.getFactoryBeanName())) .orElseThrow(() -> { log.info("Unable to register Bean from Configuration class [{}]: " + "Configuration class not annotated or is not of Singleton scope.", beanName); return new NoSuchBeanException(beanDefinition.getBeanClass()); });
package io.github.blyznytsiaorg.bring.core.context.impl; /** * Responsible for creating beans and injecting dependencies into these beans based on provided definitions. * * @author Blyzhnytsia Team * @since 1.0 */ @Slf4j public class BeanCreator { private final AnnotationBringBeanRegistry beanRegistry; private final ConstructorBeanInjection createBeanUsingConstructor; private final FieldBeanInjection fieldBeanInjection; private final SetterBeanInjection setterBeanInjection; /** * Constructs a BeanCreator. * * @param beanRegistry The registry storing beans and their definitions. * @param classPathScannerFactory The factory for creating class path scanners. */ public BeanCreator(AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { this.beanRegistry = beanRegistry; this.createBeanUsingConstructor = new ConstructorBeanInjection(beanRegistry, classPathScannerFactory); this.fieldBeanInjection = new FieldBeanInjection(beanRegistry, classPathScannerFactory); this.setterBeanInjection = new SetterBeanInjection(beanRegistry, classPathScannerFactory); } /** * Creates a bean of the specified class and injects dependencies into it. * * @param clazz The class of the bean to be created. * @param beanName The name of the bean being created. * @param beanDefinition The definition of the bean being created. * @return The created bean object. */ public Object create(Class<?> clazz, String beanName, BeanDefinition beanDefinition) { log.debug("Creating Bean \"{}\" of [{}]", beanName, clazz.getName()); Object bean = createBeanUsingConstructor.create(clazz, beanName, beanDefinition); log.debug("Injecting dependencies to Bean \"{}\"", beanName); injectDependencies(clazz, bean); return bean; } /** * Registers a configuration bean in the context based on the provided bean name and definition. * Resolves dependencies and instantiates the configuration bean within the context. * * @param beanName The name of the configuration bean to be registered. * @param beanDefinition The definition of the configuration bean. * @return The registered configuration bean. */ public Object registerConfigurationBean(String beanName, BeanDefinition beanDefinition) { Object configObj = Optional.ofNullable(beanRegistry.getSingletonObjects().get(beanDefinition.getFactoryBeanName())) .orElseThrow(() -> { log.info("Unable to register Bean from Configuration class [{}]: " + "Configuration class not annotated or is not of Singleton scope.", beanName); return new NoSuchBeanException(beanDefinition.getBeanClass()); });
List<String> methodParamNames = ReflectionUtils.getParameterNames(beanDefinition.getMethod());
3
2023-11-10 13:42:05+00:00
8k
johndeweyzxc/AWPS-Command
app/src/main/java/com/johndeweydev/awps/view/autoarmafragment/AutoArmaFragment.java
[ { "identifier": "BAUD_RATE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int BAUD_RATE = 19200;" }, { "identifier": "DATA_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int DATA_BITS = 8;" }, { "identifier": "PARITY_NONE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final String PARITY_NONE = \"PARITY_NONE\";" }, { "identifier": "STOP_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int STOP_BITS = 1;" }, { "identifier": "HashInfoEntity", "path": "app/src/main/java/com/johndeweydev/awps/model/data/HashInfoEntity.java", "snippet": "@Entity(tableName = \"hash_information\")\npublic class HashInfoEntity {\n\n @PrimaryKey(autoGenerate = true)\n public int uid;\n @ColumnInfo(name = \"ssid\")\n public String ssid;\n @ColumnInfo(name = \"bssid\")\n public String bssid;\n @ColumnInfo(name = \"client_mac_address\")\n public String clientMacAddress;\n\n // The key type can be either \"PMKID\" in the case of PMKID based attack or \"MIC\" in the case\n // of MIC based attack\n @ColumnInfo(name = \"key_type\")\n public String keyType;\n\n // The anonce or access point nonce from the first eapol message, this is initialized in the\n // case of MIC based attack otherwise its value is \"None\" in the case of PMKID based attack\n @ColumnInfo(name = \"a_nonce\")\n public String aNonce;\n\n // The hash data is where the actual PMKID or MIC is stored\n @ColumnInfo(name = \"hash_data\")\n public String hashData;\n\n // The key data is where the second eapol authentication message is stored in the case of\n // MIC based attack otherwise its value is \"None\"\n @ColumnInfo(name = \"key_data\")\n public String keyData;\n @ColumnInfo(name = \"date_captured\")\n public String dateCaptured;\n\n @ColumnInfo(name = \"latitude\")\n public String latitude;\n @ColumnInfo(name = \"longitude\")\n public String longitude;\n @ColumnInfo(name = \"address\")\n public String address;\n\n public HashInfoEntity(\n @Nullable String ssid,\n @Nullable String bssid,\n @Nullable String clientMacAddress,\n @Nullable String keyType,\n @Nullable String aNonce,\n @Nullable String hashData,\n @Nullable String keyData,\n @Nullable String dateCaptured,\n @Nullable String latitude,\n @Nullable String longitude,\n @Nullable String address\n ) {\n this.ssid = ssid;\n this.bssid = bssid;\n this.clientMacAddress = clientMacAddress;\n this.keyType = keyType;\n this.aNonce = aNonce;\n this.hashData = hashData;\n this.keyData = keyData;\n this.dateCaptured = dateCaptured;\n this.latitude = latitude;\n this.longitude = longitude;\n this.address = address;\n }\n}" }, { "identifier": "SessionRepoSerial", "path": "app/src/main/java/com/johndeweydev/awps/model/repo/serial/sessionreposerial/SessionRepoSerial.java", "snippet": "public class SessionRepoSerial extends RepositoryIOControl implements Launcher.UsbSerialIOEvent {\n\n public interface RepositoryEvent extends RepositoryIOEvent, InitializationPhase,\n TargetLockingPhase, ExecutionPhase, PostExecutionPhase {}\n\n private SessionRepoSerial.RepositoryEvent repositoryEvent;\n private final StringBuilder queueData = new StringBuilder();\n @Override\n public void onUsbSerialOutput(String data) {\n char[] dataChar = data.toCharArray();\n for (char c : dataChar) {\n if (c == '\\n') {\n processFormattedOutput();\n queueData.setLength(0);\n } else {\n queueData.append(c);\n }\n }\n }\n\n @Override\n public void onUsbSerialOutputError(String error) {\n repositoryEvent.onRepoOutputError(error);\n }\n\n @Override\n public void onUsbSerialInputError(String input) {\n repositoryEvent.onRepoInputError(input);\n }\n\n public void setEventHandler(SessionRepoSerial.RepositoryEvent repositoryEvent) {\n this.repositoryEvent = repositoryEvent;\n Log.d(\"dev-log\", \"SessionRepository.setEventHandler: Session repository event \" +\n \"callback set\");\n }\n\n public void setLauncherEventHandler() {\n LauncherSingleton.getInstance().getLauncher().setLauncherEventHandler(\n this);\n Log.d(\"dev-log\", \"SessionRepository.setLauncherEventHandler: Launcher event \" +\n \"callback set in the context of session repository\");\n }\n\n private void processFormattedOutput() {\n String data = queueData.toString();\n String time = createStringTime();\n\n LauncherOutputData launcherOutputData = new LauncherOutputData(time, data);\n\n char firstChar = data.charAt(0);\n char lastChar = data.charAt(data.length() - 2);\n if (firstChar == '{' && lastChar == '}') {\n repositoryEvent.onRepoOutputFormatted(launcherOutputData);\n data = data.replace(\"{\", \"\").replace(\"}\", \"\");\n String[] splitStrData = data.split(\",\");\n\n ArrayList<String> strDataList = new ArrayList<>(Arrays.asList(splitStrData));\n processContentOfFormattedOutput(strDataList);\n }\n }\n\n private String createStringTime() {\n Calendar calendar = Calendar.getInstance();\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\", Locale.getDefault());\n return dateFormat.format(calendar.getTime());\n }\n\n private void processContentOfFormattedOutput(ArrayList<String> strDataList) {\n StringBuilder dataArguments = new StringBuilder();\n for (int i = 0; i < strDataList.size(); i++) {\n dataArguments.append(strDataList.get(i));\n dataArguments.append(\"-\");\n }\n\n switch (strDataList.get(0)) {\n case \"ESP_STARTED\" -> repositoryEvent.onRepoStarted();\n case \"CMD_PARSER\" -> cmdParserContext(strDataList);\n case \"ARMAMENT\" -> armamentContext(strDataList);\n case \"PMKID\" -> pmkidContext(strDataList);\n case \"MIC\" -> micContext(strDataList);\n case \"DEAUTH\" -> deauthContext(strDataList);\n case \"RECONNAISSANCE\" -> reconnaissanceContext(strDataList);\n }\n }\n\n private void cmdParserContext(ArrayList<String> strDataList) {\n String currentArmament = strDataList.get(2);\n String currentBssidTarget = strDataList.get(3);\n\n String namedArmament = switch (currentArmament) {\n case \"01\" -> \"Reconnaissance\";\n case \"02\" -> \"PMKID\";\n case \"03\" -> \"MIC\";\n case \"04\" -> \"Deauth\";\n default -> \"\";\n };\n\n String formattedBssid = currentBssidTarget.substring(0, 2) + \":\" +\n currentBssidTarget.substring(2, 4) + \":\" +\n currentBssidTarget.substring(4, 6) + \":\" +\n currentBssidTarget.substring(6, 8) + \":\" +\n currentBssidTarget.substring(8, 10) + \":\" +\n currentBssidTarget.substring(10, 12);\n\n switch (strDataList.get(1)) {\n case \"CURRENT_ARMA\" -> repositoryEvent.onRepoArmamentStatus(\n namedArmament, formattedBssid);\n case \"TARGET_ARMA_SET\" -> repositoryEvent.onRepoInstructionIssued(\n namedArmament, formattedBssid);\n }\n }\n\n private void armamentContext(ArrayList<String> strDataList) {\n if (Objects.equals(strDataList.get(1), \"ACTIVATE\")) {\n repositoryEvent.onRepoArmamentActivation();\n } else if (Objects.equals(strDataList.get(1), \"DEACTIVATE\")) {\n repositoryEvent.onRepoArmamentDeactivation();\n }\n }\n\n private void pmkidContext(ArrayList<String> strDataList) {\n switch (strDataList.get(1)) {\n case \"AP_NOT_FOUND\" -> repositoryEvent.onRepoTargetAccessPointNotFound();\n case \"LAUNCHING_SEQUENCE\" -> repositoryEvent.onRepoLaunchingSequence();\n case \"SNIFF_STARTED\" -> repositoryEvent.onRepoMainTaskCreated();\n case \"WRONG_KEY_TYPE\" -> {\n String keyType = strDataList.get(3);\n repositoryEvent.onRepoPmkidWrongKeyType(keyType);\n }\n case \"WRONG_OUI\" -> repositoryEvent.onRepoPmkidWrongOui(strDataList.get(2));\n case \"WRONG_KDE\" -> repositoryEvent.onRepoPmkidWrongKde(strDataList.get(2));\n case \"SNIFF_STATUS\" -> {\n int status = Integer.parseInt(strDataList.get(2));\n repositoryEvent.onRepoMainTaskCurrentStatus(\"PMKID\", status);\n }\n case \"MSG_1\" -> handlePmkidMessage1(strDataList);\n case \"FINISHING_SEQUENCE\" -> repositoryEvent.onRepoFinishingSequence();\n case \"SUCCESS\" -> repositoryEvent.onRepoSuccess();\n case \"FAILURE\" -> repositoryEvent.onRepoFailure(strDataList.get(2));\n }\n }\n\n private void handlePmkidMessage1(ArrayList<String> dataList) {\n String bssid = dataList.get(2);\n String client = dataList.get(3);\n String pmkid = dataList.get(4);\n PmkidFirstMessageData pmkidFirstMessageData = new PmkidFirstMessageData(bssid, client, pmkid);\n repositoryEvent.onRepoReceivedEapolMessage(\n \"PMKID\", 1, pmkidFirstMessageData,\n null, null);\n }\n\n private void micContext(ArrayList<String> strDataList) {\n switch (strDataList.get(1)) {\n case \"AP_NOT_FOUND\" -> repositoryEvent.onRepoTargetAccessPointNotFound();\n case \"LAUNCHING_SEQUENCE\" -> repositoryEvent.onRepoLaunchingSequence();\n case \"DEAUTH_STARTED\" -> repositoryEvent.onRepoMainTaskCreated();\n case \"INJECTED_DEAUTH\" -> {\n int status = Integer.parseInt(strDataList.get(2));\n repositoryEvent.onRepoMainTaskCurrentStatus(\"MIC\", status);\n }\n case \"MSG_1\" -> handleMicMessage1(strDataList);\n case \"MSG_2\" -> handleMicMessage2(strDataList);\n case \"FINISHING SEQUENCE\" -> repositoryEvent.onRepoFinishingSequence();\n case \"SUCCESS\" -> repositoryEvent.onRepoSuccess();\n case \"FAILURE\" -> repositoryEvent.onRepoFailure(strDataList.get(2));\n }\n }\n\n private void handleMicMessage1(ArrayList<String> dataList) {\n String bssid = dataList.get(2);\n String client = dataList.get(3);\n String anonce = dataList.get(4);\n MicFirstMessageData micFirstMessageData = new MicFirstMessageData(bssid, client, anonce);\n repositoryEvent.onRepoReceivedEapolMessage(\n \"MIC\", 1, null,\n micFirstMessageData, null);\n }\n\n private void handleMicMessage2(ArrayList<String> dataList) {\n String version = dataList.get(4);\n String type = dataList.get(5);\n String length = dataList.get(6);\n String keyDescriptionType = dataList.get(7);\n String keyInformation = dataList.get(8);\n String keyLength = dataList.get(9);\n\n String replayCounter = dataList.get(10);\n String snonce = dataList.get(11);\n String keyIv = dataList.get(12);\n String keyRsc = dataList.get(13);\n String keyId = dataList.get(14);\n String mic = dataList.get(15);\n\n String keyDataLength = dataList.get(16);\n String keyData = dataList.get(17);\n\n MicSecondMessageData micSecondMessageData = new MicSecondMessageData(\n version, type, length, keyDescriptionType, keyInformation, keyLength,\n replayCounter, snonce, keyIv, keyRsc, keyId, mic, keyDataLength, keyData);\n\n repositoryEvent.onRepoReceivedEapolMessage(\"MIC\", 2,\n null, null, micSecondMessageData);\n }\n\n private void reconnaissanceContext(ArrayList<String> strDataList) {\n\n switch (strDataList.get(1)) {\n case \"FOUND_APS\" -> {\n String numberOfAps = strDataList.get(2);\n repositoryEvent.onRepoNumberOfFoundAccessPoints(numberOfAps);\n }\n case \"SCAN\" -> processScannedAccessPointsAndNotifyViewModel(strDataList);\n case \"FINISH_SCAN\" -> repositoryEvent.onRepoFinishScan();\n }\n }\n\n private void deauthContext(ArrayList<String> strDataList) {\n switch (strDataList.get(1)) {\n case \"AP_NOT_FOUND\" -> repositoryEvent.onRepoTargetAccessPointNotFound();\n case \"FINISH_SCAN\" -> repositoryEvent.onRepoFinishScan();\n case \"LAUNCHING_SEQUENCE\" -> repositoryEvent.onRepoLaunchingSequence();\n case \"DEAUTH_STARTED\" -> repositoryEvent.onRepoMainTaskCreated();\n case \"INJECTED_DEAUTH\" -> {\n int numberOfInjectedDeauthentications = Integer.parseInt(strDataList.get(2));\n repositoryEvent.onRepoMainTaskCurrentStatus(\"DEAUTH\",\n numberOfInjectedDeauthentications);\n }\n case \"STOPPED\" ->\n repositoryEvent.onRepoMainTaskInDeautherStopped(strDataList.get(2));\n }\n }\n\n private void processScannedAccessPointsAndNotifyViewModel(\n ArrayList<String> strDataList\n ) {\n String macAddress = strDataList.get(2);\n String ssid = strDataList.get(3);\n StringBuilder asciiSsid = new StringBuilder();\n\n // Decodes the SSID from hexadecimal string to ascii characters\n for (int i = 0; i < ssid.length(); i += 2) {\n String hex = ssid.substring(i, i + 2);\n int decimal = Integer.parseInt(hex, 16);\n asciiSsid.append((char) decimal);\n }\n\n String rssi = strDataList.get(4);\n String channel = strDataList.get(5);\n AccessPointData accessPointData = new AccessPointData(\n macAddress, asciiSsid.toString(), Integer.parseInt(rssi), Integer.parseInt(channel)\n );\n repositoryEvent.onRepoFoundAccessPoint(accessPointData);\n }\n\n}" }, { "identifier": "SessionAutoViewModel", "path": "app/src/main/java/com/johndeweydev/awps/viewmodel/serial/sessionviewmodel/SessionAutoViewModel.java", "snippet": "public class SessionAutoViewModel extends SessionViewModel {\n\n public MutableLiveData<AccessPointData> currentTarget = new MutableLiveData<>(null);\n\n public MutableLiveData<Integer> nearbyAps = new MutableLiveData<>(0);\n public MutableLiveData<Integer> failedAttacks = new MutableLiveData<>(0);\n public MutableLiveData<Integer> pwned = new MutableLiveData<>(0);\n\n public MutableLiveData<String> userCommandState = new MutableLiveData<>(\"STOPPED\");\n\n public ArrayList<AccessPointData> previouslyAttackedTargets = new ArrayList<>();\n\n public SessionAutoViewModel(SessionRepoSerial sessionRepoSerial) {\n super(sessionRepoSerial);\n }\n\n public void startAttack() {\n userCommandState.setValue(\"RUN\");\n writeInstructionCodeForScanningDevicesToLauncher();\n }\n\n public void stopAttack() {\n userCommandState.setValue(\"PENDING STOP\");\n }\n\n @Override\n public void onRepoStarted() {\n super.onRepoStarted();\n if (Objects.equals(userCommandState.getValue(), \"RUN\")) {\n writeInstructionCodeForScanningDevicesToLauncher();\n } else if (Objects.equals(userCommandState.getValue(), \"PENDING STOP\")) {\n // Stop is issued by user, notify view that the stop was acknowledge\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") On started state, stop command \" +\n \"was found\");\n attackLogNumber++;\n userCommandState.postValue(\"STOPPED\");\n }\n }\n\n @Override\n public void onRepoInstructionIssued(String armament, String targetBssid) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \")\" + \" Using \" + armament);\n attackLogNumber++;\n if (Objects.equals(userCommandState.getValue(), \"RUN\")) {\n writeControlCodeActivationToLauncher();\n } else if (Objects.equals(userCommandState.getValue(), \"PENDING STOP\")) {\n // Stop issued by user, notify view that the stop was acknowledge\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") On instruction state, stop command \" +\n \"was found\");\n attackLogNumber++;\n userCommandState.postValue(\"STOPPED\");\n }\n }\n\n @Override\n public void onRepoNumberOfFoundAccessPoints(String numberOfAps) {\n super.onRepoNumberOfFoundAccessPoints(numberOfAps);\n nearbyAps.postValue(Integer.parseInt(numberOfAps));\n }\n\n @Override\n public void onRepoFoundAccessPoint(AccessPointData accessPointData) {\n String ssid = accessPointData.ssid();\n int channel = accessPointData.channel();\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + ssid + \" at channel \" + channel);\n attackLogNumber++;\n\n if (!accessPointWasAttackBefore(accessPointData)) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Adding \" + ssid +\n \" as potential target\");\n attackLogNumber++;\n accessPointDataList.add(accessPointData);\n }\n }\n\n private boolean accessPointWasAttackBefore(AccessPointData accessPointData) {\n for (int i = 0; i < previouslyAttackedTargets.size(); i++) {\n AccessPointData prevTarget = previouslyAttackedTargets.get(i);\n\n if (Objects.equals(prevTarget.ssid(), accessPointData.ssid()) &&\n Objects.equals(prevTarget.macAddress(), accessPointData.macAddress())) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + accessPointData.ssid() +\n \" was attacked before\");\n attackLogNumber++;\n return true;\n }\n }\n return false;\n }\n\n @Override\n public void onRepoFinishScan() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") Selecting target\");\n attackLogNumber++;\n\n if (Objects.equals(userCommandState.getValue(), \"RUN\")) {\n selectTarget();\n } else if (Objects.equals(userCommandState.getValue(), \"PENDING STOP\")) {\n // Stop is issued by user, notify view that the stop was acknowledge\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") On finish scan state, stop command \" +\n \"was found\");\n attackLogNumber++;\n userCommandState.postValue(\"STOPPED\");\n }\n }\n\n private void selectTarget() {\n if (accessPointDataList.isEmpty()) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") No potential targets found, \" +\n \"doing a scan again\");\n attackLogNumber++;\n writeInstructionCodeForScanningDevicesToLauncher();\n } else {\n\n AccessPointData selectedTarget = accessPointDataList.get(0);\n currentTarget.postValue(selectedTarget);\n String ssid = selectedTarget.ssid();\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") Initiating attack on \" + ssid);\n attackLogNumber++;\n\n // Set the SSID in the super class because it causes null value when saving it\n // in the database\n targetAccessPointSsid = selectedTarget.ssid();\n writeInstructionCodeToLauncher(selectedTarget.macAddress());\n }\n }\n\n public String formatMacAddress(String bssid) {\n StringBuilder formattedMac = new StringBuilder();\n for (int i = 0; i < bssid.length(); i += 2) {\n formattedMac.append(bssid.substring(i, i + 2));\n if (i < bssid.length() - 2) {\n formattedMac.append(\":\");\n }\n }\n return formattedMac.toString().toUpperCase();\n }\n\n @Override\n public void onRepoTargetAccessPointNotFound() {\n super.onRepoTargetAccessPointNotFound();\n\n if (Objects.equals(userCommandState.getValue(), \"RUN\")) {\n writeInstructionCodeForScanningDevicesToLauncher();\n } else if (Objects.equals(userCommandState.getValue(), \"PENDING STOP\")) {\n // Stop is issued by user, notify view that the stop was acknowledge\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") On target not found state, stop \" +\n \"command was found\");\n attackLogNumber++;\n userCommandState.postValue(\"STOPPED\");\n }\n }\n\n @Override\n public void onRepoMainTaskCurrentStatus(String attackType, int attackStatus) {\n super.onRepoMainTaskCurrentStatus(attackType, attackStatus);\n\n if (Objects.equals(userCommandState.getValue(), \"PENDING STOP\")) {\n writeControlCodeDeactivationToLauncher();\n } else {\n if (attackStatus == UserDefinedSettings.ALLOCATED_TIME_FOR_EACH_ATTACK) {\n writeControlCodeDeactivationToLauncher();\n }\n }\n }\n\n @Override\n public void onRepoSuccess() {\n super.onRepoSuccess();\n\n int currentNumberOfKeys;\n if (pwned.getValue() == null) {\n currentNumberOfKeys = 0;\n } else {\n currentNumberOfKeys = pwned.getValue();\n }\n\n pwned.postValue(currentNumberOfKeys + 1);\n checkSizeOfPreviouslyAttackedTargets();\n previouslyAttackedTargets.add(currentTarget.getValue());\n writeInstructionCodeForScanningDevicesToLauncher();\n }\n\n @Override\n public void onRepoFailure(String targetBssid) {\n super.onRepoFailure(targetBssid);\n\n int currentNumberOfFailedAttacks;\n if (failedAttacks.getValue() == null) {\n currentNumberOfFailedAttacks = 0;\n } else {\n currentNumberOfFailedAttacks = failedAttacks.getValue();\n }\n\n failedAttacks.postValue(currentNumberOfFailedAttacks + 1);\n checkSizeOfPreviouslyAttackedTargets();\n previouslyAttackedTargets.add(currentTarget.getValue());\n }\n\n private void checkSizeOfPreviouslyAttackedTargets() {\n if (previouslyAttackedTargets.size() ==\n UserDefinedSettings.NUMBER_OF_PREVIOUSLY_ATTACKED_TARGETS) {\n AccessPointData accessPointData = previouslyAttackedTargets.remove(0);\n String ssid = accessPointData.ssid();\n currentAttackLog.postValue(\"(\" + attackLogNumber + \")\" + \" Removed \" + ssid + \" from \" +\n \"previously attacked targets\");\n attackLogNumber++;\n }\n }\n}" }, { "identifier": "SessionAutoViewModelFactory", "path": "app/src/main/java/com/johndeweydev/awps/viewmodel/serial/sessionviewmodel/SessionAutoViewModelFactory.java", "snippet": "public class SessionAutoViewModelFactory implements ViewModelProvider.Factory {\n\n private final SessionRepoSerial sessionRepoSerial;\n public SessionAutoViewModelFactory(SessionRepoSerial sessionRepoSerial) {\n this.sessionRepoSerial = sessionRepoSerial;\n }\n\n @NonNull\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {\n return (T) new SessionAutoViewModel(sessionRepoSerial);\n }\n}" } ]
import static com.johndeweydev.awps.AppConstants.BAUD_RATE; import static com.johndeweydev.awps.AppConstants.DATA_BITS; import static com.johndeweydev.awps.AppConstants.PARITY_NONE; import static com.johndeweydev.awps.AppConstants.STOP_BITS; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.johndeweydev.awps.R; import com.johndeweydev.awps.databinding.FragmentAutoArmaBinding; import com.johndeweydev.awps.model.data.AccessPointData; import com.johndeweydev.awps.model.data.DeviceConnectionParamData; import com.johndeweydev.awps.model.data.HashInfoEntity; import com.johndeweydev.awps.model.repo.serial.sessionreposerial.SessionRepoSerial; import com.johndeweydev.awps.viewmodel.hashinfoviewmodel.HashInfoViewModel; import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionAutoViewModel; import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionAutoViewModelFactory; import java.util.Objects;
5,929
package com.johndeweydev.awps.view.autoarmafragment; public class AutoArmaFragment extends Fragment { private FragmentAutoArmaBinding binding; private AutoArmaArgs autoArmaArgs = null; private SessionAutoViewModel sessionAutoViewModel; private HashInfoViewModel hashInfoViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SessionRepoSerial sessionRepoSerial = new SessionRepoSerial();
package com.johndeweydev.awps.view.autoarmafragment; public class AutoArmaFragment extends Fragment { private FragmentAutoArmaBinding binding; private AutoArmaArgs autoArmaArgs = null; private SessionAutoViewModel sessionAutoViewModel; private HashInfoViewModel hashInfoViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SessionRepoSerial sessionRepoSerial = new SessionRepoSerial();
SessionAutoViewModelFactory sessionAutoViewModelFactory = new SessionAutoViewModelFactory(
7
2023-11-15 15:54:39+00:00
8k
Charles7c/continew-starter
continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/base/BaseController.java
[ { "identifier": "StringConstants", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/constant/StringConstants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringConstants implements StrPool {\n\n /**\n * 空字符串\n */\n public static final String EMPTY = \"\";\n\n /**\n * 空格\n */\n public static final String SPACE = \" \";\n\n /**\n * 分号\n */\n public static final String SEMICOLON = \";\";\n\n /**\n * 星号\n */\n public static final String ASTERISK = \"*\";\n\n /**\n * 问号\n */\n public static final String QUESTION_MARK = \"?\";\n\n /**\n * 中文逗号\n */\n public static final String CHINESE_COMMA = \",\";\n\n /**\n * 路径模式\n */\n public static final String PATH_PATTERN = \"/**\";\n}" }, { "identifier": "Api", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/enums/Api.java", "snippet": "public enum Api {\n\n /**\n * 所有 API\n */\n ALL,\n /**\n * 分页\n */\n PAGE,\n /**\n * 树列表\n */\n TREE,\n /**\n * 列表\n */\n LIST,\n /**\n * 详情\n */\n GET,\n /**\n * 新增\n */\n ADD,\n /**\n * 修改\n */\n UPDATE,\n /**\n * 删除\n */\n DELETE,\n /**\n * 导出\n */\n EXPORT,\n}" }, { "identifier": "PageQuery", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/query/PageQuery.java", "snippet": "@Data\n@ParameterObject\n@NoArgsConstructor\n@Schema(description = \"分页查询条件\")\npublic class PageQuery extends SortQuery {\n\n @Serial\n private static final long serialVersionUID = 1L;\n /**\n * 默认页码:1\n */\n private static final int DEFAULT_PAGE = 1;\n /**\n * 默认每页条数:10\n */\n private static final int DEFAULT_SIZE = 10;\n\n /**\n * 页码\n */\n @Schema(description = \"页码\", example = \"1\")\n @Min(value = 1, message = \"页码最小值为 {value}\")\n private Integer page = DEFAULT_PAGE;\n\n /**\n * 每页条数\n */\n @Schema(description = \"每页条数\", example = \"10\")\n @Range(min = 1, max = 1000, message = \"每页条数(取值范围 {min}-{max})\")\n private Integer size = DEFAULT_SIZE;\n\n /**\n * 基于分页查询条件转换为 MyBatis Plus 分页条件\n *\n * @param <T> 列表数据类型\n * @return MyBatis Plus 分页条件\n */\n public <T> IPage<T> toPage() {\n Page<T> mybatisPage = new Page<>(this.getPage(), this.getSize());\n Sort pageSort = this.getSort();\n if (CollUtil.isNotEmpty(pageSort)) {\n for (Sort.Order order : pageSort) {\n OrderItem orderItem = new OrderItem();\n orderItem.setAsc(order.isAscending());\n orderItem.setColumn(StrUtil.toUnderlineCase(order.getProperty()));\n mybatisPage.addOrder(orderItem);\n }\n }\n return mybatisPage;\n }\n}" }, { "identifier": "SortQuery", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/query/SortQuery.java", "snippet": "@Data\n@Schema(description = \"排序查询条件\")\npublic class SortQuery implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 排序条件\n */\n @Schema(description = \"排序条件\", example = \"createTime,desc\")\n private String[] sort;\n\n /**\n * 解析排序条件为 Spring 分页排序实体\n *\n * @return Spring 分页排序实体\n */\n public Sort getSort() {\n if (ArrayUtil.isEmpty(sort)) {\n return Sort.unsorted();\n }\n\n List<Sort.Order> orders = new ArrayList<>(sort.length);\n if (StrUtil.contains(sort[0], StringConstants.COMMA)) {\n // e.g \"sort=createTime,desc&sort=name,asc\"\n for (String s : sort) {\n List<String> sortList = StrUtil.splitTrim(s, StringConstants.COMMA);\n Sort.Order order =\n new Sort.Order(Sort.Direction.valueOf(sortList.get(1).toUpperCase()), sortList.get(0));\n orders.add(order);\n }\n } else {\n // e.g \"sort=createTime,desc\"\n Sort.Order order = new Sort.Order(Sort.Direction.valueOf(sort[1].toUpperCase()), sort[0]);\n orders.add(order);\n }\n return Sort.by(orders);\n }\n}" }, { "identifier": "PageDataResp", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/resp/PageDataResp.java", "snippet": "@Data\n@Schema(description = \"分页信息\")\npublic class PageDataResp<L> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 列表数据\n */\n @Schema(description = \"列表数据\")\n private List<L> list;\n\n /**\n * 总记录数\n */\n @Schema(description = \"总记录数\", example = \"10\")\n private long total;\n\n /**\n * 基于 MyBatis Plus 分页数据构建分页信息,并将源数据转换为指定类型数据\n *\n * @param page MyBatis Plus 分页数据\n * @param targetClass 目标类型 Class 对象\n * @param <T> 源列表数据类型\n * @param <L> 目标列表数据类型\n * @return 分页信息\n */\n public static <T, L> PageDataResp<L> build(IPage<T> page, Class<L> targetClass) {\n if (null == page) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(BeanUtil.copyToList(page.getRecords(), targetClass));\n pageDataResp.setTotal(page.getTotal());\n return pageDataResp;\n }\n\n /**\n * 基于 MyBatis Plus 分页数据构建分页信息\n *\n * @param page MyBatis Plus 分页数据\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n public static <L> PageDataResp<L> build(IPage<L> page) {\n if (null == page) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(page.getRecords());\n pageDataResp.setTotal(page.getTotal());\n return pageDataResp;\n }\n\n /**\n * 基于列表数据构建分页信息\n *\n * @param page 页码\n * @param size 每页条数\n * @param list 列表数据\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n public static <L> PageDataResp<L> build(int page, int size, List<L> list) {\n if (CollUtil.isEmpty(list)) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setTotal(list.size());\n // 对列表数据进行分页\n int fromIndex = (page - 1) * size;\n int toIndex = page * size + size;\n if (fromIndex > list.size()) {\n pageDataResp.setList(new ArrayList<>(0));\n } else if (toIndex >= list.size()) {\n pageDataResp.setList(list.subList(fromIndex, list.size()));\n } else {\n pageDataResp.setList(list.subList(fromIndex, toIndex));\n }\n return pageDataResp;\n }\n\n /**\n * 空分页信息\n *\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n private static <L> PageDataResp<L> empty() {\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(new ArrayList<>(0));\n return pageDataResp;\n }\n}" }, { "identifier": "R", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/resp/R.java", "snippet": "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@Schema(description = \"响应信息\")\npublic class R<T> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 是否成功\n */\n @Schema(description = \"是否成功\", example = \"true\")\n private boolean success;\n\n /**\n * 业务状态码\n */\n @Schema(description = \"业务状态码\", example = \"200\")\n private int code;\n\n /**\n * 业务状态信息\n */\n @Schema(description = \"业务状态信息\", example = \"操作成功\")\n private String msg;\n\n /**\n * 响应数据\n */\n @Schema(description = \"响应数据\")\n private T data;\n\n /**\n * 时间戳\n */\n @Schema(description = \"时间戳\", example = \"1691453288\")\n private long timestamp = DateUtil.currentSeconds();\n\n /**\n * 成功状态码\n */\n private static final int SUCCESS_CODE = HttpStatus.OK.value();\n /**\n * 失败状态码\n */\n private static final int FAIL_CODE = HttpStatus.INTERNAL_SERVER_ERROR.value();\n\n private R(boolean success, int code, String msg, T data) {\n this.success = success;\n this.code = code;\n this.msg = msg;\n this.data = data;\n }\n\n public static <T> R<T> ok() {\n return new R<>(true, SUCCESS_CODE, \"操作成功\", null);\n }\n\n public static <T> R<T> ok(T data) {\n return new R<>(true, SUCCESS_CODE, \"操作成功\", data);\n }\n\n public static <T> R<T> ok(String msg) {\n return new R<>(true, SUCCESS_CODE, msg, null);\n }\n\n public static <T> R<T> ok(String msg, T data) {\n return new R<>(true, SUCCESS_CODE, msg, data);\n }\n\n public static <T> R<T> fail() {\n return new R<>(false, FAIL_CODE, \"操作失败\", null);\n }\n\n public static <T> R<T> fail(String msg) {\n return new R<>(false, FAIL_CODE, msg, null);\n }\n\n public static <T> R<T> fail(T data) {\n return new R<>(false, FAIL_CODE, \"操作失败\", data);\n }\n\n public static <T> R<T> fail(String msg, T data) {\n return new R<>(false, FAIL_CODE, msg, data);\n }\n\n public static <T> R<T> fail(int code, String msg) {\n return new R<>(false, code, msg, null);\n }\n}" } ]
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.util.StrUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import jakarta.servlet.http.HttpServletResponse; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import top.charles7c.continew.starter.core.constant.StringConstants; import top.charles7c.continew.starter.extension.crud.annotation.CrudRequestMapping; import top.charles7c.continew.starter.extension.crud.enums.Api; import top.charles7c.continew.starter.extension.crud.model.query.PageQuery; import top.charles7c.continew.starter.extension.crud.model.query.SortQuery; import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp; import top.charles7c.continew.starter.extension.crud.model.resp.R; import java.util.List;
3,651
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.extension.crud.base; /** * 控制器基类 * * @param <S> 业务接口 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ @NoArgsConstructor public abstract class BaseController<S extends BaseService<L, D, Q, C>, L, D, Q, C extends BaseReq> { @Autowired protected S baseService; /** * 分页查询列表 * * @param query 查询条件 * @param pageQuery 分页查询条件 * @return 分页信息 */ @Operation(summary = "分页查询列表", description = "分页查询列表") @ResponseBody @GetMapping public R<PageDataResp<L>> page(Q query, @Validated PageQuery pageQuery) { this.checkPermission(Api.LIST); PageDataResp<L> pageData = baseService.page(query, pageQuery); return R.ok(pageData); } /** * 查询树列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 树列表信息 */ @Operation(summary = "查询树列表", description = "查询树列表") @ResponseBody @GetMapping("/tree")
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.extension.crud.base; /** * 控制器基类 * * @param <S> 业务接口 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ @NoArgsConstructor public abstract class BaseController<S extends BaseService<L, D, Q, C>, L, D, Q, C extends BaseReq> { @Autowired protected S baseService; /** * 分页查询列表 * * @param query 查询条件 * @param pageQuery 分页查询条件 * @return 分页信息 */ @Operation(summary = "分页查询列表", description = "分页查询列表") @ResponseBody @GetMapping public R<PageDataResp<L>> page(Q query, @Validated PageQuery pageQuery) { this.checkPermission(Api.LIST); PageDataResp<L> pageData = baseService.page(query, pageQuery); return R.ok(pageData); } /** * 查询树列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 树列表信息 */ @Operation(summary = "查询树列表", description = "查询树列表") @ResponseBody @GetMapping("/tree")
public R<List<Tree<Long>>> tree(Q query, SortQuery sortQuery) {
3
2023-11-16 15:48:18+00:00
8k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/managers/ShrineManager.java
[ { "identifier": "Devotions", "path": "src/main/java/me/xidentified/devotions/Devotions.java", "snippet": "@Getter\npublic class Devotions extends JavaPlugin {\n @Getter private static Devotions instance;\n private DevotionManager devotionManager;\n private RitualManager ritualManager;\n private final Map<String, Miracle> miraclesMap = new HashMap<>();\n private CooldownManager cooldownManager;\n private MeditationManager meditationManager;\n private ShrineListener shrineListener;\n private YamlConfiguration deitiesConfig;\n private FileConfiguration ritualConfig;\n private FileConfiguration soundsConfig;\n private StorageManager storageManager;\n private DevotionStorage devotionStorage;\n private Translator translations;\n private FileConfiguration savedItemsConfig = null;\n private File savedItemsConfigFile = null;\n\n @Override\n public void onEnable() {\n saveDefaultConfig();\n initializePlugin();\n loadSoundsConfig();\n reloadSavedItemsConfig();\n\n TinyTranslationsBukkit.enable(this);\n translations = TinyTranslationsBukkit.application(this);\n translations.setMessageStorage(new YamlMessageStorage(new File(getDataFolder(), \"/lang/\")));\n translations.setStyleStorage(new YamlStyleStorage(new File(getDataFolder(), \"/lang/styles.yml\")));\n\n translations.addMessages(TinyTranslations.messageFieldsFromClass(Messages.class));\n\n loadLanguages();\n\n // Set the LocaleProvider\n translations.setLocaleProvider(audience -> {\n // Read settings from config\n boolean usePlayerClientLocale = getConfig().getBoolean(\"use-player-client-locale\", true);\n String fallbackLocaleCode = getConfig().getString(\"default-locale\", \"en\");\n Locale fallbackLocale = Locale.forLanguageTag(fallbackLocaleCode);\n\n if (audience == null || !usePlayerClientLocale) {\n return fallbackLocale;\n }\n\n return audience.getOrDefault(Identity.LOCALE, fallbackLocale);\n });\n\n // If PAPI is installed we'll register placeholders\n if(Bukkit.getPluginManager().getPlugin(\"PlaceholderAPI\") != null) {\n new Placeholders(this).register();\n debugLog(\"PlaceholderAPI expansion enabled!\");\n }\n }\n\n private Map<String, Deity> loadDeities(YamlConfiguration deitiesConfig) {\n Map<String, Deity> deityMap = new HashMap<>();\n ConfigurationSection deitiesSection = deitiesConfig.getConfigurationSection(\"deities\");\n assert deitiesSection != null;\n for (String deityKey : deitiesSection.getKeys(false)) {\n ConfigurationSection deityConfig = deitiesSection.getConfigurationSection(deityKey);\n\n assert deityConfig != null;\n String name = deityConfig.getString(\"name\");\n String lore = deityConfig.getString(\"lore\");\n String domain = deityConfig.getString(\"domain\");\n String alignment = deityConfig.getString(\"alignment\");\n List<String> favoredRituals = deityConfig.getStringList(\"rituals\");\n\n // Load offerings\n List<String> offeringStrings = deityConfig.getStringList(\"offerings\");\n List<Offering> favoredOfferings = offeringStrings.stream()\n .map(offeringString -> {\n String[] parts = offeringString.split(\":\");\n if (parts.length < 3) {\n getLogger().warning(\"Invalid offering format for deity \" + deityKey + \": \" + offeringString);\n return null;\n }\n\n String type = parts[0];\n String itemId = parts[1];\n int favorValue;\n try {\n favorValue = Integer.parseInt(parts[2]);\n } catch (NumberFormatException e) {\n getLogger().warning(\"Invalid favor value in offerings for deity \" + deityKey + \": \" + parts[2]);\n return null;\n }\n\n List<String> commands = new ArrayList<>();\n if (parts.length > 3) {\n commands = Arrays.asList(parts[3].split(\";\"));\n debugLog(\"Loaded commands for offering: \" + commands);\n }\n\n ItemStack itemStack;\n if (\"Saved\".equalsIgnoreCase(type)) {\n itemStack = loadSavedItem(itemId);\n if (itemStack == null) {\n getLogger().warning(\"Saved item not found: \" + itemId + \" for deity: \" + deityKey);\n return null;\n }\n } else {\n Material material = Material.matchMaterial(itemId);\n if (material == null) {\n getLogger().warning(\"Invalid material in offerings for deity \" + deityKey + \": \" + itemId);\n return null;\n }\n itemStack = new ItemStack(material);\n }\n return new Offering(itemStack, favorValue, commands);\n })\n .filter(Objects::nonNull)\n .collect(Collectors.toList());\n\n // Parse blessings\n List<Blessing> deityBlessings = deityConfig.getStringList(\"blessings\").stream()\n .map(this::parseBlessing)\n .collect(Collectors.toList());\n\n // Parse curses\n List<Curse> deityCurses = deityConfig.getStringList(\"curses\").stream()\n .map(this::parseCurse)\n .collect(Collectors.toList());\n\n List<Miracle> deityMiracles = new ArrayList<>();\n\n for (String miracleString : deityConfig.getStringList(\"miracles\")) {\n Miracle miracle = parseMiracle(miracleString);\n if (miracle != null) {\n deityMiracles.add(miracle);\n miraclesMap.put(miracleString, miracle);\n } else {\n debugLog(\"Failed to parse miracle: \" + miracleString + \" for deity \" + deityKey);\n }\n }\n\n Deity deity = new Deity(this, name, lore, domain, alignment, favoredOfferings, favoredRituals, deityBlessings, deityCurses, deityMiracles);\n deityMap.put(deityKey.toLowerCase(), deity);\n getLogger().info(\"Loaded deity \" + deity.getName() + \" with \" + favoredOfferings.size() + \" offerings.\");\n }\n\n return deityMap;\n }\n\n private Miracle parseMiracle(String miracleString) {\n debugLog(\"Parsing miracle: \" + miracleString);\n MiracleEffect effect;\n List<Condition> conditions = new ArrayList<>();\n\n String[] parts = miracleString.split(\":\", 2);\n String miracleType = parts[0]; // Define miracleType here\n\n debugLog(\"Parsed miracleString: \" + miracleString);\n debugLog(\"Miracle type: \" + miracleType);\n if (parts.length > 1) {\n debugLog(\"Command/Argument: \" + parts[1]);\n }\n\n switch (miracleType) {\n case \"revive_on_death\" -> {\n effect = new ReviveOnDeath();\n conditions.add(new IsDeadCondition());\n }\n case \"stop_burning\" -> {\n effect = new SaveFromBurning();\n conditions.add(new IsOnFireCondition());\n }\n case \"repair_all\" -> {\n effect = new RepairAllItems();\n conditions.add(new HasRepairableItemsCondition());\n }\n case \"summon_aid\" -> {\n effect = new SummonAidEffect(3); // Summoning 3 entities.\n conditions.add(new LowHealthCondition());\n conditions.add(new NearHostileMobsCondition());\n }\n case \"village_hero\" -> {\n effect = new HeroEffectInVillage();\n conditions.add(new NearVillagersCondition());\n }\n case \"double_crops\" -> {\n if (parts.length > 1) {\n try {\n int duration = Integer.parseInt(parts[1]);\n effect = new DoubleCropDropsEffect(this, duration);\n conditions.add(new NearCropsCondition());\n } catch (NumberFormatException e) {\n debugLog(\"Invalid duration provided for double_crops miracle.\");\n return null;\n }\n } else {\n debugLog(\"No duration provided for double_crops miracle.\");\n return null;\n }\n }\n case \"run_command\" -> {\n if (parts.length > 1) {\n String command = parts[1];\n effect = new ExecuteCommandEffect(command);\n } else {\n debugLog(\"No command provided for run_command miracle.\");\n return null;\n }\n }\n default -> {\n debugLog(\"Unrecognized miracle encountered in parseMiracle!\");\n return null;\n }\n }\n\n return new Miracle(miracleType, conditions, effect);\n }\n\n private Blessing parseBlessing(String blessingString) {\n String[] parts = blessingString.split(\",\");\n PotionEffectType effect = PotionEffectType.getByName(parts[0]);\n int strength = Integer.parseInt(parts[1]);\n int duration = Integer.parseInt(parts[2]);\n return new Blessing(parts[0], duration, strength, effect);\n }\n\n private Curse parseCurse(String curseString) {\n String[] parts = curseString.split(\",\");\n PotionEffectType effect = PotionEffectType.getByName(parts[0]);\n int strength = Integer.parseInt(parts[1]);\n int duration = Integer.parseInt(parts[2]);\n return new Curse(parts[0], duration, strength, effect);\n }\n\n public YamlConfiguration getDeitiesConfig() {\n if (deitiesConfig == null) {\n File deitiesFile = new File(getDataFolder(), \"deities.yml\");\n deitiesConfig = YamlConfiguration.loadConfiguration(deitiesFile);\n }\n return deitiesConfig;\n }\n\n private void loadRituals() {\n ConfigurationSection ritualsSection = ritualConfig.getConfigurationSection(\"rituals\");\n if (ritualsSection == null) {\n getLogger().warning(\"No rituals section found in config.\");\n return;\n }\n\n for (String key : ritualsSection.getKeys(false)) {\n try {\n String path = \"rituals.\" + key + \".\";\n\n // Parse general info\n String displayName = ritualConfig.getString(path + \"display_name\");\n String description = ritualConfig.getString(path + \"description\");\n int favorReward = ritualConfig.getInt(path + \"favor\");\n\n // Parse item\n String itemString = ritualConfig.getString(path + \"item\");\n RitualItem ritualItem = null;\n if (itemString != null) {\n String[] parts = itemString.split(\":\");\n if (parts.length == 2) {\n String type = parts[0];\n String itemId = parts[1];\n\n if (\"SAVED\".equalsIgnoreCase(type)) {\n ItemStack savedItem = loadSavedItem(itemId);\n if (savedItem == null) {\n getLogger().warning(\"Saved item not found: \" + itemId + \" for ritual: \" + key);\n } else {\n ritualItem = new RitualItem(\"SAVED\", savedItem);\n }\n } else if (\"VANILLA\".equalsIgnoreCase(type)) {\n ritualItem = new RitualItem(\"VANILLA\", itemId);\n } else {\n getLogger().warning(\"Unknown item type: \" + type + \" for ritual: \" + key);\n }\n }\n }\n\n // Parse conditions\n String expression = ritualConfig.getString(path + \"conditions.expression\", \"\");\n String time = ritualConfig.getString(path + \"conditions.time\");\n String biome = ritualConfig.getString(path + \"conditions.biome\");\n String weather = ritualConfig.getString(path + \"conditions.weather\");\n String moonPhase = ritualConfig.getString(path + \"conditions.moon_phase\");\n double minAltitude = ritualConfig.getDouble(path + \"conditions.min_altitude\", 0.0);\n int minExperience = ritualConfig.getInt(path + \"conditions.min_experience\", 0);\n double minHealth = ritualConfig.getDouble(path + \"conditions.min_health\", 0.0);\n int minHunger = ritualConfig.getInt(path + \"conditions.min_hunger\", 0);\n\n RitualConditions ritualConditions = new RitualConditions(expression, time, biome, weather, moonPhase,\n minAltitude, minExperience, minHealth, minHunger);\n\n // Parse outcome\n List<String> outcomeCommands;\n if (ritualConfig.isList(path + \"outcome-command\")) {\n outcomeCommands = ritualConfig.getStringList(path + \"outcome-command\");\n } else {\n String singleCommand = ritualConfig.getString(path + \"outcome-command\");\n if (singleCommand == null || singleCommand.isEmpty()) {\n getLogger().warning(\"No outcome specified for ritual: \" + key);\n continue; // Skip if no command is provided\n }\n outcomeCommands = Collections.singletonList(singleCommand);\n }\n RitualOutcome ritualOutcome = new RitualOutcome(\"RUN_COMMAND\", outcomeCommands);\n\n // Parse objectives\n List<RitualObjective> objectives = new ArrayList<>();\n try {\n List<Map<?, ?>> objectivesList = ritualConfig.getMapList(path + \"objectives\");\n for (Map<?, ?> objectiveMap : objectivesList) {\n String typeStr = (String) objectiveMap.get(\"type\");\n RitualObjective.Type type = RitualObjective.Type.valueOf(typeStr);\n String objDescription = (String) objectiveMap.get(\"description\");\n String target = (String) objectiveMap.get(\"target\");\n int count = (Integer) objectiveMap.get(\"count\");\n\n RitualObjective objective = new RitualObjective(this, type, objDescription, target, count);\n objectives.add(objective);\n debugLog(\"Loaded objective \" + objDescription + \" for ritual \" + key);\n }\n } catch (Exception e) {\n getLogger().warning(\"Failed to load objectives for ritual: \" + key);\n e.printStackTrace();\n }\n\n\n // Create and store the ritual\n Ritual ritual = new Ritual(this, displayName, description, ritualItem, favorReward, ritualConditions, ritualOutcome, objectives);\n RitualManager.getInstance(this).addRitual(key, ritual); // Store the ritual and key\n } catch (Exception e) {\n getLogger().severe(\"Failed to load ritual with key: \" + key);\n e.printStackTrace();\n }\n }\n }\n\n public void spawnParticles(Location location, Particle particle, int count, double radius, double velocity) {\n World world = location.getWorld();\n Particle.DustOptions dustOptions = null;\n if (particle == Particle.REDSTONE) {\n dustOptions = new Particle.DustOptions(Color.RED, 1.0f); // You can adjust the color and size as needed\n }\n\n for (int i = 0; i < count; i++) {\n double phi = Math.acos(2 * Math.random() - 1); // Angle for elevation\n double theta = 2 * Math.PI * Math.random(); // Angle for azimuth\n\n double x = radius * Math.sin(phi) * Math.cos(theta);\n double y = radius * Math.sin(phi) * Math.sin(theta);\n double z = radius * Math.cos(phi);\n\n Location particleLocation = location.clone().add(x, y, z);\n Vector direction = particleLocation.toVector().subtract(location.toVector()).normalize().multiply(velocity);\n\n if (dustOptions != null) {\n world.spawnParticle(particle, particleLocation, 0, direction.getX(), direction.getY(), direction.getZ(), 0, dustOptions);\n } else {\n world.spawnParticle(particle, particleLocation, 0, direction.getX(), direction.getY(), direction.getZ(), 0);\n }\n }\n }\n\n public void spawnRitualMobs(Location center, EntityType entityType, int count, double radius) {\n World world = center.getWorld();\n List<Location> validLocations = new ArrayList<>();\n\n // Find valid spawn locations\n for (int i = 0; i < count * 10; i++) {\n double angle = 2 * Math.PI * i / count;\n double x = center.getX() + radius * Math.sin(angle);\n double z = center.getZ() + radius * Math.cos(angle);\n Location potentialLocation = new Location(world, x, center.getY(), z);\n Block block = potentialLocation.getBlock();\n if (block.getType() == Material.AIR && block.getRelative(BlockFace.DOWN).getType().isSolid() && block.getRelative(BlockFace.UP).getType() == Material.AIR) {\n validLocations.add(potentialLocation);\n }\n }\n\n // Spawn mobs at valid locations\n for (int i = 0; i < Math.min(count, validLocations.size()); i++) {\n world.spawnEntity(validLocations.get(i), entityType);\n }\n }\n\n public void reloadConfigurations() {\n reloadConfig();\n reloadRitualConfig();\n reloadSoundsConfig();\n loadLanguages();\n\n // Reset the DevotionManager\n if (devotionManager != null) {\n devotionManager.reset();\n }\n\n initializePlugin();\n }\n\n private void loadRitualConfig() {\n File ritualFile = new File(getDataFolder(), \"rituals.yml\");\n if (!ritualFile.exists()) {\n saveResource(\"rituals.yml\", false);\n }\n ritualConfig = YamlConfiguration.loadConfiguration(ritualFile);\n }\n\n private void reloadRitualConfig() {\n File ritualFile = new File(getDataFolder(), \"rituals.yml\");\n if (ritualFile.exists()) {\n ritualConfig = YamlConfiguration.loadConfiguration(ritualFile);\n }\n loadRituals();\n }\n\n private Map<String, Deity> reloadDeitiesConfig() {\n File deitiesFile = new File(getDataFolder(), \"deities.yml\");\n if (!deitiesFile.exists()) {\n saveResource(\"deities.yml\", false);\n }\n\n if (deitiesFile.exists()) {\n deitiesConfig = YamlConfiguration.loadConfiguration(deitiesFile);\n return loadDeities(deitiesConfig);\n } else {\n getLogger().severe(\"Unable to create default deities.yml\");\n return new HashMap<>(); // Return an empty map as a fallback\n }\n }\n\n private void reloadSoundsConfig() {\n File soundFile = new File(getDataFolder(), \"sounds.yml\");\n if (soundFile.exists()) {\n soundsConfig = YamlConfiguration.loadConfiguration(soundFile);\n }\n loadRituals();\n }\n\n public void reloadSavedItemsConfig() {\n if (savedItemsConfigFile == null) {\n savedItemsConfigFile = new File(getDataFolder(), \"savedItems.yml\");\n }\n savedItemsConfig = YamlConfiguration.loadConfiguration(savedItemsConfigFile);\n\n // Look for defaults in the jar\n InputStream defConfigStream = getResource(\"savedItems.yml\");\n if (defConfigStream != null) {\n YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream));\n savedItemsConfig.setDefaults(defConfig);\n }\n }\n\n public FileConfiguration getSavedItemsConfig() {\n if (savedItemsConfig == null) {\n reloadSavedItemsConfig();\n }\n return savedItemsConfig;\n }\n\n /**\n * Run to reload changes to message files\n */\n public void loadLanguages() {\n\n if (!new File(getDataFolder(), \"/lang/styles.yml\").exists()) {\n saveResource(\"lang/styles.yml\", false);\n }\n translations.loadStyles();\n\n // save default translations\n translations.saveLocale(Locale.ENGLISH);\n saveResource(\"lang/de.yml\", false);\n\n // load\n translations.loadLocales();\n }\n\n public void loadSoundsConfig() {\n File soundsFile = new File(getDataFolder(), \"sounds.yml\");\n if (!soundsFile.exists()) {\n saveResource(\"sounds.yml\", false);\n }\n soundsConfig = YamlConfiguration.loadConfiguration(soundsFile);\n debugLog(\"sounds.yml successfully loaded!\");\n }\n\n private void initializePlugin() {\n HandlerList.unregisterAll(this);\n instance = this;\n loadRitualConfig();\n\n // Initiate manager classes\n this.storageManager = new StorageManager(this);\n\n // Clear existing data before re-initializing\n if (devotionManager != null) {\n devotionManager.clearData();\n }\n\n Map<String, Deity> loadedDeities = reloadDeitiesConfig();\n this.devotionStorage = new DevotionStorage(storageManager);\n this.devotionManager = new DevotionManager(this, loadedDeities);\n ShrineManager shrineManager = new ShrineManager(this);\n loadRituals();\n ShrineStorage shrineStorage = new ShrineStorage(this, storageManager);\n shrineManager.setShrineStorage(shrineStorage);\n ritualManager = RitualManager.getInstance(this);\n this.cooldownManager = new CooldownManager(this);\n this.meditationManager = new MeditationManager(this);\n FavorCommand favorCmd = new FavorCommand(this);\n ShrineCommandExecutor shrineCmd = new ShrineCommandExecutor(devotionManager, shrineManager);\n DeityCommand deityCmd = new DeityCommand(this);\n RitualCommand ritualCommand = new RitualCommand(this);\n\n // Register commands\n Objects.requireNonNull(getCommand(\"deity\")).setExecutor(deityCmd);\n Objects.requireNonNull(getCommand(\"deity\")).setTabCompleter(deityCmd);\n Objects.requireNonNull(getCommand(\"favor\")).setExecutor(favorCmd);\n Objects.requireNonNull(getCommand(\"favor\")).setTabCompleter(favorCmd);\n Objects.requireNonNull(getCommand(\"shrine\")).setExecutor(shrineCmd);\n Objects.requireNonNull(getCommand(\"shrine\")).setTabCompleter(shrineCmd);\n Objects.requireNonNull(getCommand(\"devotions\")).setExecutor(new DevotionsCommandExecutor(this));\n Objects.requireNonNull(getCommand(\"ritual\")).setExecutor(ritualCommand);\n Objects.requireNonNull(getCommand(\"ritual\")).setTabCompleter(ritualCommand);\n\n // Register admin commands\n TestMiracleCommand testMiracleCmd = new TestMiracleCommand(miraclesMap);\n Objects.requireNonNull(getCommand(\"testmiracle\")).setExecutor(testMiracleCmd);\n\n // Register listeners\n this.shrineListener = new ShrineListener(this, shrineManager, cooldownManager);\n RitualListener.initialize(this, shrineManager);\n getServer().getPluginManager().registerEvents(new DoubleCropDropsEffect(this, 90), this);\n getServer().getPluginManager().registerEvents(new PlayerListener(this), this);\n\n // Register events\n getServer().getPluginManager().registerEvents(RitualListener.getInstance(), this);\n getServer().getPluginManager().registerEvents(shrineListener, this);\n getServer().getPluginManager().registerEvents(shrineCmd, this);\n\n debugLog(\"Devotions successfully initialized!\");\n }\n\n @Override\n public void onDisable() {\n // Unregister all listeners\n HandlerList.unregisterAll(this);\n\n // Save all player devotions to ensure data is not lost on shutdown\n devotionManager.saveAllPlayerDevotions();\n\n // Cancel tasks\n getServer().getScheduler().cancelTasks(this);\n ritualManager.ritualDroppedItems.clear();\n\n translations.close();\n }\n\n public int getShrineLimit() {\n return getConfig().getInt(\"shrine-limit\", 3);\n }\n\n public void debugLog(String message) {\n if (getConfig().getBoolean(\"debug_mode\")) {\n getLogger().info(\"[DEBUG] \" + message);\n }\n }\n\n public void playConfiguredSound(Player player, String key) {\n if (soundsConfig == null) {\n debugLog(\"soundsConfig is null.\");\n return;\n }\n\n String soundKey = \"sounds.\" + key;\n if (soundsConfig.contains(soundKey)) {\n String soundName = soundsConfig.getString(soundKey + \".sound\");\n float volume = (float) soundsConfig.getDouble(soundKey + \".volume\");\n float pitch = (float) soundsConfig.getDouble(soundKey + \".pitch\");\n\n Sound sound = Sound.valueOf(soundName);\n player.playSound(player.getLocation(), sound, volume, pitch);\n } else {\n debugLog(\"Sound \" + soundKey + \" not found in sounds.yml!\");\n }\n }\n\n private ItemStack loadSavedItem(String name) {\n File storageFolder = new File(getDataFolder(), \"storage\");\n File itemsFile = new File(storageFolder, \"savedItems.yml\");\n FileConfiguration config = YamlConfiguration.loadConfiguration(itemsFile);\n\n if (config.contains(\"items.\" + name)) {\n return ItemStack.deserialize(config.getConfigurationSection(\"items.\" + name).getValues(false));\n }\n return null;\n }\n\n public void sendMessage(CommandSender sender, ComponentLike componentLike) {\n if (componentLike instanceof Message msg) {\n // Translate the message into the locale of the command sender\n componentLike = translations.process(msg, TinyTranslationsBukkit.getLocale(sender));\n }\n TinyTranslationsBukkit.sendMessage(sender, componentLike);\n }\n\n}" }, { "identifier": "Shrine", "path": "src/main/java/me/xidentified/devotions/Shrine.java", "snippet": "@Getter\npublic class Shrine {\n private final Location location;\n private final UUID owner;\n @Setter private Deity deity;\n\n public Shrine(Location location, Deity deity, UUID owner) {\n this.location = location;\n this.deity = deity;\n this.owner = owner;\n }\n\n}" }, { "identifier": "ShrineStorage", "path": "src/main/java/me/xidentified/devotions/storage/ShrineStorage.java", "snippet": "public class ShrineStorage {\n private final Devotions plugin;\n private final File shrineFile;\n private final YamlConfiguration yaml;\n\n public ShrineStorage(Devotions plugin, StorageManager storageManager) {\n this.plugin = plugin;\n shrineFile = new File(storageManager.getStorageFolder(), \"shrines.yml\");\n if (!shrineFile.exists()) {\n try {\n shrineFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n yaml = YamlConfiguration.loadConfiguration(shrineFile);\n }\n\n public void saveShrine(Shrine shrine) {\n String key = generateShrineKey(shrine);\n String deityName = shrine.getDeity().getName();\n\n // Save the shrine details in a single line format\n yaml.set(\"shrines.\" + key, deityName);\n save();\n }\n\n public void removeShrine(Location location, UUID ownerUUID) {\n String key = findKeyByLocationAndOwner(location, ownerUUID);\n if (key != null) {\n yaml.set(\"shrines.\" + key, null);\n save();\n }\n }\n\n private String generateShrineKey(Shrine shrine) {\n Location location = shrine.getLocation();\n UUID ownerUUID = shrine.getOwner();\n return location.getWorld().getName() + \",\" +\n location.getBlockX() + \",\" +\n location.getBlockY() + \",\" +\n location.getBlockZ() + \",\" +\n ownerUUID.toString();\n }\n\n private String findKeyByLocationAndOwner(Location location, UUID ownerUUID) {\n ConfigurationSection shrinesSection = yaml.getConfigurationSection(\"shrines\");\n if (shrinesSection == null) return null;\n\n for (String key : shrinesSection.getKeys(false)) {\n String[] parts = key.split(\",\");\n if (parts.length < 5) continue; // Skip if the format is incorrect\n\n World world = Bukkit.getWorld(parts[0]);\n int x = Integer.parseInt(parts[1]);\n int y = Integer.parseInt(parts[2]);\n int z = Integer.parseInt(parts[3]);\n UUID storedOwnerUUID = UUID.fromString(parts[4]);\n\n Location storedLocation = new Location(world, x, y, z);\n if (storedLocation.equals(location) && storedOwnerUUID.equals(ownerUUID)) {\n return key;\n }\n }\n\n return null;\n }\n\n\n public List<Shrine> loadAllShrines(DevotionManager devotionManager) {\n List<Shrine> loadedShrines = new ArrayList<>();\n ConfigurationSection shrineSection = yaml.getConfigurationSection(\"shrines\");\n if (shrineSection == null) {\n plugin.debugLog(\"Shrine section is null.\");\n return loadedShrines;\n }\n\n for (String shrineKey : shrineSection.getKeys(false)) {\n String[] parts = shrineKey.split(\",\");\n World world = Bukkit.getWorld(parts[0]);\n if (world == null) {\n plugin.debugLog(\"World not found: \" + parts[0]);\n continue;\n }\n int x = Integer.parseInt(parts[1]);\n int y = Integer.parseInt(parts[2]);\n int z = Integer.parseInt(parts[3]);\n UUID ownerUUID = UUID.fromString(parts[4]);\n\n String deityName = shrineSection.getString(shrineKey);\n Deity deity = devotionManager.getDeityByName(deityName);\n if (deity == null) {\n plugin.debugLog(\"Deity not found: \" + deityName);\n continue;\n }\n\n Location location = new Location(world, x, y, z);\n Shrine shrine = new Shrine(location, deity, ownerUUID);\n loadedShrines.add(shrine);\n }\n\n plugin.getLogger().info(\"Loaded \" + loadedShrines.size() + \" shrines.\");\n return loadedShrines;\n }\n\n private void save() {\n try {\n yaml.save(shrineFile);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}" } ]
import lombok.Getter; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.Shrine; import me.xidentified.devotions.storage.ShrineStorage; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap;
6,922
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin; private ShrineStorage shrineStorage;
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin; private ShrineStorage shrineStorage;
private final List<Shrine> allShrinesList;
1
2023-11-10 07:03:24+00:00
8k
Appu26J/Calculator
src/appu26j/Calculator.java
[ { "identifier": "Assets", "path": "src/appu26j/assets/Assets.java", "snippet": "public class Assets\n{\n\tprivate static final String tempDirectory = System.getProperty(\"java.io.tmpdir\");\n\tprivate static final ArrayList<String> assets = new ArrayList<>();\n\t\n\tstatic\n\t{\n\t\tassets.add(\"segoeui.ttf\");\n\t}\n\t\n\tpublic static void loadAssets()\n\t{\n\t\tFile assetsDirectory = new File(tempDirectory, \"calculator\");\n\t\t\n\t\tif (!assetsDirectory.exists())\n\t\t{\n\t\t\tassetsDirectory.mkdirs();\n\t\t}\n\t\t\n\t\tfor (String name : assets)\n\t\t{\n\t\t\tFile asset = new File(assetsDirectory, name);\n\n\t\t\tif (!asset.getParentFile().exists())\n\t\t\t{\n\t\t\t\tasset.getParentFile().mkdirs();\n\t\t\t}\n\n\t\t\tif (!asset.exists())\n\t\t\t{\n\t\t\t\tFileOutputStream fileOutputStream = null;\n\t\t\t\tInputStream inputStream = null;\n\t\t\t\t\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tinputStream = Assets.class.getResourceAsStream(name);\n\t\t\t\t\t\n\t\t\t\t\tif (inputStream == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new NullPointerException();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfileOutputStream = new FileOutputStream(asset);\n\t\t\t\t\tbyte[] bytes = new byte[4096];\n\t\t\t\t int read;\n\t\t\t\t \n\t\t\t\t while ((read = inputStream.read(bytes)) != -1)\n\t\t\t\t {\n\t\t\t\t \tfileOutputStream.write(bytes, 0, read);\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfinally\n\t\t\t\t{\n\t\t\t\t\tif (fileOutputStream != null)\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfileOutputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcatch (Exception e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (inputStream != null)\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcatch (Exception e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static File getAsset(String name)\n\t{\n\t\treturn new File(tempDirectory, \"calculator\" + File.separator + name);\n\t}\n}" }, { "identifier": "FontRenderer", "path": "src/appu26j/gui/font/FontRenderer.java", "snippet": "public class FontRenderer\n{\n private final HashMap<Character, Float> cachedWidths = new HashMap<>();\n public static final int CHAR_DATA_MALLOC_SIZE = 96;\n public static final int FONT_TEX_W = 512;\n public static final int FONT_TEX_H = FONT_TEX_W;\n public static final int BAKE_FONT_FIRST_CHAR = 32;\n public static final int GLYPH_COUNT = CHAR_DATA_MALLOC_SIZE;\n protected final STBTTBakedChar.Buffer charData;\n protected final STBTTFontinfo fontInfo;\n protected final int fontSize, textureID;\n protected final float ascent, descent, lineGap;\n \n public FontRenderer(File font, int fontSize)\n {\n this.fontSize = fontSize;\n this.charData = STBTTBakedChar.malloc(CHAR_DATA_MALLOC_SIZE);\n this.fontInfo = STBTTFontinfo.create();\n int textureID = 0;\n float ascent = 0, descent = 0, lineGap = 0;\n \n try\n {\n ByteBuffer ttfFileData = this.getByteBuffer(font);\n ByteBuffer texData = BufferUtils.createByteBuffer(FONT_TEX_W * FONT_TEX_H);\n STBTruetype.stbtt_BakeFontBitmap(ttfFileData, fontSize, texData, FONT_TEX_W, FONT_TEX_H, BAKE_FONT_FIRST_CHAR, charData);\n \n try (MemoryStack stack = MemoryStack.stackPush())\n {\n STBTruetype.stbtt_InitFont(this.fontInfo, ttfFileData);\n float pixelScale = STBTruetype.stbtt_ScaleForPixelHeight(this.fontInfo, fontSize);\n IntBuffer ascentBuffer = stack.ints(0);\n IntBuffer descentBuffer = stack.ints(0);\n IntBuffer lineGapBuffer = stack.ints(0);\n STBTruetype.stbtt_GetFontVMetrics(this.fontInfo, ascentBuffer, descentBuffer, lineGapBuffer);\n ascent = ascentBuffer.get(0) * pixelScale;\n descent = descentBuffer.get(0) * pixelScale;\n }\n \n textureID = glGenTextures();\n glBindTexture(GL_TEXTURE_2D, textureID);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, FONT_TEX_W, FONT_TEX_H, 0, GL_ALPHA, GL_UNSIGNED_BYTE, texData);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n \n catch (Exception e)\n {\n \te.printStackTrace();\n }\n \n this.textureID = textureID;\n this.ascent = ascent;\n this.descent = descent;\n this.lineGap = lineGap;\n char[] allLetters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~`!@#$%^&*()_+-={}[];':\\\"<>?,./ \".toCharArray();\n\n for (char letter : allLetters)\n {\n this.cachedWidths.put(letter, getCharWidth(letter));\n }\n }\n \n public void shutdown()\n {\n this.charData.free();\n this.fontInfo.free();\n \n if (this.textureID != 0)\n {\n glDeleteTextures(this.textureID);\n }\n }\n \n public ByteBuffer getByteBuffer(File file) throws IOException \n {\n ByteBuffer buffer;\n \n try (FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel())\n {\n buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());\n }\n \n return buffer;\n }\n \n public void drawStringWithShadow(String text, float x, float y, Color color)\n {\n \tthis.drawString(text, x + ((float) this.fontSize / 12), y + ((float) this.fontSize / 12), color.darker().darker().darker().darker());\n \tthis.drawString(text, x, y, color);\n }\n \n public void drawString(String text, float x, float y, Color color)\n {\n y += this.ascent;\n\n try (MemoryStack stack = MemoryStack.stackPush())\n {\n FloatBuffer xPosition = stack.mallocFloat(1);\n FloatBuffer yPosition = stack.mallocFloat(1);\n xPosition.put(x);\n yPosition.put(y);\n xPosition.flip();\n yPosition.flip();\n STBTTAlignedQuad stbttAlignedQuad = STBTTAlignedQuad.malloc(stack);\n glBindTexture(GL_TEXTURE_2D, this.textureID);\n GlStateManager.enableTexture2D();\n GlStateManager.enableAlpha();\n\t\t\tGlStateManager.enableBlend();\n\t\t\tGlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);\n\t\t\tGlStateManager.alphaFunc(516, 0);\n\t\t\tGlStateManager.color(color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, color.getAlpha() / 255F);\n glBegin(GL_TRIANGLES);\n int firstCP = BAKE_FONT_FIRST_CHAR;\n int lastCP = BAKE_FONT_FIRST_CHAR + GLYPH_COUNT - 1;\n \n for (int i = 0; i < text.length(); i++)\n {\n int codePoint = text.codePointAt(i);\n \n if (codePoint == '§')\n {\n \tGlStateManager.color(color.getRed() / 340F, color.getGreen() / 340F, color.getBlue() / 340F, color.getAlpha() / 340F);\n \tcontinue;\n }\n \n if (codePoint == '\\n')\n {\n \txPosition.put(0, x);\n yPosition.put(0, yPosition.get(0) + fontSize);\n continue;\n }\n \n else if (codePoint < firstCP || codePoint > lastCP)\n {\n continue;\n }\n \n STBTruetype.stbtt_GetBakedQuad(this.charData, FONT_TEX_W, FONT_TEX_H, codePoint - firstCP, xPosition, yPosition, stbttAlignedQuad, true);\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y0());\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());\n }\n \n glEnd();\n\t\t\tGlStateManager.disableBlend();\n\t\t\tGlStateManager.disableAlpha();\n\t\t\tGlStateManager.disableTexture2D();\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n }\n\n public float getStringWidth(String text)\n {\n float length = 0;\n\n for (char character : text.toCharArray())\n {\n if (this.cachedWidths.containsKey(character))\n {\n length += this.cachedWidths.get(character);\n }\n\n else\n {\n float charWidth = this.getCharWidth(character);\n this.cachedWidths.put(character, charWidth);\n length += charWidth;\n }\n }\n\n return length;\n }\n\n private float getCharWidth(char character)\n {\n float length = 0;\n\n try (MemoryStack memoryStack = MemoryStack.stackPush())\n {\n IntBuffer advancedWidth = memoryStack.mallocInt(1);\n IntBuffer leftSideBearing = memoryStack.mallocInt(1);\n STBTruetype.stbtt_GetCodepointHMetrics(this.fontInfo, character, advancedWidth, leftSideBearing);\n length += advancedWidth.get(0);\n }\n\n return length * STBTruetype.stbtt_ScaleForPixelHeight(this.fontInfo, this.fontSize);\n }\n}" }, { "identifier": "GuiCalculator", "path": "src/appu26j/gui/screens/GuiCalculator.java", "snippet": "public class GuiCalculator extends GuiScreen\n{\n private final ArrayList<Button> buttons = new ArrayList<>();\n private String equation = \"0\";\n\n @Override\n public void drawScreen(float mouseX, float mouseY)\n {\n for (Button button : this.buttons)\n {\n button.drawScreen(mouseX, mouseY);\n }\n\n String string = this.equation;\n\n if (string.endsWith(\"root\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"root(\" + number + \")\";\n }\n\n else if (string.endsWith(\"xx\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = number + \" * \" + number;\n }\n\n else if (string.endsWith(\"sin\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"sin(\" + number + \")\";\n }\n\n else if (string.endsWith(\"cos\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"cos(\" + number + \")\";\n }\n\n else if (string.endsWith(\"&\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"1 / \" + number;\n }\n\n this.fontRendererExtraBig.drawString(string, this.width - (this.fontRendererExtraBig.getStringWidth(string) + 10), this.height / 15, new Color(50, 50, 50));\n }\n\n @Override\n public void mouseClicked(int mouseButton, float mouseX, float mouseY)\n {\n super.mouseClicked(mouseButton, mouseX, mouseY);\n\n for (Button button : this.buttons)\n {\n button.mouseClicked(mouseButton, mouseX, mouseY);\n }\n }\n\n @Override\n public void initGUI(float width, float height)\n {\n super.initGUI(width, height);\n\n if (this.buttons.isEmpty())\n {\n float xOffset = 15, yOffset = height - 430;\n this.buttons.add(new Button(\"x2\", false, xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"root\", false, 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"sin\", false, 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"cos\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"<-\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"7\", xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"8\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"9\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"/\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"%\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"4\", xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"5\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"6\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"*\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"1/x\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"1\", xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"2\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"3\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"-\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"+\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"clr\", false, xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"0\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\".\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"=\", false, 255 + xOffset, yOffset, 160, 75, this));\n }\n }\n\n public String getEquation()\n {\n return this.equation;\n }\n\n public void appendEquation(String text)\n {\n if (this.equation.equals(\"0\") && !this.containsOperator(text))\n {\n this.equation = \"\";\n }\n\n this.equation += text;\n }\n\n public void backSpaceEquation()\n {\n if (this.equation.length() > 1)\n {\n this.equation = this.equation.substring(0, this.equation.length() - 1);\n this.equation = this.equation.trim();\n }\n\n else\n {\n this.equation = \"0\";\n }\n }\n\n public void appendAtStartEquation(String text)\n {\n this.equation = text + this.equation;\n }\n\n public void setEquation(String equation)\n {\n this.equation = equation;\n }\n\n public void clearEquation()\n {\n this.equation = \"0\";\n }\n\n public boolean containsOperator(String text)\n {\n text = text.trim();\n return text.endsWith(\"xx\") || text.endsWith(\"root\") || text.endsWith(\"sin\") || text.endsWith(\"cos\") || text.endsWith(\"/\") || text.endsWith(\"%\") || text.endsWith(\"*\") || text.endsWith(\"&\") || text.endsWith(\"-\") || text.endsWith(\"+\");\n }\n}" }, { "identifier": "GuiScreen", "path": "src/appu26j/gui/screens/GuiScreen.java", "snippet": "public abstract class GuiScreen extends Gui\n{\n\tprotected FontRenderer fontRendererExtraBig, fontRendererBig, fontRendererMid, fontRendererMidSmall, fontRenderer;\n\tprotected float width = 0, height = 0;\n\t\n\tpublic abstract void drawScreen(float mouseX, float mouseY);\n\t\n\tpublic void mouseClicked(int mouseButton, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\t\n\tpublic void mouseReleased(int mouseButton, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void charTyped(char character, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void keyPressed(int key, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\t\n\tpublic void initGUI(float width, float height)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.fontRenderer = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 28);\n\t\tthis.fontRendererMidSmall = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 36);\n\t\tthis.fontRendererMid = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 54);\n\t\tthis.fontRendererBig = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 72);\n\t\tthis.fontRendererExtraBig = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 88);\n\t}\n\t\n\tprotected boolean isInsideBox(float mouseX, float mouseY, float x, float y, float width, float height)\n\t{\n\t\treturn mouseX > x && mouseX < width && mouseY > y && mouseY < height;\n\t}\n\t\n\tpublic ArrayList<FontRenderer> getFontRenderers()\n\t{\n\t\treturn new ArrayList<>(Arrays.asList(this.fontRenderer, this.fontRendererMidSmall, this.fontRendererMid, this.fontRendererBig, this.fontRendererExtraBig));\n\t}\n}" } ]
import appu26j.assets.Assets; import appu26j.gui.font.FontRenderer; import appu26j.gui.screens.GuiCalculator; import appu26j.gui.screens.GuiScreen; import org.lwjgl.glfw.GLFWCharCallback; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWKeyCallback; import org.lwjgl.glfw.GLFWMouseButtonCallback; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import java.nio.DoubleBuffer; import java.util.Objects; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*;
5,859
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0; private GuiScreen currentScreen; private long window = 0; public void start() { this.initializeWindow(); this.setupOpenGL(); this.loop(); } private void initializeWindow() { Assets.loadAssets(); GLFWErrorCallback.createPrint(System.err).set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize GLFW"); } glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); this.window = glfwCreateWindow(this.width, this.height, "Calculator", 0, 0); glfwSetWindowPos(this.window, 50, 50); if (this.window == 0) { throw new IllegalStateException("Unable to create the GLFW window"); } glfwMakeContextCurrent(this.window); glfwSwapInterval(1); glfwSetCharCallback(this.window, new GLFWCharCallback() { @Override public void invoke(long window, int codepoint) { currentScreen.charTyped((char) codepoint, Calculator.this.mouseX, Calculator.this.mouseY); } }); glfwSetKeyCallback(this.window, new GLFWKeyCallback() { @Override public void invoke(long window, int key, int scancode, int action, int mods) { if (action == 1) { currentScreen.keyPressed(key, Calculator.this.mouseX, Calculator.this.mouseY); } } }); glfwSetMouseButtonCallback(this.window, new GLFWMouseButtonCallback() { public void invoke(long window, int button, int action, int mods) { if (action == 1) { currentScreen.mouseClicked(button, Calculator.this.mouseX, Calculator.this.mouseY); } else { currentScreen.mouseReleased(button, Calculator.this.mouseX, Calculator.this.mouseY); } } }); } private void setupOpenGL() { GL.createCapabilities(); glClearColor(0.875F, 0.875F, 0.875F, 1); glLoadIdentity(); glViewport(0, 0, this.width, this.height); glOrtho(0, this.width, this.height, 0, 1, 0); } private void loop() { this.currentScreen = new GuiCalculator(); this.currentScreen.initGUI(this.width, this.height); glfwShowWindow(this.window); while (!glfwWindowShouldClose(this.window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); try (MemoryStack memoryStack = MemoryStack.stackPush()) { DoubleBuffer mouseX = memoryStack.mallocDouble(1); DoubleBuffer mouseY = memoryStack.mallocDouble(1); glfwGetCursorPos(this.window, mouseX, mouseY); this.mouseX = (float) mouseX.get(); this.mouseY = (float) mouseY.get(); } this.currentScreen.drawScreen(this.mouseX, this.mouseY); glfwSwapBuffers(this.window); glfwPollEvents(); }
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0; private GuiScreen currentScreen; private long window = 0; public void start() { this.initializeWindow(); this.setupOpenGL(); this.loop(); } private void initializeWindow() { Assets.loadAssets(); GLFWErrorCallback.createPrint(System.err).set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize GLFW"); } glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); this.window = glfwCreateWindow(this.width, this.height, "Calculator", 0, 0); glfwSetWindowPos(this.window, 50, 50); if (this.window == 0) { throw new IllegalStateException("Unable to create the GLFW window"); } glfwMakeContextCurrent(this.window); glfwSwapInterval(1); glfwSetCharCallback(this.window, new GLFWCharCallback() { @Override public void invoke(long window, int codepoint) { currentScreen.charTyped((char) codepoint, Calculator.this.mouseX, Calculator.this.mouseY); } }); glfwSetKeyCallback(this.window, new GLFWKeyCallback() { @Override public void invoke(long window, int key, int scancode, int action, int mods) { if (action == 1) { currentScreen.keyPressed(key, Calculator.this.mouseX, Calculator.this.mouseY); } } }); glfwSetMouseButtonCallback(this.window, new GLFWMouseButtonCallback() { public void invoke(long window, int button, int action, int mods) { if (action == 1) { currentScreen.mouseClicked(button, Calculator.this.mouseX, Calculator.this.mouseY); } else { currentScreen.mouseReleased(button, Calculator.this.mouseX, Calculator.this.mouseY); } } }); } private void setupOpenGL() { GL.createCapabilities(); glClearColor(0.875F, 0.875F, 0.875F, 1); glLoadIdentity(); glViewport(0, 0, this.width, this.height); glOrtho(0, this.width, this.height, 0, 1, 0); } private void loop() { this.currentScreen = new GuiCalculator(); this.currentScreen.initGUI(this.width, this.height); glfwShowWindow(this.window); while (!glfwWindowShouldClose(this.window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); try (MemoryStack memoryStack = MemoryStack.stackPush()) { DoubleBuffer mouseX = memoryStack.mallocDouble(1); DoubleBuffer mouseY = memoryStack.mallocDouble(1); glfwGetCursorPos(this.window, mouseX, mouseY); this.mouseX = (float) mouseX.get(); this.mouseY = (float) mouseY.get(); } this.currentScreen.drawScreen(this.mouseX, this.mouseY); glfwSwapBuffers(this.window); glfwPollEvents(); }
this.currentScreen.getFontRenderers().forEach(FontRenderer::shutdown);
1
2023-11-10 18:00:58+00:00
8k
SplitfireUptown/datalinkx
flinkx/flinkx-vertica/flinkx-vertica-reader/src/main/java/com/dtstack/flinkx/vertica/reader/VerticaReader.java
[ { "identifier": "DataTransferConfig", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/config/DataTransferConfig.java", "snippet": "public class DataTransferConfig extends AbstractConfig {\n\n JobConfig job;\n\n public DataTransferConfig(Map<String, Object> map) {\n super(map);\n job = new JobConfig((Map<String, Object>) map.get(\"job\"));\n }\n\n public JobConfig getJob() {\n return job;\n }\n\n public void setJob(JobConfig job) {\n this.job = job;\n }\n\n String monitorUrls;\n\n public String getMonitorUrls() {\n return monitorUrls;\n }\n\n public void setMonitorUrls(String monitorUrls) {\n this.monitorUrls = monitorUrls;\n }\n\n String pluginRoot;\n\n public String getPluginRoot() {\n return pluginRoot;\n }\n\n public void setPluginRoot(String pluginRoot) {\n this.pluginRoot = pluginRoot;\n }\n\n String remotePluginPath;\n\n public String getRemotePluginPath() {\n return remotePluginPath;\n }\n\n public void setRemotePluginPath(String remotePluginPath) {\n this.remotePluginPath = remotePluginPath;\n }\n\n private static void checkConfig(DataTransferConfig config) {\n Preconditions.checkNotNull(config);\n\n JobConfig jobConfig = config.getJob();\n Preconditions.checkNotNull(jobConfig, \"Must specify job element\");\n\n List<ContentConfig> contentConfig = jobConfig.getContent();\n Preconditions.checkNotNull(contentConfig, \"Must specify content array\");\n Preconditions.checkArgument(contentConfig.size() != 0, \"Must specify at least one content element\");\n\n // 暂时只考虑只包含一个Content元素的情况\n ContentConfig content = contentConfig.get(0);\n\n // 检查reader配置\n ReaderConfig readerConfig = content.getReader();\n Preconditions.checkNotNull(readerConfig, \"Must specify a reader element\");\n Preconditions.checkNotNull(readerConfig.getName(), \"Must specify reader name\");\n ReaderConfig.ParameterConfig readerParameter = readerConfig.getParameter();\n Preconditions.checkNotNull(readerParameter, \"Must specify parameter for reader\");\n\n\n // 检查writer配置\n WriterConfig writerConfig = content.getWriter();\n Preconditions.checkNotNull(writerConfig, \"Must specify a writer element\");\n Preconditions.checkNotNull(writerConfig.getName(), \"Must specify the writer name\");\n WriterConfig.ParameterConfig writerParameter = writerConfig.getParameter();\n Preconditions.checkNotNull(writerParameter, \"Must specify parameter for the writer\");\n\n }\n\n public static DataTransferConfig parse(String json) {\n Map<String,Object> map = GsonUtil.GSON.fromJson(json, GsonUtil.gsonMapTypeToken);\n map = MapUtil.convertToHashMap(map);\n DataTransferConfig config = new DataTransferConfig(map);\n checkConfig(config);\n return config;\n }\n\n public static DataTransferConfig parse(Reader reader) {\n DataTransferConfig config = GsonUtil.GSON.fromJson(reader, DataTransferConfig.class);\n checkConfig(config);\n return config;\n }\n\n\n}" }, { "identifier": "ConstantValue", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/constants/ConstantValue.java", "snippet": "public class ConstantValue {\n\n public static final String STAR_SYMBOL = \"*\";\n public static final String POINT_SYMBOL = \".\";\n public static final String TWO_POINT_SYMBOL = \"..\";\n public static final String EQUAL_SYMBOL = \"=\";\n public static final String COLON_SYMBOL = \":\";\n public static final String SINGLE_QUOTE_MARK_SYMBOL = \"'\";\n public static final String DOUBLE_QUOTE_MARK_SYMBOL = \"\\\"\";\n public static final String COMMA_SYMBOL = \",\";\n public static final String SEMICOLON_SYMBOL = \";\";\n\n public static final String SINGLE_SLASH_SYMBOL = \"/\";\n public static final String DOUBLE_SLASH_SYMBOL = \"//\";\n\n public static final String LEFT_PARENTHESIS_SYMBOL = \"(\";\n public static final String RIGHT_PARENTHESIS_SYMBOL = \")\";\n\n\n public static final String DATA_TYPE_UNSIGNED = \"UNSIGNED\";\n\n\n public static final String KEY_HTTP = \"http\";\n\n public static final String PROTOCOL_HTTP = \"http://\";\n public static final String PROTOCOL_HTTPS = \"https://\";\n public static final String PROTOCOL_HDFS = \"hdfs://\";\n public static final String PROTOCOL_JDBC_MYSQL = \"jdbc:mysql://\";\n\n public static final String SYSTEM_PROPERTIES_KEY_OS = \"os.name\";\n public static final String SYSTEM_PROPERTIES_KEY_USER_DIR = \"user.dir\";\n public static final String SYSTEM_PROPERTIES_KEY_JAVA_VENDOR = \"java.vendor\";\n public static final String SYSTEM_PROPERTIES_KEY_FILE_ENCODING = \"file.encoding\";\n\n public static final String OS_WINDOWS = \"windows\";\n\n public static final String SHIP_FILE_PLUGIN_LOAD_MODE = \"shipfile\";\n public static final String CLASS_PATH_PLUGIN_LOAD_MODE = \"classpath\";\n\n public static final String TIME_SECOND_SUFFIX = \"sss\";\n public static final String TIME_MILLISECOND_SUFFIX = \"SSS\";\n\n public static final String FILE_SUFFIX_XML = \".xml\";\n\n public static final int MAX_BATCH_SIZE = 200000;\n\n public static final long STORE_SIZE_G = 1024L * 1024 * 1024;\n\n public static final long STORE_SIZE_M = 1024L * 1024;\n}" }, { "identifier": "JdbcDataReader", "path": "flinkx/flinkx-rdb/flinkx-rdb-reader/src/main/java/com.dtstack.flinkx.rdb.datareader/JdbcDataReader.java", "snippet": "public class JdbcDataReader extends BaseDataReader {\n\n protected String username;\n protected String password;\n protected String dbUrl;\n protected Properties properties;\n\n\n protected String table;\n protected String where;\n protected String customSql;\n protected String orderByColumn;\n\n protected String splitKey;\n protected int fetchSize;\n protected int queryTimeOut;\n\n protected IncrementConfig incrementConfig;\n protected DatabaseInterface databaseInterface;\n protected TypeConverterInterface typeConverter;\n protected List<MetaColumn> metaColumns;\n\n public JdbcDataReader(DataTransferConfig config, StreamExecutionEnvironment env) {\n super(config, env);\n\n ReaderConfig readerConfig = config.getJob().getContent().get(0).getReader();\n dbUrl = readerConfig.getParameter().getConnection().get(0).getJdbcUrl().get(0);\n username = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_USER_NAME);\n password = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_PASSWORD);\n table = readerConfig.getParameter().getConnection().get(0).getTable().get(0);\n where = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_WHERE);\n metaColumns = MetaColumn.getMetaColumns(readerConfig.getParameter().getColumn());\n fetchSize = readerConfig.getParameter().getIntVal(JdbcConfigKeys.KEY_FETCH_SIZE,0);\n queryTimeOut = readerConfig.getParameter().getIntVal(JdbcConfigKeys.KEY_QUERY_TIME_OUT,0);\n splitKey = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_SPLIK_KEY);\n customSql = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_CUSTOM_SQL,null);\n orderByColumn = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_ORDER_BY_COLUMN,null);\n properties = readerConfig.getParameter().getProperties(JdbcConfigKeys.KEY_PROPERTIES, null);\n\n buildIncrementConfig(readerConfig);\n }\n\n @Override\n public DataStream<Row> readData() {\n JdbcInputFormatBuilder builder = getBuilder();\n builder.setDataTransferConfig(dataTransferConfig);\n builder.setDriverName(databaseInterface.getDriverClass());\n builder.setDbUrl(dbUrl);\n builder.setUsername(username);\n builder.setPassword(password);\n builder.setBytes(bytes);\n builder.setMonitorUrls(monitorUrls);\n builder.setTable(table);\n builder.setDatabaseInterface(databaseInterface);\n builder.setTypeConverter(typeConverter);\n builder.setMetaColumn(metaColumns);\n builder.setFetchSize(fetchSize == 0 ? databaseInterface.getFetchSize() : fetchSize);\n builder.setQueryTimeOut(queryTimeOut == 0 ? databaseInterface.getQueryTimeout() : queryTimeOut);\n builder.setIncrementConfig(incrementConfig);\n builder.setSplitKey(splitKey);\n builder.setNumPartitions(numPartitions);\n builder.setCustomSql(customSql);\n builder.setProperties(properties);\n builder.setRestoreConfig(restoreConfig);\n builder.setHadoopConfig(hadoopConfig);\n builder.setTestConfig(testConfig);\n builder.setLogConfig(logConfig);\n builder.setRateCounterLimit(rateCounterLimit);\n\n QuerySqlBuilder sqlBuilder = new QuerySqlBuilder(this);\n builder.setQuery(sqlBuilder.buildSql());\n\n BaseRichInputFormat format = builder.finish();\n return createInput(format);\n }\n\n protected JdbcInputFormatBuilder getBuilder() {\n throw new RuntimeException(\"code error : com.dtstack.flinkx.rdb.datareader.JdbcDataReader.getBuilder must be overwrite by subclass.\");\n }\n\n private void buildIncrementConfig(ReaderConfig readerConfig){\n boolean polling = readerConfig.getParameter().getBooleanVal(JdbcConfigKeys.KEY_POLLING, false);\n String increColumn = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_INCRE_COLUMN);\n String startLocation = readerConfig.getParameter().getStringVal(JdbcConfigKeys.KEY_START_LOCATION,null);\n boolean useMaxFunc = readerConfig.getParameter().getBooleanVal(JdbcConfigKeys.KEY_USE_MAX_FUNC, false);\n int requestAccumulatorInterval = readerConfig.getParameter().getIntVal(JdbcConfigKeys.KEY_REQUEST_ACCUMULATOR_INTERVAL, 2);\n long pollingInterval = readerConfig.getParameter().getLongVal(JdbcConfigKeys.KEY_POLLING_INTERVAL, 5000);\n\n incrementConfig = new IncrementConfig();\n //增量字段不为空,表示任务为增量或间隔轮询任务\n if (StringUtils.isNotBlank(increColumn)){\n String type = null;\n String name = null;\n int index = -1;\n\n //纯数字则表示增量字段在column中的顺序位置\n if(NumberUtils.isNumber(increColumn)){\n int idx = Integer.parseInt(increColumn);\n if(idx > metaColumns.size() - 1){\n throw new RuntimeException(\n String.format(\"config error : incrementColumn must less than column.size() when increColumn is number, column = %s, size = %s, increColumn = %s\",\n GsonUtil.GSON.toJson(metaColumns),\n metaColumns.size(),\n increColumn));\n }\n MetaColumn metaColumn = metaColumns.get(idx);\n type = metaColumn.getType();\n name = metaColumn.getName();\n index = metaColumn.getIndex();\n } else {\n for (MetaColumn metaColumn : metaColumns) {\n if(Objects.equals(increColumn, metaColumn.getName())){\n type = metaColumn.getType();\n name = metaColumn.getName();\n index = metaColumn.getIndex();\n break;\n }\n }\n }\n if (type == null || name == null){\n throw new IllegalArgumentException(\n String.format(\"config error : increColumn's name or type is null, column = %s, increColumn = %s\",\n GsonUtil.GSON.toJson(metaColumns),\n increColumn));\n }\n\n incrementConfig.setIncrement(true);\n incrementConfig.setPolling(polling);\n incrementConfig.setColumnName(name);\n incrementConfig.setColumnType(type);\n incrementConfig.setStartLocation(startLocation);\n incrementConfig.setUseMaxFunc(useMaxFunc);\n incrementConfig.setColumnIndex(index);\n incrementConfig.setRequestAccumulatorInterval(requestAccumulatorInterval);\n incrementConfig.setPollingInterval(pollingInterval);\n }\n }\n\n public void setDatabaseInterface(DatabaseInterface databaseInterface) {\n this.databaseInterface = databaseInterface;\n }\n\n public void setTypeConverterInterface(TypeConverterInterface typeConverter) {\n this.typeConverter = typeConverter;\n }\n}" }, { "identifier": "JdbcInputFormatBuilder", "path": "flinkx/flinkx-rdb/flinkx-rdb-reader/src/main/java/com.dtstack.flinkx.rdb.inputformat/JdbcInputFormatBuilder.java", "snippet": "public class JdbcInputFormatBuilder extends BaseRichInputFormatBuilder {\n\n protected JdbcInputFormat format;\n\n public JdbcInputFormatBuilder(JdbcInputFormat format) {\n super.format = this.format = format;\n }\n\n public void setDriverName(String driverName) {\n format.driverName = driverName;\n }\n\n public void setDbUrl(String dbUrl) {\n format.dbUrl = dbUrl;\n }\n\n public void setQuery(String query) {\n format.queryTemplate = query;\n }\n\n public void setUsername(String username) {\n format.username = username;\n }\n\n public void setPassword(String password) {\n format.password = password;\n }\n\n public void setTable(String table) {\n format.table = table;\n }\n\n public void setDatabaseInterface(DatabaseInterface databaseInterface) {\n format.databaseInterface = databaseInterface;\n }\n\n public void setTypeConverter(TypeConverterInterface converter){\n format.typeConverter = converter;\n }\n\n public void setMetaColumn(List<MetaColumn> metaColumns){\n format.metaColumns = metaColumns;\n }\n\n public void setFetchSize(int fetchSize){\n format.fetchSize = fetchSize;\n }\n\n public void setQueryTimeOut(int queryTimeOut){\n format.queryTimeOut = queryTimeOut;\n }\n\n public void setSplitKey(String splitKey){\n format.splitKey = splitKey;\n }\n\n public void setNumPartitions(int numPartitions){\n format.numPartitions = numPartitions;\n }\n\n public void setCustomSql(String customSql){\n format.customSql = customSql;\n }\n\n public void setProperties(Properties properties){\n format.properties = properties;\n }\n\n public void setHadoopConfig(Map<String,Object> dirtyHadoopConfig) {\n format.hadoopConfig = dirtyHadoopConfig;\n }\n\n public void setIncrementConfig(IncrementConfig incrementConfig){\n format.incrementConfig = incrementConfig;\n }\n\n @Override\n protected void checkFormat() {\n\n if (format.username == null) {\n LOG.info(\"Username was not supplied separately.\");\n }\n\n if (format.password == null) {\n LOG.info(\"Password was not supplied separately.\");\n }\n\n if (format.dbUrl == null) {\n throw new IllegalArgumentException(\"No database URL supplied\");\n }\n\n if (format.driverName == null) {\n throw new IllegalArgumentException(\"No dsdriver supplied\");\n }\n\n if (StringUtils.isEmpty(format.splitKey) && format.numPartitions > 1){\n throw new IllegalArgumentException(\"Must specify the split column when the channel is greater than 1\");\n }\n\n if (format.fetchSize > ConstantValue.MAX_BATCH_SIZE) {\n throw new IllegalArgumentException(\"批量读取条数必须小于[200000]条\");\n }\n }\n\n}" }, { "identifier": "VerticaDatabaseMeta", "path": "flinkx/flinkx-vertica/flinkx-vertica-core/src/main/java/com/dtstack/flinkx/vertica/VerticaDatabaseMeta.java", "snippet": "public class VerticaDatabaseMeta extends BaseDatabaseMeta {\n\n @Override\n public String quoteTable(String table) {\n table = table.replace(\"\\\"\",\"\");\n String[] part = table.split(\"\\\\.\");\n if(part.length == DB_TABLE_PART_SIZE) {\n table = getStartQuote() + part[0] + getEndQuote() + \".\" + getStartQuote() + part[1] + getEndQuote();\n } else {\n table = getStartQuote() + table + getEndQuote();\n }\n return table;\n }\n\n @Override\n public EDatabaseType getDatabaseType() {\n return EDatabaseType.Vertica;\n }\n\n @Override\n public String getDriverClass() {\n return \"com.vertica.jdbc.Driver\";\n }\n\n @Override\n public String getSqlQueryFields(String tableName) {\n return \"SELECT /*+FIRST_ROWS*/ * FROM \" + tableName + \" LIMIT 0\";\n }\n\n @Override\n public String getSqlQueryColumnFields(List<String> column, String table) {\n return \"SELECT /*+FIRST_ROWS*/ \" + quoteColumns(column) + \" FROM \" + quoteTable(table) + \" LIMIT 0\";\n }\n\n @Override\n public String quoteValue(String value, String column) {\n return String.format(\"%s as %s%s%s\",value, getStartQuote(), column, getEndQuote());\n }\n\n @Override\n public String getSplitFilter(String columnName) {\n return String.format(\"mod(%s, ${N}) = ${M}\", getStartQuote() + columnName + getEndQuote());\n }\n\n @Override\n public String getSplitFilterWithTmpTable(String tmpTable, String columnName) {\n return String.format(\"mod(%s.%s, ${N}) = ${M}\", tmpTable, getStartQuote() + columnName + getEndQuote());\n }\n\n private String makeValues(int nCols) {\n return \"(\" + StringUtils.repeat(\"?\", \",\", nCols) + \")\";\n }\n\n @Override\n protected String makeValues(List<String> column) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n protected String makeReplaceValues(List<String> column, List<String> fullColumn){\n List<String> values = new ArrayList<>();\n boolean contains = false;\n\n for (String col : column) {\n values.add(\"? \" + quoteColumn(col));\n }\n\n for (String col : fullColumn) {\n for (String c : column) {\n if (c.equalsIgnoreCase(col)){\n contains = true;\n break;\n }\n }\n\n if (contains){\n contains = false;\n continue;\n } else {\n values.add(\"null \" + quoteColumn(col));\n }\n\n contains = false;\n }\n\n return \"SELECT \" + org.apache.commons.lang3.StringUtils.join(values,\",\") + \" FROM DUAL\";\n }\n\n @Override\n public String getRowNumColumn(String orderBy) {\n throw new RuntimeException(\"Not support row_number function\");\n }\n\n @Override\n public int getFetchSize(){\n return 1000;\n }\n\n @Override\n public int getQueryTimeout(){\n return 3000;\n }\n}" }, { "identifier": "VerticaInputFormat", "path": "flinkx/flinkx-vertica/flinkx-vertica-reader/src/main/java/com/dtstack/flinkx/vertica/format/VerticaInputFormat.java", "snippet": "public class VerticaInputFormat extends JdbcInputFormat {\n\n @Override\n public Row nextRecordInternal(Row row) throws IOException {\n if (!hasNext) {\n return null;\n }\n row = new Row(columnCount);\n\n try {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n for (int pos = 0; pos < row.getArity(); pos++) {\n Object obj = resultSet.getObject(pos + 1);\n if(obj != null) {\n if (metaColumns.get(pos).getValue() != null && \"now()\".equals(metaColumns.get(pos).getValue())) {\n obj = dateFormat.format(new java.util.Date());\n } else if (metaColumns.get(pos).getTimeFormat() != null) {\n try {\n obj = dateFormat.format(metaColumns.get(pos).getTimeFormat().parse(obj.toString()));\n } catch (Exception e) {\n LOG.info(\"fmt error\");\n }\n } else if ((obj instanceof java.util.Date\n || obj.getClass().getSimpleName().toUpperCase().contains(\"TIMESTAMP\")) ) {\n obj = resultSet.getTimestamp(pos + 1);\n } else if (obj instanceof Blob) {\n Blob blob = (Blob) obj;\n long length = blob.length();\n LOG.info(\"读取到blob字段数据,数据长度为:\" + length);\n obj = blob.getBytes(1, Integer.parseInt(length + \"\"));\n } else if (obj instanceof Boolean) {\n obj = ((Boolean)obj) ? 1 : 0;\n }\n obj = clobToString(obj);\n }\n\n row.setField(pos, obj);\n }\n return super.nextRecordInternal(row);\n }catch (Exception e) {\n throw new IOException(\"Couldn't read data - \" + e.getMessage(), e);\n }\n }\n}" } ]
import com.dtstack.flinkx.config.DataTransferConfig; import com.dtstack.flinkx.constants.ConstantValue; import com.dtstack.flinkx.rdb.datareader.JdbcDataReader; import com.dtstack.flinkx.rdb.inputformat.JdbcInputFormatBuilder; import com.dtstack.flinkx.vertica.VerticaDatabaseMeta; import com.dtstack.flinkx.vertica.format.VerticaInputFormat; import org.apache.commons.lang3.StringUtils; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
5,217
/* * 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.dtstack.flinkx.vertica.reader; /** * Oracle reader plugin * * Company: www.dtstack.com * @author [email protected] */ public class VerticaReader extends JdbcDataReader { public VerticaReader(DataTransferConfig config, StreamExecutionEnvironment env) { super(config, env); String schema = config.getJob().getContent().get(0).getReader().getParameter().getConnection().get(0).getSchema(); if(StringUtils.isNotBlank(schema)){ table = schema + ConstantValue.POINT_SYMBOL + table; } setDatabaseInterface(new VerticaDatabaseMeta()); } @Override
/* * 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.dtstack.flinkx.vertica.reader; /** * Oracle reader plugin * * Company: www.dtstack.com * @author [email protected] */ public class VerticaReader extends JdbcDataReader { public VerticaReader(DataTransferConfig config, StreamExecutionEnvironment env) { super(config, env); String schema = config.getJob().getContent().get(0).getReader().getParameter().getConnection().get(0).getSchema(); if(StringUtils.isNotBlank(schema)){ table = schema + ConstantValue.POINT_SYMBOL + table; } setDatabaseInterface(new VerticaDatabaseMeta()); } @Override
protected JdbcInputFormatBuilder getBuilder() {
3
2023-11-16 02:22:52+00:00
8k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/BetterFlowers.java
[ { "identifier": "CustomFlowerBrushListener", "path": "src/main/java/com/uroria/betterflowers/listeners/CustomFlowerBrushListener.java", "snippet": "public final class CustomFlowerBrushListener implements Listener {\n\n private final FlowerManager flowerManager;\n private final List<Block> flowerBlocks;\n\n public CustomFlowerBrushListener(BetterFlowers betterFlowers) {\n this.flowerManager = betterFlowers.getFlowerManager();\n this.flowerBlocks = new ArrayList<>();\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(PlayerInteractEvent playerInteractEvent) {\n\n if (playerInteractEvent.getAction().isLeftClick()) return;\n if (playerInteractEvent.getHand() != EquipmentSlot.HAND) return;\n if (!playerInteractEvent.hasItem() || playerInteractEvent.getItem() == null) return;\n if (playerInteractEvent.getItem().getType() != Material.BLAZE_ROD) return;\n\n final var currentLocation = playerInteractEvent.getPlayer().getTargetBlock(null, 200).getLocation();\n if (currentLocation.getBlock().getType() == Material.AIR) return;\n if (currentLocation.getBlock().getType() != Material.SHORT_GRASS) currentLocation.add(0, 1, 0);\n\n final var oldBlocks = new HashMap<Vector, BlockData>();\n final var item = playerInteractEvent.getItem();\n\n if (!flowerManager.getBrushes().containsKey(item)) return;\n final var radius = flowerManager.getBrushes().get(item).radius();\n final var airRandomizer = flowerManager.getBrushes().get(item).airRandomizer();\n handleRadiusPlacement(playerInteractEvent, oldBlocks, radius, currentLocation, airRandomizer);\n handleFlowerHistory(playerInteractEvent, oldBlocks);\n\n playerInteractEvent.getPlayer().playSound(currentLocation, Sound.BLOCK_AMETHYST_BLOCK_RESONATE, 1, 0);\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(BlockPhysicsEvent blockPhysicsEvent) {\n var currentBlock = blockPhysicsEvent.getBlock();\n if (flowerBlocks.contains(currentBlock)) blockPhysicsEvent.setCancelled(true);\n }\n\n private void handleRadiusPlacement(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks, int radius, Location location, float air) {\n\n for (var innerLocation : getPlayerCircle(location, radius)) {\n if (air >= new Random().nextFloat()) continue;\n if (!adjustHeight(innerLocation)) continue;\n handleFlowerPlacement(playerInteractEvent, oldBlocks, innerLocation);\n }\n }\n\n private void handleFlowerPlacement(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks, Location currentLocation) {\n\n final var item = playerInteractEvent.getItem();\n final var flowerBrush = flowerManager.getBrushes().get(item);\n final var flowerOptions = flowerBrush.flowerGroupData();\n final var flowerGroup = flowerOptions.get(new Random().nextInt(flowerOptions.size()));\n final var flowers = flowerGroup.flowerData();\n final var values = flowerManager.getFlowerRandomizer().get(flowerGroup);\n\n if (!onCorrectGround(currentLocation, flowerGroup, flowerBrush.maskData())) return;\n\n for (int i = 0; i < flowers.size(); i++) {\n if (values.get(i) && new Random().nextBoolean()) continue;\n\n final var currentBlock = currentLocation.getBlock();\n oldBlocks.put(currentBlock.getLocation().toVector(), currentBlock.getBlockData());\n\n flowerBlocks.add(currentBlock);\n flowers.get(i).getSingleFlower().setFlower(currentBlock);\n currentLocation.add(0, 1, 0);\n }\n }\n\n private Collection<Location> getPlayerCircle(Location location, int radius) {\n final var locations = new ArrayList<Location>();\n\n for (int x = -radius; x < radius; x++)\n for (int z = -radius; z < radius; z++) {\n final var newLocation = new Location(location.getWorld(), location.getX() + x, location.getY(), location.getZ() + z);\n if (location.distance(newLocation) < radius) locations.add(newLocation);\n }\n\n return locations;\n }\n\n private void handleFlowerHistory(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks) {\n\n final var player = playerInteractEvent.getPlayer();\n final var uuid = player.getUniqueId();\n final var history = new Operation(oldBlocks, player.getWorld());\n\n if (flowerManager.getOperationHistory().containsKey(uuid)) {\n var copy = new ArrayList<>(List.copyOf(flowerManager.getOperationHistory().get(uuid)));\n copy.add(history);\n\n flowerManager.getOperationHistory().put(uuid, copy);\n } else flowerManager.getOperationHistory().put(uuid, List.of(history));\n }\n\n private boolean adjustHeight(Location location) {\n final var block = location.getBlock();\n\n for (var index = 0; index < 10; index++) {\n\n final var y = block.isSolid() ? location.getBlockY() + index : location.getBlockY() - index;\n final var currentBlock = location.getWorld().getBlockAt(location.getBlockX(), y, location.getBlockZ());\n\n if (currentBlock.isSolid()) {\n location.setY(currentBlock.getY() + 1);\n return true;\n }\n\n final var nextBlock = block.isSolid() ? currentBlock.getRelative(BlockFace.UP) : currentBlock.getRelative(BlockFace.DOWN);\n if (!nextBlock.isSolid()) continue;\n location.setY(nextBlock.getY() + 1);\n return true;\n }\n\n return false;\n }\n\n private boolean onCorrectGround(Location location, FlowerGroupData data, Map<FlowerGroupData, Material> maskData) {\n final var floorType = location.getBlock().getRelative(BlockFace.DOWN).getType();\n\n if (maskData.isEmpty()) return true;\n if (!maskData.containsKey(data)) return true;\n return maskData.get(data) == floorType;\n }\n}" }, { "identifier": "CustomFlowerPlaceListener", "path": "src/main/java/com/uroria/betterflowers/listeners/CustomFlowerPlaceListener.java", "snippet": "public final class CustomFlowerPlaceListener implements Listener {\n\n private final FlowerManager flowerManager;\n private final List<Block> flowerBlocks;\n\n public CustomFlowerPlaceListener(BetterFlowers betterFlowers) {\n this.flowerManager = betterFlowers.getFlowerManager();\n this.flowerBlocks = new ArrayList<>();\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(PlayerInteractEvent playerInteractEvent) {\n\n if (playerInteractEvent.getAction().isLeftClick()) return;\n if (playerInteractEvent.getHand() != EquipmentSlot.HAND) return;\n if (!playerInteractEvent.hasItem() || playerInteractEvent.getItem() == null) return;\n\n if (playerInteractEvent.getItem().getType() != Material.BLAZE_POWDER) return;\n if (playerInteractEvent.getClickedBlock() == null) return;\n if (playerInteractEvent.getInteractionPoint() == null) return;\n\n final var currentLocation = playerInteractEvent.getInteractionPoint();\n final var oldBlocks = new HashMap<Vector, BlockData>();\n\n handleFlowerPlacement(playerInteractEvent, oldBlocks, currentLocation);\n handleFlowerHistory(playerInteractEvent, oldBlocks);\n\n playerInteractEvent.getPlayer().playSound(currentLocation, Sound.BLOCK_AMETHYST_BLOCK_RESONATE, 1, 0);\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(BlockPhysicsEvent blockPhysicsEvent) {\n var currentBlock = blockPhysicsEvent.getBlock();\n if (flowerBlocks.contains(currentBlock)) blockPhysicsEvent.setCancelled(true);\n }\n\n private void handleFlowerPlacement(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks, Location currentLocation) {\n\n final var item = playerInteractEvent.getItem();\n if (!flowerManager.getFlowers().containsKey(item)) return;\n\n final var flowerGroupData = flowerManager.getFlowers().get(item);\n final var flowers = flowerGroupData.flowerData();\n final var values = flowerManager.getFlowerRandomizer().get(flowerGroupData);\n final var offset = playerLookUp(playerInteractEvent.getPlayer()) ? -1 : 1;\n if (playerLookUp(playerInteractEvent.getPlayer())) currentLocation.add(0, -1, 0);\n\n for (int i = 0; i < flowers.size(); i++) {\n if (values.get(i) && new Random().nextBoolean()) continue;\n\n final var currentBlock = currentLocation.getBlock();\n oldBlocks.put(currentBlock.getLocation().toVector(), currentBlock.getBlockData());\n\n flowerBlocks.add(currentBlock);\n flowers.get(i).getSingleFlower().setFlower(currentBlock);\n currentLocation.add(0, offset, 0);\n }\n }\n\n private void handleFlowerHistory(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks) {\n\n final var location = playerInteractEvent.getClickedBlock();\n if (location == null) return;\n\n final var history = new Operation(oldBlocks, playerInteractEvent.getClickedBlock().getWorld());\n final var uuid = playerInteractEvent.getPlayer().getUniqueId();\n\n if (flowerManager.getOperationHistory().containsKey(uuid)) {\n var copy = new ArrayList<>(List.copyOf(flowerManager.getOperationHistory().get(uuid)));\n copy.add(history);\n\n flowerManager.getOperationHistory().put(uuid, copy);\n } else flowerManager.getOperationHistory().put(uuid, List.of(history));\n }\n\n private boolean playerLookUp(Player player) {\n return player.getPitch() < 0.0F;\n }\n}" }, { "identifier": "FlowerManager", "path": "src/main/java/com/uroria/betterflowers/managers/FlowerManager.java", "snippet": "@Getter\npublic final class FlowerManager {\n\n private final Map<ItemStack, FlowerGroupData> flowers;\n private final Map<ItemStack, BrushData> brushes;\n private final Map<FlowerGroupData, List<Boolean>> flowerRandomizer;\n private final Map<UUID, List<Operation>> operationHistory;\n\n public FlowerManager() {\n this.flowers = new HashMap<>();\n this.brushes = new HashMap<>();\n this.flowerRandomizer = new HashMap<>();\n this.operationHistory = new HashMap<>();\n }\n}" }, { "identifier": "LanguageManager", "path": "src/main/java/com/uroria/betterflowers/managers/LanguageManager.java", "snippet": "public final class LanguageManager {\n\n private final Map<String, String> singleMessage;\n private final Map<String, List<String>> multiMessage;\n\n public LanguageManager() {\n this.singleMessage = new HashMap<>();\n this.multiMessage = new HashMap<>();\n\n readConfig();\n }\n\n public void sendPlayerMessage(Player player, String key) {\n player.sendMessage(getComponent(key));\n }\n\n public void sendPlayersMessage(Collection<Player> players, String key) {\n players.forEach(player -> sendPlayerMessage(player, key));\n }\n\n public Component getComponent(String key, String regex, String value) {\n final var string = getStringFromConfig(key).replace(regex, value);\n return MiniMessage.miniMessage().deserialize(string);\n }\n\n public Component getComponent(String key) {\n final var string = getStringFromConfig(key);\n return MiniMessage.miniMessage().deserialize(string);\n }\n\n public List<Component> getComponents(String key) {\n return getStringsFromConfig(key).stream().map(string -> MiniMessage.miniMessage().deserialize(string)).toList();\n }\n\n private void readLangaugeFromResources(String path) {\n\n final var inputStream = getClass().getClassLoader().getResourceAsStream(\"language.json\");\n if (inputStream == null) return;\n\n try {\n final var reader = new BufferedReader(new InputStreamReader(inputStream));\n final var stringBuilder = new StringBuilder();\n\n String line;\n\n while ((line = reader.readLine()) != null) {\n stringBuilder.append(line);\n }\n\n final var jsonString = stringBuilder.toString();\n final var jsonFile = new Gson().fromJson(jsonString, JsonObject.class);\n\n jsonFile.keySet().forEach(key -> {\n\n final var element = jsonFile.get(key);\n readConfigData(key, element);\n\n });\n\n writeFile(path + \"/language.json\", jsonString);\n\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n }\n\n private void writeFile(String path, String data) {\n\n try (var fileWriter = new FileWriter(path)) {\n\n fileWriter.write(data);\n fileWriter.flush();\n\n } catch (IOException ioException) {\n throw new RuntimeException(ioException);\n }\n }\n\n private void readLanguageFileFromJson(File file) {\n\n try {\n\n final var jsonFile = JsonParser.parseReader(new FileReader(file)).getAsJsonObject();\n\n jsonFile.keySet().forEach(key -> {\n\n final var element = jsonFile.get(key);\n readConfigData(key, element);\n\n });\n\n } catch (FileNotFoundException fileNotFoundException) {\n throw new RuntimeException(fileNotFoundException);\n }\n }\n\n private void readConfigData(String key, JsonElement element) {\n\n if (element.isJsonArray()) {\n\n final var list = new ArrayList<String>();\n\n for (var jsonElement : element.getAsJsonArray().asList()) {\n list.add(jsonElement.getAsString());\n }\n\n this.multiMessage.put(key, list);\n return;\n }\n\n this.singleMessage.put(key, element.getAsString());\n }\n\n private void readConfig() {\n\n final var path = Bukkit.getPluginsFolder() + \"/BetterFlowers\";\n final var file = new File(path + \"/language.json\");\n\n try {\n\n if (new File(path).mkdir()) throw new FileNotFoundException();\n\n if (file.exists()) {\n readLanguageFileFromJson(file);\n return;\n }\n\n readLangaugeFromResources(path);\n\n } catch (FileNotFoundException exception) {\n readLangaugeFromResources(path);\n }\n }\n\n private String getStringFromConfig(String key) {\n return this.singleMessage.getOrDefault(key, key);\n }\n\n private String getStringFromConfig(String key, String optional) {\n return this.singleMessage.getOrDefault(key, optional);\n }\n\n private List<String> getStringsFromConfig(String key) {\n return this.multiMessage.getOrDefault(key, List.of(key));\n }\n\n private List<String> getStringsFromConfig(String key, List<String> optional) {\n return this.multiMessage.getOrDefault(key, optional);\n }\n}" } ]
import com.uroria.betterflowers.commands.Flower; import com.uroria.betterflowers.commands.FlowerBrush; import com.uroria.betterflowers.commands.UndoFlower; import com.uroria.betterflowers.listeners.CustomFlowerBrushListener; import com.uroria.betterflowers.listeners.CustomFlowerPlaceListener; import com.uroria.betterflowers.managers.FlowerManager; import com.uroria.betterflowers.managers.LanguageManager; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.util.List;
3,646
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin {
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin {
private final FlowerManager flowerManager;
2
2023-11-18 16:13:59+00:00
8k
Appu26J/Softuninstall
src/appu26j/gui/screens/GuiSoftuninstall.java
[ { "identifier": "Assets", "path": "src/appu26j/assets/Assets.java", "snippet": "public class Assets\n{\n\tprivate static final String tempDirectory = System.getProperty(\"java.io.tmpdir\");\n\tprivate static final ArrayList<String> assets = new ArrayList<>();\n\t\n\tstatic\n\t{\n\t\tassets.add(\"segoeui.ttf\");\n\t\tassets.add(\"delete.png\");\n\t}\n\t\n\tpublic static void loadAssets()\n\t{\n\t\tFile assetsDirectory = new File(tempDirectory, \"softuninstall\");\n\t\t\n\t\tif (!assetsDirectory.exists())\n\t\t{\n\t\t\tassetsDirectory.mkdirs();\n\t\t}\n\t\t\n\t\tfor (String name : assets)\n\t\t{\n\t\t\tFile asset = new File(assetsDirectory, name);\n\n\t\t\tif (!asset.getParentFile().exists())\n\t\t\t{\n\t\t\t\tasset.getParentFile().mkdirs();\n\t\t\t}\n\n\t\t\tif (!asset.exists())\n\t\t\t{\n\t\t\t\tFileOutputStream fileOutputStream = null;\n\t\t\t\tInputStream inputStream = null;\n\t\t\t\t\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tinputStream = Assets.class.getResourceAsStream(name);\n\t\t\t\t\t\n\t\t\t\t\tif (inputStream == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new NullPointerException();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfileOutputStream = new FileOutputStream(asset);\n\t\t\t\t\tbyte[] bytes = new byte[4096];\n\t\t\t\t int read;\n\t\t\t\t \n\t\t\t\t while ((read = inputStream.read(bytes)) != -1)\n\t\t\t\t {\n\t\t\t\t \tfileOutputStream.write(bytes, 0, read);\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfinally\n\t\t\t\t{\n\t\t\t\t\tif (fileOutputStream != null)\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfileOutputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcatch (Exception e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (inputStream != null)\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcatch (Exception e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static File getAsset(String name)\n\t{\n\t\treturn new File(tempDirectory, \"softuninstall\" + File.separator + name);\n\t}\n}" }, { "identifier": "Gui", "path": "src/appu26j/gui/Gui.java", "snippet": "public class Gui\n{\n\tpublic static void drawOutlineRect(float x, float y, float width, float height, Color color)\n\t{\n\t\tfloat lineWidth = 1;\n\t\tdrawRect(x, y, x + lineWidth, height, color);\n\t\tdrawRect(x + lineWidth, y, width - lineWidth, y + lineWidth, color);\n\t\tdrawRect(width - lineWidth, y, width, height, color);\n\t\tdrawRect(x + lineWidth, height, width - lineWidth, height - lineWidth, color);\n\t}\n\n\tpublic static void drawRect(float x, float y, float width, float height, Color color)\n\t{\n\t\tGlStateManager.enableAlpha();\n\t\tGlStateManager.enableBlend();\n\t\tGlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);\n\t\tGlStateManager.alphaFunc(516, 0);\n\t\tGlStateManager.color(color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, color.getAlpha() / 255F);\n\t\tglBegin(GL_TRIANGLES);\n\t\tglVertex2f(x, y);\n\t\tglVertex2f(x, height);\n\t\tglVertex2f(width, height);\n\t\tglVertex2f(width, height);\n\t\tglVertex2f(width, y);\n\t\tglVertex2f(x, y);\n\t\tglEnd();\n\t\tGlStateManager.disableBlend();\n\t\tGlStateManager.disableAlpha();\n\t}\n\n\tpublic static void drawImage(Texture texture, float x, float y, float u, float v, float width, float height, float renderWidth, float renderHeight)\n\t{\n\t\twidth += x;\n\t\theight += y;\n\t\twidth -= u;\n\t\theight -= v;\n\n\t\tif (texture != null)\n\t\t{\n\t\t\tglBindTexture(GL_TEXTURE_2D, texture.getId());\n\t\t\tGlStateManager.enableTexture2D();\n\t\t\tGlStateManager.enableAlpha();\n\t\t\tGlStateManager.enableBlend();\n\t\t\tGlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);\n\t\t\tGlStateManager.alphaFunc(516, 0);\n\t\t\tGlStateManager.color(1, 1, 1, 1);\n\t\t\tglBegin(GL_TRIANGLES);\n\t\t\tglTexCoord2f(u / texture.getWidth(), v / texture.getHeight());\n\t\t\tglVertex2f(x, y);\n\t\t\tglTexCoord2f(u / texture.getWidth(), 1);\n\t\t\tglVertex2f(x, height);\n\t\t\tglTexCoord2f(1, 1);\n\t\t\tglVertex2f(width, height);\n\t\t\tglTexCoord2f(1, 1);\n\t\t\tglVertex2f(width, height);\n\t\t\tglTexCoord2f(1, v / texture.getHeight());\n\t\t\tglVertex2f(width, y);\n\t\t\tglTexCoord2f(u / texture.getWidth(), v / texture.getHeight());\n\t\t\tglVertex2f(x, y);\n\t\t\tglEnd();\n\t\t\tGlStateManager.disableBlend();\n\t\t\tGlStateManager.disableAlpha();\n\t\t\tGlStateManager.disableTexture2D();\n\t\t\tglBindTexture(GL_TEXTURE_2D, 0);\n\t\t}\n\t}\n\t\n\tpublic static Texture getTexture(File image)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedImage bufferedImage = ImageIO.read(image);\n\t\t\tByteBuffer byteBuffer = getByteBuffer(bufferedImage);\n\t\t int id = glGenTextures();\n\t\t glBindTexture(GL_TEXTURE_2D, id);\n\t\t glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\t\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\t glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t\t glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bufferedImage.getWidth(), bufferedImage.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);\n\t\t return new Texture(id, bufferedImage.getWidth(), bufferedImage.getHeight());\n\t\t}\n\t\t\n\t\tcatch (Exception e)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static Texture getTexture(BufferedImage bufferedImage)\n\t{\n\t\ttry\n\t\t{\n\t\t\tByteBuffer byteBuffer = getByteBuffer(bufferedImage);\n\t\t\tint id = glGenTextures();\n\t\t\tglBindTexture(GL_TEXTURE_2D, id);\n\t\t\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\t\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bufferedImage.getWidth(), bufferedImage.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);\n\t\t\treturn new Texture(id, bufferedImage.getWidth(), bufferedImage.getHeight());\n\t\t}\n\n\t\tcatch (Exception e)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tprivate static ByteBuffer getByteBuffer(BufferedImage bufferedImage)\n\t{\n int[] pixels = new int[bufferedImage.getWidth() * bufferedImage.getHeight()];\n bufferedImage.getRGB(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), pixels, 0, bufferedImage.getWidth());\n ByteBuffer byteBuffer = BufferUtils.createByteBuffer(4 * bufferedImage.getWidth() * bufferedImage.getHeight());\n \n for (int y = 0; y < bufferedImage.getHeight(); y++)\n {\n for (int x = 0; x < bufferedImage.getWidth(); x++)\n {\n int pixel = pixels[y * bufferedImage.getWidth() + x];\n byteBuffer.put((byte) ((pixel >> 16) & 0xFF));\n byteBuffer.put((byte) ((pixel >> 8) & 0xFF));\n byteBuffer.put((byte) (pixel & 0xFF));\n byteBuffer.put((byte) ((pixel >> 24) & 0xFF));\n }\n }\n \n byteBuffer.flip();\n return byteBuffer;\n }\n}" }, { "identifier": "Texture", "path": "src/appu26j/gui/textures/Texture.java", "snippet": "public class Texture\n{\n private final int id, width, height;\n\n public Texture(int id, int width, int height)\n {\n this.id = id;\n this.width = width;\n this.height = height;\n }\n \n public int getId()\n {\n return this.id;\n }\n\n public int getWidth()\n {\n return this.width;\n }\n \n public int getHeight()\n {\n return this.height;\n }\n}" }, { "identifier": "AppUtil", "path": "src/appu26j/utils/AppUtil.java", "snippet": "public class AppUtil\n{\n public static void loadApps()\n {\n Thread thread1 = new Thread(() ->\n {\n try\n {\n loadAppsFromPath(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\");\n }\n\n catch (Exception e)\n {\n ;\n }\n\n GuiSoftuninstall.loading -= 1;\n });\n\n Thread thread2 = new Thread(() ->\n {\n try\n {\n loadAppsFromPath(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\WoW6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\");\n }\n\n catch (Exception e)\n {\n ;\n }\n\n GuiSoftuninstall.loading -= 1;\n });\n\n thread1.setDaemon(true);\n thread2.setDaemon(true);\n thread1.start();\n thread2.start();\n }\n\n private static void loadAppsFromPath(String pathToCheckAppsFrom) throws Exception\n {\n String[] paths = Registry.execute(\"QUERY \\\"\" + pathToCheckAppsFrom + \"\\\"\").split(\"\\n\");\n\n for (String path : paths)\n {\n try\n {\n String keys = Registry.execute(\"QUERY \\\"\" + path + \"\\\"\");\n boolean containsInfo = keys.contains(\"DisplayName \") && keys.contains(\"UninstallString \") && !keys.contains(\"SystemComponent \");\n\n if (!containsInfo)\n {\n continue;\n }\n\n String name = Registry.execute(\"QUERY \\\"\" + path + \"\\\" /v DisplayName\").trim().split(\" {4}\")[3];\n String publisher = keys.contains(\"Publisher\") ? Registry.execute(\"QUERY \\\"\" + path + \"\\\" /v Publisher\").trim().split(\" {4}\")[3] : \"Unknown\";\n String uninstallCmd = Registry.execute(\"QUERY \\\"\" + path + \"\\\" /v UninstallString\").trim().split(\" {4}\")[3];\n GuiSoftuninstall.apps.add(new AppInfo(name, publisher, uninstallCmd, path));\n }\n\n catch (Exception e)\n {\n ;\n }\n }\n }\n}" }, { "identifier": "ScissorUtil", "path": "src/appu26j/utils/ScissorUtil.java", "snippet": "public class ScissorUtil\n{\n public static void scissor(float x, float y, float width, float height)\n {\n GL11.glScissor((int) x, (int) (700 - height), (int) (width - x), (int) (height - y));\n }\n}" }, { "identifier": "AppInfo", "path": "src/appu26j/utils/apps/AppInfo.java", "snippet": "public class AppInfo\n{\n private final String name, publisher, uninstallCmd, registryPath;\n\n public AppInfo(String name, String publisher, String uninstallCmd, String registryPath)\n {\n this.name = name;\n this.publisher = publisher;\n this.uninstallCmd = uninstallCmd;\n this.registryPath = registryPath;\n }\n\n public String getName()\n {\n return this.name;\n }\n\n public String getPublisher()\n {\n return this.publisher;\n }\n\n public String getUninstallCmd()\n {\n return this.uninstallCmd;\n }\n\n public String getRegistryPath()\n {\n return this.registryPath;\n }\n}" } ]
import appu26j.Registry; import appu26j.assets.Assets; import appu26j.gui.Gui; import appu26j.gui.textures.Texture; import appu26j.utils.AppUtil; import appu26j.utils.ScissorUtil; import appu26j.utils.apps.AppInfo; import org.lwjgl.opengl.GL11; import java.awt.*; import java.util.ArrayList;
4,027
package appu26j.gui.screens; public class GuiSoftuninstall extends GuiScreen { public static final ArrayList<AppInfo> apps = new ArrayList<>(); private String previousUninstalledApp = ""; private float scroll = 0, maxScroll = 0; private boolean dragging = false; public static int loading = 2; private Texture delete; @Override public void drawScreen(float mouseX, float mouseY) { if (!apps.isEmpty()) { if (this.dragging) { float progress = (mouseY - 15) / (this.height - 30); this.scroll = this.maxScroll * progress; if (this.scroll < 0) { this.scroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } } this.maxScroll = 0; float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { Gui.drawRect(15, y, this.width - 40, y + 60, this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) ? new Color(235, 235, 235) : new Color(245, 245, 245)); this.fontRenderer.drawString(appInfo.getName(), 25, y, new Color(50, 50, 50)); GL11.glEnable(GL11.GL_SCISSOR_TEST); ScissorUtil.scissor(0, 0, this.width - 100, this.height); this.fontRenderer.drawString(appInfo.getUninstallCmd(), this.fontRenderer.getStringWidth(appInfo.getPublisher()) + 30, y + 27, new Color(175, 175, 175)); GL11.glDisable(GL11.GL_SCISSOR_TEST); this.fontRenderer.drawString(appInfo.getPublisher(), 25, y + 27, new Color(125, 125, 125)); Gui.drawImage(this.delete, this.width - 95, y + 4, 0, 0, 48, 48, 48, 48); y += 75; this.maxScroll += 75; } this.maxScroll -= (loading == 0 ? 685 : 625); if (this.maxScroll < 0) { this.maxScroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } if (loading != 0) { this.fontRendererMid.drawString("Loading...", (this.width / 2) - (this.fontRendererMid.getStringWidth("Loading...") / 2), y - 10, new Color(100, 100, 100)); } Gui.drawRect(this.width - 27, 15, this.width - 13, this.height - 15, new Color(200, 200, 200)); float scrollProgress = (this.scroll / this.maxScroll); float yPos = ((this.height - 180) * scrollProgress) + 90; Gui.drawRect(this.width - 27, yPos - 75, this.width - 13, yPos + 75, new Color(245, 245, 245)); } } @Override public void mouseClicked(int mouseButton, float mouseX, float mouseY) { super.mouseClicked(mouseButton, mouseX, mouseY); float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { if (this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) && !this.previousUninstalledApp.equals(appInfo.getName())) { new Thread(() -> { try { Process process = Runtime.getRuntime().exec(appInfo.getUninstallCmd()); process.waitFor(); String output = Registry.execute("QUERY " + appInfo.getRegistryPath() + " /v DisplayName"); if (output.contains("ERROR: The system was unable to find the specified registry key or value.")) { GuiSoftuninstall.apps.remove(appInfo); } this.previousUninstalledApp = ""; } catch (Exception e) { ; } }).start(); this.previousUninstalledApp = appInfo.getName(); break; } y += 75; } if (this.isInsideBox(mouseX, mouseY, this.width - 37, 5, this.width - 3, this.height - 5) && mouseButton == 0) { this.dragging = true; } } @Override public void mouseReleased(int mouseButton, float mouseX, float mouseY) { super.mouseReleased(mouseButton, mouseX, mouseY); this.dragging = false; } @Override public void initGUI(float width, float height) { super.initGUI(width, height);
package appu26j.gui.screens; public class GuiSoftuninstall extends GuiScreen { public static final ArrayList<AppInfo> apps = new ArrayList<>(); private String previousUninstalledApp = ""; private float scroll = 0, maxScroll = 0; private boolean dragging = false; public static int loading = 2; private Texture delete; @Override public void drawScreen(float mouseX, float mouseY) { if (!apps.isEmpty()) { if (this.dragging) { float progress = (mouseY - 15) / (this.height - 30); this.scroll = this.maxScroll * progress; if (this.scroll < 0) { this.scroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } } this.maxScroll = 0; float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { Gui.drawRect(15, y, this.width - 40, y + 60, this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) ? new Color(235, 235, 235) : new Color(245, 245, 245)); this.fontRenderer.drawString(appInfo.getName(), 25, y, new Color(50, 50, 50)); GL11.glEnable(GL11.GL_SCISSOR_TEST); ScissorUtil.scissor(0, 0, this.width - 100, this.height); this.fontRenderer.drawString(appInfo.getUninstallCmd(), this.fontRenderer.getStringWidth(appInfo.getPublisher()) + 30, y + 27, new Color(175, 175, 175)); GL11.glDisable(GL11.GL_SCISSOR_TEST); this.fontRenderer.drawString(appInfo.getPublisher(), 25, y + 27, new Color(125, 125, 125)); Gui.drawImage(this.delete, this.width - 95, y + 4, 0, 0, 48, 48, 48, 48); y += 75; this.maxScroll += 75; } this.maxScroll -= (loading == 0 ? 685 : 625); if (this.maxScroll < 0) { this.maxScroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } if (loading != 0) { this.fontRendererMid.drawString("Loading...", (this.width / 2) - (this.fontRendererMid.getStringWidth("Loading...") / 2), y - 10, new Color(100, 100, 100)); } Gui.drawRect(this.width - 27, 15, this.width - 13, this.height - 15, new Color(200, 200, 200)); float scrollProgress = (this.scroll / this.maxScroll); float yPos = ((this.height - 180) * scrollProgress) + 90; Gui.drawRect(this.width - 27, yPos - 75, this.width - 13, yPos + 75, new Color(245, 245, 245)); } } @Override public void mouseClicked(int mouseButton, float mouseX, float mouseY) { super.mouseClicked(mouseButton, mouseX, mouseY); float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { if (this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) && !this.previousUninstalledApp.equals(appInfo.getName())) { new Thread(() -> { try { Process process = Runtime.getRuntime().exec(appInfo.getUninstallCmd()); process.waitFor(); String output = Registry.execute("QUERY " + appInfo.getRegistryPath() + " /v DisplayName"); if (output.contains("ERROR: The system was unable to find the specified registry key or value.")) { GuiSoftuninstall.apps.remove(appInfo); } this.previousUninstalledApp = ""; } catch (Exception e) { ; } }).start(); this.previousUninstalledApp = appInfo.getName(); break; } y += 75; } if (this.isInsideBox(mouseX, mouseY, this.width - 37, 5, this.width - 3, this.height - 5) && mouseButton == 0) { this.dragging = true; } } @Override public void mouseReleased(int mouseButton, float mouseX, float mouseY) { super.mouseReleased(mouseButton, mouseX, mouseY); this.dragging = false; } @Override public void initGUI(float width, float height) { super.initGUI(width, height);
AppUtil.loadApps();
3
2023-11-13 03:20:19+00:00
8k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/controllers/OrderController.java
[ { "identifier": "Dish", "path": "src/main/java/com/myfood/dto/Dish.java", "snippet": "@Entity\n@Table(name = \"dishes\")\npublic class Dish {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n\t@Column(name = \"name\", nullable = false)\n\tprivate String name;\n\n\t@Column(name = \"description\", nullable = false)\n\tprivate String description;\n\n\t@Column(name = \"image\")\n\tprivate String image;\n\n\t@Column(name = \"price\", nullable = false)\n\tprivate double price;\n\n\t@Column(name = \"category\", nullable = false)\n\tprivate String category;\n\t\n\t@Column(name = \"attributes\")\n\tprivate List<String> attributes;\n\t\n\t@Column(name = \"visible\")\n private boolean visible = false; \n\t\n\t@ManyToMany(fetch = FetchType.EAGER)\n\t@JoinTable(\n\t name = \"dish_atribut_dish\",\n\t joinColumns = @JoinColumn(name = \"dish_id\"),\n\t inverseJoinColumns = @JoinColumn(name = \"atribut_dish_id\")\n\t)\n\t@JsonIgnore\n\tprivate List<Atribut_Dish> atribut_dish;\n\t\t\n\t@OneToMany(mappedBy = \"dish\", cascade = CascadeType.ALL, orphanRemoval = true)\n @JsonIgnore\n private List<ListOrder> listOrder;\n\t\n\t@ManyToOne(cascade = CascadeType.REMOVE)\n\t@JsonIgnore\n\t@JoinColumn(name = \"menu_id\")\n\tprivate Menu menu;\n\n\n\t\n\t\n\tpublic Dish(Long id, String name, String description, String image, double price, String category,\n\t\t\tList<String> attributes, boolean visible, List<Atribut_Dish> atribut_dish, List<ListOrder> listOrder,\n\t\t\tMenu menu) {\n\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t\tthis.image = image;\n\t\tthis.price = price;\n\t\tthis.category = category;\n\t\tthis.attributes = attributes;\n\t\tthis.visible = visible;\n\t\tthis.atribut_dish = atribut_dish;\n\t\tthis.listOrder = listOrder;\n\t\tthis.menu = menu;\n\t}\n\n\tpublic Dish() {\n\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic String getImage() {\n\t\treturn image;\n\t}\n\n\tpublic void setImage(String image) {\n\t\tthis.image = image;\n\t}\n\n\tpublic double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic String getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(String category) {\n\t\tthis.category = category;\n\t}\n\n\n\tpublic void setAttributes(List<String> attributes) {\n\t\tthis.attributes = attributes;\n\t}\n\n\tpublic boolean isVisible() {\n\t\treturn visible;\n\t}\n\n\tpublic void setVisible(boolean visible) {\n\t\tthis.visible = visible;\n\t}\n\n\tpublic List<Atribut_Dish> getAtribut_dish() {\n\t\treturn atribut_dish;\n\t}\n\n\tpublic void setAtribut_dish(List<Atribut_Dish> atribut_dish) {\n\t\tthis.atribut_dish = atribut_dish;\n\t}\n\n\tpublic List<ListOrder> getListOrder() {\n\t\treturn listOrder;\n\t}\n\n\tpublic void setListOrder(List<ListOrder> listOrder) {\n\t\tthis.listOrder = listOrder;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic void setMenu(Menu menu) {\n\t\tthis.menu = menu;\n\t}\n\t\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Dish [id=\" + id + \", name=\" + name + \", description=\" + description + \", image=\" + image + \", price=\"\n\t\t\t\t+ price + \", category=\" + category + \", attributes=\" + attributes + \", visible=\" + visible\n\t\t\t\t+ \", atribut_dish=\" + atribut_dish + \", listOrder=\" + listOrder + \", menu=\" + menu + \"]\";\n\t}\n\n\tpublic String[] getAttributes() {\n\t if (atribut_dish != null && !atribut_dish.isEmpty()) {\n\t return atribut_dish.stream()\n\t .map(Atribut_Dish::getAttributes)\n\t .toArray(String[]::new);\n\t }\n\t return new String[0]; \n\t}\n\n\t\n\n}" }, { "identifier": "ListOrder", "path": "src/main/java/com/myfood/dto/ListOrder.java", "snippet": "@Entity\n@Table(name = \"list_orders\")\npublic class ListOrder {\n\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\t@ManyToOne\n\t@JoinColumn(name = \"menu_id\")\n\tprivate Menu menu;\n\n\t@ManyToOne\n\t@JoinColumn(name = \"dish_id\")\n\tprivate Dish dish;\n\n\t@ManyToOne(cascade = CascadeType.REMOVE)\n\t@JoinColumn(name = \"order_id\")\n\tprivate Order order;\n\t\n\tpublic ListOrder() {\n\t}\n\n\tpublic ListOrder(Long id, Menu menu, Dish dish, Order order) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.menu = menu;\n\t\tthis.dish = dish;\n\t\tthis.order = order;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic void setMenu(Menu menu) {\n\t\tthis.menu = menu;\n\t}\n\n\tpublic Dish getDish() {\n\t\treturn dish;\n\t}\n\n\tpublic void setDish(Dish dish) {\n\t\tthis.dish = dish;\n\t}\n\n\tpublic Order getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(Order order) {\n\t\tthis.order = order;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ListOrder [id=\" + id + \", menu=\" + menu + \", dish=\" + dish + \", order=\" + order + \"]\";\n\t}\n\n}" }, { "identifier": "Order", "path": "src/main/java/com/myfood/dto/Order.java", "snippet": "@Entity\n@Table(name = \"orders\")\npublic class Order {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"maked\", nullable = false)\n private boolean maked;\n\n @ManyToOne\n @JoinColumn(name = \"user_id\")\n private User user;\n\n @ManyToOne\n @JoinColumn(name = \"slot_id\")\n private Slot slot;\n\n @Column(name = \"total_price\")\n private Double totalPrice;\n\n @Column(name = \"actual_date\")\n private LocalDateTime actualDate;\n \n \n @OneToMany(mappedBy = \"order\",cascade = CascadeType.ALL, orphanRemoval = false)\n @JsonIgnore\n private List<ListOrder> listOrder;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public boolean isMaked() {\n return maked;\n }\n\n public void setMaked(boolean maked) {\n this.maked = maked;\n }\n\n public User getUser() {\n return user;\n }\n\n public void setUser(User user) {\n this.user = user;\n }\n\n public Slot getSlot() {\n return slot;\n }\n\n public void setSlot(Slot slot) {\n this.slot = slot;\n }\n\n public Double getTotalPrice() {\n return totalPrice;\n }\n\n public void setTotalPrice(Double totalPrice) {\n this.totalPrice = totalPrice;\n }\n\n public LocalDateTime getActualDate() {\n return actualDate;\n }\n\n public void setActualDate(LocalDateTime actualDate) {\n this.actualDate = actualDate;\n }\n\n public List<ListOrder> getListOrder() {\n\t\treturn listOrder;\n\t}\n\n\tpublic void setListOrder(List<ListOrder> listOrder) {\n\t\tthis.listOrder = listOrder;\n\t}\n\n\t@Override\n public String toString() {\n return \"Order{\" +\n \"id=\" + id +\n \", maked=\" + maked +\n \", userId=\" + user +\n \", slot=\" + slot +\n \", totalPrice=\" + totalPrice +\n \", actualDate=\" + actualDate +\n '}';\n }\n}" }, { "identifier": "OrderCookDTO", "path": "src/main/java/com/myfood/dto/OrderCookDTO.java", "snippet": "public class OrderCookDTO {\n private Long orderId;\n private boolean maked;\n private Slot slot;\n private List<Dish> dishes;\n private Double totalPrice;\n private LocalDateTime actualDate;\n \n public OrderCookDTO() {\n\t}\n\n\t\n\n public OrderCookDTO(Long orderId, boolean maked, Slot slot, List<Dish> dishes, Double totalPrice,\n\t\t\tLocalDateTime actualDate) {\n\t\tsuper();\n\t\tthis.orderId = orderId;\n\t\tthis.maked = maked;\n\t\tthis.slot = slot;\n\t\tthis.dishes = dishes;\n\t\tthis.totalPrice = totalPrice;\n\t\tthis.actualDate = actualDate;\n\t}\n\n\n\n\tpublic Long getOrderId() {\n return orderId;\n }\n\n public void setOrderId(Long orderId) {\n this.orderId = orderId;\n }\n\n public boolean isMaked() {\n return maked;\n }\n\n public void setMaked(boolean maked) {\n this.maked = maked;\n }\n\n public Slot getSlot() {\n return slot;\n }\n\n public void setSlot(Slot slot) {\n this.slot = slot;\n }\n\n public List<Dish> getDishes() {\n return dishes;\n }\n\n public void setDishes(List<Dish> dishes) {\n this.dishes = dishes;\n }\n \n public Double getTotalPrice() {\n\t\treturn totalPrice;\n\t}\n\n\tpublic void setTotalPrice(Double totalPrice) {\n\t\tthis.totalPrice = totalPrice;\n\t}\n\n\tpublic LocalDateTime getActualDate() {\n\t\treturn actualDate;\n\t}\n\n\tpublic void setActualDate(LocalDateTime actualDate) {\n\t\tthis.actualDate = actualDate;\n\t}\n}" }, { "identifier": "OrderUserDTO", "path": "src/main/java/com/myfood/dto/OrderUserDTO.java", "snippet": "public class OrderUserDTO {\n\t\n private Long id;\n private boolean maked;\n private Slot slot;\n private Double totalPrice;\n private LocalDateTime actualDate;\n\n \n\tpublic OrderUserDTO(Long id, boolean maked, Slot slot, Double totalPrice, LocalDateTime actualDate) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.maked = maked;\n\t\tthis.slot = slot;\n\t\tthis.totalPrice = totalPrice;\n\t\tthis.actualDate = actualDate;\n\t}\n\n\tpublic OrderUserDTO() {\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic boolean isMaked() {\n\t\treturn maked;\n\t}\n\n\tpublic void setMaked(boolean maked) {\n\t\tthis.maked = maked;\n\t}\n\n\tpublic Slot getSlot() {\n\t\treturn slot;\n\t}\n\n\tpublic void setSlot(Slot slot) {\n\t\tthis.slot = slot;\n\t}\n\n\tpublic Double getTotalPrice() {\n\t\treturn totalPrice;\n\t}\n\n\tpublic void setTotalPrice(Double totalPrice) {\n\t\tthis.totalPrice = totalPrice;\n\t}\n\n\tpublic LocalDateTime getActualDate() {\n\t\treturn actualDate;\n\t}\n\n\tpublic void setActualDate(LocalDateTime actualDate) {\n\t\tthis.actualDate = actualDate;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"OrderUserDTO [id=\" + id + \", maked=\" + maked + \", slot=\" + slot + \", totalPrice=\" + totalPrice\n\t\t\t\t+ \", actualDate=\" + actualDate + \"]\";\n\t}\n\n\t\n}" }, { "identifier": "Slot", "path": "src/main/java/com/myfood/dto/Slot.java", "snippet": "@Entity\n@Table(name = \"slots\")\npublic class Slot {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"time\", nullable = false)\n private String time;\n\n @Column(name = \"limit_slot\", nullable = false)\n private int limitSlot;\n\n @Column(name = \"actual\", nullable = false)\n private int actual;\n \n @OneToMany(mappedBy = \"slot\")\n @JsonIgnore\n private List<Order> orders;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public int getLimitSlot() {\n return limitSlot;\n }\n\n public void setLimitSlot(int limitSlot) {\n this.limitSlot = limitSlot;\n }\n\n public int getActual() {\n return actual;\n }\n\n public void setActual(int actual) {\n this.actual = actual;\n }\n \n public List<Order> getOrders() {\n return orders;\n }\n\n public void setOrders(List<Order> orders) {\n this.orders = orders;\n }\n\n @Override\n public String toString() {\n return \"Slot{\" +\n \"id=\" + id +\n \", time='\" + time + '\\'' +\n \", limitSlot=\" + limitSlot +\n \", actual=\" + actual +\n '}';\n }\n}" }, { "identifier": "User", "path": "src/main/java/com/myfood/dto/User.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class User {\n\t\n\t/**\n\t* The unique identifier for the user.\n\t*/\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t/**\n\t* The email address of the user. It is unique and cannot be null.\n\t*/\n\t@Email\n\t@NotBlank\n\t@Size(max = 80)\n\t@Column(name = \"email\", unique = true)\n\tprivate String email;\n\t\n\t/**\n\t* The password associated with the user. It cannot be null.\n\t*/\n\t@NotBlank\n\t@Column(name = \"password\")\n\tprivate String password;\n\t\n\t/**\n\t* The username of the user. It cannot be null.\n\t*/\n\t@NotBlank\n\t@Size(max = 60)\n\t@Column(name = \"name\", unique = true)\n\tprivate String username;\n\t\n\t/**\n\t* Represents the role of the user within the system. Multiple users can share the same role.\n\t* This field is mapped as a one-to-one relationship with the {@code Role} entity,\n\t* and it includes cascading persistence to ensure the role is persisted along with the user.\n\t*/\n\t@ManyToOne\n\tprivate Role role;\n\n @OneToMany(mappedBy = \"user\" ,fetch = FetchType.EAGER ,cascade = CascadeType.ALL )\n @JsonIgnore\n private List<Order> orders;\n \n @Column(name = \"created_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime createdAt;\n\n @Column(name = \"updated_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime updatedAt;\n\n\t/**\n\t * Default constructor for the {@code User} class.\n\t */\n\tpublic User() {\n\t}\n\t\n\tpublic User(Long id, String email, String password, String username , LocalDateTime createdAt ,LocalDateTime updatedAt) {\n\t\tthis.id = id;\n\t\tthis.email = email;\n\t\tthis.password = password;\n\t\tthis.username = username;\n\t\tthis.role = new Role();\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\t/**\n\t * Parameterized constructor for the {@code User} class.\n\t *\n\t * @param id The unique identifier for the user.\n\t * @param email The email address of the user.\n\t * @param password The password associated with the user.\n\t * @param username The username of the user.\n\t * @param role The role of the user in the system.\n\t */\n\tpublic User(Long id, String email, String password, String username, Role role, LocalDateTime createdAt ,LocalDateTime updatedAt ) {\n\t\tthis.id = id;\n\t\tthis.email = email;\n\t\tthis.password = password;\n\t\tthis.username = username;\n\t\tthis.role = role;\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\t/**\n\t * Get the unique identifier of the user.\n\t *\n\t * @return The unique identifier of the user.\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Set the unique identifier of the user.\n\t *\n\t * @param id The unique identifier of the user.\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Get the email address of the user.\n\t *\n\t * @return The email address of the user.\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Set the email address of the user.\n\t *\n\t * @param email The email address of the user.\n\t */\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Get the password associated with the user.\n\t *\n\t * @return The password associated with the user.\n\t */\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\t/**\n\t * Set the password associated with the user.\n\t *\n\t * @param password The password associated with the user.\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * Get the username of the user.\n\t *\n\t * @return The username of the user.\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * Set the username of the user.\n\t *\n\t * @param username The username of the user.\n\t */\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * Get the role of the user in the system.\n\t *\n\t * @return The role of the user.\n\t */\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\t/**\n\t * Set the role of the user in the system.\n\t *\n\t * @param role The role of the user.\n\t */\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [id=\" + id + \", email=\" + email + \", password=\" + password + \", username=\" + username + \", role=\"\n\t\t\t\t+ role + \"]\";\n\t}\n\n\n\t/**\n\t * @return the orders\n\t */\n\tpublic List<Order> getOrders() {\n\t\treturn orders;\n\t}\n\n\t/**\n\t * @param orders the orders to set\n\t */\n\tpublic void setOrders(List<Order> orders) {\n\t\tthis.orders = orders;\n\t}\n\n\t/**\n\t * @return the createdAt\n\t */\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\t/**\n\t * @param createdAt the createdAt to set\n\t */\n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\t/**\n\t * @return the updatedAt\n\t */\n\tpublic LocalDateTime getUpdatedAt() {\n\t\treturn updatedAt;\n\t}\n\n\t/**\n\t * @param updatedAt the updatedAt to set\n\t */\n\tpublic void setUpdatedAt(LocalDateTime updatedAt) {\n\t\tthis.updatedAt = updatedAt;\n\t}\n}" }, { "identifier": "OrderServiceImpl", "path": "src/main/java/com/myfood/services/OrderServiceImpl.java", "snippet": "@Service\npublic class OrderServiceImpl implements IOrderService {\n\n @Autowired\n private IOrderDAO orderDAO;\n\n @Override\n public List<Order> getAllOrders() {\n return orderDAO.findAll();\n }\n\n @Override\n public Optional<Order> getOneOrder(Long id) {\n return orderDAO.findById(id);\n }\n\n @Override\n public Order createOrder(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public Order updateOrder(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public void deleteOrder(Long id) {\n orderDAO.deleteById(id);\n }\n\n @Override\n public Order markOrderAsMaked(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public Order updateOrderSlot(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public List<Order> getAllOrdersForCook() {\n return orderDAO.findAllByMakedIsFalse();\n }\n\n @Override\n public List<Order> getAllOrdersForUserId(Long id) {\n return orderDAO.findAllByUserIdOrderByActualDateDesc(id);\n }\n\n @Override\n public Page<Order> getAllOrdersWithPagination(Pageable pageable) {\n return orderDAO.findAll(pageable);\n }\n\n}" }, { "identifier": "SlotServiceImpl", "path": "src/main/java/com/myfood/services/SlotServiceImpl.java", "snippet": "@Service\npublic class SlotServiceImpl implements ISlotService {\n\n @Autowired\n private ISlotDAO slotDAO;\n\n @Override\n public List<Slot> getAllSlots() {\n return slotDAO.findAll();\n }\n\n @Override\n public Optional<Slot> getOneSlot(Long id) {\n return slotDAO.findById(id);\n }\n\n @Override\n public Slot createSlot(Slot entity) {\n return slotDAO.save(entity);\n }\n\n @Override\n public Slot updateSlot(Slot entity) {\n return slotDAO.save(entity);\n }\n\n @Override\n public void deleteSlot(Long id) {\n slotDAO.deleteById(id);\n }\n}" }, { "identifier": "UserServiceImpl", "path": "src/main/java/com/myfood/services/UserServiceImpl.java", "snippet": "@Service\npublic class UserServiceImpl implements IUserService {\n\t\n\t@Autowired\n\tprivate IUserDAO userDao;\n\n\t@Override\n\tpublic List<User> getAllUsers() {\n\t\treturn userDao.findAll();\n\t}\n\n\t@Override\n\tpublic Optional<User> getOneUser(Long id){\n\t\treturn userDao.findById(id);\n\t}\n\n\t@Override\n\tpublic User createUser(User entity) {\n\t\treturn userDao.save(entity);\n\t}\n\n\t@Override\n\tpublic User updateUser(User entity) {\n\t\treturn userDao.save(entity);\n\t}\n\n\t@Override\n\tpublic void deleteUser(Long id) {\n\t\tuserDao.deleteById(id);;\n\t}\n\n /**\n * Get a user by username.\n *\n * @param username The username of the user.\n * @return The user with the specified username, or null if not found.\n */\n public User getUserByUsername(String username) {\n return userDao.findByUsername(username);\n }\n\n\n\tpublic Page<User> findAllWithPagination(Pageable pageable) {\n\t\treturn userDao.findAll(pageable);\n\t}\n\n\t\n\n}" } ]
import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.data.domain.Pageable; import com.myfood.dto.Dish; import com.myfood.dto.ListOrder; import com.myfood.dto.Order; import com.myfood.dto.OrderCookDTO; import com.myfood.dto.OrderUserDTO; import com.myfood.dto.Slot; import com.myfood.dto.User; import com.myfood.services.OrderServiceImpl; import com.myfood.services.SlotServiceImpl; import com.myfood.services.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import jakarta.transaction.Transactional;
6,217
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class OrderController { @Autowired
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class OrderController { @Autowired
private OrderServiceImpl orderService;
7
2023-11-10 16:09:43+00:00
8k
Artillex-Studios/AxGraves
src/main/java/com/artillexstudios/axgraves/listeners/DeathListener.java
[ { "identifier": "GravePreSpawnEvent", "path": "src/main/java/com/artillexstudios/axgraves/api/events/GravePreSpawnEvent.java", "snippet": "public class GravePreSpawnEvent extends Event implements Cancellable {\n private static final HandlerList handlerList = new HandlerList();\n private final Player player;\n private final Grave grave;\n private boolean isCancelled = false;\n\n public GravePreSpawnEvent(@NotNull Player player, @NotNull Grave grave) {\n super(!Bukkit.isPrimaryThread());\n\n this.player = player;\n this.grave = grave;\n }\n\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return handlerList;\n }\n\n public static HandlerList getHandlerList() {\n return handlerList;\n }\n\n @NotNull\n public Player getPlayer() {\n return player;\n }\n\n @NotNull\n public Grave getGrave() {\n return grave;\n }\n\n @Override\n public boolean isCancelled() {\n return isCancelled;\n }\n\n @Override\n public void setCancelled(boolean isCancelled) {\n this.isCancelled = isCancelled;\n }\n}" }, { "identifier": "GraveSpawnEvent", "path": "src/main/java/com/artillexstudios/axgraves/api/events/GraveSpawnEvent.java", "snippet": "public class GraveSpawnEvent extends Event {\n private static final HandlerList handlerList = new HandlerList();\n private final Player player;\n private final Grave grave;\n\n public GraveSpawnEvent(@NotNull Player player, @NotNull Grave grave) {\n super(!Bukkit.isPrimaryThread());\n\n this.player = player;\n this.grave = grave;\n }\n\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return handlerList;\n }\n\n public static HandlerList getHandlerList() {\n return handlerList;\n }\n\n @NotNull\n public Player getPlayer() {\n return player;\n }\n\n @NotNull\n public Grave getGrave() {\n return grave;\n }\n}" }, { "identifier": "Grave", "path": "src/main/java/com/artillexstudios/axgraves/grave/Grave.java", "snippet": "public class Grave {\n private final long spawned;\n private final Location location;\n private final OfflinePlayer player;\n private final String playerName;\n private final StorageGui gui;\n private int storedXP;\n private final PacketArmorStand entity;\n private final Hologram hologram;\n\n public Grave(Location loc, @NotNull Player player, @NotNull ItemStack[] itemsAr, int storedXP) {\n this.location = LocationUtils.getCenterOf(loc);\n this.player = player;\n this.playerName = player.getName();\n\n final ItemStack[] items = Arrays.stream(itemsAr).filter(Objects::nonNull).toArray(ItemStack[]::new);\n this.gui = Gui.storage()\n .title(StringUtils.format(MESSAGES.getString(\"gui-name\").replace(\"%player%\", playerName)))\n .rows(items.length % 9 == 0 ? items.length / 9 : 1 + (items.length / 9))\n .create();\n\n this.storedXP = storedXP;\n this.spawned = System.currentTimeMillis();\n\n for (ItemStack it : items) {\n if (it == null) continue;\n if (BlacklistUtils.isBlacklisted(it)) continue;\n\n gui.addItem(it);\n }\n\n entity = (PacketArmorStand) PacketEntityFactory.get().spawnEntity(location.clone().add(0, CONFIG.getFloat(\"head-height\", -1.2f), 0), EntityType.ARMOR_STAND);\n entity.setItem(EquipmentSlot.HELMET, Utils.getPlayerHead(player));\n entity.setSmall(true);\n entity.setInvisible(true);\n entity.setHasBasePlate(false);\n\n if (CONFIG.getBoolean(\"rotate-head-360\", true)) {\n entity.getLocation().setYaw(player.getLocation().getYaw());\n entity.teleport(entity.getLocation());\n } else {\n entity.getLocation().setYaw(LocationUtils.getNearestDirection(player.getLocation().getYaw()));\n entity.teleport(entity.getLocation());\n }\n\n entity.onClick(event -> Scheduler.get().run(task -> interact(event.getPlayer(), event.getHand())));\n\n hologram = HologramFactory.get().spawnHologram(location.clone().add(0, CONFIG.getFloat(\"hologram-height\", 1.2f), 0), Serializers.LOCATION.serialize(location), 0.3);\n\n for (String msg : MESSAGES.getStringList(\"hologram\")) {\n msg = msg.replace(\"%player%\", playerName);\n msg = msg.replace(\"%xp%\", \"\" + storedXP);\n msg = msg.replace(\"%item%\", \"\" + countItems());\n msg = msg.replace(\"%despawn-time%\", StringUtils.formatTime(CONFIG.getInt(\"despawn-time-seconds\", 180) * 1_000L - (System.currentTimeMillis() - spawned)));\n hologram.addLine(StringUtils.format(msg));\n }\n }\n\n public void update() {\n if (CONFIG.getBoolean(\"auto-rotation.enabled\", false)) {\n entity.getLocation().setYaw(entity.getLocation().getYaw() + CONFIG.getFloat(\"auto-rotation.speed\", 10f));\n entity.teleport(entity.getLocation());\n }\n\n int items = countItems();\n\n int dTime = CONFIG.getInt(\"despawn-time-seconds\", 180);\n if (dTime != -1 && (dTime * 1_000L <= (System.currentTimeMillis() - spawned) || items == 0)) {\n remove();\n return;\n }\n\n int ms = MESSAGES.getStringList(\"hologram\").size();\n for (int i = 0; i < ms; i++) {\n String msg = MESSAGES.getStringList(\"hologram\").get(i);\n msg = msg.replace(\"%player%\", playerName);\n msg = msg.replace(\"%xp%\", \"\" + storedXP);\n msg = msg.replace(\"%item%\", \"\" + items);\n msg = msg.replace(\"%despawn-time%\", StringUtils.formatTime(dTime != -1 ? (dTime * 1_000L - (System.currentTimeMillis() - spawned)) : System.currentTimeMillis() - spawned));\n\n if (i > hologram.getLines().size() - 1) {\n hologram.addLine(StringUtils.format(msg));\n } else {\n hologram.setLine(i, StringUtils.format(msg));\n }\n }\n }\n\n public void interact(@NotNull Player player, org.bukkit.inventory.EquipmentSlot slot) {\n if (CONFIG.getBoolean(\"interact-only-own\", false) && !player.getUniqueId().equals(player.getUniqueId()) && !player.hasPermission(\"axgraves.admin\")) {\n MESSAGEUTILS.sendLang(player, \"interact.not-your-grave\");\n return;\n }\n\n final GraveInteractEvent deathChestInteractEvent = new GraveInteractEvent(player, this);\n Bukkit.getPluginManager().callEvent(deathChestInteractEvent);\n if (deathChestInteractEvent.isCancelled()) return;\n\n if (this.storedXP != 0) {\n ExperienceUtils.changeExp(player, this.storedXP);\n this.storedXP = 0;\n }\n\n if (slot.equals(org.bukkit.inventory.EquipmentSlot.HAND) && player.isSneaking()) {\n if (!CONFIG.getBoolean(\"enable-instant-pickup\", true)) return;\n if (CONFIG.getBoolean(\"instant-pickup-only-own\", false) && !player.getUniqueId().equals(player.getUniqueId())) return;\n\n for (ItemStack it : gui.getInventory().getContents()) {\n if (it == null) continue;\n\n final Collection<ItemStack> ar = player.getInventory().addItem(it).values();\n if (ar.isEmpty()) {\n it.setAmount(0);\n continue;\n }\n\n it.setAmount(ar.iterator().next().getAmount());\n }\n\n update();\n return;\n }\n\n final GraveOpenEvent deathChestOpenEvent = new GraveOpenEvent(player, this);\n Bukkit.getPluginManager().callEvent(deathChestOpenEvent);\n if (deathChestOpenEvent.isCancelled()) return;\n\n gui.open(player);\n }\n\n public void reload() {\n for (int i = 0; i < hologram.getLines().size(); i++) {\n hologram.removeLine(i);\n }\n }\n\n public int countItems() {\n int am = 0;\n for (ItemStack it : gui.getInventory().getContents()) {\n if (it == null) continue;\n am++;\n }\n return am;\n }\n\n public void remove() {\n SpawnedGrave.removeGrave(Grave.this);\n\n Scheduler.get().runAt(location, scheduledTask -> {\n removeInventory();\n\n entity.remove();\n hologram.remove();\n });\n\n }\n\n public void removeInventory() {\n closeInventory();\n\n if (CONFIG.getBoolean(\"drop-items\", true)) {\n for (ItemStack it : gui.getInventory().getContents()) {\n if (it == null) continue;\n location.getWorld().dropItem(location.clone().add(0, -1.0, 0), it);\n }\n }\n\n if (storedXP == 0) return;\n final ExperienceOrb exp = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB);\n exp.setExperience(storedXP);\n }\n\n private void closeInventory() {\n final List<HumanEntity> viewers = new ArrayList<>(gui.getInventory().getViewers());\n final Iterator<HumanEntity> viewerIterator = viewers.iterator();\n\n while (viewerIterator.hasNext()) {\n viewerIterator.next().closeInventory();\n viewerIterator.remove();\n }\n }\n\n public Location getLocation() {\n return location;\n }\n\n public OfflinePlayer getPlayer() {\n return player;\n }\n\n public long getSpawned() {\n return spawned;\n }\n\n public StorageGui getGui() {\n return gui;\n }\n\n public int getStoredXP() {\n return storedXP;\n }\n\n public PacketArmorStand getEntity() {\n return entity;\n }\n\n public Hologram getHologram() {\n return hologram;\n }\n}" }, { "identifier": "SpawnedGrave", "path": "src/main/java/com/artillexstudios/axgraves/grave/SpawnedGrave.java", "snippet": "public class SpawnedGrave {\n private static final ConcurrentLinkedQueue<Grave> chests = new ConcurrentLinkedQueue<>();\n\n public static void addGrave(Grave grave) {\n chests.add(grave);\n }\n\n public static void removeGrave(Grave grave) {\n chests.remove(grave);\n }\n\n public static ConcurrentLinkedQueue<Grave> getGraves() {\n return chests;\n }\n}" }, { "identifier": "ExperienceUtils", "path": "src/main/java/com/artillexstudios/axgraves/utils/ExperienceUtils.java", "snippet": "public final class ExperienceUtils {\n // credit: https://gist.githubusercontent.com/Jikoo/30ec040443a4701b8980/raw/0745ca25a8aaaf749ba2f2164a809e998f6a37c4/Experience.java\n\n public static int getExp(@NotNull Player player) {\n return getExpFromLevel(player.getLevel()) + Math.round(getExpToNext(player.getLevel()) * player.getExp());\n }\n\n public static int getExpFromLevel(int level) {\n if (level > 30) {\n return (int) (4.5 * level * level - 162.5 * level + 2220);\n }\n if (level > 15) {\n return (int) (2.5 * level * level - 40.5 * level + 360);\n }\n return level * level + 6 * level;\n }\n\n public static double getLevelFromExp(long exp) {\n int level = getIntLevelFromExp(exp);\n\n // Get remaining exp progressing towards next level. Cast to float for next bit of math.\n float remainder = exp - (float) getExpFromLevel(level);\n\n // Get level progress with float precision.\n float progress = remainder / getExpToNext(level);\n\n // Slap both numbers together and call it a day. While it shouldn't be possible for progress\n // to be an invalid value (value < 0 || 1 <= value)\n return ((double) level) + progress;\n }\n\n public static int getIntLevelFromExp(long exp) {\n if (exp > 1395) {\n return (int) ((Math.sqrt(72 * exp - 54215D) + 325) / 18);\n }\n if (exp > 315) {\n return (int) (Math.sqrt(40 * exp - 7839D) / 10 + 8.1);\n }\n if (exp > 0) {\n return (int) (Math.sqrt(exp + 9D) - 3);\n }\n return 0;\n }\n\n private static int getExpToNext(int level) {\n if (level >= 30) {\n // Simplified formula. Internal: 112 + (level - 30) * 9\n return level * 9 - 158;\n }\n if (level >= 15) {\n // Simplified formula. Internal: 37 + (level - 15) * 5\n return level * 5 - 38;\n }\n // Internal: 7 + level * 2\n return level * 2 + 7;\n }\n\n public static void changeExp(Player player, int exp) {\n exp += getExp(player);\n\n if (exp < 0) {\n exp = 0;\n }\n\n double levelAndExp = getLevelFromExp(exp);\n int level = (int) levelAndExp;\n player.setLevel(level);\n player.setExp((float) (levelAndExp - level));\n }\n}" }, { "identifier": "CONFIG", "path": "src/main/java/com/artillexstudios/axgraves/AxGraves.java", "snippet": "public static Config CONFIG;" } ]
import com.artillexstudios.axgraves.api.events.GravePreSpawnEvent; import com.artillexstudios.axgraves.api.events.GraveSpawnEvent; import com.artillexstudios.axgraves.grave.Grave; import com.artillexstudios.axgraves.grave.SpawnedGrave; import com.artillexstudios.axgraves.utils.ExperienceUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import static com.artillexstudios.axgraves.AxGraves.CONFIG;
3,622
package com.artillexstudios.axgraves.listeners; public class DeathListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onDeath(@NotNull PlayerDeathEvent event) { if (CONFIG.getStringList("disabled-worlds") != null && CONFIG.getStringList("disabled-worlds").contains(event.getEntity().getWorld().getName())) return; if (!CONFIG.getBoolean("override-keep-inventory", true) && event.getKeepInventory()) return; final Player player = event.getEntity(); if (player.getInventory().isEmpty() && player.getTotalExperience() == 0) return;
package com.artillexstudios.axgraves.listeners; public class DeathListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onDeath(@NotNull PlayerDeathEvent event) { if (CONFIG.getStringList("disabled-worlds") != null && CONFIG.getStringList("disabled-worlds").contains(event.getEntity().getWorld().getName())) return; if (!CONFIG.getBoolean("override-keep-inventory", true) && event.getKeepInventory()) return; final Player player = event.getEntity(); if (player.getInventory().isEmpty() && player.getTotalExperience() == 0) return;
Grave grave = null;
2
2023-11-18 16:37:27+00:00
8k
GoldenStack/minestom-ca
src/main/java/dev/goldenstack/minestom_ca/Program.java
[ { "identifier": "Parser", "path": "src/main/java/dev/goldenstack/minestom_ca/parser/Parser.java", "snippet": "public final class Parser {\r\n private int line;\r\n private List<Token> tokens;\r\n private int index;\r\n\r\n private final AtomicInteger stateCounter = new AtomicInteger(0);\r\n\r\n private final Map<String, Integer> properties = new HashMap<>();\r\n private final List<Rule> rules = new ArrayList<>();\r\n\r\n public Parser() {\r\n }\r\n\r\n public void feedTokens(List<Token> tokens) {\r\n this.line++;\r\n this.tokens = tokens;\r\n this.index = 0;\r\n while (!isAtEnd()) {\r\n List<Rule.Condition> conditions = new ArrayList<>();\r\n List<Rule.Result> results = new ArrayList<>();\r\n while (!(peek() instanceof Token.Arrow)) {\r\n conditions.add(nextCondition());\r\n if (peek() instanceof Token.And) advance();\r\n }\r\n consume(Token.Arrow.class, \"Expected '->'\");\r\n while (!(peek() instanceof Token.EOF)) results.add(nextResult());\r\n this.rules.add(new Rule(conditions.size() == 1 ? conditions.get(0) :\r\n new Rule.Condition.And(conditions), results));\r\n }\r\n }\r\n\r\n private Rule.Condition nextCondition() {\r\n CountPredicate countPredicate = new CountPredicate(1, false, false, 0);\r\n if (peek() instanceof Token.LeftBracket) {\r\n countPredicate = nextCountPredicate();\r\n }\r\n\r\n if (peek() instanceof Token.Constant) {\r\n // Self block check\r\n final Block block = nextBlock();\r\n return new Rule.Condition.Equal(block);\r\n } else if (peek() instanceof Token.Exclamation) {\r\n // Self block check not\r\n advance();\r\n final Token.Constant constant = consume(Token.Constant.class, \"Expected constant\");\r\n final Block block = Block.fromNamespaceId(constant.value());\r\n if (block == null) throw error(\"Unknown block \" + constant.value());\r\n return new Rule.Condition.Not(new Rule.Condition.Equal(block));\r\n } else if (peek() instanceof Token.Identifier identifier) {\r\n advance();\r\n if (!(peek() instanceof Token.At)) {\r\n // Self identifier\r\n final int index = getIndex(identifier.value());\r\n return switch (advance()) {\r\n case Token.Equals ignored -> new Rule.Condition.Equal(\r\n new Rule.Expression.Index(index),\r\n nextExpression()\r\n );\r\n case Token.Exclamation ignored -> new Rule.Condition.Not(\r\n new Rule.Condition.Equal(\r\n new Rule.Expression.Index(index),\r\n nextExpression()\r\n ));\r\n default -> throw error(\"Expected operator\");\r\n };\r\n } else {\r\n // Neighbor block check\r\n consume(Token.At.class, \"Expected '@'\");\r\n final List<Point> targets = NAMED.get(identifier.value());\r\n Rule.Expression neighborsCount = new Rule.Expression.NeighborsCount(targets, nextCondition());\r\n if (countPredicate.compare) {\r\n return new Rule.Condition.Equal(\r\n new Rule.Expression.Compare(neighborsCount, new Rule.Expression.Literal(countPredicate.compareWith())),\r\n new Rule.Expression.Literal(countPredicate.value())\r\n );\r\n } else if (countPredicate.not) {\r\n return new Rule.Condition.Not(\r\n new Rule.Condition.Equal(\r\n neighborsCount,\r\n new Rule.Expression.Literal(countPredicate.value())\r\n ));\r\n } else {\r\n return new Rule.Condition.Equal(\r\n neighborsCount,\r\n new Rule.Expression.Literal(countPredicate.value())\r\n );\r\n }\r\n }\r\n }\r\n throw error(\"Expected condition\");\r\n }\r\n\r\n private CountPredicate nextCountPredicate() {\r\n consume(Token.LeftBracket.class, \"Expected '['\");\r\n if (peek() instanceof Token.Number number && peekNext() instanceof Token.RightBracket) {\r\n // Constant\r\n advance();\r\n consume(Token.RightBracket.class, \"Expected ']'\");\r\n return new CountPredicate((int) number.value(), false, false, 0);\r\n } else if (peek() instanceof Token.Exclamation && peekNext() instanceof Token.Number number) {\r\n // Not\r\n advance();\r\n advance();\r\n consume(Token.RightBracket.class, \"Expected ']'\");\r\n return new CountPredicate((int) number.value(), false, true, 0);\r\n } else if (peek() instanceof Token.GreaterThan && peekNext() instanceof Token.Number number) {\r\n // Greater than\r\n advance();\r\n advance();\r\n consume(Token.RightBracket.class, \"Expected ']'\");\r\n return new CountPredicate(1, true, false, (int) number.value());\r\n } else if (peek() instanceof Token.LessThan && peekNext() instanceof Token.Number number) {\r\n // Lesser than\r\n advance();\r\n advance();\r\n consume(Token.RightBracket.class, \"Expected ']'\");\r\n return new CountPredicate(-1, true, false, (int) number.value());\r\n }\r\n throw error(\"Expected count predicate\");\r\n }\r\n\r\n record CountPredicate(int value, boolean compare, boolean not, int compareWith) {\r\n }\r\n\r\n private Rule.Result nextResult() {\r\n if (peek() instanceof Token.Constant) {\r\n // Change block\r\n final Block block = nextBlock();\r\n return new Rule.Result.SetIndex(0, new Rule.Expression.Literal(block));\r\n } else if (peek() instanceof Token.Identifier identifier) {\r\n // Change state\r\n advance();\r\n consume(Token.Equals.class, \"Expected '='\");\r\n final int index = getIndex(identifier.value());\r\n return new Rule.Result.SetIndex(index, nextExpression());\r\n } else if (peek() instanceof Token.Tilde) {\r\n // Block copy\r\n advance();\r\n Token.Identifier identifier = consume(Token.Identifier.class, \"Expected identifier\");\r\n final List<Point> targets = NAMED.get(identifier.value());\r\n if (targets.size() > 1) throw error(\"Block copy can only be used with a single target\");\r\n final Point first = targets.get(0);\r\n return new Rule.Result.BlockCopy(first.blockX(), first.blockY(), first.blockZ());\r\n } else if (peek() instanceof Token.Dollar) {\r\n // Event triggering\r\n advance();\r\n final Token.Identifier identifier = consume(Token.Identifier.class, \"Expected identifier\");\r\n Rule.Expression expression = null;\r\n if (peek() instanceof Token.Equals) {\r\n consume(Token.Equals.class, \"Expected '='\");\r\n expression = nextExpression();\r\n }\r\n return new Rule.Result.TriggerEvent(identifier.value(), expression);\r\n }\r\n throw error(\"Expected result\");\r\n }\r\n\r\n private Rule.Expression nextExpression() {\r\n Rule.Expression expression = null;\r\n if (peek() instanceof Token.Number number) {\r\n advance();\r\n expression = new Rule.Expression.Literal((int) number.value());\r\n } else if (peek() instanceof Token.Constant) {\r\n final Block block = nextBlock();\r\n expression = new Rule.Expression.Literal(block);\r\n } else if (peek() instanceof Token.Identifier identifier) {\r\n advance();\r\n if (!(peek() instanceof Token.At)) {\r\n // Self state\r\n final int index = getIndex(identifier.value());\r\n expression = new Rule.Expression.Index(index);\r\n } else {\r\n // Neighbor state\r\n advance();\r\n final List<Point> targets = NAMED.get(identifier.value());\r\n final Point first = targets.get(0);\r\n final Token.Identifier identifier2 = consume(Token.Identifier.class, \"Expected identifier\");\r\n final int index = getIndex(identifier2.value());\r\n expression = new Rule.Expression.NeighborIndex(\r\n first.blockX(), first.blockY(), first.blockZ(),\r\n index);\r\n }\r\n }\r\n if (expression == null) throw error(\"Expected number\");\r\n final Rule.Expression.Operation.Type type = switch (peek()) {\r\n case Token.Plus ignored -> Rule.Expression.Operation.Type.ADD;\r\n case Token.Minus ignored -> Rule.Expression.Operation.Type.SUBTRACT;\r\n default -> null;\r\n };\r\n if (type != null) {\r\n advance();\r\n return new Rule.Expression.Operation(expression, nextExpression(), type);\r\n }\r\n return expression;\r\n }\r\n\r\n private Block nextBlock() {\r\n final Token.Constant constant = consume(Token.Constant.class, \"Expected constant\");\r\n Block block = Block.fromNamespaceId(constant.value());\r\n if (block == null) throw error(\"Unknown block: \" + constant.value());\r\n if (peek() instanceof Token.LeftBracket && peekNext() instanceof Token.Identifier) {\r\n // Block has properties\r\n advance();\r\n while (!(peek() instanceof Token.RightBracket)) {\r\n final Token.Identifier propertyName = consume(Token.Identifier.class, \"Expected property name\");\r\n consume(Token.Equals.class, \"Expected '='\");\r\n String propertyValue;\r\n if (peek() instanceof Token.Identifier identifier) {\r\n advance();\r\n propertyValue = identifier.value();\r\n } else if (peek() instanceof Token.Number number) {\r\n advance();\r\n propertyValue = String.valueOf(number.value());\r\n } else {\r\n throw error(\"Expected property value\");\r\n }\r\n block = block.withProperty(propertyName.value(), propertyValue);\r\n if (peek() instanceof Token.Comma) advance();\r\n }\r\n consume(Token.RightBracket.class, \"Expected ']'\");\r\n }\r\n return block;\r\n }\r\n\r\n public Program program() {\r\n return new Program(rules, properties);\r\n }\r\n\r\n int getIndex(String identifier) {\r\n return this.properties.computeIfAbsent(identifier,\r\n s -> stateCounter.incrementAndGet());\r\n }\r\n\r\n <T extends Token> T consume(Class<T> type, String message) {\r\n if (check(type)) return (T) advance();\r\n throw error(message);\r\n }\r\n\r\n Token advance() {\r\n if (!isAtEnd()) index++;\r\n return previous();\r\n }\r\n\r\n Token previous() {\r\n return tokens.get(index - 1);\r\n }\r\n\r\n boolean check(Class<? extends Token> type) {\r\n if (isAtEnd()) return false;\r\n // peek() instanceof type\r\n return peek().getClass().isAssignableFrom(type);\r\n }\r\n\r\n boolean isAtEnd() {\r\n return peek() instanceof Token.EOF;\r\n }\r\n\r\n Token peek() {\r\n return tokens.get(index);\r\n }\r\n\r\n Token peekNext() {\r\n return tokens.get(index + 1);\r\n }\r\n\r\n private RuntimeException error(String message) {\r\n return new RuntimeException(\"Error at line \" + (line - 1) + \": \" + message + \" got \" + peek().getClass().getSimpleName());\r\n }\r\n}\r" }, { "identifier": "Scanner", "path": "src/main/java/dev/goldenstack/minestom_ca/parser/Scanner.java", "snippet": "public final class Scanner {\r\n private final String input;\r\n private int index;\r\n private int line;\r\n\r\n public Scanner(String input) {\r\n this.input = input;\r\n }\r\n\r\n public sealed interface Token {\r\n record Identifier(String value) implements Token {\r\n }\r\n\r\n record Constant(String value) implements Token {\r\n }\r\n\r\n record Number(long value) implements Token {\r\n }\r\n\r\n record Offset(long x, long y) implements Token {\r\n }\r\n\r\n record Arrow() implements Token {\r\n }\r\n\r\n record At() implements Token {\r\n }\r\n\r\n record Dollar() implements Token {\r\n }\r\n\r\n record Tilde() implements Token {\r\n }\r\n\r\n record And() implements Token {\r\n }\r\n\r\n record Exclamation() implements Token {\r\n }\r\n\r\n record Comma() implements Token {\r\n }\r\n\r\n record Separator() implements Token {\r\n }\r\n\r\n record LeftBracket() implements Token {\r\n }\r\n\r\n record RightBracket() implements Token {\r\n }\r\n\r\n record Colon() implements Token {\r\n }\r\n\r\n record Equals() implements Token {\r\n }\r\n\r\n record Plus() implements Token {\r\n }\r\n\r\n record Minus() implements Token {\r\n }\r\n\r\n record GreaterThan() implements Token {\r\n }\r\n\r\n record LessThan() implements Token {\r\n }\r\n\r\n record EOF() implements Token {\r\n }\r\n }\r\n\r\n Token nextToken() {\r\n if (isAtEnd()) return null;\r\n if (peek() == '\\n') {\r\n advance();\r\n line++;\r\n return nextToken();\r\n }\r\n skipWhitespace();\r\n if (isAtEnd()) return null;\r\n skipComment();\r\n if (peek() == '\\n') {\r\n advance();\r\n line++;\r\n return nextToken();\r\n }\r\n\r\n if (isAtEnd()) return null;\r\n\r\n char c = advance();\r\n\r\n if (Character.isLetter(c)) {\r\n final String value = nextIdentifier();\r\n return new Token.Identifier(value);\r\n }\r\n if (c == '#') {\r\n advance();\r\n final String value = nextIdentifier();\r\n return new Token.Constant(value);\r\n }\r\n if (Character.isDigit(c)) {\r\n index--;\r\n final long value = nextNumber();\r\n return new Token.Number(value);\r\n }\r\n if (c == '{') {\r\n skipWhitespace();\r\n final long x = nextNumber();\r\n skipWhitespace();\r\n consume(',');\r\n skipWhitespace();\r\n final long y = nextNumber();\r\n skipWhitespace();\r\n consume('}');\r\n return new Token.Offset(x, y);\r\n }\r\n if (c == '-' && peek() == '>') {\r\n advance();\r\n return new Token.Arrow();\r\n }\r\n if (c == '@') return new Token.At();\r\n if (c == '$') return new Token.Dollar();\r\n if (c == '~') return new Token.Tilde();\r\n if (c == '&') return new Token.And();\r\n if (c == '!') return new Token.Exclamation();\r\n if (c == ',') return new Token.Comma();\r\n if (c == '|') return new Token.Separator();\r\n if (c == ':') return new Token.Colon();\r\n if (c == '[') return new Token.LeftBracket();\r\n if (c == ']') return new Token.RightBracket();\r\n if (c == '=') return new Token.Equals();\r\n if (c == '+') return new Token.Plus();\r\n if (c == '-') return new Token.Minus();\r\n if (c == '>') return new Token.GreaterThan();\r\n if (c == '<') return new Token.LessThan();\r\n\r\n throw new IllegalArgumentException(\"Unexpected character: \" + c);\r\n }\r\n\r\n private long nextNumber() {\r\n final int startIndex = index;\r\n while (Character.isDigit(peek())) advance();\r\n return Long.parseLong(input.substring(startIndex, index));\r\n }\r\n\r\n public List<Token> scanTokens() {\r\n List<Token> tokens = new ArrayList<>();\r\n Token token;\r\n while ((token = nextToken()) != null) {\r\n tokens.add(token);\r\n }\r\n tokens.add(new Token.EOF());\r\n return List.copyOf(tokens);\r\n }\r\n\r\n void skipComment() {\r\n if (peek() == '/' && peekNext() == '/') {\r\n while (peek() != '\\n' && !isAtEnd()) advance();\r\n }\r\n }\r\n\r\n private String nextIdentifier() {\r\n var start = index - 1;\r\n char peek;\r\n while (Character.isLetterOrDigit((peek = peek())) || peek == '_' || peek == '\\'') advance();\r\n return input.substring(start, index);\r\n }\r\n\r\n private void consume(char c) {\r\n final char peek = peek();\r\n if (peek != c) throw new IllegalArgumentException(\"Expected '\" + c + \"' but got '\" + peek + \"'\");\r\n advance();\r\n }\r\n\r\n void skipWhitespace() {\r\n while (Character.isWhitespace(peek())) advance();\r\n }\r\n\r\n char advance() {\r\n return input.charAt(index++);\r\n }\r\n\r\n char peekNext() {\r\n return input.charAt(index + 1);\r\n }\r\n\r\n char peek() {\r\n if (isAtEnd()) return '\\0';\r\n return input.charAt(index);\r\n }\r\n\r\n private boolean isAtEnd() {\r\n return index >= input.length();\r\n }\r\n}\r" } ]
import dev.goldenstack.minestom_ca.parser.Parser; import dev.goldenstack.minestom_ca.parser.Scanner; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map;
3,861
package dev.goldenstack.minestom_ca; public record Program(List<Rule> rules, Map<String, Integer> variables) { public Program { rules = List.copyOf(rules); variables = Map.copyOf(variables); } public static Program fromFile(Path path) { final String program; try { program = Files.readAllLines(path).stream().reduce("", (a, b) -> a + "\n" + b); } catch (IOException e) { throw new RuntimeException(e); } return fromString(program); } public static Program fromString(String program) { List<String> lines = List.of(program.split("\n"));
package dev.goldenstack.minestom_ca; public record Program(List<Rule> rules, Map<String, Integer> variables) { public Program { rules = List.copyOf(rules); variables = Map.copyOf(variables); } public static Program fromFile(Path path) { final String program; try { program = Files.readAllLines(path).stream().reduce("", (a, b) -> a + "\n" + b); } catch (IOException e) { throw new RuntimeException(e); } return fromString(program); } public static Program fromString(String program) { List<String> lines = List.of(program.split("\n"));
Parser parser = new Parser();
0
2023-11-18 21:49:11+00:00
8k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/world/features/mineshaft/MineSegment.java
[ { "identifier": "EnumLogVerbosity", "path": "src/main/java/enviromine/core/EM_ConfigHandler.java", "snippet": "public enum EnumLogVerbosity\n{\n\tNONE(0),\n\tLOW(1),\n\tNORMAL(2),\n\tALL(3);\n\n\tprivate final int level;\n\n\tprivate EnumLogVerbosity(int level)\n\t{\n\t\tthis.level = level;\n\t}\n\n\tpublic int getLevel()\n\t{\n\t\treturn this.level;\n\t}\n}" }, { "identifier": "EM_Settings", "path": "src/main/java/enviromine/core/EM_Settings.java", "snippet": "public class EM_Settings\n{\n\tpublic static final UUID FROST1_UUID = UUID.fromString(\"B0C5F86A-78F3-417C-8B5A-527B90A1E919\");\n\tpublic static final UUID FROST2_UUID = UUID.fromString(\"5C4111A7-A66C-40FB-9FAD-1C6ADAEE7E27\");\n\tpublic static final UUID FROST3_UUID = UUID.fromString(\"721E793E-2203-4F6F-883F-6F44D7DDCCE1\");\n\tpublic static final UUID HEAT1_UUID = UUID.fromString(\"CA6E2CFA-4C53-4CD2-AAD3-3D6177A4F126\");\n\tpublic static final UUID DEHY1_UUID = UUID.fromString(\"38909A39-E1A1-4E93-9016-B2CCBE83D13D\");\n\n\tpublic static File worldDir = null;\n\n\t//Mod Data\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String MOD_ID = \"enviromine\";\n\tpublic static final String MOD_NAME = \"EnviroMine\";\n\tpublic static final String MOD_NAME_COLORIZED = EnumChatFormatting.AQUA + MOD_NAME + EnumChatFormatting.RESET;\n\tpublic static final String Channel = \"EM_CH\";\n\tpublic static final String Proxy = \"enviromine.core.proxies\";\n\tpublic static final String URL = \"https://modrinth.com/mod/enviromine-for-galaxy-odyssey\";\n\tpublic static final String VERSION_CHECKER_URL = \"https://gitgud.io/AstroTibs/enviromine-for-galaxy-odyssey/-/raw/1.7.10/CURRENT_VERSION\";\n\tpublic static final String GUI_FACTORY = MOD_ID+\".client.gui.menu.config.EnviroMineGuiFactory\";\n\n\tpublic static boolean versionChecker;\n\n\tpublic static int loggerVerbosity;\n\n public static boolean DeathFromHeartAttack;\n\n public static int HeartAttackTimeToDie;\n public static int HbmGasMaskBreakMultiplier;\n\n public static int EnviromineGasMaskBreakMultiplier;\n public static int HbmGasMaskBreakChanceNumber;\n\n public static boolean hardcoregases = false;\n\n\tpublic static boolean enablePhysics = false;\n\tpublic static boolean enableLandslide = true;\n\tpublic static boolean waterCollapse = true; // Added out of necessity/annoyance -- AstroTibs\n\n\tpublic static float blockTempDropoffPower = 0.75F;\n\tpublic static int scanRadius = 6;\n\tpublic static float auraRadius = 0.5F;\n\n\t@ShouldOverride\n\tpublic static boolean enableAirQ = true;\n\t@ShouldOverride\n\tpublic static boolean enableHydrate = true;\n\t@ShouldOverride\n\tpublic static boolean enableSanity = true;\n\t@ShouldOverride\n\tpublic static boolean enableBodyTemp = true;\n\n\tpublic static boolean trackNonPlayer = false;\n\n\tpublic static boolean spreadIce = false;\n\n\tpublic static boolean useFarenheit = false;\n\tpublic static String heatBarPos;\n\tpublic static String waterBarPos;\n\tpublic static String sanityBarPos;\n\tpublic static String oxygenBarPos;\n\n\tpublic static int dirtBottleID = 5001;\n\tpublic static int saltBottleID = 5002;\n\tpublic static int coldBottleID = 5003;\n\tpublic static int camelPackID = 5004;\n\n\tpublic static final String GAS_MASK_FILL_TAG_KEY = \"gasMaskFill\";\n\tpublic static final String GAS_MASK_MAX_TAG_KEY = \"gasMaskMax\";\n\tpublic static final String CAMEL_PACK_FILL_TAG_KEY = \"camelPackFill\";\n\tpublic static final String CAMEL_PACK_MAX_TAG_KEY = \"camelPackMax\";\n\tpublic static final String IS_CAMEL_PACK_TAG_KEY = \"isCamelPack\";\n\tpublic static int gasMaskMax = 1000;\n\tpublic static int filterRestore = 500;\n\tpublic static int camelPackMax = 100;\n\tpublic static float gasMaskUpdateRestoreFraction = 1F;\n\n\t/*\n\tpublic static int gasMaskID = 5005;\n\tpublic static int airFilterID = 5006;\n\tpublic static int hardHatID = 5007;\n\tpublic static int rottenFoodID = 5008;\n\n\tpublic static int blockElevatorTopID = 501;\n\tpublic static int blockElevatorBottomID = 502;\n\tpublic static int gasBlockID = 503;\n\tpublic static int fireGasBlockID = 504;\n\t*/\n\n\tpublic static int hypothermiaPotionID = 27;\n\tpublic static int heatstrokePotionID = 28;\n\tpublic static int frostBitePotionID = 29;\n\tpublic static int dehydratePotionID = 30;\n\tpublic static int insanityPotionID = 31;\n\n\tpublic static boolean enableHypothermiaGlobal = true;\n\tpublic static boolean enableHeatstrokeGlobal = true;\n\tpublic static boolean enableFrostbiteGlobal = true;\n\tpublic static boolean frostbitePermanent = true;\n\n\t//Gases\n\tpublic static boolean renderGases = false;\n\tpublic static int gasTickRate = 32; //GasFires are 4x faster than this\n\tpublic static int gasPassLimit = -1;\n\tpublic static boolean gasWaterLike = true;\n\tpublic static boolean slowGases = true; // Normal gases use random ticks to move\n\tpublic static boolean noGases = false;\n\n\t//World Gen\n\tpublic static boolean shaftGen = true;\n\tpublic static boolean gasGen = true;\n\tpublic static boolean oldMineGen = true;\n\n\t//Properties\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.ArmorPropsEncoder\")\n\t@ShouldOverride({String.class, ArmorProperties.class})\n\tpublic static HashMap<String,ArmorProperties> armorProperties = new HashMap<String,ArmorProperties>();\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.BlocksPropsEncoder\")\n\t@ShouldOverride({String.class, BlockProperties.class})\n\tpublic static HashMap<String,BlockProperties> blockProperties = new HashMap<String,BlockProperties>();\n\t@ShouldOverride({Integer.class, EntityProperties.class})\n\tpublic static HashMap<Integer,EntityProperties> livingProperties = new HashMap<Integer,EntityProperties>();\n\t@ShouldOverride({String.class, ItemProperties.class})\n\tpublic static HashMap<String,ItemProperties> itemProperties = new HashMap<String,ItemProperties>();\n\t@ShouldOverride({Integer.class, BiomeProperties.class})\n\tpublic static HashMap<Integer,BiomeProperties> biomeProperties = new HashMap<Integer,BiomeProperties>();\n\t@ShouldOverride({Integer.class, DimensionProperties.class})\n\tpublic static HashMap<Integer,DimensionProperties> dimensionProperties = new HashMap<Integer,DimensionProperties>();\n\n\tpublic static HashMap<String,StabilityType> stabilityTypes = new HashMap<String,StabilityType>();\n\n\t@ShouldOverride({String.class, RotProperties.class})\n\tpublic static HashMap<String,RotProperties> rotProperties = new HashMap<String,RotProperties>();\n\n\tpublic static boolean streamsDrink = true;\n\tpublic static boolean witcheryVampireImmunities = true;\n\tpublic static boolean witcheryWerewolfImmunities = true;\n\tpublic static boolean matterOverdriveAndroidImmunities = true;\n\n\tpublic static int updateCap = 128;\n\tpublic static boolean stoneCracks = true;\n\tpublic static String defaultStability = \"loose\";\n\n\tpublic static double sanityMult = 1.0D;\n\tpublic static double hydrationMult = 1.0D;\n\tpublic static double tempMult = 1.0D;\n\tpublic static double airMult = 1.0D;\n\n\t//public static boolean updateCheck = true;\n\t//public static boolean useDefaultConfig = true;\n\tpublic static boolean genConfigs = false;\n\tpublic static boolean genDefaults = false;\n\n\tpublic static int physInterval = 6;\n\tpublic static int worldDelay = 1000;\n\tpublic static int chunkDelay = 1000;\n\tpublic static int entityFailsafe = 1;\n\tpublic static boolean villageAssist = true;\n\n\tpublic static boolean minimalHud;\n\tpublic static boolean limitCauldron;\n\tpublic static boolean allowTinting = true;\n\tpublic static boolean torchesBurn = true;\n\tpublic static boolean torchesGoOut = true;\n\tpublic static boolean genFlammableCoal = true; // In case you don't want burny-coal\n\tpublic static boolean randomizeInsanityPitch = true;\n\tpublic static boolean catchFireAtHighTemps = true;\n\n\tpublic static int caveDimID = -3;\n\tpublic static int caveBiomeID = 23;\n\tpublic static boolean disableCaves = false;\n\tpublic static int limitElevatorY = 10;\n\tpublic static boolean caveOreEvent = true;\n\tpublic static boolean caveLava = false;\n\tpublic static int caveRavineRarity = 30;\n\tpublic static int caveTunnelRarity = 7;\n\tpublic static int caveDungeons = 8;\n\tpublic static int caveLiquidY = 32;\n\tpublic static boolean caveFlood = true;\n\tpublic static boolean caveRespawn = false;\n\tpublic static boolean enforceWeights = false;\n\tpublic static ArrayList<CaveGenProperties> caveGenProperties = new ArrayList<CaveGenProperties>();\n\tpublic static HashMap<Integer, CaveSpawnProperties> caveSpawnProperties = new HashMap<Integer, CaveSpawnProperties>();\n\n\tpublic static boolean foodSpoiling = true;\n\tpublic static int foodRotTime = 7;\n\n\t/** Whether or not this overridden with server settings */\n\tpublic static boolean isOverridden = false;\n\tpublic static boolean enableConfigOverride = false;\n\tpublic static boolean profileOverride = false;\n\tpublic static String profileSelected = \"default\";\n\n\tpublic static boolean enableQuakes = true;\n\tpublic static boolean quakePhysics = true;\n\tpublic static int quakeRarity = 100;\n\n\tpublic static boolean finiteWater = false;\n\tpublic static float thingChance = 0.000001F;\n\tpublic static boolean noNausea = false;\n\tpublic static boolean keepStatus = false;\n\tpublic static boolean renderGear = true;\n\tpublic static String[] cauldronHeatingBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\tpublic static String[] notWaterBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\n\tpublic static boolean voxelMenuExists = false;\n\n\t/**\n\t * Tells the server that this field should be sent to the client to overwrite<br>\n\t * Usage:<br>\n\t * <tt>@ShouldOverride</tt> - for ints/booleans/floats/Strings<br>\n\t * <tt>@ShouldOverride(Class[] value)</tt> - for ArrayList or HashMap types\n\t * */\n\t@Target(ElementType.FIELD)\n\t@Retention(RetentionPolicy.RUNTIME)\n\tpublic @interface ShouldOverride\n\t{\n\t\tClass<?>[] value() default {};\n\t}\n}" }, { "identifier": "EnviroMine", "path": "src/main/java/enviromine/core/EnviroMine.java", "snippet": "@Mod(modid = EM_Settings.MOD_ID, name = EM_Settings.MOD_NAME, version = EM_Settings.VERSION, guiFactory = EM_Settings.GUI_FACTORY)\npublic class EnviroMine\n{\n\tpublic static Logger logger;\n\tpublic static BiomeGenCaves caves;\n\tpublic static EnviroTab enviroTab;\n\n\t@Instance(EM_Settings.MOD_ID)\n\tpublic static EnviroMine instance;\n\n\t@SidedProxy(clientSide = EM_Settings.Proxy + \".EM_ClientProxy\", serverSide = EM_Settings.Proxy + \".EM_CommonProxy\")\n\tpublic static EM_CommonProxy proxy;\n\n\tpublic SimpleNetworkWrapper network;\n\n\t//public static EM_WorldData theWorldEM;\n\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent event)\n\t{\n\t\t// The following overrides the mcmod.info file!\n\t\t// Adapted from Jabelar's Magic Beans:\n\t\t// https://github.com/jabelar/MagicBeans-1.7.10/blob/e48456397f9c6c27efce18e6b9ad34407e6bc7c7/src/main/java/com/blogspot/jabelarminecraft/magicbeans/MagicBeans.java\n event.getModMetadata().autogenerated = false ; // stops it from complaining about missing mcmod.info\n\n event.getModMetadata().name = \t\t\t// name\n \t\tEnumChatFormatting.AQUA +\n \t\tEM_Settings.MOD_NAME;\n\n event.getModMetadata().version = \t\t// version\n \t\tEnumChatFormatting.DARK_AQUA +\n \t\tEM_Settings.VERSION;\n\n event.getModMetadata().credits = \t\t// credits\n \t\tEnumChatFormatting.AQUA +\n \t\t\"Big thanks to the IronArmy and EpicNation for all the hard work debugging this mod.\";\n\n event.getModMetadata().authorList.clear();\n event.getModMetadata().authorList.add( // authorList - added as a list\n \t\tEnumChatFormatting.BLUE +\n \t\t\"Funwayguy, TimbuckTato, GenDeathrow, thislooksfun, AstroTibs\"\n \t\t);\n\n event.getModMetadata().url = EnumChatFormatting.GRAY +\n \t\tEM_Settings.URL;\n\n event.getModMetadata().description = \t// description\n\t \t\tEnumChatFormatting.GREEN +\n\t \t\t\"Adds more realism to Minecraft with environmental effects, physics, gases and a cave dimension.\";\n\n event.getModMetadata().logoFile = \"title.png\";\n\n\n\t\tlogger = event.getModLog();\n\n\t\tenviroTab = new EnviroTab(\"enviromine.enviroTab\");\n\n\t\tLegacyHandler.preInit();\n\t\tLegacyHandler.init();\n\n\t\tproxy.preInit(event);\n\n\t\tObjectHandler.initItems();\n\t\tObjectHandler.registerItems();\n\t\tObjectHandler.initBlocks();\n\t\tObjectHandler.registerBlocks();\n\n\t\t// Load Configuration files And Custom files\n\t\tEM_ConfigHandler.initConfig();\n\n\n // Version check monitors\n\t\t// Have to be initialized after the configs so that the value is read\n/* \tif ((EM_Settings.VERSION).contains(\"DEV\"))\n \t{\n \t\tFMLCommonHandler.instance().bus().register(DevVersionWarning.instance);\n \t}\n \telse if (EM_Settings.versionChecker)\n \t{\n \t\tFMLCommonHandler.instance().bus().register(VersionChecker.instance);\n \t}\n*/\n\n\t\tObjectHandler.registerGases();\n\t\tObjectHandler.registerEntities();\n\n\t\tif(EM_Settings.shaftGen == true)\n\t\t{\n\t\t\tVillagerRegistry.instance().registerVillageCreationHandler(new EnviroShaftCreationHandler());\n\t\t\tMapGenStructureIO.func_143031_a(EM_VillageMineshaft.class, \"ViMS\");\n\t\t}\n\n\t\tthis.network = NetworkRegistry.INSTANCE.newSimpleChannel(EM_Settings.Channel);\n\t\tthis.network.registerMessage(PacketEnviroMine.HandlerServer.class, PacketEnviroMine.class, 0, Side.SERVER);\n\t\tthis.network.registerMessage(PacketEnviroMine.HandlerClient.class, PacketEnviroMine.class, 1, Side.CLIENT);\n\t\tthis.network.registerMessage(PacketAutoOverride.Handler.class, PacketAutoOverride.class, 2, Side.CLIENT);\n\t\tthis.network.registerMessage(PacketServerOverride.Handler.class, PacketServerOverride.class, 3, Side.CLIENT);\n\n\n\t\tGameRegistry.registerWorldGenerator(new WorldFeatureGenerator(), 20);\n\t}\n\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent event)\n\t{\n\t\tproxy.init(event);\n\n\t\tObjectHandler.registerRecipes();\n\n\t\tEnviroUtils.extendPotionList();\n\n\t\tEnviroPotion.RegisterPotions();\n\n\t\tEnviroAchievements.InitAchievements();\n\n\t\tcaves = (BiomeGenCaves)(new BiomeGenCaves(EM_Settings.caveBiomeID).setColor(0).setBiomeName(\"Caves\").setDisableRain().setTemperatureRainfall(1.0F, 0.0F));\n\t\t//GameRegistry.addBiome(caves);\n\t\tBiomeDictionary.registerBiomeType(caves, Type.WASTELAND);\n\n\n\t\tDimensionManager.registerProviderType(EM_Settings.caveDimID, WorldProviderCaves.class, false);\n\t\tDimensionManager.registerDimension(EM_Settings.caveDimID, EM_Settings.caveDimID);\n\n\n\t\tproxy.registerTickHandlers();\n\t\tproxy.registerEventHandlers();\n\t}\n\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent event)\n\t{\n\t\tproxy.postInit(event);\n\n\t\t//TODO Moved inside of Config Handler.general config to add in custom list\n\t\t//ObjectHandler.LoadIgnitionSources();\n\n\t\tEM_ConfigHandler.initConfig(); // Second pass for object initialized after pre-init\n\t}\n\n\t@EventHandler\n\tpublic void serverStart(FMLServerStartingEvent event)\n\t{\n\t\tMinecraftServer server = MinecraftServer.getServer();\n\t\tICommandManager command = server.getCommandManager();\n\t\tServerCommandManager manager = (ServerCommandManager) command;\n\n\t\tmanager.registerCommand(new CommandPhysics());\n\t\tmanager.registerCommand(new EnviroCommand());\n\t\tmanager.registerCommand(new QuakeCommand());\n\t}\n}" } ]
import static net.minecraftforge.common.ChestGenHooks.DUNGEON_CHEST; import java.util.ArrayList; import org.apache.logging.log4j.Level; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; import net.minecraftforge.common.ChestGenHooks;
5,447
package enviromine.world.features.mineshaft; public abstract class MineSegment { // Rotation = 90 * value (top-down clockwise direction)(+X = forward, +Z = right) int rot = 0; World world; int posX = 0; int posY = 0; int posZ = 0; int minX = 0; int minZ = 0; int minY = 0; int maxX = 0; int maxY = 0; int maxZ = 0; int chunkMinX = 0; int chunkMaxX = 0; int chunkMinZ = 0; int chunkMaxZ = 0; int decay = 0; MineshaftBuilder builder; public MineSegment(World world, int x, int y, int z, int rotation, MineshaftBuilder builder) { this.world = world; this.posX = x; this.posY = y; this.posZ = z; this.rot = rotation%4; this.builder = builder; } public abstract boolean build(); void setBlockBounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { this.minX = minX; this.minY = minY; this.minZ = minZ; this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; } void setChunkBounds(int minX, int minZ, int maxX, int maxZ) { this.chunkMinX = minX; this.chunkMinZ = minZ; this.chunkMaxX = maxX; this.chunkMaxZ = maxZ; } public void setDecay(int decay) { this.decay = decay; } public int[] getExitPoint(int rotation) { return new int[]{posX,posY,posZ}; } public int[] getExitPoint(int rotation, int yDir) { int[] point = getExitPoint(rotation); return point; } public boolean canBuild() { if(posY + maxY > 255) { return false; } else if(posY - minY < 0) { return false; } return true; } public ArrayList<String> getRequiredChunks() { ArrayList<String> chunks = new ArrayList<String>(); int xOffMin = this.xOffset(chunkMinX, chunkMinZ)/16; int zOffMin = this.zOffset(chunkMinX, chunkMinX)/16; int xOffMax = this.xOffset(chunkMaxX, chunkMaxZ)/16; int zOffMax = this.zOffset(chunkMaxX, chunkMaxZ)/16; if(xOffMin > xOffMax) { int tmp = xOffMin; xOffMin = xOffMax; xOffMax = tmp; } if(zOffMin > zOffMax) { int tmp = zOffMin; zOffMin = zOffMax; zOffMax = tmp; } for(int i = xOffMin; i <= xOffMax; i++) { for(int k = zOffMin; k <= zOffMax; k++) { chunks.add("" + i + "," + k); } } return chunks; } public void linkChunksToBuilder() { ArrayList<String> chunks = this.getRequiredChunks(); if(chunks.size() <= 0) {
package enviromine.world.features.mineshaft; public abstract class MineSegment { // Rotation = 90 * value (top-down clockwise direction)(+X = forward, +Z = right) int rot = 0; World world; int posX = 0; int posY = 0; int posZ = 0; int minX = 0; int minZ = 0; int minY = 0; int maxX = 0; int maxY = 0; int maxZ = 0; int chunkMinX = 0; int chunkMaxX = 0; int chunkMinZ = 0; int chunkMaxZ = 0; int decay = 0; MineshaftBuilder builder; public MineSegment(World world, int x, int y, int z, int rotation, MineshaftBuilder builder) { this.world = world; this.posX = x; this.posY = y; this.posZ = z; this.rot = rotation%4; this.builder = builder; } public abstract boolean build(); void setBlockBounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { this.minX = minX; this.minY = minY; this.minZ = minZ; this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; } void setChunkBounds(int minX, int minZ, int maxX, int maxZ) { this.chunkMinX = minX; this.chunkMinZ = minZ; this.chunkMaxX = maxX; this.chunkMaxZ = maxZ; } public void setDecay(int decay) { this.decay = decay; } public int[] getExitPoint(int rotation) { return new int[]{posX,posY,posZ}; } public int[] getExitPoint(int rotation, int yDir) { int[] point = getExitPoint(rotation); return point; } public boolean canBuild() { if(posY + maxY > 255) { return false; } else if(posY - minY < 0) { return false; } return true; } public ArrayList<String> getRequiredChunks() { ArrayList<String> chunks = new ArrayList<String>(); int xOffMin = this.xOffset(chunkMinX, chunkMinZ)/16; int zOffMin = this.zOffset(chunkMinX, chunkMinX)/16; int xOffMax = this.xOffset(chunkMaxX, chunkMaxZ)/16; int zOffMax = this.zOffset(chunkMaxX, chunkMaxZ)/16; if(xOffMin > xOffMax) { int tmp = xOffMin; xOffMin = xOffMax; xOffMax = tmp; } if(zOffMin > zOffMax) { int tmp = zOffMin; zOffMin = zOffMax; zOffMax = tmp; } for(int i = xOffMin; i <= xOffMax; i++) { for(int k = zOffMin; k <= zOffMax; k++) { chunks.add("" + i + "," + k); } } return chunks; } public void linkChunksToBuilder() { ArrayList<String> chunks = this.getRequiredChunks(); if(chunks.size() <= 0) {
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.LOW.getLevel()) EnviroMine.logger.log(Level.WARN, "ERROR: MineSegment is registering 0 chunks! It will not generate!");
1
2023-11-16 18:15:29+00:00
8k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/RewriteProjectParserIntegrationTest.java
[ { "identifier": "SbmSupportRewriteConfiguration", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/boot/autoconfigure/SbmSupportRewriteConfiguration.java", "snippet": "@AutoConfiguration\n@Import({ RecipeDiscoveryConfiguration.class, RewriteParserConfiguration.class, ProjectResourceSetConfiguration.class })\npublic class SbmSupportRewriteConfiguration {\n\n}" }, { "identifier": "RewriteMavenProjectParser", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/maven/RewriteMavenProjectParser.java", "snippet": "public class RewriteMavenProjectParser {\n\n\tprivate final MavenPlexusContainer mavenPlexusContainer;\n\n\tprivate final ParsingEventListener parsingListener;\n\n\tprivate final MavenExecutor mavenRunner;\n\n\tprivate final MavenMojoProjectParserFactory mavenMojoProjectParserFactory;\n\n\tprivate final ScanScope scanScope;\n\n\tprivate final ConfigurableListableBeanFactory beanFactory;\n\n\tprivate final ExecutionContext executionContext;\n\n\tpublic RewriteMavenProjectParser(MavenPlexusContainer mavenPlexusContainer, ParsingEventListener parsingListener,\n\t\t\tMavenExecutor mavenRunner, MavenMojoProjectParserFactory mavenMojoProjectParserFactory, ScanScope scanScope,\n\t\t\tConfigurableListableBeanFactory beanFactory, ExecutionContext executionContext) {\n\t\tthis.mavenPlexusContainer = mavenPlexusContainer;\n\t\tthis.parsingListener = parsingListener;\n\t\tthis.mavenRunner = mavenRunner;\n\t\tthis.mavenMojoProjectParserFactory = mavenMojoProjectParserFactory;\n\t\tthis.scanScope = scanScope;\n\t\tthis.beanFactory = beanFactory;\n\t\tthis.executionContext = executionContext;\n\t}\n\n\t/**\n\t * Parses a list of {@link Resource}s in given {@code baseDir} to OpenRewrite AST. It\n\t * uses default settings for configuration.\n\t */\n\tpublic RewriteProjectParsingResult parse(Path baseDir) {\n\t\tParsingExecutionContextView.view(executionContext).setParsingListener(parsingListener);\n\t\treturn parse(baseDir, executionContext);\n\t}\n\n\t@NotNull\n\tpublic RewriteProjectParsingResult parse(Path baseDir, ExecutionContext executionContext) {\n\t\tfinal Path absoluteBaseDir = getAbsolutePath(baseDir);\n\t\tPlexusContainer plexusContainer = mavenPlexusContainer.get();\n\t\tRewriteProjectParsingResult parsingResult = parseInternal(absoluteBaseDir, executionContext, plexusContainer);\n\t\treturn parsingResult;\n\t}\n\n\tprivate RewriteProjectParsingResult parseInternal(Path baseDir, ExecutionContext executionContext,\n\t\t\tPlexusContainer plexusContainer) {\n\t\tclearScanScopedBeans();\n\n\t\tAtomicReference<RewriteProjectParsingResult> parsingResult = new AtomicReference<>();\n\t\tmavenRunner.onProjectSucceededEvent(baseDir, List.of(\"clean\", \"package\"), event -> {\n\t\t\ttry {\n\t\t\t\tMavenSession session = event.getSession();\n\t\t\t\tList<MavenProject> mavenProjects = session.getAllProjects();\n\t\t\t\tMavenMojoProjectParser rewriteProjectParser = mavenMojoProjectParserFactory.create(baseDir,\n\t\t\t\t\t\tmavenProjects, plexusContainer, session);\n\t\t\t\tList<NamedStyles> styles = List.of();\n\t\t\t\tList<SourceFile> sourceFiles = parseSourceFiles(rewriteProjectParser, mavenProjects, styles,\n\t\t\t\t\t\texecutionContext);\n\t\t\t\tparsingResult.set(new RewriteProjectParsingResult(sourceFiles, executionContext));\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t});\n\t\treturn parsingResult.get();\n\t}\n\n\tprivate void clearScanScopedBeans() {\n\t\tscanScope.clear(beanFactory);\n\t}\n\n\tprivate List<SourceFile> parseSourceFiles(MavenMojoProjectParser rewriteProjectParser,\n\t\t\tList<MavenProject> mavenProjects, List<NamedStyles> styles, ExecutionContext executionContext) {\n\t\ttry {\n\t\t\tStream<SourceFile> sourceFileStream = rewriteProjectParser.listSourceFiles(\n\t\t\t\t\tmavenProjects.get(mavenProjects.size() - 1), // FIXME: Order and\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// access to root\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// module\n\t\t\t\t\tstyles, executionContext);\n\t\t\treturn sourcesWithAutoDetectedStyles(sourceFileStream);\n\t\t}\n\t\tcatch (DependencyResolutionRequiredException | MojoExecutionException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t@NotNull\n\tprivate static Path getAbsolutePath(Path baseDir) {\n\t\tif (!baseDir.isAbsolute()) {\n\t\t\tbaseDir = baseDir.toAbsolutePath().normalize();\n\t\t}\n\t\treturn baseDir;\n\t}\n\n\t// copied from OpenRewrite for now, TODO: remove and reuse\n\tList<SourceFile> sourcesWithAutoDetectedStyles(Stream<SourceFile> sourceFiles) {\n\t\torg.openrewrite.java.style.Autodetect.Detector javaDetector = org.openrewrite.java.style.Autodetect.detector();\n\t\torg.openrewrite.xml.style.Autodetect.Detector xmlDetector = org.openrewrite.xml.style.Autodetect.detector();\n\t\tList<SourceFile> sourceFileList = sourceFiles.peek(javaDetector::sample)\n\t\t\t.peek(xmlDetector::sample)\n\t\t\t.collect(toList());\n\n\t\tMap<Class<? extends Tree>, NamedStyles> stylesByType = new HashMap<>();\n\t\tstylesByType.put(JavaSourceFile.class, javaDetector.build());\n\t\tstylesByType.put(Xml.Document.class, xmlDetector.build());\n\n\t\treturn ListUtils.map(sourceFileList, applyAutodetectedStyle(stylesByType));\n\t}\n\n\t// copied from OpenRewrite for now, TODO: remove and reuse\n\tUnaryOperator<SourceFile> applyAutodetectedStyle(Map<Class<? extends Tree>, NamedStyles> stylesByType) {\n\t\treturn before -> {\n\t\t\tfor (Map.Entry<Class<? extends Tree>, NamedStyles> styleTypeEntry : stylesByType.entrySet()) {\n\t\t\t\tif (styleTypeEntry.getKey().isAssignableFrom(before.getClass())) {\n\t\t\t\t\tbefore = before.withMarkers(before.getMarkers().add(styleTypeEntry.getValue()));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn before;\n\t\t};\n\t}\n\n}" }, { "identifier": "SbmTestConfiguration", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/maven/SbmTestConfiguration.java", "snippet": "@TestConfiguration\n@Import(RewriteParserConfiguration.class)\npublic class SbmTestConfiguration {\n\n\t@Autowired\n\tprivate SpringRewriteProperties springRewriteProperties;\n\n\t@Bean\n\tMavenConfigFileParser configFileParser() {\n\t\treturn new MavenConfigFileParser();\n\t}\n\n\t@Bean\n\tMavenExecutionRequestFactory requestFactory(MavenConfigFileParser configFileParser) {\n\t\treturn new MavenExecutionRequestFactory(configFileParser);\n\t}\n\n\t@Bean\n\tMavenExecutor mavenExecutor(MavenExecutionRequestFactory requestFactory, MavenPlexusContainer plexusContainer) {\n\t\treturn new MavenExecutor(requestFactory, plexusContainer);\n\t}\n\n\t@Bean\n\tMavenMojoProjectParserFactory projectParserFactory() {\n\t\treturn new MavenMojoProjectParserFactory(springRewriteProperties);\n\t}\n\n\t@Bean\n\tMavenPlexusContainer plexusContainer() {\n\t\treturn new MavenPlexusContainer();\n\t}\n\n\t@Bean\n\tMavenModelReader modelReader() {\n\t\treturn new MavenModelReader();\n\t}\n\n\t@Bean\n\tRewriteMavenProjectParser rewriteMavenProjectParser(MavenPlexusContainer plexusContainer,\n\t\t\tParsingEventListener parsingEventListenerAdapter, MavenExecutor mavenExecutor,\n\t\t\tMavenMojoProjectParserFactory mavenMojoProjectParserFactory, ScanScope scanScope,\n\t\t\tConfigurableListableBeanFactory beanFactory, ExecutionContext executionContext) {\n\t\treturn new RewriteMavenProjectParser(plexusContainer, parsingEventListenerAdapter, mavenExecutor,\n\t\t\t\tmavenMojoProjectParserFactory, scanScope, beanFactory, executionContext);\n\t}\n\n}" }, { "identifier": "ParserParityTestHelper", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/test/util/ParserParityTestHelper.java", "snippet": "public class ParserParityTestHelper {\n\n\tprivate final Path baseDir;\n\n\tprivate SpringRewriteProperties springRewriteProperties = new SpringRewriteProperties();\n\n\tprivate boolean isParallelParse = true;\n\n\tprivate ExecutionContext executionContext;\n\n\tprivate ParserParityTestHelper(Path baseDir) {\n\t\tthis.baseDir = baseDir;\n\t}\n\n\tpublic static ParserParityTestHelper scanProjectDir(Path baseDir) {\n\t\tParserParityTestHelper helper = new ParserParityTestHelper(baseDir);\n\t\treturn helper;\n\t}\n\n\t/**\n\t * Sequentially parse given project using tested parser and then comparing parser. The\n\t * parsers are executed in parallel by default.\n\t */\n\tpublic ParserParityTestHelper parseSequentially() {\n\t\tthis.isParallelParse = false;\n\t\treturn this;\n\t}\n\n\tpublic ParserParityTestHelper withParserProperties(SpringRewriteProperties springRewriteProperties) {\n\t\tthis.springRewriteProperties = springRewriteProperties;\n\t\treturn this;\n\t}\n\n\tpublic ParserParityTestHelper withExecutionContextForComparingParser(ExecutionContext executionContext) {\n\t\tthis.executionContext = executionContext;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Use this method when no additional assertions required.\n\t */\n\tpublic void verifyParity() {\n\t\tverifyParity((expectedParsingResult, actualParsingResult) -> {\n\t\t\t// nothing extra to verify\n\t\t});\n\t}\n\n\t/**\n\t * Use this method if additional assertions are required.\n\t */\n\tpublic void verifyParity(CustomParserResultParityChecker customParserResultParityChecker) {\n\t\tRewriteProjectParsingResult expectedParserResult = null;\n\t\tRewriteProjectParsingResult actualParserResult = null;\n\n\t\tresolveDependencies();\n\n\t\tParserExecutionHelper parserExecutionHelper = new ParserExecutionHelper();\n\t\tif (isParallelParse) {\n\t\t\tParallelParsingResult result = parserExecutionHelper.parseParallel(baseDir, springRewriteProperties,\n\t\t\t\t\texecutionContext);\n\t\t\texpectedParserResult = result.expectedParsingResult();\n\t\t\tactualParserResult = result.actualParsingResult();\n\t\t}\n\t\telse {\n\t\t\tactualParserResult = parserExecutionHelper.parseWithRewriteProjectParser(baseDir, springRewriteProperties);\n\t\t\texpectedParserResult = parserExecutionHelper.parseWithComparingParser(baseDir, springRewriteProperties,\n\t\t\t\t\texecutionContext);\n\t\t}\n\n\t\tDefaultParserResultParityChecker.verifyParserResultParity(baseDir, expectedParserResult, actualParserResult);\n\n\t\t// additional checks\n\t\tcustomParserResultParityChecker.accept(actualParserResult, expectedParserResult);\n\t}\n\n\tprivate void resolveDependencies() {\n\t\ttry {\n\t\t\tDefaultInvoker defaultInvoker = new DefaultInvoker();\n\t\t\tInvocationRequest request = new DefaultInvocationRequest();\n\t\t\trequest.setGoals(List.of(\"clean\", \"test-compile\"));\n\t\t\trequest.setBaseDirectory(baseDir.toFile());\n\t\t\t// request.setBatchMode(true);\n\t\t\trequest.setPomFile(baseDir.resolve(\"pom.xml\").toFile());\n\n\t\t\tString mavenHome = \"\";\n\t\t\tif (System.getenv(\"MAVEN_HOME\") != null) {\n\t\t\t\tmavenHome = System.getenv(\"MAVEN_HOME\");\n\t\t\t}\n\t\t\telse if (System.getenv(\"MVN_HOME\") != null) {\n\t\t\t\tmavenHome = System.getenv(\"MVN_HOME\");\n\t\t\t}\n\t\t\telse if (System.getenv(\"M2_HOME\") != null) {\n\t\t\t\tmavenHome = System.getenv(\"M2_HOME\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalStateException(\"Neither MVN_HOME nor MAVEN_HOME set but required by MavenInvoker.\");\n\t\t\t}\n\n\t\t\tSystem.out.println(\"Using Maven %s\".formatted(mavenHome));\n\n\t\t\trequest.setMavenHome(new File(mavenHome));\n\t\t\tdefaultInvoker.execute(request);\n\t\t}\n\t\tcatch (MavenInvocationException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic interface CustomParserResultParityChecker\n\t\t\textends BiConsumer<RewriteProjectParsingResult, RewriteProjectParsingResult> {\n\n\t\t@Override\n\t\tvoid accept(RewriteProjectParsingResult expectedParsingResult, RewriteProjectParsingResult actualParsingResult);\n\n\t}\n\n\tprivate class DefaultParserResultParityChecker {\n\n\t\tpublic static void verifyParserResultParity(Path baseDir, RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tverifyEqualNumberOfParsedResources(expectedParserResult, actualParserResult);\n\t\t\tverifyEqualResourcePaths(baseDir, expectedParserResult, actualParserResult);\n\t\t\tRewriteMarkerParityVerifier.verifyEqualMarkers(expectedParserResult, actualParserResult);\n\t\t}\n\n\t\tprivate static void verifyEqualResourcePaths(Path baseDir, RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tList<String> expectedResultPaths = expectedParserResult.sourceFiles()\n\t\t\t\t.stream()\n\t\t\t\t.map(sf -> baseDir.resolve(sf.getSourcePath()).toAbsolutePath().normalize().toString())\n\t\t\t\t.toList();\n\t\t\tList<String> actualResultPaths = actualParserResult.sourceFiles()\n\t\t\t\t.stream()\n\t\t\t\t.map(sf -> baseDir.resolve(sf.getSourcePath()).toAbsolutePath().normalize().toString())\n\t\t\t\t.toList();\n\t\t\tassertThat(actualResultPaths).containsExactlyInAnyOrder(expectedResultPaths.toArray(String[]::new));\n\t\t}\n\n\t\tprivate static void verifyEqualNumberOfParsedResources(RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tassertThat(actualParserResult.sourceFiles().size())\n\t\t\t\t.as(renderErrorMessage(expectedParserResult, actualParserResult))\n\t\t\t\t.isEqualTo(expectedParserResult.sourceFiles().size());\n\t\t}\n\n\t\tprivate static String renderErrorMessage(RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tList<SourceFile> collect = new ArrayList<>();\n\t\t\tif (expectedParserResult.sourceFiles().size() > actualParserResult.sourceFiles().size()) {\n\t\t\t\tcollect = expectedParserResult.sourceFiles()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(element -> !actualParserResult.sourceFiles().contains(element))\n\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcollect = actualParserResult.sourceFiles()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(element -> !expectedParserResult.sourceFiles().contains(element))\n\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t}\n\n\t\t\treturn \"ComparingParserResult had %d sourceFiles whereas TestedParserResult had %d sourceFiles. Files were %s\"\n\t\t\t\t.formatted(expectedParserResult.sourceFiles().size(), actualParserResult.sourceFiles().size(), collect);\n\t\t}\n\n\t}\n\n\tprivate static class RewriteMarkerParityVerifier {\n\n\t\tstatic void verifyEqualMarkers(RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tList<SourceFile> expectedSourceFiles = expectedParserResult.sourceFiles();\n\t\t\tList<SourceFile> actualSourceFiles = actualParserResult.sourceFiles();\n\n\t\t\t// bring to same order\n\t\t\texpectedSourceFiles.sort(Comparator.comparing(SourceFile::getSourcePath));\n\t\t\tactualSourceFiles.sort(Comparator.comparing(SourceFile::getSourcePath));\n\n\t\t\t// Compare and verify markers of all source files\n\t\t\tfor (SourceFile curExpectedSourceFile : expectedSourceFiles) {\n\t\t\t\tint index = expectedSourceFiles.indexOf(curExpectedSourceFile);\n\t\t\t\tSourceFile curGivenSourceFile = actualSourceFiles.get(index);\n\t\t\t\tverifyEqualSourceFileMarkers(curExpectedSourceFile, curGivenSourceFile);\n\t\t\t}\n\t\t}\n\n\t\tstatic void verifyEqualSourceFileMarkers(SourceFile curExpectedSourceFile, SourceFile curGivenSourceFile) {\n\t\t\tMarkers expectedMarkers = curExpectedSourceFile.getMarkers();\n\t\t\tList<Marker> expectedMarkersList = expectedMarkers.getMarkers();\n\t\t\tMarkers givenMarkers = curGivenSourceFile.getMarkers();\n\t\t\tList<Marker> actualMarkersList = givenMarkers.getMarkers();\n\n\t\t\tassertThat(actualMarkersList.size()).isEqualTo(expectedMarkersList.size());\n\n\t\t\tSoftAssertions softAssertions = new SoftAssertions();\n\n\t\t\tactualMarkersList.sort(Comparator.comparing(o -> o.getClass().getName()));\n\t\t\texpectedMarkersList.sort(Comparator.comparing(o -> o.getClass().getName()));\n\n\t\t\texpectedMarkersList.forEach(expectedMarker -> {\n\t\t\t\tint i = expectedMarkersList.indexOf(expectedMarker);\n\t\t\t\tMarker actualMarker = actualMarkersList.get(i);\n\n\t\t\t\tassertThat(actualMarker).isInstanceOf(expectedMarker.getClass());\n\n\t\t\t\tif (MavenResolutionResult.class.isInstance(actualMarker)) {\n\t\t\t\t\tMavenResolutionResult expected = (MavenResolutionResult) expectedMarker;\n\t\t\t\t\tMavenResolutionResult actual = (MavenResolutionResult) actualMarker;\n\t\t\t\t\tcompareMavenResolutionResultMarker(softAssertions, expected, actual);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcompareMarker(softAssertions, expectedMarker, actualMarker);\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t\tsoftAssertions.assertAll();\n\n\t\t\tif (curExpectedSourceFile.getMarkers().findFirst(JavaSourceSet.class).isPresent()) {\n\t\t\t\t// Tested parser must have JavaSourceSet marker when comparing parser has\n\t\t\t\t// it\n\t\t\t\tassertThat(givenMarkers.findFirst(JavaSourceSet.class)).isPresent();\n\n\t\t\t\t// assert classpath equality\n\t\t\t\tList<String> expectedClasspath = expectedMarkers.findFirst(JavaSourceSet.class)\n\t\t\t\t\t.get()\n\t\t\t\t\t.getClasspath()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.toList();\n\t\t\t\tList<String> actualClasspath = givenMarkers.findFirst(JavaSourceSet.class)\n\t\t\t\t\t.get()\n\t\t\t\t\t.getClasspath()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.toList();\n\n\t\t\t\tassertThat(actualClasspath.size()).isEqualTo(expectedClasspath.size());\n\n\t\t\t\tassertThat(expectedClasspath).withFailMessage(() -> {\n\t\t\t\t\tList<String> additionalElementsInExpectedClasspath = expectedClasspath.stream()\n\t\t\t\t\t\t.filter(element -> !actualClasspath.contains(element))\n\t\t\t\t\t\t.collect(Collectors.toList());\n\n\t\t\t\t\tif (!additionalElementsInExpectedClasspath.isEmpty()) {\n\t\t\t\t\t\treturn \"Classpath of comparing and tested parser differ: comparing classpath contains additional entries: %s\"\n\t\t\t\t\t\t\t.formatted(additionalElementsInExpectedClasspath);\n\t\t\t\t\t}\n\n\t\t\t\t\tList<String> additionalElementsInActualClasspath = actualClasspath.stream()\n\t\t\t\t\t\t.filter(element -> !expectedClasspath.contains(element))\n\t\t\t\t\t\t.collect(Collectors.toList());\n\n\t\t\t\t\tif (!additionalElementsInActualClasspath.isEmpty()) {\n\t\t\t\t\t\treturn \"Classpath of comparing and tested parser differ: tested classpath contains additional entries: %s\"\n\t\t\t\t\t\t\t.formatted(additionalElementsInActualClasspath);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new IllegalStateException(\"Something went terribly wrong...\");\n\t\t\t\t}).containsExactlyInAnyOrder(actualClasspath.toArray(String[]::new));\n\t\t\t}\n\t\t}\n\n\t\tstatic void compareMavenResolutionResultMarker(SoftAssertions softAssertions, MavenResolutionResult expected,\n\t\t\t\tMavenResolutionResult actual) {\n\t\t\tsoftAssertions.assertThat(actual)\n\t\t\t\t.usingRecursiveComparison()\n\t\t\t\t.withEqualsForFieldsMatchingRegexes(customRepositoryEquals(\"mavenSettings.localRepository\"),\n\t\t\t\t\t\t\"mavenSettings.localRepository\", \".*\\\\.repository\", \"mavenSettings.mavenLocal.uri\")\n\t\t\t\t.ignoringFields(\"modules\", // checked further down\n\t\t\t\t\t\t\"dependencies\", // checked further down\n\t\t\t\t\t\t\"parent.modules\" // TODO:\n\t\t\t\t// https://github.com/spring-projects-experimental/spring-boot-migrator/issues/991\n\t\t\t\t)\n\t\t\t\t.ignoringFieldsOfTypes(UUID.class)\n\t\t\t\t.isEqualTo(expected);\n\n\t\t\t// verify modules\n\t\t\tverifyEqualModulesInMavenResolutionResult(softAssertions, expected, actual);\n\n\t\t\t// verify dependencies\n\t\t\tverifyEqualDependencies(softAssertions, expected, actual);\n\t\t}\n\n\t\tprivate static void verifyEqualDependencies(SoftAssertions softAssertions, MavenResolutionResult expected,\n\t\t\t\tMavenResolutionResult actual) {\n\t\t\tSet<Scope> keys = expected.getDependencies().keySet();\n\t\t\tkeys.forEach(k -> {\n\t\t\t\tList<ResolvedDependency> expectedDependencies = expected.getDependencies().get(k);\n\t\t\t\tList<ResolvedDependency> actualDependencies = actual.getDependencies().get(k);\n\n\t\t\t\t// same order\n\t\t\t\texpectedDependencies.sort(Comparator.comparing(o -> o.getGav().toString()));\n\t\t\t\tactualDependencies.sort(Comparator.comparing(o -> o.getGav().toString()));\n\n\t\t\t\tsoftAssertions.assertThat(actualDependencies)\n\t\t\t\t\t.usingRecursiveComparison()\n\t\t\t\t\t.withEqualsForFieldsMatchingRegexes(customRepositoryEquals(\".*\\\\.repository\"), \".*\\\\.repository\")\n\t\t\t\t\t.ignoringFieldsOfTypes(UUID.class)\n\t\t\t\t\t.isEqualTo(expectedDependencies);\n\t\t\t});\n\t\t}\n\n\t\tprivate static void verifyEqualModulesInMavenResolutionResult(SoftAssertions softAssertions,\n\t\t\t\tMavenResolutionResult expected, MavenResolutionResult actual) {\n\t\t\tList<MavenResolutionResult> expectedModules = expected.getModules();\n\t\t\tList<MavenResolutionResult> actualModules = actual.getModules();\n\t\t\t// bring modules in same order\n\t\t\texpectedModules.sort(Comparator.comparing(o -> o.getPom().getGav().toString()));\n\t\t\tactualModules.sort(Comparator.comparing(o -> o.getPom().getGav().toString()));\n\t\t\t// test modules\n\t\t\texpectedModules.forEach(cm -> {\n\t\t\t\tMavenResolutionResult actualMavenResolutionResult = actualModules.get(expectedModules.indexOf(cm));\n\t\t\t\tcompareMavenResolutionResultMarker(softAssertions, cm, actualMavenResolutionResult);\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Custom equals comparing fields names with 'repository' URI. This is required\n\t\t * because the repository URI can be 'file:host' or 'file//host' which is\n\t\t * effectively the same. But the strict comparison fails. This custom equals\n\t\t * method can be used instead. <pre>\n\t\t * .withEqualsForFieldsMatchingRegexes(\n\t\t * customRepositoryEquals(),\n\t\t * \".*\\\\.repository\"\n\t\t * )\n\t\t * </pre>\n\t\t */\n\t\t@NotNull\n\t\tprivate static BiPredicate<Object, Object> customRepositoryEquals(String s) {\n\t\t\t// System.out.println(s);\n\t\t\treturn (Object actual, Object expected) -> {\n\t\t\t\t// field null?\n\t\t\t\tif (actual == null) {\n\t\t\t\t\tif (expected == null) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t// normal equals?\n\t\t\t\tboolean equals = actual.equals(expected);\n\t\t\t\tif (equals) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t// Compare Repository URI\n\t\t\t\tif (actual.getClass() == actual.getClass()) {\n\t\t\t\t\tif (actual instanceof URI) {\n\t\t\t\t\t\tURI f1 = (URI) actual;\n\t\t\t\t\t\tURI f2 = (URI) expected;\n\t\t\t\t\t\treturn equals ? true\n\t\t\t\t\t\t\t\t: f1.getScheme().equals(f2.getScheme()) && f1.getHost().equals(f2.getHost())\n\t\t\t\t\t\t\t\t\t\t&& f1.getPath().equals(f2.getPath())\n\t\t\t\t\t\t\t\t\t\t&& f1.getFragment().equals(f2.getFragment());\n\t\t\t\t\t}\n\t\t\t\t\telse if (actual instanceof String) {\n\t\t\t\t\t\tURI f1 = new File((String) actual).toURI();\n\t\t\t\t\t\tURI f2 = new File((String) expected).toURI();\n\t\t\t\t\t\t// @formatter:off\n return\n f1.getScheme() != null && f2.getScheme() != null ? f1.getScheme().equals(f2.getScheme()) : f1.getScheme() == null && f2.getScheme() == null ? true : false\n &&\n f1.getHost() != null && f2.getHost() != null ? f1.getHost().equals(f2.getHost()) : f1.getHost() == null && f2.getHost() == null ? true : false\n &&\n f1.getPath() != null && f2.getPath() != null ? f1.getPath().equals(f2.getPath()) : f1.getPath() == null && f2.getPath() == null ? true : false\n &&\n f1.getFragment() != null && f2.getFragment() != null ? f1.getFragment().equals(f2.getFragment()) : f1.getFragment() == null && f2.getFragment() == null ? true : false;\n // @formatter:on\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t};\n\t\t}\n\n\t\tstatic void compareMarker(SoftAssertions softAssertions, Marker expectedMarker, Marker actualMarker) {\n\t\t\tsoftAssertions.assertThat(actualMarker)\n\t\t\t\t.usingRecursiveComparison()\n\t\t\t\t.withStrictTypeChecking()\n\t\t\t\t.ignoringCollectionOrder()\n\t\t\t\t.withEqualsForFields(equalsClasspath(), \"classpath\")\n\t\t\t\t.ignoringFields(\n\t\t\t\t\t\t// FIXME:\n\t\t\t\t\t\t// https://github.com/spring-projects-experimental/spring-boot-migrator/issues/982\n\t\t\t\t\t\t\"styles\")\n\t\t\t\t.ignoringFieldsOfTypes(UUID.class,\n\t\t\t\t\t\t// FIXME:\n\t\t\t\t\t\t// https://github.com/spring-projects-experimental/spring-boot-migrator/issues/982\n\t\t\t\t\t\tStyle.class)\n\t\t\t\t.isEqualTo(expectedMarker);\n\t\t}\n\n\t\tprivate static BiPredicate<?, ?> equalsClasspath() {\n\t\t\treturn (List<JavaType.FullyQualified> c1, List<JavaType.FullyQualified> c2) -> {\n\t\t\t\tList<String> c1Sorted = c1.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.sorted()\n\t\t\t\t\t.toList();\n\t\t\t\tList<String> c2Sorted = c2.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.sorted()\n\t\t\t\t\t.toList();\n\t\t\t\treturn c1Sorted.equals(c2Sorted);\n\t\t\t};\n\t\t}\n\n\t}\n\n}" }, { "identifier": "TestProjectHelper", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/test/util/TestProjectHelper.java", "snippet": "public class TestProjectHelper {\n\n\tprivate final Path targetDir;\n\n\tprivate List<Resource> resources = new ArrayList<>();\n\n\tprivate boolean initializeGitRepo;\n\n\tprivate String gitUrl;\n\n\tprivate String gitTag;\n\n\tprivate boolean deleteDirIfExists = false;\n\n\tpublic TestProjectHelper(Path targetDir) {\n\t\tthis.targetDir = targetDir;\n\t}\n\n\tpublic static Path getMavenProject(String s) {\n\t\treturn Path.of(\"./testcode/maven-projects/\").resolve(s).toAbsolutePath().normalize();\n\t}\n\n\tpublic static TestProjectHelper createTestProject(Path targetDir) {\n\t\treturn new TestProjectHelper(targetDir);\n\t}\n\n\tpublic static TestProjectHelper createTestProject(String targetDir) {\n\t\treturn new TestProjectHelper(Path.of(targetDir).toAbsolutePath().normalize());\n\t}\n\n\tpublic TestProjectHelper withResources(Resource... resources) {\n\t\tthis.resources.addAll(Arrays.asList(resources));\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper initializeGitRepo() {\n\t\tthis.initializeGitRepo = true;\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper cloneGitProject(String url) {\n\t\tthis.gitUrl = url;\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper checkoutTag(String tag) {\n\t\tthis.gitTag = tag;\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper deleteDirIfExists() {\n\t\tthis.deleteDirIfExists = true;\n\t\treturn this;\n\t}\n\n\tpublic void writeToFilesystem() {\n\t\tif (deleteDirIfExists) {\n\t\t\ttry {\n\t\t\t\tFileUtils.deleteDirectory(targetDir.toFile());\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\n\t\tif (initializeGitRepo) {\n\t\t\ttry {\n\t\t\t\tGit.init().setDirectory(targetDir.toFile()).call();\n\t\t\t}\n\t\t\tcatch (GitAPIException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t\telse if (gitUrl != null) {\n\t\t\ttry {\n\t\t\t\tFile directory = targetDir.toFile();\n\t\t\t\tGit git = Git.cloneRepository().setDirectory(directory).setURI(this.gitUrl).call();\n\n\t\t\t\tif (gitTag != null) {\n\t\t\t\t\tgit.checkout().setName(\"refs/tags/\" + gitTag).call();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (GitAPIException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t\tResourceUtil.write(targetDir, resources);\n\t}\n\n}" } ]
import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junitpioneer.jupiter.Issue; import org.openrewrite.java.tree.J; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.rewrite.boot.autoconfigure.SbmSupportRewriteConfiguration; import org.springframework.rewrite.parsers.maven.RewriteMavenProjectParser; import org.springframework.rewrite.parsers.maven.SbmTestConfiguration; import org.springframework.rewrite.test.util.ParserParityTestHelper; import org.springframework.rewrite.test.util.TestProjectHelper; import java.nio.file.Path;
7,047
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers; /** * @author Fabian Krüger */ @DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.") @Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12") @SpringBootTest(classes = { SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class }) public class RewriteProjectParserIntegrationTest { @Autowired RewriteProjectParser sut; @Autowired ProjectScanner projectScanner; @Autowired RewriteMavenProjectParser mavenProjectParser; @Test @DisplayName("testFailingProject") void testFailingProject() { Path baseDir = Path.of("./testcode/maven-projects/failing");
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers; /** * @author Fabian Krüger */ @DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.") @Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12") @SpringBootTest(classes = { SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class }) public class RewriteProjectParserIntegrationTest { @Autowired RewriteProjectParser sut; @Autowired ProjectScanner projectScanner; @Autowired RewriteMavenProjectParser mavenProjectParser; @Test @DisplayName("testFailingProject") void testFailingProject() { Path baseDir = Path.of("./testcode/maven-projects/failing");
ParserParityTestHelper.scanProjectDir(baseDir).verifyParity((comparingParsingResult, testedParsingResult) -> {
3
2023-11-14 23:02:37+00:00
8k
giftorg/gift
gift-analyze/src/main/java/org/giftorg/analyze/entity/Repository.java
[ { "identifier": "BigModel", "path": "gift-common/src/main/java/org/giftorg/common/bigmodel/BigModel.java", "snippet": "public interface BigModel extends Serializable {\n\n /**\n * 大模型聊天接口\n */\n String chat(List<Message> messages) throws Exception;\n\n /**\n * 计算文本嵌入向量\n */\n List<Double> textEmbedding(String prompt) throws Exception;\n\n /**\n * 大模型消息结构\n */\n @Data\n @ToString\n class Message {\n public String role;\n public String content;\n\n public Message(String user, String hello) {\n this.role = user;\n this.content = hello;\n }\n }\n}" }, { "identifier": "ChatGPT", "path": "gift-common/src/main/java/org/giftorg/common/bigmodel/impl/ChatGPT.java", "snippet": "@Slf4j\npublic class ChatGPT implements Serializable, BigModel {\n private static final String baseUrl = StringUtil.trimEnd(Config.chatGPTConfig.getHost(), \"/\");\n private static final List<String> apiKeys = Config.chatGPTConfig.getApiKeys();\n private static final String model = Config.chatGPTConfig.getModel();\n private static final String apiUrl = baseUrl + \"/v1/chat/completions\";\n private static final TokenPool tokenPool = TokenPool.getTokenPool(apiKeys, 64, 3);\n\n /**\n * 聊天接口,接收一个消息列表,返回大模型回复的消息\n */\n public String chat(List<Message> messages) {\n Request req = new Request(model, messages);\n AtomicReference<HttpResponse> atResp = new AtomicReference<>();\n log.info(\"chat request: {}\", messages);\n\n APITaskResult result = tokenPool.runTask(token -> {\n HttpResponse resp = HttpRequest.post(apiUrl)\n .header(\"Authorization\", \"Bearer \" + token)\n .header(\"Content-Type\", \"application/json\")\n .body(JSON.toJSONBytes(req))\n .execute();\n atResp.set(resp);\n });\n\n if (!result.getSuccess()) {\n throw new RuntimeException(result.getException());\n }\n\n HttpResponse resp = atResp.get();\n Response res = JSONUtil.toBean(resp.body(), Response.class);\n if (res.choices == null || res.choices.isEmpty()) {\n log.error(\"chat response error, response.body: {}\", resp.body());\n throw new RuntimeException(\"chat response error, response.body: \" + resp.body());\n }\n\n log.info(\"chat answer: {}\", res.choices.get(0).message.content);\n return res.choices.get(0).message.content;\n }\n\n @Override\n public List<Double> textEmbedding(String prompt) throws Exception {\n throw new Exception(\"not implemented\");\n }\n\n /**\n * ChatGPT 请求体\n */\n public static class Request {\n public String model;\n public List<Message> messages;\n\n public Request(String model, List<Message> messages) {\n this.model = model;\n this.messages = messages;\n }\n }\n\n /**\n * ChatGPT 响应体\n */\n @ToString\n public static class Response {\n public List<Choice> choices;\n }\n\n @ToString\n public static class Choice {\n public Message message;\n }\n\n public static void main(String[] args) throws Exception {\n ChatGPT gpt = new ChatGPT();\n ArrayList<BigModel.Message> messages = new ArrayList<>();\n messages.add(new BigModel.Message(\"user\", \"hello\"));;\n String answer = gpt.chat(messages);\n System.out.println(answer);\n TokenPool.closeDefaultTokenPool();\n }\n}" }, { "identifier": "XingHuo", "path": "gift-common/src/main/java/org/giftorg/common/bigmodel/impl/XingHuo.java", "snippet": "@Slf4j\npublic class XingHuo extends WebSocketListener implements Serializable, BigModel {\n private static final String hostUrl = Config.xingHouConfig.getHostUrl();\n private static final String appid = Config.xingHouConfig.getAppid();\n private static final String apiSecret = Config.xingHouConfig.getApiSecret();\n private static final String apiKey = Config.xingHouConfig.getApiKey();\n\n public static final Gson gson = new Gson();\n\n public List<Message> messages;\n public String answer = \"\";\n private BlockingDeque<Boolean> doneChannel;\n\n public XingHuo() {\n }\n\n public XingHuo(List<Message> messages) {\n this.messages = messages;\n this.doneChannel = new LinkedBlockingDeque<>();\n }\n\n /**\n * 聊天接口,接收一个消息列表,返回大模型回复的消息\n */\n public String chat(List<Message> messages) throws Exception {\n log.info(\"chat request: {}\", messages);\n OkHttpClient client = new OkHttpClient.Builder().build();\n String url = getAuthUrl().replace(\"http://\", \"ws://\").replace(\"https://\", \"wss://\");\n Request request = new Request.Builder().url(url).build();\n\n XingHuo bigModel = new XingHuo(messages);\n client.newWebSocket(request, bigModel);\n Boolean done = bigModel.doneChannel.poll(100 * 1000L, TimeUnit.MILLISECONDS);\n if (!Boolean.TRUE.equals(done)) {\n throw new Exception(\"xing-hou chat timeout\");\n }\n log.info(\"chat answer: {}\", bigModel.answer);\n return bigModel.answer;\n }\n\n @Override\n public List<Double> textEmbedding(String prompt) throws Exception {\n throw new Exception(\"not implemented\");\n }\n\n @Override\n public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {\n super.onOpen(webSocket, response);\n webSocket.send(newRequestBody(messages).toString());\n }\n\n @Override\n public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {\n JsonParse jsonParse = gson.fromJson(text, JsonParse.class);\n if (jsonParse.header.code != 0) {\n log.error(\"onMessage error, code: {}, sid: {}\", jsonParse.header.code, jsonParse.header.sid);\n webSocket.close(1000, \"\");\n }\n List<Message> texts = jsonParse.payload.choices.text;\n StringBuilder ans = new StringBuilder();\n for (Message t : texts) {\n ans.append(t.content);\n }\n log.info(\"onMessage: {}\", ans);\n answer += ans.toString();\n if (jsonParse.header.status == 2) {\n webSocket.close(1000, \"\");\n }\n }\n\n @Override\n public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) {\n doneChannel.add(true);\n super.onFailure(webSocket, t, response);\n try {\n if (null != response) {\n log.error(\"onFailure code: {}\", response.code());\n log.error(\"onFailure body: {}\", response.body() != null ? response.body().string() : \"\");\n if (response.code() != 101) {\n log.error(\"connection failed\");\n }\n }\n } catch (IOException e) {\n log.error(e.toString());\n }\n }\n\n @Override\n public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {\n doneChannel.add(true);\n super.onClosed(webSocket, code, reason);\n }\n\n // 鉴权方法\n public static String getAuthUrl() throws Exception {\n URL url = new URL(hostUrl);\n // 时间\n SimpleDateFormat format = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss z\", Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n String date = format.format(new Date());\n // 拼接\n String preStr = \"host: \" + url.getHost() + \"\\n\" +\n \"date: \" + date + \"\\n\" +\n \"GET \" + url.getPath() + \" HTTP/1.1\";\n // SHA256加密\n Mac mac = Mac.getInstance(\"hmacsha256\");\n SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), \"hmacsha256\");\n mac.init(spec);\n\n byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));\n // Base64加密\n String sha = Base64.getEncoder().encodeToString(hexDigits);\n // 拼接\n String authorization = String.format(\"api_key=\\\"%s\\\", algorithm=\\\"%s\\\", headers=\\\"%s\\\", signature=\\\"%s\\\"\", apiKey, \"hmac-sha256\", \"host date request-line\", sha);\n // 拼接地址\n HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse(\"https://\" + url.getHost() + url.getPath())).newBuilder().//\n addQueryParameter(\"authorization\", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//\n addQueryParameter(\"date\", date).//\n addQueryParameter(\"host\", url.getHost()).//\n build();\n\n return httpUrl.toString();\n }\n\n // 创建聊天请求体\n public static JSONObject newRequestBody(List<Message> messages) {\n JSONObject request = new JSONObject();\n\n // header\n JSONObject header = new JSONObject();\n header.put(\"app_id\", appid);\n header.put(\"uid\", UUID.randomUUID().toString().substring(0, 10));\n\n // parameter\n JSONObject parameter = new JSONObject();\n JSONObject chat = new JSONObject();\n chat.put(\"domain\", \"generalv2\");\n chat.put(\"temperature\", 0.5);\n chat.put(\"max_tokens\", 4096);\n parameter.put(\"chat\", chat);\n\n // payload\n JSONObject payload = new JSONObject();\n JSONObject message = new JSONObject();\n JSONArray text = new JSONArray();\n\n // set messages\n for (Message m : messages) {\n text.add(JSON.toJSON(m));\n }\n message.put(\"text\", text);\n payload.put(\"message\", message);\n\n // request\n request.put(\"header\", header);\n request.put(\"parameter\", parameter);\n request.put(\"payload\", payload);\n\n return request;\n }\n\n // 响应体结构\n static class JsonParse {\n Header header;\n Payload payload;\n }\n\n static class Header {\n int code;\n int status;\n String sid;\n }\n\n static class Payload {\n Choices choices;\n }\n\n static class Choices {\n List<Message> text;\n }\n\n public static void main(String[] args) throws Exception {\n XingHuo xh = new XingHuo();\n String chat = xh.chat(Arrays.asList(new Message(\"user\", \"hello\")));\n System.out.println(chat);\n }\n}" }, { "identifier": "TokenPool", "path": "gift-common/src/main/java/org/giftorg/common/tokenpool/TokenPool.java", "snippet": "@Slf4j\n@Getter\npublic class TokenPool extends Thread {\n // 全局 TokenPool\n private static TokenPool tokenPool = null;\n\n // token 列表\n private final List<Token> tokens;\n\n // 可用 token 队列\n private final BlockingQueue<Token> tokenQueue;\n\n // api 任务队列\n private final BlockingQueue<APITask> apiTaskQueue;\n\n // 每个 token 在每个周期的可用次数\n private final Integer frequency;\n\n // 周期(秒)\n private final Integer cycle;\n\n // 最大线程数\n private Integer maxThread = 10;\n\n // 线程池\n private ExecutorService executorService;\n\n // 程序状态\n private Boolean active = true;\n\n // 定时器\n private Timer tokenTimer;\n\n public TokenPool(List<String> tokens, Integer cycle, Integer frequency) {\n this.cycle = cycle;\n this.frequency = frequency;\n this.tokenQueue = new LinkedBlockingQueue<>();\n this.apiTaskQueue = new LinkedBlockingQueue<>();\n\n this.tokens = new ArrayList<>();\n for (String token : tokens) {\n Token t = new Token(token);\n this.tokens.add(t);\n for (int i = 0; i < frequency; i++) {\n tokenQueue.add(t);\n }\n }\n\n this.start();\n }\n\n public TokenPool(List<String> tokens, Integer cycle, Integer frequency, Integer maxThread) {\n this.cycle = cycle;\n this.frequency = frequency;\n this.tokenQueue = new LinkedBlockingQueue<>();\n this.apiTaskQueue = new LinkedBlockingQueue<>();\n this.maxThread = maxThread;\n\n this.tokens = new ArrayList<>();\n for (String token : tokens) {\n Token t = new Token(token);\n this.tokens.add(t);\n for (int i = 0; i < frequency; i++) {\n tokenQueue.add(t);\n }\n }\n\n this.start();\n }\n\n /**\n * 获取全局的 TokenPool\n */\n public static TokenPool getTokenPool(List<String> tokens, Integer cycle, Integer frequency) {\n if (tokenPool == null) {\n tokenPool = new TokenPool(tokens, cycle, frequency);\n }\n return tokenPool;\n }\n\n /**\n * 获取全局的 TokenPool,并指定 api token 任务执行的最大线程数\n */\n public static TokenPool getTokenPool(List<String> tokens, Integer cycle, Integer frequency, Integer maxThread) {\n if (tokenPool == null) {\n tokenPool = new TokenPool(tokens, cycle, frequency, maxThread);\n }\n return tokenPool;\n }\n\n /**\n * 添加 api token 任务,异步执行\n */\n public void addTask(APITask apiTask) {\n apiTaskQueue.add(apiTask);\n }\n\n /**\n * 添加 api token 任务,同步执行并返回执行结态\n */\n public APITaskResult runTask(APITask apiTask) {\n APITasker apiTasker = new APITasker(apiTask);\n apiTaskQueue.add(apiTasker);\n try {\n return apiTasker.getResult();\n } catch (InterruptedException e) {\n return new APITaskResult(e);\n }\n }\n\n /**\n * Token 池的调度程序\n */\n public void run() {\n tokenTimer = new Timer();\n executorService = Executors.newFixedThreadPool(maxThread);\n\n // 从队列中取出 token,执行任务\n while (active) {\n // 从任务队列中取出任务\n APITask apiTask;\n try {\n apiTask = apiTaskQueue.take();\n } catch (InterruptedException ignored) {\n continue;\n } catch (Exception e) {\n log.error(\"take api task error: {}\", e.toString());\n continue;\n }\n\n // 从 token 队列中取出 token\n Token token;\n try {\n token = tokenQueue.take();\n } catch (InterruptedException ignored) {\n continue;\n } catch (Exception e) {\n log.error(\"take token error: {}\", e.toString());\n continue;\n }\n\n // 执行任务\n executorService.submit(() -> {\n try {\n apiTask.run(useToken(token));\n } catch (Exception e) {\n e.getStackTrace();\n log.error(\"api task error: {}\", e.toString());\n }\n });\n }\n }\n\n private String useToken(Token token) {\n String t = token.useToken();\n tokenTimer.schedule(new TimerTask() {\n @Override\n public void run() {\n tokenQueue.add(token);\n }\n }, cycle * 1000 - (System.currentTimeMillis() - token.pollLastTime()));\n return t;\n }\n\n /**\n * 关闭 TokenPool\n */\n public void close() {\n active = false;\n tokenTimer.cancel();\n executorService.shutdown();\n super.interrupt();\n }\n\n /**\n * 关闭全局的 TokenPool\n */\n public static void closeDefaultTokenPool() {\n if (tokenPool != null) {\n tokenPool.close();\n }\n }\n}" }, { "identifier": "CharsetUtil", "path": "gift-common/src/main/java/org/giftorg/common/utils/CharsetUtil.java", "snippet": "public class CharsetUtil {\n /**\n * 判断是否为中文字符\n */\n public static boolean isChinese(char c) {\n return c >= 0x4E00 && c <= 0x9FA5;\n }\n\n /**\n * 判断是否为中文字符串\n */\n public static boolean isChinese(String str) {\n double ratio = 0.5;\n\n int total = 0;\n char[] chars = str.toCharArray();\n for (char c : chars) {\n if (isChinese(c)) total++;\n if (total >= ratio * chars.length) return true;\n }\n return false;\n }\n}" }, { "identifier": "MarkdownUtil", "path": "gift-common/src/main/java/org/giftorg/common/utils/MarkdownUtil.java", "snippet": "public class MarkdownUtil {\n /**\n * 提取 markdown 中的文本\n */\n public static String extractText(String markdown) {\n Parser parser = Parser.builder().build();\n Node document = parser.parse(markdown);\n return extractText(document);\n }\n\n private static String extractText(Node node) {\n StringBuilder sb = new StringBuilder();\n for (Node child : node.getChildren()) {\n if (child instanceof Text) {\n sb.append(child.getChars());\n } else {\n sb.append(extractText(child));\n }\n }\n return sb.toString();\n }\n}" }, { "identifier": "StringUtil", "path": "gift-common/src/main/java/org/giftorg/common/utils/StringUtil.java", "snippet": "public class StringUtil {\n /**\n * 修剪字符串结尾的指定后缀\n */\n @NotNull\n public static String trimEnd(String str, String suffix) {\n if (str.endsWith(suffix)) {\n return str.substring(0, str.length() - suffix.length());\n }\n return str;\n }\n\n /**\n * 修剪字符串开头的指定前缀\n */\n @NotNull\n public static String trimStart(String str, String prefix) {\n if (str.startsWith(prefix)) {\n return str.substring(prefix.length());\n }\n return str;\n }\n}" } ]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.giftorg.common.bigmodel.BigModel; import org.giftorg.common.bigmodel.impl.ChatGPT; import org.giftorg.common.bigmodel.impl.XingHuo; import org.giftorg.common.tokenpool.TokenPool; import org.giftorg.common.utils.CharsetUtil; import org.giftorg.common.utils.MarkdownUtil; import org.giftorg.common.utils.StringUtil; import java.io.Serializable;
5,005
/** * Copyright 2023 GiftOrg Authors * * 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.giftorg.analyze.entity; @Slf4j @Data public class Repository implements Serializable, Cloneable { private Integer id; private Integer repoId; private String name; private String fullName; private Integer stars; private String author; private String url; private String description; private Integer size; private String defaultBranch; private String readme; private String readmeCn; private List<String> tags; private String hdfsPath; private boolean isTranslated = false; private boolean isTagged = false; private static final int CHUNK_SIZE = 1000; public Repository() { } public Repository(String name, String readme) { this.name = name; this.readme = readme; } @Override public Repository clone() throws CloneNotSupportedException { return (Repository) super.clone(); } private static final String REPOSITORY_TRANSLATION_PROMPT = "去除以上文档中任何链接、许可等无关内容,使用中文总结上面的内容,保留核心文字描述,且必须保留文档中的名词、相关的项目名称。"; /** * 翻译项目文档 */ public void translation() throws Exception { if (isTranslated) return; if (!CharsetUtil.isChinese(readme)) {
/** * Copyright 2023 GiftOrg Authors * * 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.giftorg.analyze.entity; @Slf4j @Data public class Repository implements Serializable, Cloneable { private Integer id; private Integer repoId; private String name; private String fullName; private Integer stars; private String author; private String url; private String description; private Integer size; private String defaultBranch; private String readme; private String readmeCn; private List<String> tags; private String hdfsPath; private boolean isTranslated = false; private boolean isTagged = false; private static final int CHUNK_SIZE = 1000; public Repository() { } public Repository(String name, String readme) { this.name = name; this.readme = readme; } @Override public Repository clone() throws CloneNotSupportedException { return (Repository) super.clone(); } private static final String REPOSITORY_TRANSLATION_PROMPT = "去除以上文档中任何链接、许可等无关内容,使用中文总结上面的内容,保留核心文字描述,且必须保留文档中的名词、相关的项目名称。"; /** * 翻译项目文档 */ public void translation() throws Exception { if (isTranslated) return; if (!CharsetUtil.isChinese(readme)) {
BigModel xingHuo = new ChatGPT();
0
2023-11-15 08:58:35+00:00
8k
exadel-inc/etoolbox-anydiff
core/src/main/java/com/exadel/etoolbox/anydiff/runner/FileRunner.java
[ { "identifier": "Constants", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/Constants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Constants {\n\n public static final String ROOT_PACKAGE = \"com.exadel.etoolbox.anydiff\";\n\n public static final int DEFAULT_COLUMN_WIDTH = 60;\n public static final boolean DEFAULT_ARRANGE_ATTRIBUTES = true;\n public static final boolean DEFAULT_IGNORE_SPACES = true;\n public static final int DEFAULT_INDENT = 2;\n public static final boolean DEFAULT_NORMALIZE = true;\n\n public static final int MAX_CONTEXT_LENGTH = 8;\n\n public static final String AT = \"@\";\n public static final char COLON_CHAR = ':';\n public static final char DASH_CHAR = '-';\n public static final String DOT = \".\";\n public static final String ELLIPSIS = \"...\";\n public static final String EQUALS = \"=\";\n public static final String HASH = \"#\";\n public static final String PIPE = \"|\";\n public static final String QUOTE = \"\\\"\";\n public static final String SLASH = \"/\";\n public static final char SLASH_CHAR = '/';\n public static final char UNDERSCORE_CHAR = '_';\n\n public static final String ATTR_HREF = \"href\";\n public static final String ATTR_ID = \"id\";\n\n public static final String CLASS_HEADER = \"header\";\n public static final String CLASS_LEFT = \"left\";\n public static final String CLASS_PATH = \"path\";\n public static final String CLASS_RIGHT = \"right\";\n\n public static final char BRACKET_OPEN = '[';\n public static final char BRACKET_CLOSE = ']';\n\n public static final String TAG_AUTO_CLOSE = \"/>\";\n public static final String TAG_CLOSE = \">\";\n public static final char TAG_CLOSE_CHAR = '>';\n public static final String TAG_OPEN = \"<\";\n public static final char TAG_OPEN_CHAR = '<';\n public static final String TAG_PRE_CLOSE = \"</\";\n\n public static final String TAG_ATTR_OPEN = EQUALS + QUOTE;\n public static final String TAG_ATTR_CLOSE = QUOTE;\n\n public static final String LABEL_LEFT = \"Left\";\n public static final String LABEL_RIGHT = \"Right\";\n}" }, { "identifier": "ContentType", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/ContentType.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\n@Getter\npublic enum ContentType {\n\n UNDEFINED {\n @Override\n public boolean matchesMime(String value) {\n return false;\n }\n\n @Override\n boolean matchesExtension(String value) {\n return false;\n }\n },\n\n XML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"xml\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsIgnoreCase(value, \"xml\");\n }\n },\n\n HTML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"html\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"htl\",\n \"html\",\n \"htm\");\n }\n },\n\n TEXT {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"text\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"css\",\n \"csv\",\n \"ecma\",\n \"info\",\n \"java\",\n \"jsp\",\n \"jspx\",\n \"js\",\n \"json\",\n \"log\",\n \"md\",\n \"mf\",\n \"php\",\n \"properties\",\n \"ts\",\n \"txt\");\n }\n };\n\n /**\n * Checks if the given MIME-type is matched by the current content type\n * @param value MIME-type to check\n * @return True or false\n */\n abstract boolean matchesMime(String value);\n\n /**\n * Checks if the given file extension is matched by the current content type\n * @param value File extension to check\n * @return True or false\n */\n abstract boolean matchesExtension(String value);\n\n /**\n * Gets the content type that matches the given MIME type\n * @param value MIME-type\n * @return {@code ContentType} enum value\n */\n public static ContentType fromMimeType(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n String effectiveType = StringUtils.substringBefore(value, \";\");\n for (ContentType contentType : values()) {\n if (contentType.matchesMime(effectiveType)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n\n /**\n * Gets the content type that matches the given file extension\n * @param value File extension\n * @return {@code ContentType} enum value\n */\n public static ContentType fromExtension(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n for (ContentType contentType : values()) {\n if (contentType.matchesExtension(value)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n}" }, { "identifier": "DiffTask", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/comparison/DiffTask.java", "snippet": "@Builder(builderClassName = \"Builder\")\npublic class DiffTask {\n\n private static final UnaryOperator<String> EMPTY_NORMALIZER = StringUtils::defaultString;\n\n private final ContentType contentType;\n\n private final String leftId;\n private String leftLabel;\n private final Object leftContent;\n\n private final String rightId;\n private String rightLabel;\n private final Object rightContent;\n\n private final Predicate<DiffEntry> filter;\n\n private DiffState anticipatedState;\n\n private TaskParameters taskParameters;\n\n /* ------------------\n Property accessors\n ------------------ */\n\n private Preprocessor getPreprocessor(String contentId) {\n return Preprocessor.forType(contentType, taskParameters).withContentId(contentId);\n }\n\n private Postprocessor getPostprocessor() {\n return Postprocessor.forType(contentType, taskParameters);\n }\n\n /* ---------\n Execution\n --------- */\n\n /**\n * Performs the comparison between the left and right content\n * @return {@link Diff} object\n */\n public Diff run() {\n if (Objects.equals(leftContent, rightContent)) {\n return new DiffImpl(leftId, rightId); // This object will report the \"equals\" state\n }\n int columnWidth = taskParameters.getColumnWidth() - 1;\n if (anticipatedState == DiffState.CHANGE) {\n BlockImpl change = BlockImpl\n .builder()\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .lines(Collections.singletonList(new LineImpl(\n new MarkedString(String.valueOf(leftContent)).markPlaceholders(Marker.DELETE),\n new MarkedString(String.valueOf(rightContent)).markPlaceholders(Marker.INSERT)\n )))\n .build(DisparityBlockImpl::new);\n return new DiffImpl(leftId, rightId).withChildren(change);\n }\n if (leftContent == null || anticipatedState == DiffState.LEFT_MISSING) {\n MissBlockImpl miss = MissBlockImpl\n .left(rightId)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .build();\n return new DiffImpl(leftId, rightId).withChildren(miss);\n }\n if (rightContent == null || anticipatedState == DiffState.RIGHT_MISSING) {\n MissBlockImpl miss = MissBlockImpl\n .right(leftId)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .build();\n return new DiffImpl(leftId, rightId).withChildren(miss);\n }\n return contentType == ContentType.UNDEFINED ? runForBinary() : runForText();\n }\n\n private Diff runForBinary() {\n DiffImpl result = new DiffImpl(leftId, rightId);\n DisparityBlockImpl disparity = DisparityBlockImpl\n .builder()\n .leftContent(leftContent)\n .rightContent(rightContent)\n .columnWidth(taskParameters.getColumnWidth() - 1)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .build(DisparityBlockImpl::new);\n return result.withChildren(disparity);\n }\n\n private Diff runForText() {\n DiffRowGenerator generator = DiffRowGenerator\n .create()\n .ignoreWhiteSpaces(taskParameters.ignoreSpaces())\n .showInlineDiffs(true)\n .oldTag(isStart -> isStart ? Marker.DELETE.toString() : Marker.RESET.toString())\n .newTag(isStart -> isStart ? Marker.INSERT.toString() : Marker.RESET.toString())\n .lineNormalizer(EMPTY_NORMALIZER) // One needs this to override the OOTB preprocessor that spoils HTML\n .inlineDiffBySplitter(SplitterUtil::getTokens)\n .build();\n String leftPreprocessed = getPreprocessor(leftId).apply(leftContent.toString());\n String rightPreprocessed = getPreprocessor(rightId).apply(rightContent.toString());\n List<String> leftLines = StringUtil.splitByNewline(leftPreprocessed);\n List<String> rightLines = StringUtil.splitByNewline(rightPreprocessed);\n List<DiffRow> diffRows = getPostprocessor().apply(generator.generateDiffRows(leftLines, rightLines));\n\n DiffImpl result = new DiffImpl(leftId, rightId);\n List<AbstractBlock> blocks = getDiffBlocks(diffRows)\n .stream()\n .peek(block -> block.setDiff(result))\n .filter(filter != null ? filter : entry -> true)\n .collect(Collectors.toList());\n return result.withChildren(blocks);\n }\n\n private List<AbstractBlock> getDiffBlocks(List<DiffRow> allRows) {\n List<AbstractBlock> result = new ArrayList<>();\n BlockImpl pendingDiffBlock = null;\n for (int i = 0; i < allRows.size(); i++) {\n DiffRow row = allRows.get(i);\n boolean isNeutralRow = row.getTag() == DiffRow.Tag.EQUAL;\n boolean isNonNeutralStreakEnding = isNeutralRow && pendingDiffBlock != null;\n if (isNonNeutralStreakEnding) {\n pendingDiffBlock.addContext(row);\n result.add(pendingDiffBlock);\n pendingDiffBlock = null;\n }\n if (isNeutralRow) {\n continue;\n }\n if (pendingDiffBlock == null) {\n List<DiffRow> lookbehindContext = getLookbehindContext(allRows, i);\n pendingDiffBlock = BlockImpl\n .builder()\n .path(getContextPath(allRows, i))\n .compactify(taskParameters.normalize())\n .contentType(contentType)\n .ignoreSpaces(taskParameters.ignoreSpaces())\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(taskParameters.getColumnWidth() - 1)\n .build(BlockImpl::new);\n pendingDiffBlock.addContext(lookbehindContext);\n }\n pendingDiffBlock.add(row);\n }\n if (pendingDiffBlock != null) {\n result.add(pendingDiffBlock);\n }\n return result;\n }\n\n private String getContextPath(List<DiffRow> allRows, int position) {\n if (contentType != ContentType.HTML && contentType != ContentType.XML) {\n return StringUtils.EMPTY;\n }\n return PathUtil.getPath(allRows, position);\n }\n\n private List<DiffRow> getLookbehindContext(List<DiffRow> allRows, int position) {\n if (position == 0) {\n return null;\n }\n if (contentType != ContentType.HTML && contentType != ContentType.XML) {\n return Collections.singletonList(allRows.get(position - 1));\n }\n\n int nearestTagRowIndex = PathUtil.getPrecedingTagRowIndex(allRows, position - 1);\n if (nearestTagRowIndex >= 0) {\n return truncateContext(allRows.subList(nearestTagRowIndex, position));\n }\n return Collections.singletonList(allRows.get(position - 1));\n }\n\n private static List<DiffRow> truncateContext(List<DiffRow> rows) {\n if (rows.size() <= Constants.MAX_CONTEXT_LENGTH) {\n return rows;\n }\n List<DiffRow> upperPart = rows.subList(0, Constants.MAX_CONTEXT_LENGTH / 2);\n List<DiffRow> lowerPart = rows.subList(rows.size() - Constants.MAX_CONTEXT_LENGTH / 2, rows.size());\n List<DiffRow> result = new ArrayList<>(upperPart);\n result.add(new DiffRow(DiffRow.Tag.EQUAL, Marker.ELLIPSIS, Marker.ELLIPSIS));\n result.addAll(lowerPart);\n return result;\n }\n\n /**\n * Creates a builder for constructing a new {@code DiffTask} object\n * @return {@link DiffTask.Builder} instance\n */\n public static Builder builder() {\n return new InitializingBuilder();\n }\n\n /**\n * Constructs a new {@code DiffTask} instance with critical values initialized\n */\n private static class InitializingBuilder extends DiffTask.Builder {\n @Override\n public DiffTask build() {\n DiffTask result = super.build();\n\n TaskParameters perRequest = result.taskParameters;\n TaskParameters perContentType = TaskParameters.from(result.contentType);\n result.taskParameters = TaskParameters.merge(perContentType, perRequest);\n\n if (result.anticipatedState == null) {\n result.anticipatedState = DiffState.UNCHANGED;\n }\n\n result.leftLabel = StringUtils.defaultIfBlank(result.leftLabel, Constants.LABEL_LEFT);\n result.rightLabel = StringUtils.defaultIfBlank(result.rightLabel, Constants.LABEL_RIGHT);\n\n return result;\n }\n }\n}" }, { "identifier": "Diff", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Diff.java", "snippet": "public interface Diff extends PrintableEntry, EntryHolder {\n\n /**\n * Gets the \"kind\" of difference. E.g., \"change\", \"insertion\", \"deletion\", etc.\n * @return {@link DiffState} instance\n */\n DiffState getState();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}\n * @return Integer value\n */\n int getCount();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}.\n * Counts only the differences that have not been \"silenced\" (accepted) with a {@link Filter}\n * @return Integer value\n */\n int getPendingCount();\n\n /**\n * Gets the left part of the comparison\n * @return String value\n */\n String getLeft();\n\n /**\n * Gets the right part of the comparison\n * @return String value\n */\n String getRight();\n}" } ]
import java.util.List; import com.exadel.etoolbox.anydiff.Constants; import com.exadel.etoolbox.anydiff.ContentType; import com.exadel.etoolbox.anydiff.comparison.DiffTask; import com.exadel.etoolbox.anydiff.diff.Diff; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Date;
4,141
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.runner; /** * Extends {@link DiffRunner} to implement extracting data from file system files */ @RequiredArgsConstructor @Slf4j class FileRunner extends DiffRunner { private final Path left; private final Path right; @Override public List<Diff> runInternal() { ContentType contentType = getCommonTypeOrDefault( left.toAbsolutePath().toString(), right.toAbsolutePath().toString(), getContentType()); Object leftContent = contentType != ContentType.UNDEFINED ? getContent(left) : getMetadata(left); Object rightContent = contentType != ContentType.UNDEFINED ? getContent(right) : getMetadata(right); DiffTask diffTask = DiffTask .builder() .contentType(contentType) .leftId(left.toAbsolutePath().toString()) .leftLabel(getLeftLabel()) .leftContent(leftContent) .rightId(right.toAbsolutePath().toString()) .rightLabel(getRightLabel()) .rightContent(rightContent) .filter(getEntryFilter()) .taskParameters(getTaskParameters()) .build(); Diff diff = diffTask.run(); return Collections.singletonList(diff); } private static ContentType getCommonTypeOrDefault(String left, String right, ContentType defaultType) { ContentType commonContentTypeByMime = getCommonTypeByMime(left, right); if (commonContentTypeByMime != ContentType.UNDEFINED) { return commonContentTypeByMime; }
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.runner; /** * Extends {@link DiffRunner} to implement extracting data from file system files */ @RequiredArgsConstructor @Slf4j class FileRunner extends DiffRunner { private final Path left; private final Path right; @Override public List<Diff> runInternal() { ContentType contentType = getCommonTypeOrDefault( left.toAbsolutePath().toString(), right.toAbsolutePath().toString(), getContentType()); Object leftContent = contentType != ContentType.UNDEFINED ? getContent(left) : getMetadata(left); Object rightContent = contentType != ContentType.UNDEFINED ? getContent(right) : getMetadata(right); DiffTask diffTask = DiffTask .builder() .contentType(contentType) .leftId(left.toAbsolutePath().toString()) .leftLabel(getLeftLabel()) .leftContent(leftContent) .rightId(right.toAbsolutePath().toString()) .rightLabel(getRightLabel()) .rightContent(rightContent) .filter(getEntryFilter()) .taskParameters(getTaskParameters()) .build(); Diff diff = diffTask.run(); return Collections.singletonList(diff); } private static ContentType getCommonTypeOrDefault(String left, String right, ContentType defaultType) { ContentType commonContentTypeByMime = getCommonTypeByMime(left, right); if (commonContentTypeByMime != ContentType.UNDEFINED) { return commonContentTypeByMime; }
String leftExtension = StringUtils.substringAfterLast(left, Constants.DOT);
0
2023-11-16 14:29:45+00:00
8k
Walter-Stroebel/Jllama
src/main/java/nl/infcomtec/jllama/TextImage.java
[ { "identifier": "ImageObject", "path": "src/main/java/nl/infcomtec/simpleimage/ImageObject.java", "snippet": "public class ImageObject extends Image {\n\n private BufferedImage image;\n private final Semaphore lock = new Semaphore(0);\n private final List<ImageObjectListener> listeners = new LinkedList<>();\n\n public ImageObject(Image image) {\n putImage(image);\n }\n\n /**\n * @return The most recent image.\n */\n public BufferedImage getImage() {\n return image;\n }\n\n /**\n * Stay informed.\n *\n * @param listener called when another client changes the image.\n */\n public synchronized void addListener(ImageObjectListener listener) {\n listeners.add(listener);\n }\n\n void sendSignal(Object msg) {\n for (ImageObjectListener listener : listeners) {\n listener.signal(msg);\n }\n }\n\n public enum MouseEvents {\n clicked_left, clicked_right, dragged, moved, pressed_left, released_left, pressed_right, released_right\n };\n\n public synchronized void forwardMouse(MouseEvents ev, Point2D p) {\n for (ImageObjectListener listener : listeners) {\n listener.mouseEvent(this, ev, p);\n }\n }\n\n /**\n * Replace image.\n *\n * @param replImage If null image may still have been altered in place, else\n * replace image with replImage. All listeners will be notified.\n */\n public synchronized final void putImage(Image replImage) {\n int oldWid = null == this.image ? 0 : this.image.getWidth();\n if (null != replImage) {\n this.image = new BufferedImage(replImage.getWidth(null), replImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = this.image.createGraphics();\n g2.drawImage(replImage, 0, 0, null);\n g2.dispose();\n }\n for (ImageObjectListener listener : listeners) {\n if (0 == oldWid) {\n listener.imageChanged(this, 1.0);\n } else {\n listener.imageChanged(this, 1.0 * oldWid / this.image.getWidth());\n }\n }\n }\n\n public int getWidth() {\n return getWidth(null);\n }\n\n @Override\n public int getWidth(ImageObserver io) {\n return image.getWidth(io);\n }\n\n @Override\n public int getHeight(ImageObserver io) {\n return image.getHeight(io);\n }\n\n public int getHeight() {\n return getHeight(null);\n }\n\n @Override\n public ImageProducer getSource() {\n return image.getSource();\n }\n\n @Override\n public Graphics getGraphics() {\n return image.getGraphics();\n }\n\n @Override\n public Object getProperty(String string, ImageObserver io) {\n return image.getProperty(string, null);\n }\n\n public HashMap<String, BitShape> calculateClosestAreas(final Map<String, Point2D> pois) {\n long nanos = System.nanoTime();\n final HashMap<String, BitShape> ret = new HashMap<>();\n for (Map.Entry<String, Point2D> e : pois.entrySet()) {\n ret.put(e.getKey(), new BitShape(getWidth()));\n }\n\n int numThreads = Runtime.getRuntime().availableProcessors() - 2; // Number of threads to use, leaving some cores for routine work.\n if (numThreads < 1) {\n numThreads = 1;\n }\n ExecutorService executor = Executors.newFixedThreadPool(numThreads);\n\n int rowsPerThread = getHeight() / numThreads;\n for (int i = 0; i < numThreads; i++) {\n final int yStart = i * rowsPerThread;\n final int yEnd = (i == numThreads - 1) ? getHeight() : yStart + rowsPerThread;\n executor.submit(new Runnable() {\n @Override\n public void run() {\n for (int y = yStart; y < yEnd; y++) {\n for (int x = 0; x < getWidth(); x++) {\n double d = 0;\n String poi = null;\n for (Map.Entry<String, Point2D> e : pois.entrySet()) {\n double d2 = e.getValue().distance(x, y);\n if (poi == null || d2 < d) {\n poi = e.getKey();\n d = d2;\n }\n }\n synchronized (ret.get(poi)) {\n ret.get(poi).set(new Point2D.Double(x, y));\n }\n }\n }\n }\n });\n }\n executor.shutdown();\n try {\n if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {\n throw new RuntimeException(\"This cannot be right.\");\n }\n } catch (InterruptedException ex) {\n throw new RuntimeException(\"We are asked to stop?\", ex);\n }\n System.out.format(\"calculateClosestAreas W=%d,H=%d,P=%d,T=%.2f ms\\n\",\n getWidth(), getHeight(), pois.size(), (System.nanoTime() - nanos) / 1e6);\n return ret;\n }\n\n /**\n * Callback listener.\n */\n public static class ImageObjectListener {\n\n public final String name;\n\n public ImageObjectListener(String name) {\n this.name = name;\n }\n\n /**\n * Image may have been altered.\n *\n * @param imgObj Source.\n * @param resizeHint The width of the previous image divided by the\n * width of the new image. See ImageViewer why this is useful.\n */\n public void imageChanged(ImageObject imgObj, double resizeHint) {\n // default is no action\n }\n\n /**\n * Used to forward mouse things by viewer implementations.\n *\n * @param imgObj Source.\n * @param ev Our event definition.\n * @param p Point of the event in image pixels.\n */\n public void mouseEvent(ImageObject imgObj, MouseEvents ev, Point2D p) {\n // default ignore\n }\n\n /**\n * Generic signal, generally causes viewer implementations to repaint.\n *\n * @param any\n */\n public void signal(Object any) {\n // default ignore\n }\n }\n}" }, { "identifier": "ImageViewer", "path": "src/main/java/nl/infcomtec/simpleimage/ImageViewer.java", "snippet": "public class ImageViewer {\n\n private static final int MESSAGE_HEIGHT = 200;\n private static final int MESSAGE_WIDTH = 800;\n public List<Component> tools;\n private String message = null;\n private long messageMillis = 0;\n private long shownLast = 0;\n private Font messageFont = UIManager.getFont(\"Label.font\");\n\n protected final ImageObject imgObj;\n private LUT lut;\n private List<Marker> marks;\n\n public ImageViewer(ImageObject imgObj) {\n this.imgObj = imgObj;\n }\n\n public ImageViewer(Image image) {\n imgObj = new ImageObject(image);\n }\n\n public synchronized void flashMessage(Font font, String msg, long millis) {\n messageFont = font;\n messageMillis = millis;\n message = msg;\n shownLast = 0;\n imgObj.sendSignal(null);\n }\n\n public synchronized void flashMessage(String msg, long millis) {\n flashMessage(messageFont, msg, millis);\n }\n\n public synchronized void flashMessage(String msg) {\n flashMessage(messageFont, msg, 3000);\n }\n\n public synchronized void addMarker(Marker marker) {\n if (null == marks) {\n marks = new LinkedList<>();\n }\n marks.add(marker);\n imgObj.putImage(null);\n }\n\n public synchronized void clearMarkers() {\n marks = null;\n imgObj.putImage(null);\n }\n\n public ImageViewer(File f) {\n ImageObject tmp;\n try {\n tmp = new ImageObject(ImageIO.read(f));\n } catch (Exception ex) {\n tmp = showError(f);\n }\n imgObj = tmp;\n }\n\n /**\n * Although there are many reasons an image may not load, all we can do\n * about it is tell the user by creating an image with the failure.\n *\n * @param f File we tried to load.\n */\n private ImageObject showError(File f) {\n BufferedImage img = new BufferedImage(MESSAGE_WIDTH, MESSAGE_HEIGHT, BufferedImage.TYPE_BYTE_BINARY);\n Graphics2D gr = img.createGraphics();\n String msg1 = \"Cannot open image:\";\n String msg2 = f.getAbsolutePath();\n Font font = gr.getFont();\n float points = 24;\n int w, h;\n do {\n font = font.deriveFont(points);\n gr.setFont(font);\n FontMetrics metrics = gr.getFontMetrics(font);\n w = Math.max(metrics.stringWidth(msg1), metrics.stringWidth(msg2));\n h = metrics.getHeight() * 2; // For two lines of text\n if (w > MESSAGE_WIDTH - 50 || h > MESSAGE_HEIGHT / 3) {\n points--;\n }\n } while (w > MESSAGE_WIDTH || h > MESSAGE_HEIGHT / 3);\n gr.drawString(msg1, 50, MESSAGE_HEIGHT / 3);\n gr.drawString(msg2, 50, MESSAGE_HEIGHT / 3 * 2);\n gr.dispose();\n return new ImageObject(img);\n }\n\n /**\n * Often images have overly bright or dark areas. This permits to have a\n * lighter or darker view.\n *\n * @return this for chaining.\n */\n public synchronized ImageViewer addShadowView() {\n ButtonGroup bg = new ButtonGroup();\n addChoice(bg, new AbstractAction(\"Dark\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.darker();\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Normal\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.unity();\n imgObj.putImage(null);\n }\n }, true);\n addChoice(bg, new AbstractAction(\"Bright\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.brighter();\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Brighter\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.sqrt(0);\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Extreme\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.sqrt2();\n imgObj.putImage(null);\n }\n });\n return this;\n }\n\n /**\n * Add a choice,\n *\n * @param group If not null, only one choice in the group can be active.\n * @param action Choice.\n * @return For chaining.\n */\n public synchronized ImageViewer addChoice(ButtonGroup group, Action action) {\n return addChoice(group, action, false);\n }\n\n /**\n * Add a choice,\n *\n * @param group If not null, only one choice in the group can be active.\n * @param action Choice.\n * @param selected Only useful if true.\n * @return For chaining.\n */\n public synchronized ImageViewer addChoice(ButtonGroup group, Action action, boolean selected) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n JCheckBox button = new JCheckBox(action);\n button.setSelected(selected);\n if (null != group) {\n group.add(button);\n if (selected) {\n group.setSelected(button.getModel(), selected);\n }\n }\n tools.add(button);\n return this;\n }\n\n public synchronized ImageViewer addButton(Action action) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(action));\n return this;\n }\n\n public synchronized ImageViewer addMaxButton(String dsp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(new AbstractAction(dsp) {\n @Override\n public void actionPerformed(ActionEvent ae) {\n imgObj.sendSignal(ScaleCommand.SCALE_MAX);\n }\n }));\n return this;\n }\n\n public synchronized ImageViewer addOrgButton(String dsp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(new AbstractAction(dsp) {\n @Override\n public void actionPerformed(ActionEvent ae) {\n imgObj.sendSignal(ScaleCommand.SCALE_ORG);\n }\n }));\n return this;\n }\n\n public synchronized ImageViewer addAnything(Component comp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(comp);\n return this;\n }\n\n /**\n * Show the image in a JPanel component with simple pan(drag) and zoom(mouse\n * wheel).\n *\n * @return the JPanel.\n */\n public JPanel getScalePanPanel() {\n final JPanel ret = new JPanelImpl();\n return ret;\n }\n\n /**\n * Show the image in a JPanel component with simple pan(drag) and zoom(mouse\n * wheel). Includes a JToolbar if tools are provided, see add functions.\n *\n * @return the JPanel.\n */\n public JPanel getScalePanPanelTools() {\n final JPanel outer = new JPanel();\n outer.setLayout(new BorderLayout());\n outer.add(new JPanelImpl(), BorderLayout.CENTER);\n if (null != tools) {\n JToolBar tb = new JToolBar();\n for (Component c : tools) {\n tb.add(c);\n }\n outer.add(tb, BorderLayout.NORTH);\n }\n return outer;\n }\n\n /**\n * Show the image in a JFrame component with simple pan(drag) and zoom(mouse\n * wheel). Includes a JToolbar if tools are provided, see add functions.\n *\n * @return the JFrame.\n */\n public JFrame getScalePanFrame() {\n final JFrame ret = new JFrame();\n ret.setAlwaysOnTop(true);\n ret.getContentPane().setLayout(new BorderLayout());\n ret.getContentPane().add(new JPanelImpl(), BorderLayout.CENTER);\n if (null != tools) {\n JToolBar tb = new JToolBar();\n for (Component c : tools) {\n tb.add(c);\n }\n ret.getContentPane().add(tb, BorderLayout.NORTH);\n }\n ret.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n ret.pack();\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n ret.setVisible(true);\n }\n });\n return ret;\n }\n\n public ImageObject getImageObject() {\n return imgObj;\n }\n\n public enum ScaleCommand {\n SCALE_ORG, SCALE_MAX\n }\n\n private class JPanelImpl extends JPanel {\n\n int ofsX = 0;\n int ofsY = 0;\n double scale = 1;\n private BufferedImage dispImage = null;\n\n private Point pixelMouse(MouseEvent e) {\n int ax = e.getX() - ofsX;\n int ay = e.getY() - ofsY;\n ax = (int) Math.round(ax / scale);\n ay = (int) Math.round(ay / scale);\n return new Point(ax, ay);\n }\n\n public JPanelImpl() {\n MouseAdapter ma = new MouseAdapter() {\n private int lastX, lastY;\n\n @Override\n public void mousePressed(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.pressed_right, pixelMouse(e));\n } else {\n lastX = e.getX();\n lastY = e.getY();\n }\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.released_right, pixelMouse(e));\n } else {\n imgObj.forwardMouse(ImageObject.MouseEvents.released_left, pixelMouse(e));\n }\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.clicked_right, pixelMouse(e));\n } else {\n imgObj.forwardMouse(ImageObject.MouseEvents.clicked_left, pixelMouse(e));\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.dragged, pixelMouse(e));\n } else {\n ofsX += e.getX() - lastX;\n ofsY += e.getY() - lastY;\n lastX = e.getX();\n lastY = e.getY();\n repaint(); // Repaint the panel to reflect the new position\n }\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int notches = e.getWheelRotation();\n scale += notches * 0.1; // Adjust the scaling factor\n if (scale < 0.1) {\n scale = 0.1; // Prevent the scale from becoming too small\n }\n dispImage = null;\n repaint(); // Repaint the panel to reflect the new scale\n }\n };\n addMouseListener(ma);\n addMouseMotionListener(ma);\n addMouseWheelListener(ma);\n imgObj.addListener(new ImageObject.ImageObjectListener(\"Repaint\") {\n @Override\n public void imageChanged(ImageObject imgObj, double resizeHint) {\n // If the image we are displaying is for instance 512 pixels and\n // the new image is 1536, we need to adjust scaling to match.\n scale *= resizeHint;\n dispImage = null;\n repaint(); // Repaint the panel to reflect any changes\n }\n\n @Override\n public void signal(Object any) {\n if (any instanceof ScaleCommand) {\n ScaleCommand sc = (ScaleCommand) any;\n switch (sc) {\n case SCALE_MAX: {\n double w = (1.0 * getWidth()) / imgObj.getWidth();\n double h = (1.0 * getHeight()) / imgObj.getHeight();\n System.out.format(\"%f %f %d %d\\n\", w, h, imgObj.getWidth(), getWidth());\n if (w > h) {\n scale = h;\n } else {\n scale = w;\n }\n }\n break;\n case SCALE_ORG: {\n scale = 1;\n }\n break;\n }\n dispImage = null;\n }\n repaint();\n }\n });\n Dimension dim = new Dimension(imgObj.getWidth(), imgObj.getHeight());\n setPreferredSize(dim);\n }\n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.DARK_GRAY);\n g.fillRect(0, 0, getWidth(), getHeight());\n if (null == dispImage) {\n int scaledWidth = (int) (imgObj.getWidth() * scale);\n int scaledHeight = (int) (imgObj.getHeight() * scale);\n dispImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = dispImage.createGraphics();\n g2.drawImage(imgObj.getScaledInstance(scaledWidth, scaledHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);\n g2.dispose();\n if (null != lut) {\n dispImage = lut.apply(dispImage);\n }\n if (null != marks) {\n for (Marker marker : marks) {\n marker.mark(dispImage);\n }\n }\n }\n g.drawImage(dispImage, ofsX, ofsY, null);\n if (null != message) {\n if (0 == shownLast) {\n shownLast = System.currentTimeMillis();\n }\n if (shownLast + messageMillis >= System.currentTimeMillis()) {\n g.setFont(messageFont);\n g.setColor(Color.WHITE);\n g.setXORMode(Color.BLACK);\n int ofs = g.getFontMetrics().getHeight();\n System.out.println(message + \" \" + ofs);\n g.drawString(message, ofs, ofs * 2);\n } else {\n message = null;\n shownLast = 0;\n }\n }\n }\n }\n}" } ]
import java.awt.BorderLayout; import java.awt.Container; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.util.concurrent.ExecutorService; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import nl.infcomtec.simpleimage.ImageObject; import nl.infcomtec.simpleimage.ImageViewer;
5,005
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame;
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame;
public final ImageObject imgObj;
0
2023-11-16 00:37:47+00:00
8k
jimbro1000/DriveWire4Rebuild
src/main/java/org/thelair/dw4/drivewire/DWCore.java
[ { "identifier": "DWIPort", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPort.java", "snippet": "public interface DWIPort {\n /**\n * Open target port with given definition and register with port handler.\n * @param port definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void openWith(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Modify port from definition.\n * @param port revised definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void setPortDef(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Identify port type.\n * @return port type id.\n */\n int identifyPort();\n\n /**\n * Close port and deregister with port handler.\n */\n void closePort();\n\n /**\n * Serialise port definition as String.\n *\n * @return port definition values\n */\n String getPortDefinition();\n}" }, { "identifier": "DWIPortManager", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPortManager.java", "snippet": "public interface DWIPortManager {\n /**\n * Provide a count of all ports recorded.\n * @return total number of ports\n */\n int getPortCount();\n\n /**\n * Provide a count of open ports.\n * @return total number of open ports\n */\n int getOpenPortCount();\n\n /**\n * Provide a count of closed ports.\n * @return total number of closed ports\n */\n int getClosedPortCount();\n /**\n * Register an unused port as open.\n * @param port generic closed port\n */\n void registerOpenPort(DWIPort port);\n\n /**\n * Register a used port as closed.\n * @param port generic open port\n */\n void registerClosedPort(DWIPort port);\n\n /**\n * Create a new port instance.\n * @param portType type of port to create\n * @return unused port\n */\n DWIPort createPortInstance(DWIPortType.DWPortTypeIdentity portType);\n\n /**\n * Dispose of unused port.\n * @param port generic closed port\n */\n void disposePort(DWIPort port);\n\n\n /**\n * Handles context shutdown event.\n * Close all open ports. Dispose of all ports\n *\n * @param event context event\n */\n void contextDestroyed(ServletContextEvent event);\n}" }, { "identifier": "DWIPortType", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPortType.java", "snippet": "public interface DWIPortType {\n /**\n * Port type enum.\n * Implements a conversion to int\n */\n enum DWPortTypeIdentity {\n /**\n * null port.\n */\n NULL_PORT(0),\n /**\n * RS232 serial port.\n */\n SERIAL_PORT(1),\n /**\n * TCP port.\n */\n TCP_PORT(2);\n /**\n * int equivalent of port type.\n */\n private final int type;\n DWPortTypeIdentity(final int portType) {\n this.type = portType;\n }\n\n /**\n * Get enum port type as int.\n * @return port type as int\n */\n public int getPortType() {\n return type;\n }\n }\n\n /**\n * Identify type of port.\n * @return port type\n */\n DWPortTypeIdentity identify();\n\n /**\n * Get map of port definition.\n * @return port definition\n */\n Map<String, Integer> getPortDetail();\n}" }, { "identifier": "InvalidPortTypeDefinition", "path": "src/main/java/org/thelair/dw4/drivewire/ports/InvalidPortTypeDefinition.java", "snippet": "@Getter\npublic class InvalidPortTypeDefinition extends InvalidObjectException {\n /**\n * Port definition causing the exception.\n */\n private final BasePortDef sourcePortDef;\n /**\n * Constructs an {@code InvalidObjectException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n * @param portDef Causing port definition object\n * @see ObjectInputValidation\n */\n public InvalidPortTypeDefinition(final String reason,\n final BasePortDef portDef) {\n super(reason);\n sourcePortDef = portDef;\n }\n}" }, { "identifier": "SerialPortDef", "path": "src/main/java/org/thelair/dw4/drivewire/ports/serial/SerialPortDef.java", "snippet": "@Getter\n@EqualsAndHashCode(callSuper = true)\n@Data\n@AllArgsConstructor\npublic final class SerialPortDef extends BasePortDef {\n /**\n * RS232 baud rate.\n */\n @Setter\n private int baudRate;\n /**\n * data bits per byte.\n */\n @Setter\n private int dataBits;\n /**\n * RS232 parity type 0/1.\n */\n @Setter\n private int parityType;\n /**\n * Unique port identifier.\n */\n @Setter\n private int portId;\n /**\n * Required port name.\n */\n @Setter\n private String portName;\n /**\n * RS232 stop bits 0/1.\n */\n @Setter\n private int stopBits;\n\n @Override\n public DWPortTypeIdentity identify() {\n return DWPortTypeIdentity.SERIAL_PORT;\n }\n\n @Override\n public Map<String, Integer> getPortDetail() {\n final Map<String, Integer> result = new HashMap<>();\n result.put(\"BaudRate\", baudRate);\n result.put(\"DataBits\", dataBits);\n result.put(\"Identity\", DWPortTypeIdentity.SERIAL_PORT.getPortType());\n result.put(\"ParityType\", parityType);\n result.put(\"PortId\", portId);\n result.put(\"StopBits\", stopBits);\n return result;\n }\n}" }, { "identifier": "Transaction", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/Transaction.java", "snippet": "@Getter\npublic enum Transaction {\n /**\n * RESET1 - $FF.\n */\n OP_RESET1(\"OP_RESET1\", 0xFF, 0, 0),\n /**\n * RESET2 - $FE.\n */\n OP_RESET2(\"OP_RESET2\", 0xFE, 0, 0),\n /**\n * RESET3 - $F8.\n */\n OP_RESET3(\"OP_RESET3\", 0xF8, 0, 0),\n /**\n * RE-READ EXTENDED - $F2.\n */\n OP_REREADEX(\"OP_REREADEX\", 0xF2, 4, 4),\n /**\n * READ EXTENDED - $D2.\n */\n OP_READEX(\"OP_READEX\", 0xD2, 4, 4),\n /**\n * SERIAL TERMINATE - $C5.\n */\n OP_SERTERM(\"OP_SERTERM\", 0xC5, 1, 1),\n /**\n * SERIAL SET STAT - $C4.\n */\n OP_SERSETSTAT(\"OP_SERSETSTAT\", 0xC4, 2, 28),\n /**\n * SERIAL WRITE - $C3.\n */\n OP_SERWRITE(\"OP_SERWRITE\", 0xC3, 2, 2),\n /**\n * FAST WRITE - $80.\n */\n OP_FASTWRITE(\"OP_FASTWRITE\", 0x80, 1, 1),\n /**\n * RE-WRITE - $77.\n */\n OP_REWRITE(\"OP_REWRITE\", 0x77, 262, 262),\n /**\n * RE-READ - $72.\n */\n OP_REREAD(\"OP_REREAD\", 0x72, 4, 4),\n /**\n * SERIAL WRITE MULTI-BYTE - $64.\n */\n OP_SERWRITEM(\"OP_SERWRITEM\", 0x64, 258, 258),\n /**\n * SERIAL READ MULTI-BYTE - $63.\n */\n OP_SERREADM(\"OP_SERREADM\", 0x63, 2, 2),\n /**\n * DRIVEWIRE 4 INIT - $5A.\n */\n OP_DWINIT(\"OP_DWINIT\", 0x5A, 1, 1),\n /**\n * WRITE - $57.\n */\n OP_WRITE(\"OP_WRITE\", 0x57, 262, 262),\n /**\n * TERMINATE - $54.\n */\n OP_TERM(\"OP_TERM\", 0x54, 0, 0),\n /**\n * SET STAT - $53.\n */\n OP_SETSTAT(\"OP_SETSTAT\", 0x53, 2, 2),\n /**\n * READ - $52.\n */\n OP_READ(\"OP_READ\", 0x52, 4, 4),\n /**\n * PRINT (BYTE) - $50.\n */\n OP_PRINT(\"OP_PRINT\", 0x50, 1, 1),\n /**\n * DRIVEWIRE 3 INIT - $49.\n */\n OP_INIT(\"OP_INIT\", 0x49, 0, 0),\n /**\n * GET STAT - $47.\n */\n OP_GETSTAT(\"OP_GETSTAT\", 0x47, 2, 2),\n /**\n * FLUSH PRINT - $46.\n */\n OP_PRINTFLUSH(\"OP_PRINTFLUSH\", 0x46, 0, 0),\n /**\n * SERIAL INIT - $45.\n */\n OP_SERINIT(\"OP_SERINIT\", 0x45, 1, 1),\n /**\n * SERIAL GET STAT - $44.\n */\n OP_SERGETSTAT(\"OP_SERGETSTAT\", 0x44, 2, 2),\n /**\n * SERIAL READ - $43.\n */\n OP_SERREAD(\"OP_SERREAD\", 0x43, 0, 0),\n /**\n * (SYNC) TIME - $43.\n */\n OP_TIME(\"OP_TIME\", 0x23, 0, 0),\n /**\n * CREATE NAMED OBJECT - $02.\n */\n OP_NAMEOBJ_CREATE(\"OP_NAMEOBJ_CREATE\", 0x02, 1, 1),\n /**\n * MOUNT NAMED OBJECT - $01.\n */\n OP_NAMEOBJ_MOUNT(\"OP_NAMEOBJ_MOUNT\", 0x01, 1, 1),\n /**\n * NO OPERATION - $00.\n */\n OP_NOP(\"OP_NOP\", 0x00, 0, 0);\n\n /**\n * operation code (byte).\n * -- GETTER --\n * Get operation code byte.\n *\n * @return opcode byte value\n\n */\n private final int opCode;\n /**\n * Expected remaining bytes to read in message.\n * -- GETTER --\n * Get operation byte length.\n *\n * @return expected number of following bytes\n\n */\n private final int opLength;\n /**\n * Maximum remaining bytes where message is variable.\n * -- GETTER --\n * Get maximum operation byte length where size is variable.\n *\n * @return maximum number of following bytes\n\n */\n private final int opMaxLength;\n /**\n * operation name (as per specification).\n * -- GETTER --\n * Get operation name.\n *\n * @return operation code name\n\n */\n private final String opName;\n Transaction(final String name, final int code, final int len, final int max) {\n this.opName = name;\n this.opCode = code;\n this.opLength = len;\n this.opMaxLength = max;\n }\n\n}" }, { "identifier": "TransactionRouter", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/TransactionRouter.java", "snippet": "@Component\npublic class TransactionRouter {\n /**\n * Map of opcode:transaction pairs.\n * -- GETTER --\n * Get dictionary of drive wire transactions.\n *\n * @return map of opcode to transactions\n */\n @Getter\n private final Map<Integer, Transaction> dictionary;\n /**\n * Map of transaction:operation pairs.\n */\n private final Map<Transaction, Operation> routing;\n\n /**\n * Create transaction router.\n */\n public TransactionRouter() {\n dictionary = new HashMap<>();\n routing = new HashMap<>();\n buildDictionary();\n }\n\n /**\n * Match transaction opCode to a handling function.\n * @param opCode Transaction enum\n * @param opFunction operation implementation\n */\n public void registerOperation(\n final Transaction opCode, final Operation opFunction\n ) {\n routing.put(opCode, opFunction);\n }\n\n private void buildDictionary() {\n for (final Transaction entry : Transaction.values()) {\n dictionary.put(entry.getOpCode(), entry);\n }\n }\n\n private void sendResponse(final RCResponse resultCode, final int[] data) {\n // write result code\n // if data.length > 0 : write result data\n }\n\n private boolean validateOpCode(final int code, final int length) {\n if (!dictionary.containsKey(code)) {\n sendResponse(RCResponse.RC_SYNTAX_ERROR, new int[] {});\n return false;\n }\n final Transaction transaction = dictionary.get(code);\n if (length > transaction.getOpMaxLength()\n || length < transaction.getOpLength()) {\n sendResponse(RCResponse.RC_SYNTAX_ERROR, new int[] {});\n return false;\n }\n return true;\n }\n\n /**\n * Accepts client request and route to correct handler.\n * @param data request data\n */\n public void processRequest(final int[] data) {\n if (validateOpCode(data[0], data.length - 1)) {\n sendResponse(RCResponse.RC_SYNTAX_ERROR, new int[] {});\n return;\n }\n final Transaction transaction = dictionary.get(data[0]);\n final Operation function = routing.get(transaction);\n function.process(data);\n }\n\n /**\n * Listen for response from request handler.\n *\n * @param event DWMessageEvent response\n */\n @Async\n @EventListener\n public void processResponse(final DWMessageEvent event) {\n sendResponse(RCResponse.RC_SUCCESS, event.getMessage());\n }\n}" }, { "identifier": "DwInit", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwInit.java", "snippet": "@Component\npublic class DwInit extends BaseOp implements Operation {\n /**\n * Log appender.\n */\n private static final Logger LOGGER = LogManager.getLogger(DwInit.class);\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n if (data[0] == OP_INIT.getOpCode()) {\n LOGGER.info(\"DW3 client init\");\n getController().setClientVersion(0);\n return;\n }\n LOGGER.info(\"DW4 client version byte: \" + data[1]);\n getController().setClientVersion(data[1]);\n new DWMessageEvent(\n this,\n new int[] {this.getController().reportCapability()}\n );\n }\n}" }, { "identifier": "DwNop", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwNop.java", "snippet": "public class DwNop extends BaseOp implements Operation {\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n // no operation\n }\n}" }, { "identifier": "DwReset", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwReset.java", "snippet": "public class DwReset extends BaseOp implements Operation {\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n final int code = data[0];\n\n }\n}" }, { "identifier": "DwTime", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwTime.java", "snippet": "public class DwTime extends BaseOp implements Operation {\n /**\n * Base year offset.\n */\n public static final int BASE_YEAR = 1900;\n /**\n * Byte size of response data.\n */\n public static final int RESPONSE_SIZE = 6;\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n final LocalDateTime currentTime = LocalDateTime.now();\n int[] response = new int[RESPONSE_SIZE];\n int index = 0;\n response[index++] = currentTime.getYear() - BASE_YEAR;\n response[index++] = currentTime.getMonth().getValue();\n response[index++] = currentTime.getDayOfMonth();\n response[index++] = currentTime.getHour();\n response[index++] = currentTime.getMinute();\n response[index] = currentTime.getSecond();\n new DWMessageEvent(this, response);\n }\n}" } ]
import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.thelair.dw4.drivewire.ports.DWIPort; import org.thelair.dw4.drivewire.ports.DWIPortManager; import org.thelair.dw4.drivewire.ports.DWIPortType; import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition; import org.thelair.dw4.drivewire.ports.serial.SerialPortDef; import org.thelair.dw4.drivewire.transactions.Transaction; import org.thelair.dw4.drivewire.transactions.TransactionRouter; import org.thelair.dw4.drivewire.transactions.operations.DwInit; import org.thelair.dw4.drivewire.transactions.operations.DwNop; import org.thelair.dw4.drivewire.transactions.operations.DwReset; import org.thelair.dw4.drivewire.transactions.operations.DwTime;
4,525
package org.thelair.dw4.drivewire; /** * Core application to DriveWire. */ @Component public class DWCore implements ApplicationListener<ApplicationReadyEvent> { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWCore.class); /** * Enabled features. */ private static final int DW4_FEATURES = 0x00; /** * Default serial baud rate of 2400. */ public static final int DEFAULT_BAUD_RATE = 2400; /** * Default serial data bits. */ public static final int DEFAULT_DATA_BITS = 8; /** * port manager. */ private final DWIPortManager portManager; /** * transaction router. */
package org.thelair.dw4.drivewire; /** * Core application to DriveWire. */ @Component public class DWCore implements ApplicationListener<ApplicationReadyEvent> { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWCore.class); /** * Enabled features. */ private static final int DW4_FEATURES = 0x00; /** * Default serial baud rate of 2400. */ public static final int DEFAULT_BAUD_RATE = 2400; /** * Default serial data bits. */ public static final int DEFAULT_DATA_BITS = 8; /** * port manager. */ private final DWIPortManager portManager; /** * transaction router. */
private final TransactionRouter router;
6
2023-11-18 11:35:16+00:00
8k
sbmatch/miui_regain_runningserice
app/src/main/java/com/ma/bitchgiveitback/app_process/Main.java
[ { "identifier": "MultiJarClassLoader", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/MultiJarClassLoader.java", "snippet": "public class MultiJarClassLoader extends ClassLoader {\n static MultiJarClassLoader multiJarClassLoader;\n List<DexClassLoader> dexClassLoaders = new ArrayList<>();\n private MultiJarClassLoader(ClassLoader parentClassLoader) {\n super(parentClassLoader);\n }\n\n public synchronized static MultiJarClassLoader getInstance(){\n if (multiJarClassLoader == null){\n multiJarClassLoader = new MultiJarClassLoader(ClassLoader.getSystemClassLoader());\n }\n return multiJarClassLoader;\n }\n\n public void addJar(String jarPath) {\n DexClassLoader dexClassLoader = new DexClassLoader(\n jarPath,\n null,\n null, // 额外的库路径,可以为 null\n getParent() // 父类加载器\n );\n dexClassLoaders.add(dexClassLoader);\n }\n\n @Override\n protected Class<?> findClass(String className) throws ClassNotFoundException {\n // 遍历所有的 DexClassLoader 实例,尝试加载类\n for (DexClassLoader dexClassLoader : dexClassLoaders) {\n try {\n return dexClassLoader.loadClass(className);\n } catch (ClassNotFoundException ignored) {\n // 忽略类未找到的异常,继续下一个 DexClassLoader\n }\n }\n throw new ClassNotFoundException(\"Class not found: \" + className);\n }\n}" }, { "identifier": "Netd", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/Netd.java", "snippet": "public class Netd {\n private IInterface manager;\n public Netd(IInterface netd) {\n this.manager = netd;\n }\n\n public IBinder getOemNetd() {\n try {\n return (IBinder) manager.getClass().getMethod(\"getOemNetd\").invoke(manager);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n}" }, { "identifier": "NotificationManager", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/NotificationManager.java", "snippet": "public class NotificationManager {\n\n private IInterface manager;\n private Method updateNotificationChannelForPackageMethod;\n private Method unlockFieldsMethod;\n private Method setNotificationsEnabledForPackageMethod;\n private Method areNotificationsEnabledForPackageMethod;\n private Method unlockAllNotificationChannelsMethod;\n private Method unlockNotificationChannelMethod;\n private Method updateNotificationChannelGroupForPackageMethod;\n private Method isImportanceLockedMethod;\n private Method setInterruptionFilterMethod;\n private Method setNotificationPolicyMethod;\n private Method isNotificationPolicyAccessGrantedForPackageMethod;\n private Method setNotificationPolicyAccessGrantedMethod;\n public NotificationManager(IInterface manager){\n this.manager = manager;\n }\n\n private Method getUpdateNotificationChannelForPackageMethod() throws NoSuchMethodException {\n\n if (updateNotificationChannelForPackageMethod == null){\n updateNotificationChannelForPackageMethod = manager.getClass().getMethod(\"updateNotificationChannelForPackage\", String.class , int.class , NotificationChannel.class);\n }\n return updateNotificationChannelForPackageMethod;\n }\n\n private Method getSetNotificationsEnabledForPackageMethod() throws NoSuchMethodException {\n if (setNotificationsEnabledForPackageMethod == null){\n setNotificationsEnabledForPackageMethod = manager.getClass().getMethod(\"setNotificationsEnabledForPackage\", String.class, int.class, boolean.class);\n }\n return setNotificationsEnabledForPackageMethod;\n }\n\n private Method getAreNotificationsEnabledForPackageMethod() throws NoSuchMethodException {\n if (areNotificationsEnabledForPackageMethod == null){\n areNotificationsEnabledForPackageMethod = manager.getClass().getMethod(\"areNotificationsEnabledForPackage\", String.class, int.class);\n }\n return areNotificationsEnabledForPackageMethod;\n }\n\n private Method getUpdateNotificationChannelGroupForPackageMethod() throws NoSuchMethodException {\n if (updateNotificationChannelGroupForPackageMethod == null){\n updateNotificationChannelGroupForPackageMethod = manager.getClass().getMethod(\"updateNotificationChannelGroupForPackage\", String.class, int.class, NotificationChannelGroup.class);\n }\n return updateNotificationChannelGroupForPackageMethod;\n }\n\n private Method getUnlockAllNotificationChannelsMethod() throws NoSuchMethodException {\n if (unlockAllNotificationChannelsMethod == null){\n unlockAllNotificationChannelsMethod = manager.getClass().getMethod(\"unlockAllNotificationChannels\");\n }\n return unlockAllNotificationChannelsMethod;\n }\n\n private Method getIsImportanceLockedMethod() throws NoSuchMethodException {\n if (isImportanceLockedMethod == null){\n isImportanceLockedMethod = manager.getClass().getMethod(\"isImportanceLocked\", String.class, int.class);\n }\n return isImportanceLockedMethod;\n }\n\n private Method getSetInterruptionFilterMethod() throws NoSuchMethodException {\n if (setInterruptionFilterMethod == null){\n setInterruptionFilterMethod = manager.getClass().getMethod(\"setInterruptionFilter\", String.class, int.class);\n }\n return setInterruptionFilterMethod;\n }\n\n private Method getUnlockNotificationChannelMethod() throws NoSuchMethodException {\n if (unlockNotificationChannelMethod == null) unlockNotificationChannelMethod = manager.getClass().getMethod(\"unlockNotificationChannel\", String.class , int.class, String.class);\n return unlockNotificationChannelMethod;\n }\n\n private Method getSetNotificationPolicyMethod() throws NoSuchMethodException {\n if (setNotificationPolicyMethod == null){\n setNotificationPolicyMethod = manager.getClass().getMethod(\"setNotificationPolicy\", System.class, android.app.NotificationManager.Policy.class);\n }\n return setNotificationPolicyMethod;\n }\n\n private Method getIsNotificationPolicyAccessGrantedForPackageMethod() throws NoSuchMethodException {\n if (isNotificationPolicyAccessGrantedForPackageMethod == null){\n isNotificationPolicyAccessGrantedForPackageMethod = manager.getClass().getMethod(\"isNotificationPolicyAccessGrantedForPackage\",String.class);\n }\n return isNotificationPolicyAccessGrantedForPackageMethod;\n }\n\n private Method getSetNotificationPolicyAccessGrantedMethod() throws NoSuchMethodException {\n if (setNotificationPolicyAccessGrantedMethod == null){\n setNotificationPolicyAccessGrantedMethod = manager.getClass().getMethod(\"setNotificationPolicyAccessGranted\", String.class, boolean.class);\n }\n return setNotificationPolicyAccessGrantedMethod;\n }\n\n public List<NotificationChannel> getNotificationChannelsForPackage(String pkg, boolean includeDeleted){\n\n try {\n\n Object parceledListSlice = manager.getClass().getMethod(\"getNotificationChannelsForPackage\",String.class , int.class, boolean.class).invoke(manager ,pkg, ServiceManager.getPackageManager().getApplicationInfo(pkg).uid,includeDeleted);\n\n // 通过反射调用 getList 方法\n assert parceledListSlice != null;\n Method getListMethod = parceledListSlice.getClass().getDeclaredMethod(\"getList\");\n getListMethod.setAccessible(true);\n\n return (List<NotificationChannel>) getListMethod.invoke(parceledListSlice);\n\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n public void updateNotificationChannelForPackage(String pkg, int uid, NotificationChannel channel){\n try {\n Method updateNotificationChannelForPackage = getUpdateNotificationChannelForPackageMethod();\n updateNotificationChannelForPackage.invoke(manager, pkg, uid, channel);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled){\n try {\n getSetNotificationsEnabledForPackageMethod().invoke(manager, pkg, uid, enabled);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public boolean areNotificationsEnabledForPackage(String pkg, int uid){\n try {\n return (boolean) getAreNotificationsEnabledForPackageMethod().invoke(manager, pkg, uid);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n public void setNotificationPolicy(String pkg, android.app.NotificationManager.Policy policy){\n try {\n getSetNotificationPolicyMethod().invoke(manager, pkg, policy);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public boolean isNotificationPolicyAccessGrantedForPackage(String pkg){\n try {\n return (boolean) getIsNotificationPolicyAccessGrantedForPackageMethod().invoke(manager, pkg);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n public void setNotificationPolicyAccessGranted(String pkg, boolean granted){\n try {\n getSetNotificationPolicyAccessGrantedMethod().invoke(manager, pkg, granted);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void setInterruptionFilter(String pkg, int interruptionFilter){\n try {\n getSetInterruptionFilterMethod().invoke(manager, pkg, interruptionFilter);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void unlockAllNotificationChannels(){\n try {\n getUnlockAllNotificationChannelsMethod().invoke(manager);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void updateNotificationChannelGroupForPackage(String pkg, int uid, NotificationChannelGroup group){\n try {\n getUpdateNotificationChannelGroupForPackageMethod().invoke(manager, pkg, uid, group);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public boolean isImportanceLocked(String pkg, int uid){\n try {\n return (boolean) getIsImportanceLockedMethod().invoke(manager, pkg, uid);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n\n public void setImportanceLockedByCriticalDeviceFunction(NotificationChannel channel, boolean locked){\n try {\n channel.getClass().getMethod(\"setImportanceLockedByCriticalDeviceFunction\", boolean.class).invoke(channel, locked);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n\n public boolean ismImportanceLockedDefaultApp(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getField(\"mImportanceLockedDefaultApp\").get(channel);\n }catch (Throwable e){\n return false;\n }\n }\n\n public boolean getmImportanceLockedDefaultApp(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getField(\"mImportanceLockedDefaultApp\").get(channel);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n public void setmImportanceLockedDefaultApp(NotificationChannel channel, boolean locked){\n try {\n channel.getClass().getField(\"mImportanceLockedDefaultApp\").set(channel, locked);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n public boolean ismBlockableSystem(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getField(\"mBlockableSystem\").get(channel);\n }catch (Throwable e){\n return false;\n }\n }\n\n public boolean getmBlockableSystem(NotificationChannel channel){\n try {\n for (Field field: channel.getClass().getFields()){\n if (field.getName().equals(\"mBlockableSystem\")){\n return (boolean) channel.getClass().getField(\"mBlockableSystem\").get(channel);\n }\n }\n return false;\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n public void setmBlockableSystem(NotificationChannel channel, boolean locked){\n try {\n channel.getClass().getField(\"mBlockableSystem\").set(channel, locked);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n\n public void unlockFields(NotificationChannel channel){\n try {\n if (unlockFieldsMethod == null){\n unlockFieldsMethod = channel.getClass().getMethod(\"unlockFields\", int.class);\n }\n unlockFieldsMethod.invoke(channel, getUserLockedFields(channel));\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void setBlockable(NotificationChannel channel ,boolean blockable){\n try {\n channel.getClass().getMethod(\"setBlockable\",boolean.class).invoke(channel, blockable);\n } catch (IllegalAccessException | InvocationTargetException |\n NoSuchMethodException e) {\n e.printStackTrace();\n }\n }\n\n public boolean isBlockable(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getMethod(\"isBlockable\").invoke(channel);\n } catch (IllegalAccessException | InvocationTargetException |\n NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public int getUserLockedFields(NotificationChannel channel){\n try {\n return (int) channel.getClass().getMethod(\"getUserLockedFields\").invoke(channel);\n } catch (IllegalAccessException | InvocationTargetException |\n NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void unlockNotificationChannel(String pkg, int uid, String channelId){\n try {\n getUnlockNotificationChannelMethod().invoke(manager, pkg , uid , channelId);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n}" }, { "identifier": "PackageManager", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/PackageManager.java", "snippet": "public class PackageManager {\n\n private final IInterface manager;\n private Method getInstalledApplicationsMethod;\n private Method getApplicationInfoMethod;\n private Method getNameForUidMethod;\n private Method checkPermissionMethod;\n private Method getPackageInfoMethod;\n private Method isPackageAvailableMethod;\n private Method getHomeActivitiesMethod;\n private Method getChangedPackagesMethod;\n private Method queryIntentActivitiesMethod;\n\n public PackageManager(IInterface manager){\n this.manager = manager;\n }\n\n private Method getInstalledApplicationsMethod() throws NoSuchMethodException {\n if (getInstalledApplicationsMethod == null){\n getInstalledApplicationsMethod = manager.getClass().getMethod(\"getInstalledApplications\", (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ? long.class : int.class , int.class);\n }\n return getInstalledApplicationsMethod;\n }\n\n private Method getApplicationInfoMethod() throws NoSuchMethodException {\n if (getApplicationInfoMethod == null){\n getApplicationInfoMethod = manager.getClass().getMethod(\"getApplicationInfo\", String.class, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ? long.class : int.class , int.class);\n }\n return getApplicationInfoMethod;\n }\n\n private Method getGetPackageInfoMethod() throws NoSuchMethodException {\n if (getPackageInfoMethod == null){\n getPackageInfoMethod = manager.getClass().getMethod(\"getPackageInfo\", String.class, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ? long.class : int.class , int.class);\n }\n return getPackageInfoMethod;\n }\n\n private Method getNameForUidMethod() throws NoSuchMethodException {\n if (getNameForUidMethod == null){\n getNameForUidMethod = manager.getClass().getMethod(\"getNameForUid\", int.class);\n }\n return getNameForUidMethod;\n }\n\n private Method getCheckPermissionMethod() throws NoSuchMethodException {\n if (checkPermissionMethod == null){\n checkPermissionMethod = manager.getClass().getMethod(\"checkPermission\",String.class, String.class, int.class);\n }\n return checkPermissionMethod;\n }\n\n private Method getIsPackageAvailableMethod() throws NoSuchMethodException {\n if (isPackageAvailableMethod == null){\n isPackageAvailableMethod = manager.getClass().getMethod(\"isPackageAvailable\", String.class, int.class);\n }\n return isPackageAvailableMethod;\n }\n\n private Method getQueryIntentActivitiesMethod() throws NoSuchMethodException {\n if (queryIntentActivitiesMethod == null) queryIntentActivitiesMethod = manager.getClass().getMethod(\"queryIntentActivities\", Intent.class, String.class, long.class, int.class);\n return queryIntentActivitiesMethod;\n }\n private Method getGetHomeActivitiesMethod() throws NoSuchMethodException {\n if (getHomeActivitiesMethod == null){\n getHomeActivitiesMethod = manager.getClass().getMethod(\"getHomeActivities\", List.class);\n }\n return getHomeActivitiesMethod;\n }\n\n private Method getGetChangedPackagesMethod() throws NoSuchMethodException {\n if (getChangedPackagesMethod == null){\n getChangedPackagesMethod = manager.getClass().getMethod(\"getChangedPackages\", int.class, int.class);\n }\n return getChangedPackagesMethod;\n }\n\n public ComponentName getHomeActivities(List<ResolveInfo> outHomeCandidates){\n try {\n return (ComponentName) getGetHomeActivitiesMethod().invoke(manager, outHomeCandidates);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public ApplicationInfo getApplicationInfo(String packageName){\n try {\n return (ApplicationInfo) getApplicationInfoMethod().invoke(manager, packageName , 0 , UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, long flags){\n try {\n Object obj = getQueryIntentActivitiesMethod().invoke(manager, intent, resolvedType, flags, UserManager.myUserId());\n return (List<ResolveInfo>) obj.getClass().getMethod(\"getList\").invoke(obj);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public static String getApkPath(PackageManager packageManager, String packageName) {\n //获取applicationInfo\n ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName);\n return applicationInfo.sourceDir;\n }\n public ArraySet<String> getInstalledApplications() {\n\n ArraySet<String> a = new ArraySet<>();\n\n try {\n Object parceledListSlice = getInstalledApplicationsMethod().invoke(manager, 0, UserManager.myUserId());\n // 通过反射调用 getList 方法\n Method getListMethod = parceledListSlice.getClass().getDeclaredMethod(\"getList\");\n getListMethod.setAccessible(true);\n for (ApplicationInfo applicationInfo : (List<ApplicationInfo>) getListMethod.invoke(parceledListSlice)){\n a.add(applicationInfo.packageName);\n }\n return a;\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public List<String> getAllPackages(){\n try {\n return (List<String>) manager.getClass().getMethod(\"getAllPackages\").invoke(manager);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public String getAppNameForPackageName(Context context ,String packageName) {\n try{\n ApplicationInfo appInfo = (ApplicationInfo) getApplicationInfoMethod().invoke(manager, packageName , 0 , UserManager.myUserId());\n return (String) appInfo.loadLabel(context.getPackageManager());\n } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public ChangedPackages getChangedPackages(){\n try {\n return (ChangedPackages) getGetChangedPackagesMethod().invoke(manager, 0, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n\n public String getNameForUid(int uid){\n try {\n Method getNameForUid = getNameForUidMethod();\n return (String) getNameForUid.invoke(manager, uid);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public PackageInfo getPackageInfo(String packageName, Object flag){\n try {\n return (PackageInfo) getGetPackageInfoMethod().invoke(manager, packageName, flag, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public boolean isPackageAvailable(String packageName){\n try {\n return (boolean) getIsPackageAvailableMethod().invoke(manager, packageName, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public int checkPermission(String permName, String pkgName){\n try {\n Log.i(\"PackageManager\",\"checkPermission \"+ permName +\" call from pkgName \"+pkgName);\n Method checkPermission = getCheckPermissionMethod();\n return (int) checkPermission.invoke(manager, permName, pkgName, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public boolean isSystemApp(String packageName) {\n\n try {\n ApplicationInfo appInfo = (ApplicationInfo) getApplicationInfoMethod().invoke(manager, packageName , 0 , UserManager.myUserId());\n return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public boolean getBlockUninstallForUserReflect(String packageName){\n try {\n // 调用 getBlockUninstallForUser 方法并获取返回值\n return (boolean) manager.getClass().getMethod(\"getBlockUninstallForUser\", String.class, int.class).invoke(manager, packageName, UserManager.myUserId());\n } catch (Exception e2) {\n // 捕获异常并抛出运行时异常\n throw new RuntimeException(e2);\n }\n }\n\n private String getTag(){\n return PackageManager.class.getSimpleName();\n }\n}" }, { "identifier": "ServiceManager", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/ServiceManager.java", "snippet": "public class ServiceManager {\n\n private static ActivityManager activityManager;\n private static PackageManager packageManager;\n private static UserManager userManager;\n private static NotificationManager notificationManager;\n\n private ServiceManager() {\n System.out.println(this.getClass().getSimpleName()+\" 执行私有构造方法\");\n }\n private static IInterface getService(String service, String type){\n try {\n IBinder binder = getIBinderService(service);\n Class<?> clz = Class.forName(type + \"$Stub\");\n Method asInterfaceMethod = clz.getMethod(\"asInterface\", IBinder.class);\n return (IInterface) asInterfaceMethod.invoke(null, binder);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static IBinder getIBinderService(String service){\n try {\n @SuppressLint({\"DiscouragedPrivateApi\", \"PrivateApi\"})\n Method getServiceMethod = Class.forName(\"android.os.ServiceManager\").getMethod(\"getService\", String.class);\n return (IBinder) getServiceMethod.invoke(null, service);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static IBinder checkService(String name){\n try {\n @SuppressLint({\"DiscouragedPrivateApi\", \"PrivateApi\"})\n Method getServiceMethod = Class.forName(\"android.os.ServiceManager\").getMethod(\"checkService\", String.class);\n return (IBinder) getServiceMethod.invoke(null, name);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static String[] listServices() {\n try {\n return (String[]) Class.forName(\"android.os.ServiceManager\").getMethod(\"listServices\").invoke(null);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static ActivityManager getActivityManager(){\n if (activityManager == null) {\n activityManager = new ActivityManager(getService(\"activity\", \"android.app.IActivityManager\"));\n }\n return activityManager;\n }\n\n public static PackageManager getPackageManager(){\n if (packageManager == null){\n packageManager = new PackageManager(getService(\"package\", \"android.content.pm.IPackageManager\"));\n }\n return packageManager;\n }\n\n public static UserManager getUserManager(){\n if (userManager == null){\n userManager = new UserManager(getService(\"user\",\"android.os.IUserManager\"));\n }\n return userManager;\n }\n\n public static NotificationManager getNotificationManager(){\n if (notificationManager == null){\n notificationManager = new NotificationManager(getService(\"notification\",\"android.app.INotificationManager\"));\n }\n\n return notificationManager;\n }\n}" }, { "identifier": "ShellUtils", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/ShellUtils.java", "snippet": "public class ShellUtils {\n private static final String TAG = \"ShellUtils\";\n private ShellUtils() {\n }\n public static String execCommand(String command, boolean isRoot, boolean isSystem) {\n try {\n Process process = isRoot ? (isSystem ? Runtime.getRuntime().exec(new String[]{\"su\",\"system\"}) : Runtime.getRuntime().exec(new String[]{\"su\"})) : Runtime.getRuntime().exec(new String[]{\"sh\"});\n\n OutputStream outputStream = process.getOutputStream();\n outputStream.write((command + \"\\n\").getBytes());\n outputStream.flush();\n outputStream.close();\n\n StringBuilder output = new StringBuilder();\n StringBuilder error = new StringBuilder();\n\n Thread outputThread = new Thread(() -> {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {\n String line;\n while ((line = reader.readLine()) != null) {\n output.append(line).append(\"\\n\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n\n Thread errorThread = new Thread(() -> {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {\n String line;\n while ((line = reader.readLine()) != null) {\n error.append(line).append(\"\\n\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n\n outputThread.start();\n errorThread.start();\n\n int exitCode = process.waitFor();\n outputThread.join();\n errorThread.join();\n\n if (exitCode != 0) {\n return error.toString();\n }\n\n return output.toString();\n } catch (IOException | InterruptedException e) {\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n}" }, { "identifier": "SystemPropertiesUtils", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/SystemPropertiesUtils.java", "snippet": "public class SystemPropertiesUtils {\n private static Class<?> clazz;\n private static Method getMethod;\n private static Method getBooleanMethod;\n private SystemPropertiesUtils(){\n\n }\n\n private static Class<?> getClazz() throws ClassNotFoundException {\n if (clazz == null) clazz = Class.forName(\"android.os.SystemProperties\");\n return clazz;\n }\n\n private static Method getGetMethod() throws ClassNotFoundException, NoSuchMethodException {\n if (getMethod == null) getMethod = getClazz().getMethod(\"get\", String.class);\n return getMethod;\n }\n\n private static Method getGetBooleanMethod() throws ClassNotFoundException, NoSuchMethodException {\n if (getBooleanMethod == null) getBooleanMethod = getClazz().getMethod(\"getBoolean\", String.class, boolean.class);\n return getBooleanMethod;\n }\n\n public static String get(String key){\n try {\n return (String) getGetMethod().invoke(null, key);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public static boolean getBoolean(String key, boolean def){\n try {\n return (boolean) getGetBooleanMethod().invoke(null, key, def);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n}" } ]
import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Looper; import android.util.Log; import com.ma.bitchgiveitback.utils.MultiJarClassLoader; import com.ma.bitchgiveitback.utils.Netd; import com.ma.bitchgiveitback.utils.NotificationManager; import com.ma.bitchgiveitback.utils.PackageManager; import com.ma.bitchgiveitback.utils.ServiceManager; import com.ma.bitchgiveitback.utils.ShellUtils; import com.ma.bitchgiveitback.utils.SystemPropertiesUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
6,606
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager();
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager();
static MultiJarClassLoader multiJarClassLoader = MultiJarClassLoader.getInstance();
0
2023-11-17 09:58:57+00:00
8k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/attachments/mags/AssaultExpansionMag.java
[ { "identifier": "Gunscraft", "path": "src/main/java/sheridan/gunscraft/Gunscraft.java", "snippet": "@Mod(\"gunscraft\")\npublic class Gunscraft {\n\n // Directly reference a log4j logger.\n private static final Logger LOGGER = LogManager.getLogger();\n\n public static IProxy proxy = DistExecutor.safeRunForDist(()->ClientProxy::new, ()->CommonProxy::new);\n\n public static final String MOD_ID = \"gunscraft\";\n\n public Gunscraft() {\n // Register the setup method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n // Register the enqueueIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);\n // Register the processIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);\n // Register the doClientStuff method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(RenderEvents.class);\n MinecraftForge.EVENT_BUS.register(DebugEvents.class);\n MinecraftForge.EVENT_BUS.register(ControllerEvents.class);\n MinecraftForge.EVENT_BUS.register(ClientTickEvents.class);\n ModItems.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n ModContainers.CONTAINERS.register(FMLJavaModLoadingContext.get().getModEventBus());\n EntityRegister.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n SoundEvents.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n private void setup(final FMLCommonSetupEvent event) {\n // some preinit code\n LOGGER.info(\"HELLO FROM PREINIT\");\n LOGGER.info(\"DIRT BLOCK >> {}\", Blocks.DIRT.getRegistryName());\n CapabilityHandler.init();\n PacketHandler.register();\n //EntityRegister.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n EntityRegister.registerRenderer();\n proxy.commonSetUp(event);\n }\n\n private void doClientStuff(final FMLClientSetupEvent event) {\n // do something that can only be done on the client\n proxy.setUpClient(event);\n }\n\n private void enqueueIMC(final InterModEnqueueEvent event) {\n // some example code to dispatch IMC to another mod\n InterModComms.sendTo(\"gunscraft\", \"helloworld\", () -> {\n LOGGER.info(\"Hello world from the MDK\");\n return \"Hello world\";\n });\n }\n\n private void processIMC(final InterModProcessEvent event) {\n // some example code to receive and process InterModComms from other mods\n LOGGER.info(\"Got IMC {}\", event.getIMCStream().\n map(m -> m.getMessageSupplier().get()).\n collect(Collectors.toList()));\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(FMLServerStartingEvent event) {\n // do something when the server starts\n LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD\n // Event bus for receiving Registry Events)\n @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)\n public static class RegistryEvents {\n @SubscribeEvent\n public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {\n // register a new block here\n LOGGER.info(\"HELLO from Register Block\");\n }\n }\n}" }, { "identifier": "AttachmentRegistry", "path": "src/main/java/sheridan/gunscraft/items/attachments/AttachmentRegistry.java", "snippet": "public class AttachmentRegistry {\n private static Map<Integer, IGenericAttachment> registryMap = new HashMap<>();\n private static Map<String, Integer> IDMap = new HashMap<>();\n private static Map<Integer, IAttachmentModel> modelMap = new HashMap<>();\n private static int ID = -1;\n\n public static void register(int id, IGenericAttachment attachment) {\n if (!registryMap.containsKey(id)) {\n registryMap.put(id, attachment);\n }\n }\n public static int getIdByName(String name) {\n return IDMap.getOrDefault(name, NONE);\n }\n\n public static void registerModel(int id, IAttachmentModel models) {\n if (!modelMap.containsKey(id)) {\n modelMap.put(id, models);\n }\n }\n\n public static IAttachmentModel getModel(int id) {\n return modelMap.getOrDefault(id, null);\n }\n\n public static IGenericAttachment get(int id) {\n return registryMap.getOrDefault(id, null);\n }\n\n public static int getID(String name) {\n synchronized (Object.class) {\n ++ID;\n IDMap.put(name, ID);\n return ID;\n }\n }\n}" }, { "identifier": "GenericAttachment", "path": "src/main/java/sheridan/gunscraft/items/attachments/GenericAttachment.java", "snippet": "public class GenericAttachment extends Item implements IGenericAttachment{\n public static final String MUZZLE = \"muzzle\", GRIP = \"grip\", MAG = \"mag\", SCOPE = \"scope\", STOCK = \"stock\", HAND_GUARD = \"hand_guard\";\n public static final int NONE = -1;\n protected int id;\n protected String type;\n protected String name;\n\n public String getType() {\n return type;\n }\n\n public GenericAttachment(Properties properties, int id, String type, String name) {\n super(properties);\n this.id = id;\n this.type = type;\n this.name = name;\n }\n\n @Override\n public void onAttach(ItemStack stack, IGenericGun gun) {\n\n }\n\n @Override\n public void onOff(ItemStack stack, IGenericGun gun) {\n\n }\n\n @Override\n public int getId() {\n return this.id;\n }\n\n @Override\n public String getSlotType() {\n return type;\n }\n\n @Override\n public int getID() {\n return id;\n }\n\n @Override\n public String getAttachmentName() {\n return name;\n }\n\n\n @Override\n public void handleParams(GunRenderContext params) {\n switch (this.type) {\n case MUZZLE:\n params.occupiedMuzzle = true;\n break;\n case HAND_GUARD:\n params.occupiedHandGuard = true;\n break;\n case MAG:\n params.occupiedMag = true;\n break;\n case SCOPE:\n params.occupiedIS = true;\n break;\n case STOCK:\n params.occupiedStock = true;\n break;\n case GRIP:\n params.occupiedGrip = true;\n break;\n }\n }\n\n @Override\n public int getItemId() {\n return Item.getIdFromItem(this);\n }\n\n}" }, { "identifier": "GenericMag", "path": "src/main/java/sheridan/gunscraft/items/attachments/GenericMag.java", "snippet": "public class GenericMag extends GenericAttachment{\n public int ammoIncrement;\n\n public GenericMag(Properties properties, int id, String type, String name, int ammoIncrement) {\n super(properties, id, type, name);\n this.ammoIncrement = ammoIncrement;\n }\n\n @Override\n public void onAttach(ItemStack stack, IGenericGun gun) {\n gun.setMagSize(stack, gun.getMagSize(stack) + ammoIncrement);\n }\n\n @Override\n public void onOff(ItemStack stack, IGenericGun gun) {\n gun.setMagSize(stack, gun.getMagSize(stack) - ammoIncrement);\n int ammoDec = gun.getAmmoLeft(stack);\n ammoDec = ammoDec > ammoIncrement ? ammoDec - ammoIncrement : 0;\n gun.setAmmoLeft(stack, ammoDec);\n }\n\n @Override\n public void handleParams(GunRenderContext params) {\n params.occupiedMag = true;\n }\n}" }, { "identifier": "ModelAssaultExpansionMag", "path": "src/main/java/sheridan/gunscraft/model/attachments/mags/ModelAssaultExpansionMag.java", "snippet": "public class ModelAssaultExpansionMag extends EntityModel<Entity> implements IAttachmentModel {\n private final ModelRenderer mag_ar;\n private final ModelRenderer cube_r1;\n private final ModelRenderer cube_r2;\n private final ModelRenderer cube_r3;\n\n\n private final ModelRenderer mag_ak;\n private final ModelRenderer ak_cube_r1;\n private final ModelRenderer ak_cube_r2;\n private final ModelRenderer ak_cube_r3;\n private final ModelRenderer ak_cube_r4;\n private final ModelRenderer ak_cube_r5;\n private final ModelRenderer ak_cube_r6;\n private final ModelRenderer ak_cube_r7;\n private final ModelRenderer ak_cube_r8;\n private final ModelRenderer ak_cube_r9;\n private final ModelRenderer ak_cube_r10;\n\n\n private ArrayList<ResourceLocation> textures;\n\n public ModelAssaultExpansionMag(ArrayList<ResourceLocation> textures) {\n textureWidth = 128;\n textureHeight = 128;\n this.textures = textures;\n mag_ar = new ModelRenderer(this);\n mag_ar.setRotationPoint(3.5F, 24.0F, 0.1F);\n mag_ar.setTextureOffset(44, 22).addBox(-7.0F, 0.0F, 0.0F, 7.0F, 9.0F, 22.0F, 0.0F, false, true, true, false, false, true, true);\n\n cube_r1 = new ModelRenderer(this);\n cube_r1.setRotationPoint(-8.0F, 31.6F, -7.8F);\n mag_ar.addChild(cube_r1);\n setRotationAngle(cube_r1, -0.384F, 0.0F, 0.0F);\n cube_r1.setTextureOffset(0, 0).addBox(0.0F, 0.0F, 0.0F, 9.0F, 20.0F, 24.0F, 0.0F, false, true, true, true, true, true, true);\n\n cube_r2 = new ModelRenderer(this);\n cube_r2.setRotationPoint(0.0F, 9.0F, 22.0F);\n mag_ar.addChild(cube_r2);\n setRotationAngle(cube_r2, -0.1571F, 0.0F, 0.0F);\n cube_r2.setTextureOffset(58, 53).addBox(-7.0F, 0.0F, -22.0F, 7.0F, 8.0F, 22.0F, 0.0F, false, true, true, false, false, true, true);\n\n cube_r3 = new ModelRenderer(this);\n cube_r3.setRotationPoint(0.0F, 16.9474F, 20.7345F);\n mag_ar.addChild(cube_r3);\n setRotationAngle(cube_r3, -0.2967F, 0.0F, 0.0F);\n cube_r3.setTextureOffset(0, 44).addBox(-7.0F, -0.048F, -22.0F, 7.0F, 25.0F, 22.0F, 0.0F, false, true, true, false, false, true, true);\n\n\n mag_ak = new ModelRenderer(this);\n mag_ak.setRotationPoint(0.0F, 24.0F, 5.0F);\n\n\n ak_cube_r1 = new ModelRenderer(this);\n ak_cube_r1.setRotationPoint(1.9F, 56.1423F, -19.2898F);\n mag_ak.addChild(ak_cube_r1);\n setRotationAngle(ak_cube_r1, -1.0472F, 0.0F, 0.0F);\n ak_cube_r1.setTextureOffset(0, 77).addBox(-5.0F, 0.5F, -16.2F, 6.0F, 19.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r2 = new ModelRenderer(this);\n ak_cube_r2.setRotationPoint(2.9F, 60.6423F, -16.3898F);\n mag_ak.addChild(ak_cube_r2);\n setRotationAngle(ak_cube_r2, -1.0472F, 0.0F, 0.0F);\n ak_cube_r2.setTextureOffset(0, 0).addBox(-7.0F, 0.0F, -17.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r3 = new ModelRenderer(this);\n ak_cube_r3.setRotationPoint(1.9F, 43.2865F, -3.9689F);\n mag_ak.addChild(ak_cube_r3);\n setRotationAngle(ak_cube_r3, -0.829F, 0.0F, 0.0F);\n ak_cube_r3.setTextureOffset(83, 29).addBox(-5.0F, 1.1F, -16.8F, 6.0F, 19.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r4 = new ModelRenderer(this);\n ak_cube_r4.setRotationPoint(1.9F, 28.1035F, 5.8027F);\n mag_ak.addChild(ak_cube_r4);\n setRotationAngle(ak_cube_r4, -0.5672F, 0.0F, 0.0F);\n ak_cube_r4.setTextureOffset(26, 87).addBox(-5.0F, 1.0F, -17.0F, 6.0F, 15.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r5 = new ModelRenderer(this);\n ak_cube_r5.setRotationPoint(1.9F, 3.1172F, -3.8964F);\n mag_ak.addChild(ak_cube_r5);\n setRotationAngle(ak_cube_r5, -0.3054F, 0.0F, 0.0F);\n ak_cube_r5.setTextureOffset(93, 87).addBox(-5.0F, 5.0F, 0.0F, 6.0F, 14.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r6 = new ModelRenderer(this);\n ak_cube_r6.setRotationPoint(1.9F, -1.4F, -5.0F);\n mag_ak.addChild(ak_cube_r6);\n setRotationAngle(ak_cube_r6, -0.0436F, 0.0F, 0.0F);\n ak_cube_r6.setTextureOffset(33, 0).addBox(-5.0F, 1.0F, 0.0F, 6.0F, 10.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r7 = new ModelRenderer(this);\n ak_cube_r7.setRotationPoint(2.9F, 47.7865F, -1.0689F);\n mag_ak.addChild(ak_cube_r7);\n setRotationAngle(ak_cube_r7, -0.8727F, 0.0F, 0.0F);\n ak_cube_r7.setTextureOffset(33, 20).addBox(-7.0F, 0.0F, -17.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r8 = new ModelRenderer(this);\n ak_cube_r8.setRotationPoint(3.0F, 31.4035F, 10.4027F);\n mag_ak.addChild(ak_cube_r8);\n setRotationAngle(ak_cube_r8, -0.6109F, 0.0F, 0.0F);\n ak_cube_r8.setTextureOffset(0, 40).addBox(-7.1F, 0.0F, -17.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r9 = new ModelRenderer(this);\n ak_cube_r9.setRotationPoint(2.9F, 7.2172F, 0.2036F);\n mag_ak.addChild(ak_cube_r9);\n setRotationAngle(ak_cube_r9, -0.3054F, 0.0F, 0.0F);\n ak_cube_r9.setTextureOffset(50, 57).addBox(-7.0F, 0.0F, 0.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r10 = new ModelRenderer(this);\n ak_cube_r10.setRotationPoint(2.9F, -1.4F, 0.0F);\n mag_ak.addChild(ak_cube_r10);\n setRotationAngle(ak_cube_r10, -0.0436F, 0.0F, 0.0F);\n ak_cube_r10.setTextureOffset(66, 0).addBox(-7.0F, 1.0F, 0.0F, 8.0F, 12.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n }\n\n @Override\n public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {\n //previously the render function, render code was moved to a method below\n }\n\n @Override\n public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) {\n mag_ar.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha);\n }\n\n public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {\n modelRenderer.rotateAngleX = x;\n modelRenderer.rotateAngleY = y;\n modelRenderer.rotateAngleZ = z;\n }\n\n\n @Override\n public void render(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType, int packedLight, int packedOverlay, int bulletLeft, long lastFireTime, boolean mainHand, int fireMode, IGenericGun gun) {\n IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource();\n if (gun.getSeriesName().equals(\"ar\")) {\n IVertexBuilder builder = buffer.getBuffer(RenderType.getArmorCutoutNoCull(textures.get(0)));\n mag_ar.render(matrixStack, builder, packedLight, packedOverlay, 1, 1, 1, 1);\n } else if (gun.getSeriesName().equals(\"ak\")) {\n IVertexBuilder builder = buffer.getBuffer(RenderType.getArmorCutoutNoCull(textures.get(1)));\n mag_ak.render(matrixStack, builder, packedLight, packedOverlay, 1, 1, 1, 1);\n }\n buffer.finish();\n }\n}" }, { "identifier": "CreativeTabs", "path": "src/main/java/sheridan/gunscraft/tabs/CreativeTabs.java", "snippet": "public class CreativeTabs {\n public static final ItemGroup REGULAR_GUNS = new ItemGroup(\"guns\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack((IItemProvider) ModItems.PISTOL_9_MM.get());\n }\n };\n public static final ItemGroup REGULAR_ATTACHMENTS = new ItemGroup(\"attachments\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack((IItemProvider) ModItems.AR_EXPANSION_MAG.get());\n }\n };\n}" } ]
import net.minecraft.util.ResourceLocation; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.items.attachments.AttachmentRegistry; import sheridan.gunscraft.items.attachments.GenericAttachment; import sheridan.gunscraft.items.attachments.GenericMag; import sheridan.gunscraft.model.attachments.mags.ModelAssaultExpansionMag; import sheridan.gunscraft.tabs.CreativeTabs; import java.util.ArrayList; import java.util.Arrays;
5,007
package sheridan.gunscraft.items.attachments.mags; public class AssaultExpansionMag extends GenericMag { public AssaultExpansionMag() {
package sheridan.gunscraft.items.attachments.mags; public class AssaultExpansionMag extends GenericMag { public AssaultExpansionMag() {
super(new Properties().group(CreativeTabs.REGULAR_ATTACHMENTS).maxStackSize(1), AttachmentRegistry.getID("assault_expansion_mag"),
5
2023-11-14 14:00:55+00:00
8k
zpascual/5419-Arm-Example
src/main/java/com/team5419/frc2023/DriverControls.java
[ { "identifier": "Loop", "path": "src/main/java/com/team5419/frc2023/loops/Loop.java", "snippet": "public interface Loop {\n\n public void onStart(double timestamp);\n\n public void onLoop(double timestamp);\n\n public void onStop(double timestamp);\n}" }, { "identifier": "Arm", "path": "src/main/java/com/team5419/frc2023/subsystems/Arm.java", "snippet": "public class Arm extends ServoMotorSubsystem {\n private static Arm mInstance;\n public static Arm getInstance(){\n if (mInstance == null) {\n mInstance = new Arm(kArmConstants);\n }\n return mInstance;\n }\n\n private static final ServoMotorSubsystemConstants kArmConstants = Constants.Arm.kArmServoConstants;\n\n protected Arm(ServoMotorSubsystemConstants constants) {\n super(constants);\n setNeutralBrake(true);\n zeroSensors();\n }\n\n private void setNeutralBrake(boolean isEnabled) {\n NeutralMode mode = isEnabled ? NeutralMode.Brake : NeutralMode.Coast;\n mMaster.setNeutralMode(mode);\n }\n\n @Override\n public void registerEnabledLoops(ILooper mEnabledLooper) {\n mEnabledLooper.register(new Loop() {\n @Override\n public void onStart(double timestamp) {\n\n }\n\n @Override\n public void onLoop(double timestamp) {\n\n }\n\n @Override\n public void onStop(double timestamp) {\n stop();\n setNeutralBrake(true);\n }\n });\n }\n\n public Request angleRequest(double angle) {\n return new Request() {\n @Override\n public void act() {\n setSetpointMotionMagic(angle);\n }\n\n @Override\n public boolean isFinished() {\n return Util.epsilonEquals(mPeriodicIO.position_units, angle, Constants.Arm.kAngleTolerance);\n }\n\n };\n }\n\n\n}" }, { "identifier": "Intake", "path": "src/main/java/com/team5419/frc2023/subsystems/Intake.java", "snippet": "public class Intake extends Subsystem {\n\n public static Intake mInstance = null;\n\n public static Intake getInstance() {\n if (mInstance == null) {\n return mInstance = new Intake();\n }\n return mInstance;\n }\n\n protected final TalonFX motor = new TalonFX(Ports.kIntake);\n\n public Intake() {\n\n }\n\n public enum State {\n IDLE(0.0), INTAKE(6.0), OUTTAKE(12.0);\n\n public final double voltage;\n State (double voltage) {\n this.voltage = voltage;\n }\n }\n\n private State currentState = State.IDLE;\n public State getState() {\n return currentState;\n }\n\n public void setState(State wantedState) {\n if (currentState != wantedState) {\n currentState = wantedState;\n }\n }\n\n @Override\n public void registerEnabledLoops(ILooper mEnabledLooper) {\n mEnabledLooper.register(new Loop() {\n @Override\n public void onStart(double timestamp) {\n stop();\n }\n\n @Override\n public void onLoop(double timestamp) {\n mPeriodicIO.demand = currentState.voltage;\n }\n\n @Override\n public void onStop(double timestamp) {\n stop();\n }\n });\n }\n\n @Override\n public void stop() {\n motor.stopMotor();\n setState(State.IDLE);\n }\n\n public void setOpenLoop(double voltage) {\n mPeriodicIO.demand = voltage;\n }\n\n public Request stateRequest(State requestedState) {\n return new Request() {\n @Override\n public void act() {\n setState(requestedState);\n }\n\n @Override\n public boolean isFinished() {\n return mPeriodicIO.demand == requestedState.voltage;\n }\n };\n }\n\n public static PeriodicIO mPeriodicIO;\n public static class PeriodicIO {\n // Inputs\n private double timestamp;\n private double voltage;\n private double current;\n\n // Outputs\n private double demand;\n }\n\n @Override\n public void writePeriodicOutputs() {\n motor.setVoltage(mPeriodicIO.demand);\n }\n\n @Override\n public void readPeriodicInputs() {\n mPeriodicIO.timestamp = Timer.getFPGATimestamp();\n mPeriodicIO.voltage = motor.getSupplyVoltage().getValue();\n mPeriodicIO.current = motor.getSupplyCurrent().getValue();\n }\n\n @Override\n public void outputTelemetry() {\n SmartDashboard.putNumber(\"Intake Demand\", mPeriodicIO.demand);\n SmartDashboard.putNumber(\"Intake Supplied Volts\", mPeriodicIO.voltage);\n SmartDashboard.putNumber(\"Intake Current\", mPeriodicIO.current);\n SmartDashboard.putString(\"Intake State\", currentState.toString());\n }\n}" }, { "identifier": "Superstructure", "path": "src/main/java/com/team5419/frc2023/subsystems/Superstructure.java", "snippet": "public class Superstructure extends Subsystem {\n private static Superstructure mInstance = null;\n public static Superstructure getInstance() {\n if (mInstance == null) {\n mInstance = new Superstructure();\n }\n return mInstance;\n }\n\n public final Arm arm = Arm.getInstance();\n public final Wrist wrist = Wrist.getInstance();\n public final Intake intake = Intake.getInstance();\n\n private final RequestExecuter requestExecuter = new RequestExecuter();\n\n public boolean getIsCube() {\n return isCube;\n }\n\n public void setIsCube(boolean isCube) {\n this.isCube = isCube;\n }\n\n public boolean isGroundIntaking() {\n return isGroundIntaking;\n }\n\n public void setGroundIntaking(boolean groundIntaking) {\n isGroundIntaking = groundIntaking;\n }\n\n public synchronized void request(Request r) {\n requestExecuter.request(r);\n }\n\n public boolean areAllRequestsCompleted() {\n return requestExecuter.isFinished();\n }\n\n private final Loop loop = new Loop() {\n @Override\n public void onStart(double timestamp) {\n neutralState();\n }\n\n @Override\n public void onLoop(double timestamp) {\n synchronized (Superstructure.this) {\n requestExecuter.update();\n }\n }\n\n @Override\n public void onStop(double timestamp) {\n\n }\n };\n\n @Override\n public void stop() {\n request(new EmptyRequest());\n }\n\n @Override\n public void registerEnabledLoops(ILooper enabledLooper) {\n enabledLooper.register(loop);\n }\n\n private boolean notifyDrivers = false;\n public boolean needsToNotifyDrivers() {\n if (notifyDrivers) {\n notifyDrivers = false;\n return true;\n }\n return false;\n }\n\n private boolean isCube = false;\n private boolean isGroundIntaking = true;\n\n public void neutralState() {\n request(new ParallelRequest(\n new LambdaRequest(\n () -> {\n arm.stop();\n wrist.stop();\n intake.stop();\n }\n )\n ));\n }\n\n public void stowState() {\n SuperstructureGoal state = SuperstructureGoal.STOW;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist()),\n intake.stateRequest(Intake.State.IDLE)\n ));\n }\n\n public void groundIntakeState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.GROUND_INTAKE_CUBE : SuperstructureGoal.GROUND_INTAKE_CONE;\n request(new SequentialRequest(\n new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ),\n intake.stateRequest(Intake.State.INTAKE)\n ));\n }\n\n public void shelfIntakeState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SHELF_INTAKE_CUBE : SuperstructureGoal.SHELF_INTAKE_CONE;\n request(new SequentialRequest(\n new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ),\n intake.stateRequest(Intake.State.INTAKE)\n ));\n }\n\n public void scoreL1PoseState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SCORE_CUBE_L1 : SuperstructureGoal.SCORE_CONE_L1;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ));\n }\n\n public void scoreL2PoseState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SCORE_CUBE_L2 : SuperstructureGoal.SCORE_CONE_L2;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ));\n }\n\n public void scoreL3PoseState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SCORE_CUBE_L3 : SuperstructureGoal.SCORE_CONE_L3;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ));\n }\n\n @Override\n public void outputTelemetry() {\n SmartDashboard.putBoolean(\"Is Cube\", isCube);\n SmartDashboard.putBoolean(\"Is Ground Intaking\", isGroundIntaking);\n }\n\n}" }, { "identifier": "Wrist", "path": "src/main/java/com/team5419/frc2023/subsystems/Wrist.java", "snippet": "public class Wrist extends ServoMotorSubsystem {\n public static Wrist mInstance;\n public static Wrist getInstance() {\n if (mInstance == null) {\n mInstance = new Wrist(kWristConstnats);\n }\n return mInstance;\n }\n public static final ServoMotorSubsystemConstants kWristConstnats = Constants.Wrist.kWristServoConstants;\n protected Wrist(ServoMotorSubsystemConstants constants) {\n super(constants);\n zeroSensors();\n setNeutralBrake(true);\n }\n private void setNeutralBrake(boolean isEnabled) {\n NeutralMode mode = isEnabled ? NeutralMode.Brake : NeutralMode.Coast;\n mMaster.setNeutralMode(mode);\n }\n @Override\n public void registerEnabledLoops(ILooper mEnabledLooper) {\n mEnabledLooper.register(new Loop() {\n @Override\n public void onStart(double timestamp) {\n\n }\n\n @Override\n public void onLoop(double timestamp) {\n\n }\n\n @Override\n public void onStop(double timestamp) {\n stop();\n setNeutralBrake(true);\n }\n });\n }\n\n public Request angleRequest(double angle) {\n return new Request() {\n @Override\n public void act() {\n setSetpointMotionMagic(angle);\n }\n\n @Override\n public boolean isFinished() {\n return Util.epsilonEquals(mPeriodicIO.position_units, angle, Constants.Wrist.kAngleTolerance);\n }\n };\n }\n\n}" }, { "identifier": "Xbox", "path": "src/main/java/com/team5419/lib/io/Xbox.java", "snippet": "public class Xbox extends XboxController{\n private static final double PRESS_THRESHOLD = 0.05;\n private double DEAD_BAND = 0.15;\n private boolean rumbling = false;\n public ButtonCheck aButton, bButton, xButton, yButton, startButton, backButton,\n \tleftBumper, rightBumper, leftCenterClick, rightCenterClick, leftTrigger, \n \trightTrigger, POV0, POV90, POV180, POV270, POV135, POV225;\n public static final int A_BUTTON = 1;\n public static final int B_BUTTON = 2;\n public static final int X_BUTTON = 3;\n public static final int Y_BUTTON = 4;\n public static final int LEFT_BUMPER = 5;\n public static final int RIGHT_BUMPER = 6;\n public static final int BACK_BUTTON = 7;\n public static final int START_BUTTON = 8;\n public static final int LEFT_CENTER_CLICK = 9;\n public static final int RIGHT_CENTER_CLICK = 10;\n public static final int LEFT_TRIGGER = -2;\n public static final int RIGHT_TRIGGER = -3;\n public static final int POV_0 = -4;\n public static final int POV_90 = -5;\n public static final int POV_180 = -6;\n public static final int POV_270 = -7;\n\tpublic static final int POV_135 = -8;\n\tpublic static final int POV_225 = -9;\n \n public void setDeadband(double deadband){\n \tDEAD_BAND = deadband;\n }\n \n public Xbox(int usb) { \n \tsuper(usb);\n \taButton = new ButtonCheck(A_BUTTON);\n bButton = new ButtonCheck(B_BUTTON);\n xButton = new ButtonCheck(X_BUTTON);\n yButton = new ButtonCheck(Y_BUTTON);\n startButton = new ButtonCheck(START_BUTTON);\n backButton = new ButtonCheck(BACK_BUTTON);\n leftBumper = new ButtonCheck(LEFT_BUMPER);\n rightBumper = new ButtonCheck(RIGHT_BUMPER);\n leftCenterClick = new ButtonCheck(LEFT_CENTER_CLICK);\n rightCenterClick = new ButtonCheck(RIGHT_CENTER_CLICK); \n leftTrigger = new ButtonCheck(LEFT_TRIGGER);\n rightTrigger = new ButtonCheck(RIGHT_TRIGGER);\n POV0 = new ButtonCheck(POV_0);\n POV90 = new ButtonCheck(POV_90);\n POV180 = new ButtonCheck(POV_180);\n POV270 = new ButtonCheck(POV_270);\n\t\tPOV135 = new ButtonCheck(POV_135);\n\t\tPOV225 = new ButtonCheck(POV_225);\n }\n \n @Override\n public double getLeftX() {\n\t\treturn Util.deadBand(getRawAxis(0), DEAD_BAND);\n\t}\n\n\t@Override\n\tpublic double getRightX() {\n\t\treturn Util.deadBand(getRawAxis(4), DEAD_BAND);\n\t}\n\n @Override\n public double getLeftY() {\n\t\treturn Util.deadBand(getRawAxis(1), DEAD_BAND);\n\t}\n\n\t@Override\n\tpublic double getRightY() {\n\t\treturn Util.deadBand(getRawAxis(5), DEAD_BAND);\n\t}\n\n @Override\n public double getLeftTriggerAxis() {\n\t\treturn Util.deadBand(getRawAxis(2), PRESS_THRESHOLD);\n\t}\n \n\t@Override\n\tpublic double getRightTriggerAxis() {\n\t\treturn Util.deadBand(getRawAxis(3), PRESS_THRESHOLD);\n\t}\n\n\tpublic Rotation2d getPOVDirection() {\n\t\tSystem.out.println(getPOV());\n\t\treturn Rotation2d.fromDegrees(getPOV());\n\t}\n\n public void rumble(double rumblesPerSecond, double numberOfSeconds){\n \tif(!rumbling){\n \t\tRumbleThread r = new RumbleThread(rumblesPerSecond, numberOfSeconds);\n \t\tr.start();\n \t}\n }\n public boolean isRumbling(){\n \treturn rumbling;\n }\n public class RumbleThread extends Thread{\n \tpublic double rumblesPerSec = 1;\n \tpublic long interval = 500;\n \tpublic double seconds = 1;\n \tpublic double startTime = 0;\n \tpublic RumbleThread(double rumblesPerSecond, double numberOfSeconds){\n \t\trumblesPerSec = rumblesPerSecond;\n \t\tseconds = numberOfSeconds;\n \t\tinterval =(long) (1/(rumblesPerSec*2)*1000);\n \t}\n \tpublic void run(){\n \t\trumbling = true;\n \t\tstartTime = Timer.getFPGATimestamp();\n \t\ttry{\n \t\t\twhile((Timer.getFPGATimestamp() - startTime) < seconds){\n\t\t \t\tsetRumble(RumbleType.kLeftRumble, 1);\n\t\t \t\tsetRumble(RumbleType.kRightRumble, 1);\n\t\t \t\tsleep(interval);\n\t\t \t\tsetRumble(RumbleType.kLeftRumble, 0);\n\t\t \t\tsetRumble(RumbleType.kRightRumble, 0);\n\t\t \t\tsleep(interval);\n \t\t\t}\n \t\t}catch (InterruptedException e) {\n\t\t\t\trumbling = false;\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t\trumbling = false;\n \t}\n }\n \n public class ButtonCheck{\n \tboolean buttonCheck = false;\n\t\tboolean buttonActive = false;\n\t\tboolean activationReported = false;\n \tboolean longPressed = false;\n \tboolean longPressActivated = false;\n \tboolean hasBeenPressed = false;\n \tboolean longReleased = false;\n\t\tprivate double buttonStartTime = 0;\n\t\tprivate double longPressDuration = 0.5;\n\t\tpublic void setLongPressDuration(double seconds){\n\t\t\tlongPressDuration = seconds;\n\t\t}\n \tprivate int buttonNumber;\n \t\n \tpublic ButtonCheck(int id){\n \t\tbuttonNumber = id;\n \t}\n \tpublic void update(){\n \t\tif(buttonNumber > 0){\n \t\t\tbuttonCheck = getRawButton(buttonNumber);\n \t\t}else{\n \t\t\tswitch(buttonNumber){\n \t\t\t\tcase LEFT_TRIGGER:\n \t\t\t\t\tbuttonCheck = getLeftTriggerAxis() > 0;\n \t\t\t\t\tbreak;\n \t\t\t\tcase RIGHT_TRIGGER:\n \t\t\t\t\tbuttonCheck = getRightTriggerAxis() > 0;\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_0:\n \t\t\t\t\tbuttonCheck = (getPOV() == 0);\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_90:\n \t\t\t\t\tbuttonCheck = (getPOV() == 90);\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_180:\n \t\t\t\t\tbuttonCheck = (getPOV() == 180);\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_270:\n \t\t\t\t\tbuttonCheck = (getPOV() == 270);\n \t\t\t\t\tbreak;\n\t\t\t\t\tcase POV_135:\n\t\t\t\t\t\tbuttonCheck = (getPOV() == 135);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase POV_225:\n\t\t\t\t\t\tbuttonCheck = (getPOV() == 225);\n\t\t\t\t\t\tbreak;\n \t\t\t\tdefault:\n \t\t\t\t\tbuttonCheck = false;\n \t\t\t\t\tbreak;\n \t\t\t}\n \t\t}\n \t\tif(buttonCheck){\n\t \t\tif(buttonActive){\n\t \t\t\tif(((Timer.getFPGATimestamp() - buttonStartTime) > longPressDuration) && !longPressActivated){\n\t \t\t\t\tlongPressActivated = true;\n\t\t\t\t\t\tlongPressed = true;\n\t\t\t\t\t\tlongReleased = false;\n\t \t\t\t}\n\t \t\t}else{\n\t\t\t\t\tbuttonActive = true;\n\t\t\t\t\tactivationReported = false;\n\t \t\t\tbuttonStartTime = Timer.getFPGATimestamp();\n\t \t\t}\n \t\t}else{\n \t\t\tif(buttonActive){\n\t\t\t\t\tbuttonActive = false;\n\t\t\t\t\tactivationReported = true;\n \t\t\t\tif(longPressActivated){\n \t\t\t\t\thasBeenPressed = false;\n \t\t\t\t\tlongPressActivated = false;\n \t\t\t\t\tlongPressed = false;\n \t\t\t\t\tlongReleased = true;\n \t\t\t\t}else{\n\t\t\t\t\t\thasBeenPressed = true;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n\t\t}\n\n\t\t/** Returns true once the button is pressed, regardless of\n\t\t * the activation duration. Only returns true one time per\n\t\t * button press, and is reset upon release.\n\t\t */\n\t\tpublic boolean wasActivated(){\n\t\t\tif(buttonActive && !activationReported){\n\t\t\t\tactivationReported = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t/** Returns true once the button is released after being\n\t\t * held for 0.5 seconds or less. Only returns true one time\n\t\t * per button press.\n\t\t */\n \tpublic boolean shortReleased(){\n \t\tif(hasBeenPressed){\n \t\t\thasBeenPressed = false;\n \t\t\treturn true;\n \t\t}\n \t\treturn false;\n\t\t}\n\t\t\n\t\t/** Returns true once if the button is pressed for more than 0.5 seconds.\n\t\t * Only true while the button is still depressed; it becomes false once the \n\t\t * button is released.\n\t\t */\n \tpublic boolean longPressed(){\n \t\tif(longPressed){\n \t\t\tlongPressed = false;\n \t\t\treturn true;\n \t\t}\n \t\treturn false;\n\t\t}\n\t\t\n\t\t/** Returns true one time once the button is released after being held for\n\t\t * more than 0.5 seconds.\n\t\t */\n \tpublic boolean longReleased(){\n \t\tif(longReleased){\n \t\t\tlongReleased = false;\n \t\t\treturn true;\n \t\t}\n \t\treturn false;\n\t\t}\n\n\t\t/** Returns true once the button is released, regardless of activation duration. */\n\t\tpublic boolean wasReleased(){\n\t\t\treturn shortReleased() || longReleased();\n\t\t}\n\t\t\n\t\t/** Returns true if the button is currently being pressed. */\n \tpublic boolean isBeingPressed(){\n \t\treturn buttonActive;\n \t}\n }\n public void update(){\n \taButton.update();\n \tbButton.update();\n \txButton.update();\n \tyButton.update();\n \tstartButton.update();\n \tbackButton.update();\n \tleftBumper.update();\n \trightBumper.update();\n \tleftCenterClick.update();\n \trightCenterClick.update();\n \tleftTrigger.update();\n \trightTrigger.update();\n \tPOV0.update();\n \tPOV90.update();\n \tPOV180.update();\n \tPOV270.update();\n }\n}" } ]
import com.team5419.frc2023.loops.Loop; import com.team5419.frc2023.subsystems.Arm; import com.team5419.frc2023.subsystems.Intake; import com.team5419.frc2023.subsystems.Superstructure; import com.team5419.frc2023.subsystems.Wrist; import com.team5419.lib.io.Xbox; import java.util.Arrays;
5,277
package com.team5419.frc2023; public class DriverControls implements Loop { public static DriverControls mInstance = null; public static DriverControls getInstance() { if (mInstance == null) { mInstance = new DriverControls(); } return mInstance; }
package com.team5419.frc2023; public class DriverControls implements Loop { public static DriverControls mInstance = null; public static DriverControls getInstance() { if (mInstance == null) { mInstance = new DriverControls(); } return mInstance; }
Xbox driver, operator;
5
2023-11-14 06:44:40+00:00
8k
Ouest-France/querydsl-postgrest
src/test/java/fr/ouestfrance/querydsl/postgrest/app/PostRepository.java
[ { "identifier": "PostgrestClient", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/PostgrestClient.java", "snippet": "public interface PostgrestClient {\n /**\n * Search method\n *\n * @param resource resource name\n * @param params query params\n * @param <T> return type\n * @param headers header params\n * @param clazz type of return\n * @return ResponseEntity containing the results\n */\n\n <T> Page<T> search(String resource, MultiValueMap<String, String> params,\n MultiValueMap<String, String> headers, Class<T> clazz);\n\n /**\n * Save body\n *\n * @param resource resource name\n * @param value data to save\n * @param headers headers to pass\n * @param <T> return type\n * @param clazz type of return\n * @return list of inserted objects\n */\n <T> List<T> post(String resource, List<Object> value, MultiValueMap<String, String> headers, Class<T> clazz);\n\n /**\n * Patch data\n *\n * @param resource resource name\n * @param params criteria to apply on patch\n * @param value object to patch\n * @param headers headers to pass\n * @param <T> return type\n * @param clazz type of return\n * @return list of patched objects\n */\n <T> List<T> patch(String resource, MultiValueMap<String, String> params, Object value, MultiValueMap<String, String> headers, Class<T> clazz);\n\n /**\n * Delete data\n *\n * @param resource resource name\n * @param params query params\n * @param headers headers to pass\n * @param <T> return type\n * @param clazz type of return\n * @return list of deleted objects\n */\n <T> List<T> delete(String resource, MultiValueMap<String, String> params, MultiValueMap<String, String> headers, Class<T> clazz);\n\n}" }, { "identifier": "PostgrestWebClient", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/PostgrestWebClient.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\npublic class PostgrestWebClient implements PostgrestClient {\n\n /**\n * Content type\n */\n private static final String CONTENT_TYPE = \"Content-Type\";\n\n /**\n * webClient\n */\n private final WebClient webClient;\n\n /**\n * Postgrest webclient adapter\n *\n * @param webClient webClient\n * @return PostgrestWebClient implementation\n */\n public static PostgrestWebClient of(WebClient webClient) {\n return\n new PostgrestWebClient(webClient);\n }\n\n @Override\n public <T> Page<T> search(String resource, MultiValueMap<String, String> params,\n MultiValueMap<String, String> headers, Class<T> clazz) {\n ResponseEntity<List<T>> response = webClient.get().uri(uriBuilder -> {\n uriBuilder.path(resource);\n uriBuilder.queryParams(params);\n return uriBuilder.build();\n }).headers(httpHeaders ->\n safeAdd(headers, httpHeaders)\n )\n .retrieve()\n .toEntity(listRef(clazz))\n .block();\n // Retrieve result headers\n return Optional.ofNullable(response)\n .map(HttpEntity::getBody)\n .map(x -> {\n PageImpl<T> page = new PageImpl<>(x, null, x.size(), 1);\n List<String> contentRangeHeaders = response.getHeaders().get(\"Content-Range\");\n if (contentRangeHeaders != null && !contentRangeHeaders.isEmpty()) {\n Range range = Range.of(contentRangeHeaders.stream().findFirst().toString());\n page.withRange(range);\n }\n return (Page<T>) page;\n }).orElse(Page.empty());\n }\n\n private static void safeAdd(MultiValueMap<String, String> headers, HttpHeaders httpHeaders) {\n Optional.ofNullable(headers).ifPresent(httpHeaders::addAll);\n // Add contentType with default on call if webclient default is not set\n httpHeaders.put(CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE));\n }\n\n @Override\n public <T> List<T> post(String resource, List<Object> value, MultiValueMap<String, String> headers, Class<T> clazz) {\n return webClient.post().uri(uriBuilder -> {\n uriBuilder.path(resource);\n return uriBuilder.build();\n }).headers(httpHeaders -> safeAdd(headers, httpHeaders))\n .bodyValue(value)\n .retrieve()\n .bodyToMono(listRef(clazz))\n .block();\n }\n\n\n @Override\n public <T> List<T> patch(String resource, MultiValueMap<String, String> params, Object value, MultiValueMap<String, String> headers, Class<T> clazz) {\n return webClient.patch().uri(uriBuilder -> {\n uriBuilder.path(resource);\n uriBuilder.queryParams(params);\n return uriBuilder.build();\n })\n .bodyValue(value)\n .headers(httpHeaders -> safeAdd(headers, httpHeaders))\n .retrieve()\n .bodyToMono(listRef(clazz)).block();\n }\n\n @Override\n public <T> List<T> delete(String resource, MultiValueMap<String, String> params, MultiValueMap<String, String> headers, Class<T> clazz) {\n return webClient.delete().uri(uriBuilder -> {\n uriBuilder.path(resource);\n uriBuilder.queryParams(params);\n return uriBuilder.build();\n }).headers(httpHeaders -> safeAdd(headers, httpHeaders))\n .retrieve()\n .bodyToMono(listRef(clazz)).block();\n }\n\n private static <T> ParameterizedTypeReference<List<T>> listRef(Class<T> clazz) {\n return ParameterizedTypeReference.forType(TypeUtils.parameterize(List.class, clazz));\n }\n\n\n}" }, { "identifier": "PostgrestRepository", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/PostgrestRepository.java", "snippet": "public class PostgrestRepository<T> implements Repository<T> {\n\n private final QueryDslProcessorService<Filter> processorService = new PostgrestQueryProcessorService();\n private final PostgrestConfiguration annotation;\n private final Map<Header.Method, MultiValueMap<String, String>> headersMap = new EnumMap<>(Header.Method.class);\n private final PostgrestClient client;\n private final Class<T> clazz;\n\n /**\n * Postgrest Repository constructor\n *\n * @param client webClient adapter\n */\n public PostgrestRepository(PostgrestClient client) {\n this.client = client;\n if (!getClass().isAnnotationPresent(PostgrestConfiguration.class)) {\n throw new MissingConfigurationException(getClass(),\n \"Missing annotation \" + PostgrestConfiguration.class.getSimpleName());\n }\n annotation = getClass().getAnnotation(PostgrestConfiguration.class);\n // Create headerMap\n Arrays.stream(getClass().getAnnotationsByType(Header.class)).forEach(header -> Arrays.stream(header.methods())\n .forEach(method ->\n headersMap.computeIfAbsent(method, x -> new LinkedMultiValueMap<>())\n .addAll(header.key(), Arrays.asList(header.value()))\n )\n );\n //noinspection unchecked\n clazz = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), PostgrestRepository.class);\n }\n\n @Override\n public Page<T> search(Object criteria, Pageable pageable) {\n List<Filter> queryParams = processorService.process(criteria);\n MultiValueMap<String, String> headers = headerMap(Header.Method.GET);\n // Add pageable if present\n if (pageable.getPageSize() > 0) {\n headers.add(\"Range-Unit\", \"items\");\n headers.add(\"Range\", pageable.toRange());\n headers.add(\"Prefers\", \"count=\" + annotation.countStrategy().name().toLowerCase());\n }\n // Add sort if present\n if (pageable.getSort() != null) {\n queryParams.add(OrderFilter.of(pageable.getSort()));\n }\n // Add select criteria\n getSelects(criteria).ifPresent(queryParams::add);\n Page<T> response = client.search(annotation.resource(), toMap(queryParams), headers, clazz);\n if (response instanceof PageImpl<T> page) {\n page.setPageable(pageable);\n }\n // Retrieve result headers\n return response;\n }\n\n @Override\n public List<T> upsert(List<Object> values) {\n return client.post(annotation.resource(), values, headerMap(Header.Method.UPSERT), clazz);\n }\n\n\n @Override\n public List<T> patch(Object criteria, Object body) {\n List<Filter> queryParams = processorService.process(criteria);\n // Add select criteria\n getSelects(criteria).ifPresent(queryParams::add);\n return client.patch(annotation.resource(), toMap(queryParams), body, headerMap(Header.Method.UPSERT), clazz);\n }\n\n\n @Override\n public List<T> delete(Object criteria) {\n List<Filter> queryParams = processorService.process(criteria);\n // Add select criteria\n getSelects(criteria).ifPresent(queryParams::add);\n return client.delete(annotation.resource(), toMap(queryParams), headerMap(Header.Method.DELETE), clazz);\n }\n\n /**\n * Transform a filter list to map of queryString\n *\n * @param filters list of filters\n * @return map of query strings\n */\n private MultiValueMap<String, String> toMap(List<Filter> filters) {\n MultiValueMap<String, String> map = new LinkedMultiValueMap<>();\n filters.forEach(x -> map.add(x.getKey(), x.getFilterString()));\n return map;\n }\n\n\n /**\n * Extract selection on criteria and class\n *\n * @param criteria search criteria\n * @return attributes\n */\n private Optional<Filter> getSelects(Object criteria) {\n List<SelectFilter.Attribute> attributes = new ArrayList<>();\n Select[] clazzAnnotation = getClass().getAnnotationsByType(Select.class);\n if (clazzAnnotation.length > 0) {\n attributes.addAll(Arrays.stream(clazzAnnotation).map(x -> new SelectFilter.Attribute(x.alias(), x.value())).toList());\n }\n if (criteria != null) {\n Select[] criteriaAnnotation = criteria.getClass().getAnnotationsByType(Select.class);\n if (criteriaAnnotation.length > 0) {\n attributes.addAll(Arrays.stream(criteriaAnnotation).map(x -> new SelectFilter.Attribute(x.alias(), x.value())).toList());\n }\n }\n if (attributes.isEmpty()) {\n return Optional.empty();\n }\n return Optional.of(SelectFilter.of(attributes));\n }\n\n /**\n * Find one object using criteria, method can return one or empty\n *\n * @param criteria search criteria\n * @return Optional result\n * @throws PostgrestRequestException when search criteria result gave more than one item\n */\n public Optional<T> findOne(Object criteria) {\n Page<T> search = search(criteria);\n if (search.getTotalElements() > 1) {\n throw new PostgrestRequestException(annotation.resource(),\n \"Search with params \" + criteria + \" must found only one result, but found \" + search.getTotalElements() + \" results\");\n }\n return search.stream().findFirst();\n }\n\n /**\n * Get one object using criteria, method should return the response\n *\n * @param criteria search criteria\n * @return Result object\n * @throws PostgrestRequestException no element found, or more than one item\n */\n public T getOne(Object criteria) {\n return findOne(criteria).orElseThrow(\n () -> new PostgrestRequestException(annotation.resource(),\n \"Search with params \" + criteria + \" must return one result, but found 0\"));\n }\n\n /**\n * Retrieve headerMap for a specific method\n *\n * @param method method\n * @return header map\n */\n private MultiValueMap<String, String> headerMap(Header.Method method) {\n return Optional.ofNullable(headersMap.get(method)).orElse(new LinkedMultiValueMap<>());\n }\n}" }, { "identifier": "Prefer", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Prefer.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class Prefer {\n\n /**\n * Prefer Header key\n */\n public static final String HEADER = \"Prefer\";\n\n\n /**\n * Return Representation\n * The return preference can be used to obtain information about affected resource when it’s inserted, updated or deleted.\n * This helps avoid a subsequent GET request.\n */\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class Return {\n /**\n * With Prefer: return=minimal, no response body will be returned. This is the default mode for all write requests.\n */\n public static final String MINIMAL = \"return=minimal\";\n /**\n * Headers Only\n * If the table has a primary key, the response can contain a Location header describing where to find the new object\n * by including the header Prefer: return=headers-only in the request.\n * Make sure that the table is not write-only,\n * otherwise constructing the Location header will cause a permission error.\n */\n public static final String HEADERS_ONLY = \"return=headers-only\";\n /**\n * On the other end of the spectrum you can get the full created object back in the response to your request\n * by including the header Prefer: return=representation.\n * That way you won’t have to make another HTTP call to discover properties that may have been filled in on the server side\n */\n public static final String REPRESENTATION = \"return=representation\";\n\n }\n\n\n /**\n * Any missing columns in the payload will be inserted as null values\n * To use the DEFAULT column value instead, use the Prefer: missing=default header.\n */\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class Missing {\n\n /**\n * To use the DEFAULT column value instead of null, use the Prefer: missing=default header.\n */\n public static final String REPRESENTATION = \"missing=default\";\n }\n\n /**\n * Upsert resolution\n * You can make an upsert with POST and the Prefer: resolution=merge-duplicates header:\n * By default, upsert operates based on the primary key columns, you must specify all of them\n */\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class Resolution {\n\n /**\n * You can make an upsert with POST and the Prefer: resolution=merge-duplicates header\n */\n public static final String MERGE_DUPLICATES = \"resolution=merge_duplicates\";\n /**\n * You can also choose to ignore the duplicates with Prefer: resolution=ignore-duplicates\n */\n public static final String IGNORE_DUPLICATES = \"resolution=ignore_duplicates\";\n }\n}" } ]
import fr.ouestfrance.querydsl.postgrest.PostgrestClient; import fr.ouestfrance.querydsl.postgrest.PostgrestWebClient; import fr.ouestfrance.querydsl.postgrest.PostgrestRepository; import fr.ouestfrance.querydsl.postgrest.annotations.Header; import fr.ouestfrance.querydsl.postgrest.annotations.PostgrestConfiguration; import fr.ouestfrance.querydsl.postgrest.annotations.Select; import fr.ouestfrance.querydsl.postgrest.model.Prefer; import static fr.ouestfrance.querydsl.postgrest.annotations.Header.Method.UPSERT;
3,765
package fr.ouestfrance.querydsl.postgrest.app; @PostgrestConfiguration(resource = "posts") @Select("authors(*)") @Header(key = Prefer.HEADER, value = Prefer.Return.REPRESENTATION) @Header(key = Prefer.HEADER, value = Prefer.Resolution.MERGE_DUPLICATES, methods = UPSERT) public class PostRepository extends PostgrestRepository<Post> {
package fr.ouestfrance.querydsl.postgrest.app; @PostgrestConfiguration(resource = "posts") @Select("authors(*)") @Header(key = Prefer.HEADER, value = Prefer.Return.REPRESENTATION) @Header(key = Prefer.HEADER, value = Prefer.Resolution.MERGE_DUPLICATES, methods = UPSERT) public class PostRepository extends PostgrestRepository<Post> {
public PostRepository(PostgrestClient client) {
0
2023-11-14 10:45:54+00:00
8k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/tasks/ClearAppSettings.java
[ { "identifier": "APKEditorUtils", "path": "app/src/main/java/com/threethan/questpatcher/utils/APKEditorUtils.java", "snippet": "public class APKEditorUtils {\n\n public static int getThemeAccentColor(Context context) {\n TypedValue value = new TypedValue();\n context.getTheme().resolveAttribute(R.attr.colorAccent, value, true);\n return value.data;\n }\n\n public static boolean isFullVersion(Context context) {\n return true;\n }\n\n public static CharSequence fromHtml(String text) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n return Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);\n } else {\n return Html.fromHtml(text);\n }\n }\n\n public static void unzip(String zip, String path) {\n try (ZipFile zipFile = new ZipFile(zip)) {\n zipFile.extractAll(path);\n } catch (IOException ignored) {\n }\n }\n\n public static void zip(File path, File zip) {\n try (ZipFile zipFile = new ZipFile(zip)) {\n for (File mFile : Objects.requireNonNull(path.listFiles())) {\n if (mFile.isDirectory()) {\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setCompressionMethod(CompressionMethod.STORE);\n zipFile.addFolder(mFile, zipParameters);\n } else {\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setCompressionMethod(CompressionMethod.STORE);\n zipFile.addFile(mFile, zipParameters);\n }\n }\n } catch (IOException ignored) {\n }\n }\n\n public static boolean isDocumentsUI(Uri uri) {\n return \"com.android.providers.downloads.documents\".equals(uri.getAuthority());\n }\n\n}" }, { "identifier": "AppSettings", "path": "app/src/main/java/com/threethan/questpatcher/utils/AppSettings.java", "snippet": "public class AppSettings {\n\n public static int getAPKSignPosition(Context context) {\n if (isCustomKey(context)) {\n return 1;\n } else {\n return 0;\n }\n }\n\n private static int getAppLanguagePosition(Context context) {\n for (int i = 0; i < getAppLanguageMenu(context).length; i++) {\n if (getLanguage(context).equals(getAppLanguageMenu(context)[i])) {\n return i;\n }\n }\n return 0;\n }\n\n public static int getProjectExitingMenuPosition(Context context) {\n for (int i = 0; i < getProjectExitingMenu(context).length; i++) {\n if (getProjectExistAction(context).equals(getProjectExitingMenu(context)[i])) {\n return i;\n }\n }\n return 2;\n }\n\n public static int getExportAPKsPathPosition(Context context) {\n if (getExportAPKsPath(context).equals(context.getString(R.string.export_path_default))) {\n return 1;\n } else {\n return 0;\n }\n }\n\n public static int getExportPathPosition(Context context) {\n for (int i = 0; i < getExportPathMenu(context).length; i++) {\n if (getExportPath(context).equals(getExportPathMenu(context)[i])) {\n return i;\n }\n }\n return 2;\n }\n\n public static int getExportingAPKsPosition(Context context) {\n for (int i = 0; i < getExportingAPKMenu(context).length; i++) {\n if (getAPKs(context).equals(getExportingAPKMenu(context)[i])) {\n return i;\n }\n }\n return 2;\n }\n\n public static int getInstallerMenuPosition(Context context) {\n for (int i = 0; i < getInstallerMenu(context).length; i++) {\n if (getInstallerAction(context).equals(getInstallerMenu(context)[i])) {\n return i;\n }\n }\n return 2;\n }\n\n public static List<sSerializableItems> getCredits(Context context) {\n List<sSerializableItems> mData = new ArrayList<>();\n mData.add(new sSerializableItems(null, \"Willi Ye\", \"Kernel Adiutor\", \"https://github.com/Grarak/KernelAdiutor\"));\n mData.add(new sSerializableItems(null, \"Srikanth Reddy Lingala\", \"Zip4j\", \"https://github.com/srikanth-lingala/zip4j\"));\n mData.add(new sSerializableItems(null, \"Aefyr\", \"SAI\", \"https://github.com/Aefyr/SAI\"));\n if (APKEditorUtils.isFullVersion(context)) {\n mData.add(new sSerializableItems(null, \"Google\", \"apksig\", \"https://android.googlesource.com/platform/tools/apksig\"));\n }\n mData.add(new sSerializableItems(null, \"Connor Tumbleson\", \"Apktool\", \"https://github.com/iBotPeaches/Apktool/\"));\n mData.add(new sSerializableItems(null, \"Ben Gruver\", \"smali/baksmali\", \"https://github.com/JesusFreke/smali/\"));\n mData.add(new sSerializableItems(null, \"sunilpaulmathew\", \"Package Manager\", \"https://github.com/SmartPack/PackageManager\"));\n mData.add(new sSerializableItems(null, \"Gospel Gilbert\", \"App Icon\", \"https://t.me/gilgreat0295\"));\n mData.add(new sSerializableItems(null, \"Mohammed Qubati\", \"Arabic Translation\", \"https://t.me/Alqubati_MrK\"));\n mData.add(new sSerializableItems(null, \"wushidi\", \"Chinese (Simplified) Translation\", \"https://t.me/wushidi\"));\n mData.add(new sSerializableItems(null, \"fossdd\", \"German Translation\", \"https://chaos.social/@fossdd\"));\n mData.add(new sSerializableItems(null, \"bruh\", \"Vietnamese Translation\", null));\n mData.add(new sSerializableItems(null, \"Bruno\", \"French Translation\", null));\n mData.add(new sSerializableItems(null, \"Miloš Koliáš\", \"Czech Translation\", null));\n mData.add(new sSerializableItems(null, \"Mehmet Un\", \"Turkish Translation\", null));\n mData.add(new sSerializableItems(null, \"Jander Mander\", \"Arabic Translation\", null));\n mData.add(new sSerializableItems(null, \"Diego\", \"Spanish Translation\", \"https://github.com/sguinetti\"));\n mData.add(new sSerializableItems(null, \"tommynok\", \"Russian Translation\", null));\n mData.add(new sSerializableItems(null, \"Alexander Steiner\", \"Russian Translation\", null));\n mData.add(new sSerializableItems(null, \"Hoa Gia Đại Thiếu\", \"Vietnamese Translation\", null));\n mData.add(new sSerializableItems(null, \"mezysinc\", \"Portuguese (Brazilian) Translation\", \"https://github.com/mezysinc\"));\n mData.add(new sSerializableItems(null, \"Andreaugustoqueiroz999\", \"Portuguese (Portugal) Translation\", null));\n mData.add(new sSerializableItems(null, \"Dodi Studio\", \"Indonesian Translation\", \"null\"));\n mData.add(new sSerializableItems(null, \"Cooky\", \"Polish Translation\", null));\n mData.add(new sSerializableItems(null, \"Erős Pista\", \"Hungarian Translation\", null));\n mData.add(new sSerializableItems(null, \"Andrii Chvalov\", \"Ukrainian Translation\", \"null\"));\n mData.add(new sSerializableItems(null, \"Veydzher\", \"Ukrainian Translation\", null));\n mData.add(new sSerializableItems(null, \"يمني\", \"Arabic (UAE) Translation\", null));\n mData.add(new sSerializableItems(null, \"Thibault Pitoiset\", \"French (Belgium) Translation\", \"null\"));\n mData.add(new sSerializableItems(null, \"Mohd Ayan\", \"Hindi Translation\", null));\n mData.add(new sSerializableItems(null, \"tas\", \"Lithuanian Translation\", null));\n mData.add(new sSerializableItems(null, \"vuvov11\", \"Thai Translation\", null));\n mData.add(new sSerializableItems(null, \"Me\", \"Arabic (SA) Translation\", null));\n mData.add(new sSerializableItems(null, \"asdfqw\", \"Chinese (zh-Hans) Translation\", null));\n mData.add(new sSerializableItems(null, \"Fsotm. mai\", \"Chinese (zh-Hans) Translation\", null));\n mData.add(new sSerializableItems(null, \"sardonicdozen\", \"Chinese (zh-Hans) Translation\", null));\n mData.add(new sSerializableItems(null, \"始\", \"Chinese (zh-Hans) Translation\", null));\n return mData;\n }\n\n public static String getLanguage(Context context) {\n switch (sThemeUtils.getLanguage(context)) {\n case \"en_US\":\n return context.getString(R.string.language_en);\n case \"ar\":\n return context.getString(R.string.language_ar);\n case \"fr\":\n return context.getString(R.string.language_fr);\n case \"de\":\n return context.getString(R.string.language_de);\n case \"vi\":\n return context.getString(R.string.language_vi);\n case \"zh\":\n return context.getString(R.string.language_zh);\n case \"cs\":\n return context.getString(R.string.language_cs);\n case \"tr\":\n return context.getString(R.string.language_tr);\n case \"es\":\n return context.getString(R.string.language_es);\n case \"ru\":\n return context.getString(R.string.language_ru);\n case \"pl\":\n return context.getString(R.string.language_pl);\n case \"in\":\n return context.getString(R.string.language_in);\n case \"hu\":\n return context.getString(R.string.language_hu);\n case \"uk\":\n return context.getString(R.string.language_uk);\n case \"hi\":\n return context.getString(R.string.language_hi);\n case \"lt\":\n return context.getString(R.string.language_lt);\n case \"th\":\n return context.getString(R.string.language_th);\n default:\n return context.getString(R.string.app_theme_auto);\n }\n }\n\n public static String getExportAPKsPath(Context context) {\n String exportAPKPath = sCommonUtils.getString(\"exportAPKsPath\", \"externalFiles\", context);\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && exportAPKPath.equals(\"internalStorage\")) {\n return context.getString(R.string.export_path_default);\n } else {\n return context.getString(R.string.export_path_files_dir);\n }\n }\n\n public static String getExportPath(Context context) {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {\n if (sCommonUtils.getString(\"exportPath\", null, context) != null && sCommonUtils.getString(\"exportPath\", null, context).equals(Environment.getExternalStorageDirectory().toString())) {\n return context.getString(R.string.sdcard);\n } else if (sCommonUtils.getString(\"exportPath\", null, context) != null && sCommonUtils.getString(\"exportPath\", null, context).equals(Environment.getExternalStorageDirectory().toString() + \"/AEE\")) {\n return context.getString(R.string.export_path_default);\n } else {\n return context.getString(R.string.export_path_download);\n }\n } else {\n return context.getString(R.string.export_path_download);\n }\n }\n\n public static String getAPKs(Context context) {\n if (sCommonUtils.getString(\"exportAPKs\", null, context) != null) {\n return sCommonUtils.getString(\"exportAPKs\", null, context);\n } else {\n return context.getString(R.string.prompt);\n }\n }\n\n public static String getProjectExistAction(Context context) {\n if (sCommonUtils.getString(\"projectAction\", null, context) != null) {\n return sCommonUtils.getString(\"projectAction\", null, context);\n } else {\n return context.getString(R.string.prompt);\n }\n }\n\n public static String getInstallerAction(Context context) {\n if (sCommonUtils.getString(\"installerAction\", null, context) != null) {\n return sCommonUtils.getString(\"installerAction\", null, context);\n } else {\n return context.getString(R.string.prompt);\n }\n }\n\n public static String getAPKSign(Context context) {\n if (isCustomKey(context)) {\n return context.getString(R.string.sign_apk_custom);\n } else {\n return context.getString(R.string.sign_apk_default);\n }\n }\n\n private static String[] getAppLanguageMenu(Context context) {\n return new String[] {\n context.getString(R.string.app_theme_auto),\n context.getString(R.string.language_ar),\n context.getString(R.string.language_zh),\n context.getString(R.string.language_cs),\n context.getString(R.string.language_de),\n context.getString(R.string.language_en),\n context.getString(R.string.language_fr),\n context.getString(R.string.language_es),\n context.getString(R.string.language_ru),\n context.getString(R.string.language_tr),\n context.getString(R.string.language_vi),\n context.getString(R.string.language_pl),\n context.getString(R.string.language_in),\n context.getString(R.string.language_hu),\n context.getString(R.string.language_uk),\n context.getString(R.string.language_hi),\n context.getString(R.string.language_lt),\n context.getString(R.string.language_th)\n };\n }\n\n public static String[] getProjectExitingMenu(Context context) {\n return new String[] {\n context.getString(R.string.save),\n context.getString(R.string.delete),\n context.getString(R.string.prompt)\n };\n }\n\n public static String[] getAPKExportPathMenu(Context context) {\n return new String[] {\n context.getString(R.string.export_path_files_dir),\n context.getString(R.string.export_path_default)\n };\n }\n\n public static String[] getExportPathMenu(Context context) {\n if (Build.VERSION.SDK_INT < 29) {\n return new String[]{\n context.getString(R.string.sdcard),\n context.getString(R.string.export_path_default),\n context.getString(R.string.export_path_download)\n };\n } else {\n return new String[]{\n context.getString(R.string.export_path_download)\n };\n }\n }\n\n public static String[] getExportingAPKMenu(Context context) {\n return new String[] {\n context.getString(R.string.export_storage),\n context.getString(R.string.export_resign),\n context.getString(R.string.prompt)\n };\n }\n\n public static String[] getInstallerMenu(Context context) {\n return new String[] {\n context.getString(R.string.install),\n context.getString(R.string.install_resign),\n context.getString(R.string.prompt)\n };\n }\n\n public static void setLanguage(Context context) {\n new sSingleChoiceDialog(R.drawable.ic_translate, context.getString(R.string.language),\n getAppLanguageMenu(context), getAppLanguagePosition(context), context) {\n\n @Override\n public void onItemSelected(int itemPosition) {\n switch (itemPosition) {\n case 0:\n sCommonUtils.saveString(\"appLanguage\", java.util.Locale.getDefault().getLanguage(), context);\n restartApp(context);\n break;\n case 1:\n sCommonUtils.saveString(\"appLanguage\", \"ar\", context);\n restartApp(context);\n break;\n case 2:\n sCommonUtils.saveString(\"appLanguage\", \"zh\", context);\n restartApp(context);\n break;\n case 3:\n sCommonUtils.saveString(\"appLanguage\", \"cs\", context);\n restartApp(context);\n break;\n case 4:\n sCommonUtils.saveString(\"appLanguage\", \"de\", context);\n restartApp(context);\n break;\n case 5:\n sCommonUtils.saveString(\"appLanguage\", \"en_US\", context);\n restartApp(context);\n break;\n case 6:\n sCommonUtils.saveString(\"appLanguage\", \"fr\", context);\n restartApp(context);\n break;\n case 7:\n sCommonUtils.saveString(\"appLanguage\", \"es\", context);\n restartApp(context);\n break;\n case 8:\n sCommonUtils.saveString(\"appLanguage\", \"ru\", context);\n restartApp(context);\n break;\n case 9:\n sCommonUtils.saveString(\"appLanguage\", \"tr\", context);\n restartApp(context);\n break;\n case 10:\n sCommonUtils.saveString(\"appLanguage\", \"vi\", context);\n restartApp(context);\n break;\n case 11:\n sCommonUtils.saveString(\"appLanguage\", \"pl\", context);\n restartApp(context);\n break;\n case 12:\n sCommonUtils.saveString(\"appLanguage\", \"in\", context);\n restartApp(context);\n break;\n case 13:\n sCommonUtils.saveString(\"appLanguage\", \"hu\", context);\n restartApp(context);\n break;\n case 14:\n sCommonUtils.saveString(\"appLanguage\", \"uk\", context);\n restartApp(context);\n break;\n case 15:\n sCommonUtils.saveString(\"appLanguage\", \"hi\", context);\n restartApp(context);\n break;\n case 16:\n sCommonUtils.saveString(\"appLanguage\", \"lt\", context);\n restartApp(context);\n break;\n case 17:\n sCommonUtils.saveString(\"appLanguage\", \"th\", context);\n restartApp(context);\n break;\n }\n }\n }.show();\n }\n\n public static boolean isCustomKey(Context context) {\n return sCommonUtils.getString(\"PrivateKey\", null, context) != null &&\n sCommonUtils.getString(\"X509Certificate\", null, context) != null;\n }\n\n private static void restartApp(Context context) {\n Intent intent = new Intent(context, MainActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n context.startActivity(intent);\n }\n\n}" } ]
import android.app.Activity; import android.app.ProgressDialog; import com.threethan.questpatcher.R; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.AppSettings; import java.io.File; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
4,482
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <[email protected]> on January 28, 2023 */ public class ClearAppSettings extends sExecutor { private final Activity mActivity; private ProgressDialog mProgressDialog; public ClearAppSettings(Activity activity) { mActivity = activity; } @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mActivity); mProgressDialog.setMessage(mActivity.getString(R.string.clearing_cache_message)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override public void doInBackground() { sFileUtils.delete(mActivity.getCacheDir()); sFileUtils.delete(mActivity.getFilesDir());
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <[email protected]> on January 28, 2023 */ public class ClearAppSettings extends sExecutor { private final Activity mActivity; private ProgressDialog mProgressDialog; public ClearAppSettings(Activity activity) { mActivity = activity; } @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mActivity); mProgressDialog.setMessage(mActivity.getString(R.string.clearing_cache_message)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override public void doInBackground() { sFileUtils.delete(mActivity.getCacheDir()); sFileUtils.delete(mActivity.getFilesDir());
if (APKEditorUtils.isFullVersion(mActivity) && AppSettings.isCustomKey(mActivity)) {
1
2023-11-18 15:13:30+00:00
8k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/client/HarborClientImpl.java
[ { "identifier": "HarborException", "path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java", "snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public HarborException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "Artifact", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Artifact.java", "snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class Artifact {\n private long id;\n private String type;\n private String mediaType;\n private String manifestMediaType;\n private String projectId;\n private String repositoryId;\n private String repositoryName;\n private String digest;\n private long size;\n private String icon;\n private Date pushTime;\n private Date pullTime;\n private HashMap<String, Object> extraAttrs;\n private String annotations;\n private String references;\n\n @JsonIgnore\n private String tags;\n\n @JsonIgnore\n private HashMap<String, AdditionLink> additionLinks;\n\n private String labels;\n\n @SuppressWarnings(\"lgtm[jenkins/plaintext-storage]\")\n private String accessories;\n\n private HashMap<String, NativeReportSummary> scanOverview;\n\n public String getMediaType() {\n return mediaType;\n }\n\n @JsonProperty(\"media_type\")\n public void setMediaType(String mediaType) {\n this.mediaType = mediaType;\n }\n\n public long getSize() {\n return size;\n }\n\n public void setSize(long size) {\n this.size = size;\n }\n\n public Date getPushTime() {\n return pushTime;\n }\n\n @JsonProperty(\"push_time\")\n public void setPushTime(Date pushTime) {\n this.pushTime = pushTime;\n }\n\n public String getTags() {\n return tags;\n }\n\n public void setTags(String tags) {\n this.tags = tags;\n }\n\n public HashMap<String, NativeReportSummary> getScanOverview() {\n return scanOverview;\n }\n\n @JsonProperty(\"scan_overview\")\n public void setScanOverview(HashMap<String, NativeReportSummary> scanOverview) {\n this.scanOverview = scanOverview;\n }\n\n public Date getPullTime() {\n return pullTime;\n }\n\n @JsonProperty(\"pull_time\")\n public void setPullTime(Date pullTime) {\n this.pullTime = pullTime;\n }\n\n public String getLabels() {\n return labels;\n }\n\n public void setLabels(String labels) {\n this.labels = labels;\n }\n\n public String getAccessories() {\n return accessories;\n }\n\n public void setAccessories(String accessories) {\n this.accessories = accessories;\n }\n\n public String getReferences() {\n return references;\n }\n\n public void setReferences(String references) {\n this.references = references;\n }\n\n public String getManifestMediaType() {\n return manifestMediaType;\n }\n\n @JsonProperty(\"manifest_media_type\")\n public void setManifestMediaType(String manifestMediaType) {\n this.manifestMediaType = manifestMediaType;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getDigest() {\n return digest;\n }\n\n public void setDigest(String digest) {\n this.digest = digest;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public void setIcon(String icon) {\n this.icon = icon;\n }\n\n public String getRepositoryId() {\n return repositoryId;\n }\n\n @JsonProperty(\"repository_id\")\n public void setRepositoryId(String repositoryId) {\n this.repositoryId = repositoryId;\n }\n\n public HashMap<String, AdditionLink> getAdditionLinks() {\n return additionLinks;\n }\n\n @JsonProperty(\"addition_links\")\n public void setAdditionLinks(HashMap<String, AdditionLink> additionLinks) {\n this.additionLinks = additionLinks;\n }\n\n public String getProjectId() {\n return projectId;\n }\n\n @JsonProperty(\"project_id\")\n public void setProjectId(String projectId) {\n this.projectId = projectId;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getAnnotations() {\n return annotations;\n }\n\n public void setAnnotations(String annotations) {\n this.annotations = annotations;\n }\n\n public HashMap<String, Object> getExtraAttrs() {\n return extraAttrs;\n }\n\n @JsonProperty(\"extra_attrs\")\n public void setExtraAttrs(HashMap<String, Object> extraAttrs) {\n this.extraAttrs = extraAttrs;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n @JsonProperty(\"repository_name\")\n public void setRepositoryName(String repositoryName) {\n this.repositoryName = repositoryName;\n }\n}" }, { "identifier": "NativeReportSummary", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/NativeReportSummary.java", "snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class NativeReportSummary {\n private String reportId;\n\n private VulnerabilityScanStatus ScanStatus;\n\n private Severity severity;\n\n private long duration;\n\n private VulnerabilitySummary summary;\n\n private ArrayList<String> cvebypassed;\n\n private Date StartTime;\n\n private Date EndTime;\n\n private Scanner scanner;\n\n private int completePercent;\n\n @JsonIgnore\n private int totalCount;\n\n @JsonIgnore\n private int completeCount;\n\n @JsonIgnore\n private VulnerabilityItemList vulnerabilityItemList;\n\n public String getReportId() {\n return reportId;\n }\n\n @JsonProperty(\"report_id\")\n public void setReportId(String reportId) {\n this.reportId = reportId;\n }\n\n public VulnerabilityScanStatus getScanStatus() {\n return ScanStatus;\n }\n\n @JsonProperty(\"scan_status\")\n public void setScanStatus(VulnerabilityScanStatus scanStatus) {\n ScanStatus = scanStatus;\n }\n\n public Severity getSeverity() {\n return severity;\n }\n\n public void setSeverity(Severity severity) {\n this.severity = severity;\n }\n\n public long getDuration() {\n return duration;\n }\n\n public void setDuration(long duration) {\n this.duration = duration;\n }\n\n public VulnerabilitySummary getSummary() {\n return summary;\n }\n\n public void setSummary(VulnerabilitySummary summary) {\n this.summary = summary;\n }\n\n public ArrayList<String> getCvebypassed() {\n return cvebypassed;\n }\n\n @JsonIgnore\n public void setCvebypassed(ArrayList<String> cvebypassed) {\n this.cvebypassed = cvebypassed;\n }\n\n public Date getStartTime() {\n return StartTime;\n }\n\n @JsonProperty(\"start_time\")\n public void setStartTime(Date startTime) {\n StartTime = startTime;\n }\n\n public Date getEndTime() {\n return EndTime;\n }\n\n @JsonProperty(\"end_time\")\n public void setEndTime(Date endTime) {\n EndTime = endTime;\n }\n\n public Scanner getScanner() {\n return scanner;\n }\n\n public void setScanner(Scanner scanner) {\n this.scanner = scanner;\n }\n\n public int getCompletePercent() {\n return completePercent;\n }\n\n @JsonProperty(\"complete_percent\")\n public void setCompletePercent(int completePercent) {\n this.completePercent = completePercent;\n }\n\n public int getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(int totalCount) {\n this.totalCount = totalCount;\n }\n\n public int getCompleteCount() {\n return completeCount;\n }\n\n public void setCompleteCount(int completeCount) {\n this.completeCount = completeCount;\n }\n\n public VulnerabilityItemList getVulnerabilityItemList() {\n return vulnerabilityItemList;\n }\n\n public void setVulnerabilityItemList(VulnerabilityItemList vulnerabilityItemList) {\n this.vulnerabilityItemList = vulnerabilityItemList;\n }\n}" }, { "identifier": "Repository", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Repository.java", "snippet": "public class Repository {\n private Integer id;\n private String name;\n\n @JsonProperty(\"artifact_count\")\n private Integer artifactCount;\n\n @JsonProperty(\"project_id\")\n private Integer projectId;\n\n @JsonProperty(\"pull_count\")\n private Integer pullCount;\n\n @JsonProperty(\"creation_time\")\n private String creationTime;\n\n @JsonProperty(\"update_time\")\n private String updateTime;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer 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 Integer getArtifactCount() {\n return artifactCount;\n }\n\n public void setArtifactCount(Integer artifactCount) {\n this.artifactCount = artifactCount;\n }\n\n public String getCreationTime() {\n return creationTime;\n }\n\n public void setCreationTime(String creationTime) {\n this.creationTime = creationTime;\n }\n\n public Integer getProjectId() {\n return projectId;\n }\n\n public void setProjectId(Integer projectId) {\n this.projectId = projectId;\n }\n\n public Integer getPullCount() {\n return pullCount;\n }\n\n public void setPullCount(Integer pullCount) {\n this.pullCount = pullCount;\n }\n\n public String getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(String updateTime) {\n this.updateTime = updateTime;\n }\n}" }, { "identifier": "HarborConstants", "path": "src/main/java/io/jenkins/plugins/harbor/util/HarborConstants.java", "snippet": "public class HarborConstants {\n public static final String HarborVulnerabilityReportV11MimeType =\n \"application/vnd.security.vulnerability.report; version=1.1\";\n public static final String HarborVulnReportv1MimeType =\n \"application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0\";\n}" }, { "identifier": "JsonParser", "path": "src/main/java/io/jenkins/plugins/harbor/util/JsonParser.java", "snippet": "public final class JsonParser {\n private static final ObjectMapper objectMapper = new ObjectMapper()\n .setDateFormat(new StdDateFormat())\n .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\n public static <T> T toJava(String data, Class<T> type) throws JsonProcessingException {\n return objectMapper.readValue(data, type);\n }\n}" } ]
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.damnhandy.uri.template.UriTemplate; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.cli.NoCheckTrustManager; import io.jenkins.plugins.harbor.HarborException; import io.jenkins.plugins.harbor.client.models.Artifact; import io.jenkins.plugins.harbor.client.models.NativeReportSummary; import io.jenkins.plugins.harbor.client.models.Repository; import io.jenkins.plugins.harbor.util.HarborConstants; import io.jenkins.plugins.harbor.util.JsonParser; import io.jenkins.plugins.okhttp.api.JenkinsOkHttpClient; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor;
3,668
package io.jenkins.plugins.harbor.client; public class HarborClientImpl implements HarborClient { private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30; private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30; private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30; private static final String API_PING_PATH = "/ping"; private static final String API_LIST_ALL_REPOSITORIES_PATH = "/repositories"; private static final String API_LIST_ARTIFACTS_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts"; private static final String API_GET_ARTIFACT_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}"; private final String baseUrl; private final OkHttpClient httpClient; public HarborClientImpl( String baseUrl, StandardUsernamePasswordCredentials credentials, boolean isSkipTlsVerify, boolean debugLogging) throws NoSuchAlgorithmException, KeyManagementException { this.baseUrl = baseUrl; // Create Http client OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient()); addTimeout(httpClientBuilder); skipTlsVerify(httpClientBuilder, isSkipTlsVerify); addAuthenticator(httpClientBuilder, credentials); enableDebugLogging(httpClientBuilder, debugLogging); this.httpClient = httpClientBuilder.build(); } private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) { httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.setRetryOnConnectionFailure$okhttp(true); return httpClient; } @SuppressWarnings("lgtm[jenkins/unsafe-calls]") private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify) throws NoSuchAlgorithmException, KeyManagementException { if (isSkipTlsVerify) { SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()}; sslContext.init(null, trustManagers, new java.security.SecureRandom()); httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); httpClient.setHostnameVerifier$okhttp((hostname, session) -> true); } return httpClient; } private OkHttpClient.Builder addAuthenticator( OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) { if (credentials != null) { HarborInterceptor harborInterceptor = new HarborInterceptor(credentials); httpClientBuilder.addInterceptor(harborInterceptor); } return httpClientBuilder; } private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) { if (debugLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(loggingInterceptor); } return httpClient; } private String getXAcceptVulnerabilities() { return String.format( "%s, %s", HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType); } @Override
package io.jenkins.plugins.harbor.client; public class HarborClientImpl implements HarborClient { private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30; private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30; private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30; private static final String API_PING_PATH = "/ping"; private static final String API_LIST_ALL_REPOSITORIES_PATH = "/repositories"; private static final String API_LIST_ARTIFACTS_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts"; private static final String API_GET_ARTIFACT_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}"; private final String baseUrl; private final OkHttpClient httpClient; public HarborClientImpl( String baseUrl, StandardUsernamePasswordCredentials credentials, boolean isSkipTlsVerify, boolean debugLogging) throws NoSuchAlgorithmException, KeyManagementException { this.baseUrl = baseUrl; // Create Http client OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient()); addTimeout(httpClientBuilder); skipTlsVerify(httpClientBuilder, isSkipTlsVerify); addAuthenticator(httpClientBuilder, credentials); enableDebugLogging(httpClientBuilder, debugLogging); this.httpClient = httpClientBuilder.build(); } private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) { httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.setRetryOnConnectionFailure$okhttp(true); return httpClient; } @SuppressWarnings("lgtm[jenkins/unsafe-calls]") private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify) throws NoSuchAlgorithmException, KeyManagementException { if (isSkipTlsVerify) { SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()}; sslContext.init(null, trustManagers, new java.security.SecureRandom()); httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); httpClient.setHostnameVerifier$okhttp((hostname, session) -> true); } return httpClient; } private OkHttpClient.Builder addAuthenticator( OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) { if (credentials != null) { HarborInterceptor harborInterceptor = new HarborInterceptor(credentials); httpClientBuilder.addInterceptor(harborInterceptor); } return httpClientBuilder; } private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) { if (debugLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(loggingInterceptor); } return httpClient; } private String getXAcceptVulnerabilities() { return String.format( "%s, %s", HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType); } @Override
public NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference) {
2
2023-11-11 14:54:53+00:00
8k
Mapty231/SpawnFix
src/main/java/me/tye/spawnfix/PlayerRespawn.java
[ { "identifier": "Config", "path": "src/main/java/me/tye/spawnfix/utils/Config.java", "snippet": "public enum Config {\n\n default_worldName(String.class),\n default_x(Double.class),\n default_y(Double.class),\n default_z(Double.class),\n default_yaw(Float.class),\n default_pitch(Float.class),\n\n teleport_times(Integer.class),\n teleport_retryInterval(Integer.class),\n\n login(Occurrence.class),\n onSpawn(Occurrence.class),\n lang(String.class);\n\n\n\n/**\n * @param type Should be set to the class of the object this enum will be parsed as. This checks that the config values entered are valid for the used key.\n */\nConfig(Class type) {\n this.type = type;\n}\n\n/**\n Stores the class this object should be parsed as.\n */\nprivate final Class type;\n\n/**\n * @return The class of the object this enum should be parsed as.\n */\nprivate Class getType() {\n return type;\n}\n\n\n/**\n Stores the configs for this plugin.\n */\nprivate static final HashMap<Config, Object> configs = new HashMap<>();\n\n\n/**\n * @return Gets the config response for the selected enum.\n */\npublic @NotNull Object getConfig() {\n Object response = configs.get(this);\n\n assert response != null;\n\n return response;\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with String.valueOf().\n */\npublic @NotNull String getStringConfig() {\n return String.valueOf(getConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Integer.parseInt().\n */\npublic int getIntegerConfig() {\n return Integer.parseInt(getStringConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Double.parseDouble().\n */\npublic double getDoubleConfig() {\n return Double.parseDouble(getStringConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Float.parseFloat().\n */\npublic float getFloatConfig() {\n return Float.parseFloat(getStringConfig());\n}\n\n/**\n Enum for how often spawnFix should act for a certain feature.\n */\npublic enum Occurrence {\n NEVER,\n FIRST,\n EVERY;\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Occurrence.valueOf().\n */\npublic @NotNull Occurrence getOccurrenceConfig() {\n return Occurrence.valueOf(getStringConfig().toUpperCase());\n}\n\n/**\n Loads the default configs.\n */\npublic static void init() {\n //Loads the default values into the config.\n HashMap<String,Object> internalConfig = Util.parseInternalYaml(\"config.yml\");\n\n internalConfig.forEach((String key, Object value) -> {\n String formattedKey = key.replace('.', '_');\n\n try {\n Config config = Config.valueOf(formattedKey);\n\n if (!validate(config, value)) {\n //Dev warning\n throw new RuntimeException(\"\\\"\"+config+\"\\\" cannot be parsed as given object. - Dev warning\");\n }\n\n configs.put(config, value);\n\n } catch (IllegalArgumentException e) {\n //Dev warning\n throw new RuntimeException(\"\\\"\"+formattedKey + \"\\\" isn't in default config file. - Dev warning\");\n }\n });\n\n //Checks if any default values are missing.\n for (Config config : Config.values()) {\n if (configs.containsKey(config)) continue;\n\n //Dev warning.\n throw new RuntimeException(\"\\\"\"+config+\"\\\" isn't in default config file. - Dev warning\");\n }\n}\n\n/**\n Puts the keys response specified by the user into the configs map.\n */\npublic static void load() {\n //Loads in the user-set configs.\n File externalConfigFile = new File(Util.dataFolder.toPath()+File.separator+\"config.yml\");\n HashMap<String,Object> externalConfigs = Util.parseAndRepairExternalYaml(externalConfigFile, \"config.yml\");\n\n HashMap<Config, Object> userConfigs = new HashMap<>();\n\n //Gets the default keys that the user has entered.\n for (Map.Entry<String, Object> entry : externalConfigs.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n\n String formattedKey = key.replace('.', '_');\n Config config = Config.valueOf(formattedKey);\n\n if (!validate(config, value)) {\n log.warning(Lang.excepts_invalidValue.getResponse(Key.key.replaceWith(key), Key.filePath.replaceWith(externalConfigFile.getAbsolutePath())));\n continue;\n }\n\n //logs an exception if the key doesn't exist.\n try {\n userConfigs.put(config, value);\n\n } catch (IllegalArgumentException e) {\n log.warning(Lang.excepts_invalidKey.getResponse(Key.key.replaceWith(key)));\n }\n }\n\n\n //Warns the user about any config keys they are missing.\n for (Config config : configs.keySet()) {\n if (userConfigs.containsKey(config)) continue;\n\n log.warning(Lang.excepts_missingKey.getResponse(Key.key.replaceWith(config.toString()), Key.filePath.replaceWith(externalConfigFile.getAbsolutePath())));\n }\n\n configs.putAll(userConfigs);\n}\n\n/**\n Checks if config can be parsed as its intended object.\n * @param config The config to check.\n * @param value The value of the config.\n * @return True if the config can be parsed as its intended object. False if it can't.\n */\nprivate static boolean validate(Config config, Object value) {\n Class configType = config.getType();\n\n //Strings can always be parsed.\n if (configType.equals(String.class)) return true;\n\n String stringValue = value.toString();\n\n if (configType.equals(Double.class)) {\n try {\n Double.parseDouble(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Occurrence.class)) {\n try {\n Occurrence.valueOf(stringValue.toUpperCase());\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Integer.class)) {\n try {\n Integer.parseInt(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Float.class)) {\n try {\n Float.parseFloat(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n throw new RuntimeException(\"Validation for class \\\"\"+configType+\"\\\" does not exist! - Dev warning.\");\n}\n\n}" }, { "identifier": "Teleport", "path": "src/main/java/me/tye/spawnfix/utils/Teleport.java", "snippet": "public class Teleport implements Runnable{\n\npublic static final HashMap<UUID,BukkitTask> runningTasks = new HashMap<>();\n\nprivate final Player player;\nprivate final Location location;\n\nprivate int timesTeleported = 1;\nprivate final int retryLimit = Config.teleport_times.getIntegerConfig();\n\n/**\n A runnable object that teleports the given player to the given location the amount of times specified by \"teleport.times\" in the config.\n * @param player The given player.\n * @param location The given location.\n */\npublic Teleport(@NonNull Player player, @NonNull Location location) {\n this.player = player;\n this.location = location;\n}\n\n@Override\npublic void run() {\n if (timesTeleported > retryLimit) {\n runningTasks.get(player.getUniqueId()).cancel();\n return;\n }\n\n if (location == null ) {\n plugin.getLogger().warning(Lang.teleport_noLocation.getResponse());\n return;\n }\n\n if (player == null) {\n plugin.getLogger().warning(Lang.teleport_noPlayer.getResponse());\n return;\n }\n\n player.teleport(location);\n timesTeleported++;\n}\n\n}" }, { "identifier": "Util", "path": "src/main/java/me/tye/spawnfix/utils/Util.java", "snippet": "public class Util {\n\n/**\n This plugin.\n */\npublic static final JavaPlugin plugin = JavaPlugin.getPlugin(SpawnFix.class);\n\n\n/**\n The data folder.\n */\npublic static final File dataFolder = plugin.getDataFolder();\n\n/**\n The config file for this plugin.\n */\npublic static final File configFile = new File(dataFolder.toPath() + File.separator + \"config.yml\");\n\n/**\n The lang folder for this plugin.\n */\npublic static File langFolder = new File(dataFolder.toPath() + File.separator + \"langFiles\");\n\n/**\n The logger for this plugin.\n */\npublic static final Logger log = plugin.getLogger();\n\n\n/**\n * @return The default spawn location as set in the config.yml of this plugin.\n */\npublic static Location getDefaultSpawn() {\n return new Location(Bukkit.getWorld(Config.default_worldName.getStringConfig()),\n Config.default_x.getDoubleConfig(),\n Config.default_y.getDoubleConfig(),\n Config.default_z.getDoubleConfig(),\n Config.default_yaw.getFloatConfig(),\n Config.default_pitch.getFloatConfig()\n );\n}\n\n\n/**\n Formats the Map returned from Yaml.load() into a hashmap where the exact key corresponds to the value.<br>\n E.G: key: \"example.response\" value: \"test\".\n @param baseMap The Map from Yaml.load().\n @return The formatted Map. */\npublic static @NotNull HashMap<String,Object> getKeysRecursive(@Nullable Map<?,?> baseMap) {\n HashMap<String,Object> map = new HashMap<>();\n if (baseMap == null) return map;\n\n for (Object key : baseMap.keySet()) {\n Object value = baseMap.get(key);\n\n if (value instanceof Map<?,?> subMap) {\n map.putAll(getKeysRecursive(String.valueOf(key), subMap));\n } else {\n map.put(String.valueOf(key), String.valueOf(value));\n }\n\n }\n\n return map;\n}\n\n/**\n Formats the Map returned from Yaml.load() into a hashmap where the exact key corresponds to the value.\n @param keyPath The path to append to the starts of the key. (Should only be called internally).\n @param baseMap The Map from Yaml.load().\n @return The formatted Map. */\npublic static @NotNull HashMap<String,Object> getKeysRecursive(@NotNull String keyPath, @NotNull Map<?,?> baseMap) {\n if (!keyPath.isEmpty()) keyPath += \".\";\n\n HashMap<String,Object> map = new HashMap<>();\n for (Object key : baseMap.keySet()) {\n Object value = baseMap.get(key);\n\n if (value instanceof Map<?,?> subMap) {\n map.putAll(getKeysRecursive(keyPath+key, subMap));\n } else {\n map.put(keyPath+key, String.valueOf(value));\n }\n\n }\n\n return map;\n}\n\n/**\n Copies the content of an internal file to a new external one.\n @param file External file destination\n @param resource Input stream for the data to write, or null if target is an empty file/dir.\n @param isFile Set to true to create a file. Set to false to create a dir.*/\npublic static void makeRequiredFile(@NotNull File file, @Nullable InputStream resource, boolean isFile) throws IOException {\n if (file.exists())\n return;\n\n if (isFile) {\n if (!file.createNewFile())\n throw new IOException();\n }\n else {\n if (!file.mkdir())\n throw new IOException();\n }\n\n if (resource != null) {\n String text = new String(resource.readAllBytes());\n FileWriter fw = new FileWriter(file);\n fw.write(text);\n fw.close();\n }\n}\n\n/**\n Copies the content of an internal file to a new external one.\n @param file External file destination\n @param resource Input stream for the data to write, or null if target is an empty file/dir.\n @param isFile Set to true to create a file. Set to false to create a dir.*/\npublic static void createFile(@NotNull File file, @Nullable InputStream resource, boolean isFile) {\n try {\n makeRequiredFile(file, resource, isFile);\n } catch (IOException e) {\n log.log(Level.WARNING, Lang.excepts_fileCreation.getResponse(Key.filePath.replaceWith(file.getAbsolutePath())), e);\n }\n}\n\n\n/**\n Parses & formats data from the given inputStream to a Yaml resource.\n * @param yamlInputStream The given inputStream to a Yaml resource.\n * @return The parsed values in the format key: \"test1.log\" value: \"works!\"<br>\n * Or an empty hashMap if the given inputStream is null.\n * @throws IOException If the data couldn't be read from the given inputStream.\n */\nprivate static @NotNull HashMap<String, Object> parseYaml(@Nullable InputStream yamlInputStream) throws IOException {\n if (yamlInputStream == null) return new HashMap<>();\n\n byte[] resourceBytes = yamlInputStream.readAllBytes();\n\n String resourceContent = new String(resourceBytes, Charset.defaultCharset());\n\n return getKeysRecursive(new Yaml().load(resourceContent));\n}\n\n/**\n Parses the data from an internal YAML file.\n * @param resourcePath The path to the file from /src/main/resource/\n * @return The parsed values in the format key: \"test1.log\" value: \"works!\" <br>\n * Or an empty hashMap if the file couldn't be found or read.\n */\npublic static @NotNull HashMap<String, Object> parseInternalYaml(@NotNull String resourcePath) {\n try (InputStream resourceInputStream = plugin.getResource(resourcePath)) {\n return parseYaml(resourceInputStream);\n\n } catch (IOException e) {\n log.log(Level.SEVERE, \"Unable to parse internal YAML files.\\nConfig & lang might break.\\n\", e);\n return new HashMap<>();\n }\n\n}\n\n\n/**\n Parses the given external file into a hashMap. If the internal file contained keys that the external file didn't then the key-value pare is added to the external file.\n * @param externalFile The external file to parse.\n * @param pathToInternalResource The path to the internal resource to repair it with or fallback on if the external file is broken.\n * @return The key-value pairs from the external file. If any keys were missing from the external file then they are put into the hashMap with their default value.\n */\npublic static @NotNull HashMap<String, Object> parseAndRepairExternalYaml(@NotNull File externalFile, @Nullable String pathToInternalResource) {\n HashMap<String,Object> externalYaml;\n\n //tries to parse the external file.\n try (InputStream externalInputStream = new FileInputStream(externalFile)) {\n externalYaml = parseYaml(externalInputStream);\n\n } catch (FileNotFoundException e) {\n log.log(Level.SEVERE, Lang.excepts_noFile.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //returns an empty hashMap or the internal values if present.\n return pathToInternalResource == null ? new HashMap<>() : parseInternalYaml(pathToInternalResource);\n\n } catch (IOException e) {\n log.log(Level.SEVERE, Lang.excepts_parseYaml.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //returns an empty hashMap or the internal values if present.\n return pathToInternalResource == null ? new HashMap<>() : parseInternalYaml(pathToInternalResource);\n }\n\n\n //if there is no internal resource to compare against then only the external file data is returned.\n if (pathToInternalResource == null)\n return externalYaml;\n\n HashMap<String,Object> internalYaml = parseInternalYaml(pathToInternalResource);\n\n //gets the values that the external file is missing;\n HashMap<String,Object> missingPairsMap = new HashMap<>();\n internalYaml.forEach((String key, Object value) -> {\n if (externalYaml.containsKey(key))\n return;\n\n missingPairsMap.put(key, value);\n });\n\n //if no values are missing return\n if (missingPairsMap.keySet().isEmpty())\n return externalYaml;\n\n //Adds all the missing key-value pairs to a stringBuilder.\n StringBuilder missingPairs = new StringBuilder(\"\\n\");\n missingPairsMap.forEach((String key, Object value) -> {\n missingPairs.append(key)\n .append(\": \\\"\")\n .append(preserveEscapedQuotes(value))\n .append(\"\\\"\\n\");\n });\n\n //Adds al the missing pairs to the external Yaml.\n externalYaml.putAll(missingPairsMap);\n\n\n //Writes the missing pairs to the external file.\n try (FileWriter externalFileWriter = new FileWriter(externalFile, true)) {\n externalFileWriter.append(missingPairs.toString());\n\n }catch (IOException e) {\n //Logs a warning\n log.log(Level.WARNING, Lang.excepts_fileRestore.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //Logs the keys that couldn't be appended.\n missingPairsMap.forEach((String key, Object value) -> {\n log.log(Level.WARNING, key + \": \" + value);\n });\n }\n\n return externalYaml;\n}\n\n/**\n Object.toString() changes \\\" to \". This method resolves this problem.\n * @param value The object to get the string from.\n * @return The correct string from the given object.\n */\nprivate static String preserveEscapedQuotes(Object value) {\n char[] valueCharArray = value.toString().toCharArray();\n StringBuilder correctString = new StringBuilder();\n\n\n for (char character : valueCharArray) {\n if (character != '\"') {\n correctString.append(character);\n continue;\n }\n\n correctString.append('\\\\');\n correctString.append('\"');\n }\n\n return correctString.toString();\n}\n\n/**\n Writes the new value to the key in the specified external yaml file.\n * @param key The key to replace the value of.\n * @param value The new string to overwrite the old value with.\n * @param externalYaml The external yaml to perform this operation on.\n * @throws IOException If there was an error reading or writing data to the Yaml file.\n */\npublic static void writeYamlData(@NotNull String key, @NotNull String value, @NotNull File externalYaml) throws IOException {\n String fileContent;\n\n //Reads the content from the file.\n try (FileInputStream externalYamlInputStream = new FileInputStream(externalYaml)) {\n fileContent = new String(externalYamlInputStream.readAllBytes());\n }\n\n //Ensures that every key ends with \":\".\n //This avoids false matches where one key contains the starting chars of another.\n String[] keys = key.split(\"\\\\.\");\n for (int i = 0; i < keys.length; i++) {\n String k = keys[i];\n\n if (k.endsWith(\":\")) continue;\n\n k+=\":\";\n keys[i] = k;\n }\n\n\n Integer valueStartPosition = findKeyPosition(keys, fileContent);\n if (valueStartPosition == null) throw new IOException(\"Unable to find \"+key+\" in external Yaml file.\");\n\n int valueLineEnd = valueStartPosition;\n //Finds the index of the end of the line that the key is on.\n while (fileContent.charAt(valueLineEnd) != '\\n') {\n valueLineEnd++;\n }\n\n String firstPart = fileContent.substring(0, valueStartPosition);\n String secondPart = fileContent.substring(valueLineEnd, fileContent.length()-1);\n\n String newFileContent = firstPart.concat(value).concat(secondPart);\n\n try (FileWriter externalYamlWriter = new FileWriter(externalYaml)) {\n externalYamlWriter.write(newFileContent);\n }\n}\n\n/**\n Finds the given key index in the given file content split on each new line.<br>\n The key should be given in the format \"example.key1\".\n * @param keys The given keys.\n * @param fileContent The given file content.\n * @return The index of the char a space after the end of the last key.<br>\n * Example: \"key1: !\" the char index that the '!' is on.<br>\n * Or null if the key couldn't be found.\n */\nprivate static @Nullable Integer findKeyPosition(@NotNull String[] keys, @NotNull String fileContent) {\n\n //Iterates over each line in the file content.\n String[] split = fileContent.split(\"\\n\");\n\n for (int keyLine = 0, splitLength = split.length; keyLine < splitLength; keyLine++) {\n String strippedLine = split[keyLine].stripLeading();\n\n //if it doesn't start with the key value then continue\n if (!strippedLine.startsWith(keys[0])) {\n continue;\n }\n\n return findKeyPosition(keys, keyLine+1, 1, fileContent);\n\n }\n\n return null;\n}\n\n/**\n Gets the index for the line of the last sub-key given in the given fileContent.<br>\n This method executes recursively.\n * @param keys The keys to find in the file.\n * @param startLine The index of the line to start the search from.\n * @param keyIndex The index of the sub-key that is searched for.\n * @param fileContent The content of the file to search through.\n * @return The index of the char a space after the end of the last key.<br>\n * Example: \"key1: !\" the char index that the '!' is on.<br>\n * Or null if the key couldn't be found.\n */\nprivate static @Nullable Integer findKeyPosition(@NotNull String[] keys, int startLine, int keyIndex, @NotNull String fileContent) {\n //Iterates over each line in the file content.\n String[] split = fileContent.split(\"\\n\");\n\n for (int lineIndex = startLine, splitLength = split.length; lineIndex < splitLength; lineIndex++) {\n\n String line = split[lineIndex];\n\n //returns null if the key doesn't exist as a sub-key of the base key.\n if (!(line.startsWith(\" \") || line.startsWith(\"\\t\"))) {\n return null;\n }\n\n String strippedLine = line.stripLeading();\n\n //if it doesn't start with the key value then continue\n if (!strippedLine.startsWith(keys[keyIndex])) {\n continue;\n }\n\n keyIndex++;\n\n //returns the char position that the key ends on if it is the last key in the sequence.\n if (keyIndex == keys.length) {\n\n int currentLinePosition = 0;\n //Gets the char position of the current line within the string.\n for (int i = 0; i < lineIndex; i++) {\n currentLinePosition+=split[i].length()+1;\n }\n\n //Finds the char position a space after the key ends.\n for (int i = currentLinePosition; i < fileContent.length(); i++) {\n char character = fileContent.charAt(i);\n\n if (character != ':') continue;\n\n return i+2;\n\n }\n }\n\n return findKeyPosition(keys, startLine, keyIndex, fileContent);\n }\n\n return null;\n}\n\n}" } ]
import me.tye.spawnfix.utils.Config; import me.tye.spawnfix.utils.Teleport; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.scheduler.BukkitTask; import java.util.logging.Level; import static me.tye.spawnfix.utils.Util.*;
5,661
package me.tye.spawnfix; public class PlayerRespawn implements Listener { @EventHandler public static void playerRespawn(PlayerRespawnEvent e) { Player player = e.getPlayer(); Location spawnLocation = e.getPlayer().getBedSpawnLocation();
package me.tye.spawnfix; public class PlayerRespawn implements Listener { @EventHandler public static void playerRespawn(PlayerRespawnEvent e) { Player player = e.getPlayer(); Location spawnLocation = e.getPlayer().getBedSpawnLocation();
if (Config.onSpawn.getOccurrenceConfig() == Config.Occurrence.NEVER) {
0
2023-11-13 23:53:25+00:00
8k
mike1226/SpringMVCExample-01
src/main/java/com/example/servingwebcontent/controller/CountryController.java
[ { "identifier": "CountryEntity", "path": "src/main/java/com/example/servingwebcontent/entity/CountryEntity.java", "snippet": "public class CountryEntity {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.56668+09:00\", comments = \"Source field: public.country.mstcountrycd\")\n\tprivate String mstcountrycd;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.566921+09:00\", comments = \"Source field: public.country.mstcountrynanme\")\n\tprivate String mstcountrynanme;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.567064+09:00\", comments = \"Source field: public.country.updatedt\")\n\tprivate Long updatedt;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.567343+09:00\", comments = \"Source field: public.country.deletedt\")\n\tprivate Long deletedt;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.566795+09:00\", comments = \"Source field: public.country.mstcountrycd\")\n\tpublic String getMstcountrycd() {\n\t\treturn mstcountrycd;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.566855+09:00\", comments = \"Source field: public.country.mstcountrycd\")\n\tpublic void setMstcountrycd(String mstcountrycd) {\n\t\tthis.mstcountrycd = mstcountrycd;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.56697+09:00\", comments = \"Source field: public.country.mstcountrynanme\")\n\tpublic String getMstcountrynanme() {\n\t\treturn mstcountrynanme;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.567022+09:00\", comments = \"Source field: public.country.mstcountrynanme\")\n\tpublic void setMstcountrynanme(String mstcountrynanme) {\n\t\tthis.mstcountrynanme = mstcountrynanme;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.56711+09:00\", comments = \"Source field: public.country.updatedt\")\n\tpublic Long getUpdatedt() {\n\t\treturn updatedt;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.567244+09:00\", comments = \"Source field: public.country.updatedt\")\n\tpublic void setUpdatedt(Long updatedt) {\n\t\tthis.updatedt = updatedt;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.567396+09:00\", comments = \"Source field: public.country.deletedt\")\n\tpublic Long getDeletedt() {\n\t\treturn deletedt;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.567596+09:00\", comments = \"Source field: public.country.deletedt\")\n\tpublic void setDeletedt(Long deletedt) {\n\t\tthis.deletedt = deletedt;\n\t}\n}" }, { "identifier": "Customer", "path": "src/main/java/com/example/servingwebcontent/entity/Customer.java", "snippet": "public class Customer {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.550902+09:00\", comments = \"Source field: public.customer.id\")\n\tprivate String id;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552784+09:00\", comments = \"Source field: public.customer.username\")\n\tprivate String username;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552893+09:00\", comments = \"Source field: public.customer.email\")\n\tprivate String email;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552994+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tprivate String phoneNumber;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553138+09:00\", comments = \"Source field: public.customer.post_code\")\n\tprivate String postCode;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.55244+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552729+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552823+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552861+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552927+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552962+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553027+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic String getPhoneNumber() {\n\t\treturn phoneNumber;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553091+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic void setPhoneNumber(String phoneNumber) {\n\t\tthis.phoneNumber = phoneNumber;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553186+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic String getPostCode() {\n\t\treturn postCode;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553235+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic void setPostCode(String postCode) {\n\t\tthis.postCode = postCode;\n\t}\n}" }, { "identifier": "CountryForm", "path": "src/main/java/com/example/servingwebcontent/form/CountryForm.java", "snippet": "@Data\npublic class CountryForm {\n\n // country code\n private String cd;\n\n // country name\n private String name;\n\n public CountryForm() {\n this.cd = \"\";\n this.name = \"\";\n }\n\n public CountryForm(String cd, String name) {\n this.cd = cd;\n this.name = name;\n }\n \n}" }, { "identifier": "CountrySearchForm", "path": "src/main/java/com/example/servingwebcontent/form/CountrySearchForm.java", "snippet": "@Data\npublic class CountrySearchForm {\n\n @NotBlank(message = \"ID should not be blank\")\n private String mstCountryCD;\n\n public CountrySearchForm() {\n }\n\n public CountrySearchForm(String mstCountryCd) {\n this.mstCountryCD = mstCountryCd;\n }\n}" }, { "identifier": "TestForm", "path": "src/main/java/com/example/servingwebcontent/form/TestForm.java", "snippet": "@Data\npublic class TestForm {\n \n private String cd;\n\n private String name;\n\n public TestForm(){\n \n }\n \n}" }, { "identifier": "CountryEntityMapper", "path": "src/main/java/com/example/servingwebcontent/repository/CountryEntityMapper.java", "snippet": "@Mapper\npublic interface CountryEntityMapper extends CommonCountMapper, CommonDeleteMapper, CommonInsertMapper<CountryEntity>, CommonUpdateMapper {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568986+09:00\", comments = \"Source Table: public.country\")\n\tBasicColumn[] selectList = BasicColumn.columnList(mstcountrycd, mstcountrynanme, updatedt, deletedt);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568237+09:00\", comments = \"Source Table: public.country\")\n\t@SelectProvider(type = SqlProviderAdapter.class, method = \"select\")\n\t@Results(id = \"CountryEntityResult\", value = {\n\t\t\t@Result(column = \"mstcountrycd\", property = \"mstcountrycd\", jdbcType = JdbcType.CHAR, id = true),\n\t\t\t@Result(column = \"mstcountrynanme\", property = \"mstcountrynanme\", jdbcType = JdbcType.CHAR),\n\t\t\t@Result(column = \"updatedt\", property = \"updatedt\", jdbcType = JdbcType.NUMERIC),\n\t\t\t@Result(column = \"deletedt\", property = \"deletedt\", jdbcType = JdbcType.NUMERIC) })\n\tList<CountryEntity> selectMany(SelectStatementProvider selectStatement);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568391+09:00\", comments = \"Source Table: public.country\")\n\t@SelectProvider(type = SqlProviderAdapter.class, method = \"select\")\n\t@ResultMap(\"CountryEntityResult\")\n\tOptional<CountryEntity> selectOne(SelectStatementProvider selectStatement);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568476+09:00\", comments = \"Source Table: public.country\")\n\tdefault long count(CountDSLCompleter completer) {\n\t\treturn MyBatis3Utils.countFrom(this::count, countryEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568549+09:00\", comments = \"Source Table: public.country\")\n\tdefault int delete(DeleteDSLCompleter completer) {\n\t\treturn MyBatis3Utils.deleteFrom(this::delete, countryEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568607+09:00\", comments = \"Source Table: public.country\")\n\tdefault int deleteByPrimaryKey(String mstcountrycd_) {\n\t\treturn delete(c -> c.where(mstcountrycd, isEqualTo(mstcountrycd_)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568664+09:00\", comments = \"Source Table: public.country\")\n\tdefault int insert(CountryEntity row) {\n\t\treturn MyBatis3Utils.insert(this::insert, row, countryEntity,\n\t\t\t\tc -> c.map(mstcountrycd).toProperty(\"mstcountrycd\").map(mstcountrynanme).toProperty(\"mstcountrynanme\")\n\t\t\t\t\t\t.map(updatedt).toProperty(\"updatedt\").map(deletedt).toProperty(\"deletedt\"));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568773+09:00\", comments = \"Source Table: public.country\")\n\tdefault int insertMultiple(Collection<CountryEntity> records) {\n\t\treturn MyBatis3Utils.insertMultiple(this::insertMultiple, records, countryEntity,\n\t\t\t\tc -> c.map(mstcountrycd).toProperty(\"mstcountrycd\").map(mstcountrynanme).toProperty(\"mstcountrynanme\")\n\t\t\t\t\t\t.map(updatedt).toProperty(\"updatedt\").map(deletedt).toProperty(\"deletedt\"));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.568851+09:00\", comments = \"Source Table: public.country\")\n\tdefault int insertSelective(CountryEntity row) {\n\t\treturn MyBatis3Utils.insert(this::insert, row, countryEntity,\n\t\t\t\tc -> c.map(mstcountrycd).toPropertyWhenPresent(\"mstcountrycd\", row::getMstcountrycd)\n\t\t\t\t\t\t.map(mstcountrynanme).toPropertyWhenPresent(\"mstcountrynanme\", row::getMstcountrynanme)\n\t\t\t\t\t\t.map(updatedt).toPropertyWhenPresent(\"updatedt\", row::getUpdatedt).map(deletedt)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"deletedt\", row::getDeletedt));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569055+09:00\", comments = \"Source Table: public.country\")\n\tdefault Optional<CountryEntity> selectOne(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectOne(this::selectOne, selectList, countryEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569124+09:00\", comments = \"Source Table: public.country\")\n\tdefault List<CountryEntity> select(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectList(this::selectMany, selectList, countryEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569168+09:00\", comments = \"Source Table: public.country\")\n\tdefault List<CountryEntity> selectDistinct(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectDistinct(this::selectMany, selectList, countryEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.56922+09:00\", comments = \"Source Table: public.country\")\n\tdefault Optional<CountryEntity> selectByPrimaryKey(String mstcountrycd_) {\n\t\treturn selectOne(c -> c.where(mstcountrycd, isEqualTo(mstcountrycd_)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.56927+09:00\", comments = \"Source Table: public.country\")\n\tdefault int update(UpdateDSLCompleter completer) {\n\t\treturn MyBatis3Utils.update(this::update, countryEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569318+09:00\", comments = \"Source Table: public.country\")\n\tstatic UpdateDSL<UpdateModel> updateAllColumns(CountryEntity row, UpdateDSL<UpdateModel> dsl) {\n\t\treturn dsl.set(mstcountrycd).equalTo(row::getMstcountrycd).set(mstcountrynanme).equalTo(row::getMstcountrynanme)\n\t\t\t\t.set(updatedt).equalTo(row::getUpdatedt).set(deletedt).equalTo(row::getDeletedt);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569387+09:00\", comments = \"Source Table: public.country\")\n\tstatic UpdateDSL<UpdateModel> updateSelectiveColumns(CountryEntity row, UpdateDSL<UpdateModel> dsl) {\n\t\treturn dsl.set(mstcountrycd).equalToWhenPresent(row::getMstcountrycd).set(mstcountrynanme)\n\t\t\t\t.equalToWhenPresent(row::getMstcountrynanme).set(updatedt).equalToWhenPresent(row::getUpdatedt)\n\t\t\t\t.set(deletedt).equalToWhenPresent(row::getDeletedt);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569457+09:00\", comments = \"Source Table: public.country\")\n\tdefault int updateByPrimaryKey(CountryEntity row) {\n\t\treturn update(\n\t\t\t\tc -> c.set(mstcountrynanme).equalTo(row::getMstcountrynanme).set(updatedt).equalTo(row::getUpdatedt)\n\t\t\t\t\t\t.set(deletedt).equalTo(row::getDeletedt).where(mstcountrycd, isEqualTo(row::getMstcountrycd)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569576+09:00\", comments = \"Source Table: public.country\")\n\tdefault int updateByPrimaryKeySelective(CountryEntity row) {\n\t\treturn update(c -> c.set(mstcountrynanme).equalToWhenPresent(row::getMstcountrynanme).set(updatedt)\n\t\t\t\t.equalToWhenPresent(row::getUpdatedt).set(deletedt).equalToWhenPresent(row::getDeletedt)\n\t\t\t\t.where(mstcountrycd, isEqualTo(row::getMstcountrycd)));\n\t}\n}" } ]
import java.util.List; import java.util.Optional; import org.mybatis.dynamic.sql.select.SelectDSLCompleter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.view.RedirectView; import com.example.servingwebcontent.entity.CountryEntity; import com.example.servingwebcontent.entity.Customer; import com.example.servingwebcontent.form.CountryForm; import com.example.servingwebcontent.form.CountrySearchForm; import com.example.servingwebcontent.form.TestForm; import com.example.servingwebcontent.repository.CountryEntityMapper; import com.google.gson.Gson;
4,701
package com.example.servingwebcontent.controller; @Controller public class CountryController { @Autowired private CountryEntityMapper mapper; /** * The String class represents character strings. */ @GetMapping("/list")
package com.example.servingwebcontent.controller; @Controller public class CountryController { @Autowired private CountryEntityMapper mapper; /** * The String class represents character strings. */ @GetMapping("/list")
public String list(TestForm testForm) {
4
2023-11-12 08:22:27+00:00
8k
wangxianhui111/xuechengzaixian
xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/impl/MyCourseTableServicesImpl.java
[ { "identifier": "CommonError", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/CommonError.java", "snippet": "public enum CommonError {\n UNKNOWN_ERROR(\"执行过程异常,请重试。\"),\n PARAMS_ERROR(\"非法参数\"),\n OBJECT_NULL(\"对象为空\"),\n QUERY_NULL(\"查询结果为空\"),\n REQUEST_NULL(\"请求参数为空\");//\n private final String errMessage;\n\n public String getErrMessage() {\n return errMessage;\n }\n\n private CommonError(String errMessage) {\n this.errMessage = errMessage;\n }\n}" }, { "identifier": "XueChengPlusException", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java", "snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private String errMessage;\n\n public XueChengPlusException() {\n super();\n }\n\n public XueChengPlusException(String errMessage) {\n super(errMessage);\n this.errMessage = errMessage;\n }\n\n public String getErrMessage() {\n return errMessage;\n }\n\n public static void cast(CommonError commonError) {\n throw new XueChengPlusException(commonError.getErrMessage());\n }\n\n public static void cast(String errMessage) {\n throw new XueChengPlusException(errMessage);\n }\n}" }, { "identifier": "PageResult", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/model/PageResult.java", "snippet": "@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PageResult<T> implements Serializable {\n\n /**\n * 数据列表\n */\n private List<T> items;\n\n /**\n * 总记录数\n */\n private long counts;\n\n /**\n * 当前页码\n */\n private long page;\n\n /**\n * 每页记录数\n */\n private long pageSize;\n\n}" }, { "identifier": "CoursePublish", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublish.java", "snippet": "@Data\n@TableName(\"course_publish\")\npublic class CoursePublish implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键(课程id)\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 发布时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 上架时间\n */\n private LocalDateTime onlineDate;\n\n /**\n * 下架时间\n */\n private LocalDateTime offlineDate;\n\n /**\n * 发布状态<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "ContentServiceClient", "path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/feignclient/ContentServiceClient.java", "snippet": "@FeignClient(value = \"content-api\", fallbackFactory = ContentServiceClient.ContentServiceClientFallbackFactory.class)\npublic interface ContentServiceClient {\n\n @ResponseBody\n @GetMapping(\"/content/r/coursepublish/{courseId}\")\n CoursePublish getCoursePublish(@PathVariable(\"courseId\") Long courseId);\n\n /**\n * 内容管理服务远程接口降级类\n */\n @Slf4j\n class ContentServiceClientFallbackFactory implements FallbackFactory<ContentServiceClient> {\n\n @Override\n public ContentServiceClient create(Throwable cause) {\n log.error(\"调用内容管理服务接口熔断:{}\", cause.getMessage());\n return null;\n }\n }\n}" }, { "identifier": "XcChooseCourseMapper", "path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/mapper/XcChooseCourseMapper.java", "snippet": "public interface XcChooseCourseMapper extends BaseMapper<XcChooseCourse> {\n\n}" }, { "identifier": "XcCourseTablesMapper", "path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/mapper/XcCourseTablesMapper.java", "snippet": "public interface XcCourseTablesMapper extends BaseMapper<XcCourseTables> {\n\n List<MyCourseTableItemDto> myCourseTables( MyCourseTableParams params);\n\n int myCourseTablesCount( MyCourseTableParams params);\n\n}" }, { "identifier": "MyCourseTableItemDto", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/MyCourseTableItemDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@ToString\npublic class MyCourseTableItemDto extends XcCourseTables {\n\n /**\n * 最近学习时间\n */\n private LocalDateTime learnDate;\n\n /**\n * 学习时长\n */\n private Long learnLength;\n\n /**\n * 章节id\n */\n private Long teachplanId;\n\n /**\n * 章节名称\n */\n private String teachplanName;\n\n}" }, { "identifier": "MyCourseTableParams", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/MyCourseTableParams.java", "snippet": "@Data\n@ToString\npublic class MyCourseTableParams {\n\n /**\n * 用户id\n */\n private String userId;\n\n /**\n * 课程类型 [{\"code\":\"700001\",\"desc\":\"免费课程\"},{\"code\":\"700002\",\"desc\":\"收费课程\"}]\n */\n private String courseType;\n\n /**\n * 排序 1按学习时间进行排序 2按加入时间进行排序\n */\n private String sortType;\n\n /**\n * 1 即将过期、2 已经过期\n */\n private String expiresType;\n\n /**\n * 页码\n */\n int page = 1;\n\n /**\n * 开始索引\n */\n int startIndex;\n\n /**\n * 每页大小\n */\n int size = 4;\n\n}" }, { "identifier": "XcChooseCourseDto", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/XcChooseCourseDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@ToString\npublic class XcChooseCourseDto extends XcChooseCourse {\n\n /**\n * 学习资格,<p>\n * [{\"code\":\"702001\",\"desc\":\"正常学习\"},{\"code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"},{\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}]\n */\n public String learnStatus;\n\n}" }, { "identifier": "XcCourseTablesDto", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/XcCourseTablesDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@ToString\npublic class XcCourseTablesDto extends XcCourseTables {\n\n /**\n * 学习资格,[{\"code\":\"702001\",\"desc\":\"正常学习\"},{\"code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"},{\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}]\n */\n public String learnStatus;\n}" }, { "identifier": "XcChooseCourse", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/po/XcChooseCourse.java", "snippet": "@Data\n@TableName(\"xc_choose_course\")\npublic class XcChooseCourse implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 课程id\n */\n private Long courseId;\n\n /**\n * 课程名称\n */\n private String courseName;\n\n /**\n * 用户id\n */\n private String userId;\n\n /**\n * 机构id\n */\n private Long companyId;\n\n /**\n * 选课类型 <p>\n * [{\"code\":\"700001\",\"desc\":\"免费课程\"},{\"code\":\"700002\",\"desc\":\"收费课程\"}]\n */\n private String orderType;\n\n /**\n * 添加时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 课程有效期(天)\n */\n private Integer validDays;\n\n /**\n * 课程价格\n */\n private Float coursePrice;\n\n /**\n * 选课状态 <p>\n * [{\"code\":\"701001\",\"desc\":\"选课成功\"},{\"code\":\"701002\",\"desc\":\"待支付\"}]\n */\n private String status;\n\n /**\n * 开始服务时间\n */\n private LocalDateTime validtimeStart;\n\n /**\n * 结束服务时间\n */\n private LocalDateTime validtimeEnd;\n\n /**\n * 备注\n */\n private String remarks;\n\n}" }, { "identifier": "XcCourseTables", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/po/XcCourseTables.java", "snippet": "@Data\n@TableName(\"xc_course_tables\")\npublic class XcCourseTables implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 选课记录id\n */\n private Long chooseCourseId;\n\n /**\n * 用户id\n */\n private String userId;\n\n /**\n * 课程id\n */\n private Long courseId;\n\n /**\n * 机构id\n */\n private Long companyId;\n\n /**\n * 课程名称\n */\n private String courseName;\n /**\n * 课程名称\n */\n private String courseType;\n\n\n /**\n * 添加时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 开始服务时间\n */\n private LocalDateTime validtimeStart;\n\n /**\n * 到期时间\n */\n private LocalDateTime validtimeEnd;\n\n /**\n * 更新时间\n */\n private LocalDateTime updateDate;\n\n /**\n * 备注\n */\n private String remarks;\n\n\n}" }, { "identifier": "MyCourseTablesService", "path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/MyCourseTablesService.java", "snippet": "public interface MyCourseTablesService {\n\n /**\n * 添加选课\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link com.xuecheng.learning.model.dto.XcChooseCourseDto}\n * @author Wuxy\n * @since 2022/10/24 17:33\n */\n XcChooseCourseDto addChooseCourse(String userId, Long courseId);\n\n /**\n * 添加免费课程\n *\n * @param userId 用户 id\n * @param coursePublish 课程发布信息\n * @return 选课信息\n */\n XcChooseCourse addFreeCourse(String userId, CoursePublish coursePublish);\n\n /**\n * 添加收费课程\n *\n * @param userId 用户 id\n * @param coursePublish 课程发布信息\n * @return 选课信息\n */\n XcChooseCourse addChargeCourse(String userId, CoursePublish coursePublish);\n\n /**\n * 添加到我的课程表\n *\n * @param chooseCourse 选课记录\n * @return {@link com.xuecheng.learning.model.po.XcCourseTables}\n * @author Wuxy\n * @since 2022/10/3 11:24\n */\n XcCourseTables addCourseTables(XcChooseCourse chooseCourse);\n\n /**\n * 根据课程和用户查询我的课程表中某一门课程\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link com.xuecheng.learning.model.po.XcCourseTables}\n * @author Wuxy\n * @since 2022/10/2 17:07\n */\n XcCourseTables getXcCourseTables(String userId, Long courseId);\n\n /**\n * 判断学习资格\n * <pre>\n * 学习资格状态 [{\"code\":\"702001\",\"desc\":\"正常学习\"},\n * {\"code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"},\n * {\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}]\n * </pre>\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link XcCourseTablesDto}\n * @author Wuxy\n * @since 2022/10/3 7:37\n */\n XcCourseTablesDto getLearningStatus(String userId, Long courseId);\n\n boolean saveChooseCourseStatus(String chooseCourseId);\n\n PageResult<MyCourseTableItemDto> myCourseTables(MyCourseTableParams params);\n\n}" } ]
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xuecheng.base.exception.CommonError; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.base.model.PageResult; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.learning.feignclient.ContentServiceClient; import com.xuecheng.learning.mapper.XcChooseCourseMapper; import com.xuecheng.learning.mapper.XcCourseTablesMapper; import com.xuecheng.learning.model.dto.MyCourseTableItemDto; import com.xuecheng.learning.model.dto.MyCourseTableParams; import com.xuecheng.learning.model.dto.XcChooseCourseDto; import com.xuecheng.learning.model.dto.XcCourseTablesDto; import com.xuecheng.learning.model.po.XcChooseCourse; import com.xuecheng.learning.model.po.XcCourseTables; import com.xuecheng.learning.service.MyCourseTablesService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List;
4,206
package com.xuecheng.learning.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName MyCourseTableServiceImpl * @since 2023/2/2 11:54 */ @Service public class MyCourseTableServicesImpl implements MyCourseTablesService { @Resource private XcChooseCourseMapper chooseCourseMapper; @Resource
package com.xuecheng.learning.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName MyCourseTableServiceImpl * @since 2023/2/2 11:54 */ @Service public class MyCourseTableServicesImpl implements MyCourseTablesService { @Resource private XcChooseCourseMapper chooseCourseMapper; @Resource
private XcCourseTablesMapper courseTablesMapper;
6
2023-11-13 11:39:35+00:00
8k
KafeinDev/InteractiveNpcs
src/main/java/dev/kafein/interactivenpcs/InteractiveNpcs.java
[ { "identifier": "Command", "path": "src/main/java/dev/kafein/interactivenpcs/command/Command.java", "snippet": "public interface Command {\n CommandProperties getProperties();\n\n String getName();\n\n List<String> getAliases();\n\n boolean isAlias(@NotNull String alias);\n\n String getDescription();\n\n String getUsage();\n\n @Nullable String getPermission();\n\n List<Command> getSubCommands();\n\n Command findSubCommand(@NotNull String sub);\n\n Command findSubCommand(@NotNull String... subs);\n\n int findSubCommandIndex(@NotNull String... subs);\n\n List<RegisteredTabCompletion> getTabCompletions();\n\n List<RegisteredTabCompletion> getTabCompletions(int index);\n\n void execute(@NotNull CommandSender sender, @NotNull String[] args);\n}" }, { "identifier": "InteractionCommand", "path": "src/main/java/dev/kafein/interactivenpcs/commands/InteractionCommand.java", "snippet": "public final class InteractionCommand extends AbstractCommand {\n private final InteractiveNpcs plugin;\n\n public InteractionCommand(InteractiveNpcs plugin) {\n super(CommandProperties.newBuilder()\n .name(\"interaction\")\n .usage(\"/interaction\")\n .description(\"Command for InteractiveNpcs plugin\")\n .permission(\"interactions.admin\")\n .build(),\n ImmutableList.of(\n new ReloadCommand(plugin)\n ));\n this.plugin = plugin;\n }\n\n @Override\n public void execute(@NotNull CommandSender sender, @NotNull String[] args) {\n\n }\n}" }, { "identifier": "Compatibility", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/Compatibility.java", "snippet": "public interface Compatibility {\n void initialize();\n}" }, { "identifier": "CompatibilityFactory", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityFactory.java", "snippet": "public final class CompatibilityFactory {\n private CompatibilityFactory() {\n }\n\n public static Compatibility createCompatibility(@NotNull CompatibilityType type, @NotNull InteractiveNpcs plugin) {\n switch (type) {\n case VAULT:\n return new VaultCompatibility(plugin);\n case CITIZENS:\n return new CitizensCompatibility(plugin);\n default:\n return null;\n }\n }\n}" }, { "identifier": "CompatibilityType", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityType.java", "snippet": "public enum CompatibilityType {\n VAULT(\"Vault\"),\n PLACEHOLDER_API(\"PlaceholderAPI\"),\n CITIZENS(\"Citizens\");\n\n private final String pluginName;\n\n CompatibilityType(String pluginName) {\n this.pluginName = pluginName;\n }\n\n public String getPluginName() {\n return this.pluginName;\n }\n}" }, { "identifier": "Config", "path": "src/main/java/dev/kafein/interactivenpcs/configuration/Config.java", "snippet": "public final class Config {\n private final ConfigType type;\n private final ConfigurationNode node;\n private final @Nullable Path path;\n\n public Config(ConfigType type, ConfigurationNode node, @Nullable Path path) {\n this.node = node;\n this.type = type;\n this.path = path;\n }\n\n public ConfigType getType() {\n return this.type;\n }\n\n public ConfigurationNode getNode() {\n return this.node;\n }\n\n public @Nullable Path getPath() {\n return this.path;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Config)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n\n Config config = (Config) obj;\n return Objects.equals(this.type, config.type)\n && Objects.equals(this.node, config.node)\n && Objects.equals(this.path, config.path);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.type, this.node, this.path);\n }\n\n @Override\n public String toString() {\n return \"Config{\" +\n \"type=\" + this.type +\n \", node=\" + this.node +\n \", path=\" + this.path +\n '}';\n }\n}" }, { "identifier": "ConfigVariables", "path": "src/main/java/dev/kafein/interactivenpcs/configuration/ConfigVariables.java", "snippet": "public final class ConfigVariables {\n private ConfigVariables() {}\n\n public static final ConfigKey<String> OFFSET_SYMBOL = ConfigKey.of(\"%img_offset_-1%\", \"offset-symbol\");\n\n public static final ConfigKey<List<String>> SPEECH_BUBBLE_LINES_FONTS = ConfigKey.of(ImmutableList.of(), \"speech\", \"bubble-lines\", \"fonts\");\n public static final ConfigKey<String> SPEECH_BUBBLE_LINES_DEFAULT_COLOR = ConfigKey.of(\"<black>\", \"speech\", \"bubble-lines\", \"default-color\");\n public static final ConfigKey<Integer> SPEECH_BUBBLE_LINES_DEFAULT_OFFSET = ConfigKey.of(0, \"speech\", \"bubble-lines\", \"default-offset\");\n public static final ConfigKey<String> SPEECH_BUBBLE_LINES_DEFAULT_IMAGE_SYMBOL = ConfigKey.of(\"%img_bubble%\", \"speech\", \"bubble-lines\", \"image\", \"default-symbol\");\n public static final ConfigKey<Integer> SPEECH_BUBBLE_LINES_DEFAULT_IMAGE_WIDTH = ConfigKey.of(0, \"speech\", \"bubble-lines\", \"image\", \"default-width\");\n}" }, { "identifier": "ConversationManager", "path": "src/main/java/dev/kafein/interactivenpcs/conversation/ConversationManager.java", "snippet": "public final class ConversationManager {\n private final InteractiveNpcs plugin;\n\n private final Cache<Integer, InteractiveEntity> interactiveEntities;\n private final Cache<UUID, Conversation> conversations;\n\n public ConversationManager(InteractiveNpcs plugin) {\n this.plugin = plugin;\n this.interactiveEntities = CacheBuilder.newBuilder()\n .build();\n this.conversations = CacheBuilder.newBuilder()\n .build();\n }\n\n public void initialize() {\n\n }\n\n public void interact(@NotNull UUID interactantUniqueId) {\n Player player = Bukkit.getPlayer(interactantUniqueId);\n if (player != null) {\n this.interact(player);\n }\n }\n\n public void interact(@NotNull Player player) {\n\n }\n\n public void interact(@NotNull Conversation conversation) {\n\n }\n\n public Cache<Integer, InteractiveEntity> getInteractiveEntities() {\n return this.interactiveEntities;\n }\n\n public InteractiveEntity getInteractiveEntity(int name) {\n return this.interactiveEntities.getIfPresent(name);\n }\n\n public void putInteractiveEntity(@NotNull InteractiveEntity interactiveEntity) {\n this.interactiveEntities.put(interactiveEntity.getId(), interactiveEntity);\n }\n\n public void removeInteractiveEntity(int name) {\n this.interactiveEntities.invalidate(name);\n }\n\n public Cache<UUID, Conversation> getConversations() {\n return this.conversations;\n }\n\n public Conversation getConversation(@NotNull UUID uuid) {\n return this.conversations.getIfPresent(uuid);\n }\n\n public void putConversation(@NotNull Conversation conversation) {\n this.conversations.put(conversation.getInteractantUniqueId(), conversation);\n }\n\n public void removeConversation(@NotNull UUID uuid) {\n this.conversations.invalidate(uuid);\n }\n}" }, { "identifier": "CharWidthMap", "path": "src/main/java/dev/kafein/interactivenpcs/conversation/text/font/CharWidthMap.java", "snippet": "public final class CharWidthMap {\n public static final int DEFAULT_WIDTH = 3;\n\n private final InteractiveNpcs plugin;\n private final Cache<Character, Integer> widths;\n\n public CharWidthMap(InteractiveNpcs plugin) {\n this.plugin = plugin;\n this.widths = CacheBuilder.newBuilder()\n .build();\n }\n\n public void initialize() {\n CharWidth[] values = CharWidth.values();\n for (CharWidth value : values) {\n this.widths.put(value.getCharacter(), value.getWidth());\n }\n\n //load from configs\n\n this.plugin.getLogger().info(\"CharWidthMap initialized.\");\n }\n\n public Cache<Character, Integer> getWidths() {\n return this.widths;\n }\n\n public int get(Character character) {\n return Optional.ofNullable(this.widths.getIfPresent(character))\n .orElse(DEFAULT_WIDTH);\n }\n\n public void put(Character character, int width) {\n this.widths.put(character, width);\n }\n\n public void remove(Character character) {\n this.widths.invalidate(character);\n }\n}" }, { "identifier": "AbstractBukkitPlugin", "path": "src/main/java/dev/kafein/interactivenpcs/plugin/AbstractBukkitPlugin.java", "snippet": "public abstract class AbstractBukkitPlugin implements BukkitPlugin {\n private final Plugin plugin;\n\n private ConfigManager configManager;\n private CommandManager commandManager;\n private BukkitAudiences bukkitAudiences;\n private ProtocolManager protocolManager;\n\n protected AbstractBukkitPlugin(Plugin plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void load() {\n onLoad();\n }\n\n public abstract void onLoad();\n\n @Override\n public void enable() {\n getLogger().info(\"Loading configs...\");\n this.configManager = new ConfigManager(getDataPath());\n loadConfigs();\n\n onEnable();\n\n this.bukkitAudiences = BukkitAudiences.create(this.plugin);\n\n getLogger().info(\"Starting tasks...\");\n startTasks();\n\n getLogger().info(\"Registering commands...\");\n this.commandManager = new CommandManager(this.plugin);\n registerCommands();\n\n getLogger().info(\"Registering listeners...\");\n registerListeners();\n\n this.protocolManager = ProtocolLibrary.getProtocolManager();\n }\n\n public abstract void onEnable();\n\n @Override\n public void disable() {\n onDisable();\n\n this.bukkitAudiences.close();\n }\n\n public abstract void onDisable();\n\n @Override\n public void registerCommands() {\n getCommands().forEach(command -> getCommandManager().registerCommand(command));\n }\n\n public abstract Set<Command> getCommands();\n\n @Override\n public void registerListeners() {\n ListenerRegistrar.register(this, getListeners());\n }\n\n public abstract Set<Class<?>> getListeners();\n\n @Override\n public Plugin getPlugin() {\n return this.plugin;\n }\n\n @Override\n public Path getDataPath() {\n return this.plugin.getDataFolder().toPath().toAbsolutePath();\n }\n\n @Override\n public Logger getLogger() {\n return this.plugin.getLogger();\n }\n\n @Override\n public ConfigManager getConfigManager() {\n return this.configManager;\n }\n\n @Override\n public CommandManager getCommandManager() {\n return this.commandManager;\n }\n\n @Override\n public BukkitAudiences getBukkitAudiences() {\n return this.bukkitAudiences;\n }\n\n @Override\n public ProtocolManager getProtocolManager() {\n return this.protocolManager;\n }\n}" }, { "identifier": "MovementControlTask", "path": "src/main/java/dev/kafein/interactivenpcs/tasks/MovementControlTask.java", "snippet": "public final class MovementControlTask implements Runnable {\n private final InteractiveNpcs plugin;\n\n public MovementControlTask(InteractiveNpcs plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void run() {\n/* Cache<UUID, Interaction> interactionCache = this.plugin.getInteractionManager().getInteractions();\n interactionCache.asMap().forEach((uuid, interact) -> {\n Player player = Bukkit.getPlayer(uuid);\n if (player == null) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n NpcProperties npcProperties = interact.getNpcProperties();\n\n InteractiveNpc interactiveNpc = this.plugin.getInteractionManager().getNpcs().getIfPresent(npcProperties.getId());\n if (interactiveNpc == null) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n Focus focus = interactiveNpc.getFocus();\n Location playerLocation = player.getLocation().clone();\n if (playerLocation.distance(interact.getFirstLocation()) > focus.getMaxDistance()) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n Location playerLastLocation = interact.getLastLocation();\n interact.setLastLocation(playerLocation);\n if (playerLocation.distance(playerLastLocation) > 0.1\n || playerLastLocation.getYaw() != playerLocation.getYaw()\n || playerLastLocation.getPitch() != playerLocation.getPitch()) {\n return;\n }\n\n if (player.hasMetadata(\"npc-interaction\")) {\n return;\n }\n\n Location npcEyeLocation = npcProperties.getEyeLocation().clone();\n Direction direction = new Direction(playerLocation);\n Direction targetDirection = new Direction(playerLocation, npcEyeLocation);\n\n if (!targetDirection.isNearly(direction)) {\n player.setMetadata(\"npc-interaction\", new FixedMetadataValue(this.plugin.getPlugin(), true));\n\n BukkitRunnable bukkitRunnable = new DirectionAdjuster(this.plugin.getPlugin(), player, targetDirection, focus.getSpeed());\n bukkitRunnable.runTaskTimer(this.plugin.getPlugin(), 0L, 1L);\n }\n });*/\n }\n}" } ]
import com.google.common.collect.ImmutableSet; import dev.kafein.interactivenpcs.command.Command; import dev.kafein.interactivenpcs.commands.InteractionCommand; import dev.kafein.interactivenpcs.compatibility.Compatibility; import dev.kafein.interactivenpcs.compatibility.CompatibilityFactory; import dev.kafein.interactivenpcs.compatibility.CompatibilityType; import dev.kafein.interactivenpcs.configuration.Config; import dev.kafein.interactivenpcs.configuration.ConfigVariables; import dev.kafein.interactivenpcs.conversation.ConversationManager; import dev.kafein.interactivenpcs.conversation.text.font.CharWidthMap; import dev.kafein.interactivenpcs.plugin.AbstractBukkitPlugin; import dev.kafein.interactivenpcs.tasks.MovementControlTask; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; import java.util.Set;
3,632
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override public Set<Command> getCommands() { return ImmutableSet.of( new InteractionCommand(this) ); } @Override public Set<Class<?>> getListeners() { return ImmutableSet.of(); } @Override public void startTasks() { BukkitScheduler scheduler = Bukkit.getScheduler(); scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L); } @Override public void loadConfigs() {
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override public Set<Command> getCommands() { return ImmutableSet.of( new InteractionCommand(this) ); } @Override public Set<Class<?>> getListeners() { return ImmutableSet.of(); } @Override public void startTasks() { BukkitScheduler scheduler = Bukkit.getScheduler(); scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L); } @Override public void loadConfigs() {
Config settingsConfig = getConfigManager().register("settings", getClass(), "/settings.yml", "settings.yml");
5
2023-11-18 10:12:16+00:00
8k
jensjeflensje/minecraft_typewriter
src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/BaseTypeWriter.java
[ { "identifier": "TypewriterPlugin", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java", "snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin instance;\n\n @Override\n public void onEnable() {\n instance = this;\n\n getCommand(\"typewriter\").setExecutor(new SpawnCommand());\n getCommand(\"wc\").setExecutor(new CompleteCommand());\n getCommand(\"wr\").setExecutor(new RemoveCommand());\n getCommand(\"w\").setExecutor(new WriteCommand());\n getCommand(\"w\").setTabCompleter(new WriteTabCompleter());\n\n playerWriters = new HashMap<>();\n\n }\n\n @Override\n public void onDisable() {\n playerWriters.values().forEach(TypeWriter::destroy);\n }\n}" }, { "identifier": "Util", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/Util.java", "snippet": "public class Util {\n\n /**\n * Get the location of an offset from a location, rotated by a yaw.\n * @param baseLocation the origin of the rotation\n * @param offset the offset as a vector. Only uses X and Z coordinates\n * @param baseYaw the yaw for the rotation\n * @param pitch pitch value to add to the location\n * @param yaw yaw value to add to the baseYaw after rotation\n * @return the resulting Location\n */\n public static Location getRotatedLocation(\n Location baseLocation,\n Vector offset,\n float baseYaw,\n float pitch,\n float yaw\n ) {\n Location rotatedLocation = baseLocation.clone();\n rotatedLocation.add(getRotatedVector(offset, baseYaw));\n rotatedLocation.setYaw(baseYaw + yaw);\n rotatedLocation.setPitch(pitch);\n return rotatedLocation;\n }\n\n public static Vector getRotatedVector(\n Vector offset,\n float baseYaw\n ) {\n double sinus = Math.sin(baseYaw / 180 * Math.PI);\n double cosinus = Math.cos(baseYaw / 180 * Math.PI);\n double newX = offset.getX() * cosinus - offset.getZ() * sinus;\n double newZ = offset.getZ() * cosinus + offset.getX() * sinus;\n return new Vector(newX, offset.getY(), newZ);\n }\n\n}" }, { "identifier": "TypeWriterComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/TypeWriterComponent.java", "snippet": "public interface TypeWriterComponent {\n\n void setUp(Location location);\n void destroy();\n\n\n}" }, { "identifier": "BarTypeWriterButtonComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/BarTypeWriterButtonComponent.java", "snippet": "public class BarTypeWriterButtonComponent extends BaseTypeWriterButtonComponent {\n\n private final double Y_VALUE = -0.15;\n\n private ItemStack skull;\n private List<ItemDisplay> skullDisplays;\n private int amount;\n\n @Getter\n private Location location;\n\n public BarTypeWriterButtonComponent(ItemStack skull, int amount) {\n this.skull = skull;\n this.amount = amount;\n this.skullDisplays = new ArrayList<>();\n }\n\n @Override\n public void setUp(Location location) {\n this.location = location;\n\n for (int i = 0; i < this.amount; i++) {\n Location displayLocation = Util.getRotatedLocation(\n location, new Vector(-(amount*0.05) + (0.1*i), Y_VALUE, 0), this.location.getYaw(), 0, 0);\n ItemDisplay skullDisplay = (ItemDisplay) location.getWorld().spawnEntity(\n displayLocation, EntityType.ITEM_DISPLAY);\n skullDisplay.setItemStack(this.skull);\n\n Transformation skullTransformation = skullDisplay.getTransformation();\n skullTransformation.getScale().set(0.2);\n skullDisplay.setTransformation(skullTransformation);\n\n this.skullDisplays.add(skullDisplay);\n }\n\n }\n\n @Override\n public void destroy() {\n this.skullDisplays.forEach(Entity::remove);\n }\n\n /**\n * Plays pressing animation.\n */\n public void press() {\n new TypeWriterButtonComponentRunnable(this).runTaskTimer(TypewriterPlugin.getInstance(), 0, 1);\n this.location.getWorld().playSound(\n this.location, Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, SoundCategory.MASTER, 2f, 2f);\n }\n\n /**\n * Teleport each display to a specific offset from its original location.\n * @param offset a vector containing the offset\n */\n public void offsetTeleport(Vector offset) {\n this.skullDisplays.forEach(display -> {\n Location displayLocation = display.getLocation();\n displayLocation.setY(this.location.getY() + Y_VALUE);\n displayLocation.add(offset);\n display.teleport(displayLocation);\n });\n }\n}" }, { "identifier": "BaseTypeWriterButtonComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/BaseTypeWriterButtonComponent.java", "snippet": "public abstract class BaseTypeWriterButtonComponent implements TypeWriterComponent, TypeWriterButtonComponent{\n}" }, { "identifier": "CubeTypeWriterButtonComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/CubeTypeWriterButtonComponent.java", "snippet": "public class CubeTypeWriterButtonComponent extends BaseTypeWriterButtonComponent {\n\n private ItemStack skull;\n private ItemDisplay skullDisplay;\n private BlockDisplay pinDisplay;\n\n @Getter\n private Location location;\n private Location pinLocation;\n\n public CubeTypeWriterButtonComponent(ItemStack skull) {\n this.skull = skull;\n }\n\n @Override\n public void setUp(Location location) {\n this.location = location;\n this.pinLocation = this.location.clone().add(\n Util.getRotatedVector(new Vector(-0.05, -0.05, -0.01), this.location.getYaw()));\n\n this.skullDisplay = (ItemDisplay) location.getWorld().spawnEntity(\n location, EntityType.ITEM_DISPLAY);\n this.skullDisplay.setItemStack(this.skull);\n\n Transformation skullTransformation = this.skullDisplay.getTransformation();\n skullTransformation.getScale().set(0.2);\n this.skullDisplay.setTransformation(skullTransformation);\n\n this.pinDisplay = (BlockDisplay) location.getWorld().spawnEntity(\n this.pinLocation, EntityType.BLOCK_DISPLAY);\n this.pinDisplay.setBlock(Material.OAK_FENCE.createBlockData());\n this.pinDisplay.setBrightness(new Display.Brightness(3, 3));\n Transformation transformation = this.pinDisplay.getTransformation();\n transformation.getScale().set(0.1, 0.3, 0.1);\n transformation.getLeftRotation().setAngleAxis(Math.toRadians(90), 1, 0, 0);\n this.pinDisplay.setTransformation(transformation);\n }\n\n @Override\n public void destroy() {\n this.skullDisplay.remove();\n this.pinDisplay.remove();\n }\n\n /**\n * Plays pressing animation.\n */\n public void press() {\n new TypeWriterButtonComponentRunnable(this).runTaskTimer(TypewriterPlugin.getInstance(), 0, 1);\n this.location.getWorld().playSound(\n this.location, Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, SoundCategory.MASTER, 2f, 2f);\n }\n\n public void offsetTeleport(Vector offset) {\n this.skullDisplay.teleport(this.location.clone().add(offset));\n this.pinDisplay.teleport(this.pinLocation.clone().add(offset));\n }\n}" }, { "identifier": "MainTypeWriterCasingComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/casing/MainTypeWriterCasingComponent.java", "snippet": "public class MainTypeWriterCasingComponent implements TypeWriterComponent {\n\n private BlockDisplay display;\n private Location location;\n\n @Override\n public void setUp(Location location) {\n this.location = location;\n\n this.display = (BlockDisplay) location.getWorld().spawnEntity(\n location, EntityType.BLOCK_DISPLAY);\n this.display.setBlock(Material.STRIPPED_DARK_OAK_WOOD.createBlockData());\n this.display.setBrightness(new Display.Brightness(15, 15));\n Transformation transformation = this.display.getTransformation();\n transformation.getScale().set(2.5, 1, 1.65);\n transformation.getLeftRotation().setAngleAxis(Math.toRadians(10), 1, 0, 0);\n this.display.setTransformation(transformation);\n }\n\n @Override\n public void destroy() {\n this.display.remove();\n }\n\n}" }, { "identifier": "PaperTypeWriterComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/paper/PaperTypeWriterComponent.java", "snippet": "public class PaperTypeWriterComponent implements TypeWriterComponent {\n\n // 2.16 is just magic\n // this is needed because Display.getWidth() always returns 0.0\n // I know it's stupid... but I haven't figured out what I should do, yet :P\n private final float TEXT_MAGIC = 2.16f;\n private final float PAPER_MAGIC = 4.35f; // another one\n\n private final float TEXT_SIZE = 0.20f;\n private final TextColor TEXT_COLOR = TextColor.color(0);\n private final int LINE_WIDTH = 175;\n private final float LINE_OFFSET = 0.05f;\n\n private ItemDisplay paperDisplay;\n private List<TextDisplay> textDisplays;\n private Location paperLocation;\n private Location textLocation;\n\n @Override\n public void setUp(Location location) {\n this.paperLocation = location.clone().add(Util.getRotatedVector(\n new Vector(\n -0.37, // start writing on the left of the paper\n -0.55, // a bit down so it starts at the top\n 0\n ),\n location.getYaw()\n ));\n\n this.textLocation = location.clone().add(location.getDirection().multiply(-0.1)); // a bit off the paper\n this.textLocation.setYaw(this.textLocation.getYaw() + 180); // flip so it's facing the player\n this.textLocation = Util.getRotatedLocation( // in the middle of the keyboard\n this.textLocation, new Vector(0.05, 0, 0), this.textLocation.getYaw(), 0, 0);\n\n this.paperDisplay = (ItemDisplay) this.paperLocation.getWorld().spawnEntity(\n this.paperLocation, EntityType.ITEM_DISPLAY);\n this.paperDisplay.setItemStack(new ItemStack(Material.PAPER));\n Transformation paperTransformation = this.paperDisplay.getTransformation();\n paperTransformation.getLeftRotation().setAngleAxis(-0.9, 0, 0, 1);\n paperTransformation.getScale().set(2.2);\n this.paperDisplay.setTransformation(paperTransformation);\n\n this.textDisplays = new ArrayList<>();\n\n this.newLine();\n }\n\n @Override\n public void destroy() {\n this.paperDisplay.remove();\n this.textDisplays.forEach(TextDisplay::remove);\n }\n\n public void applyAllEntities(Consumer<Display> func) {\n func.accept(this.paperDisplay);\n this.textDisplays.forEach(func);\n }\n\n public void setAnimation(Vector movement, int delay, int duration) {\n applyAllEntities(display -> display.setInterpolationDelay(delay));\n applyAllEntities(display -> display.setInterpolationDuration(duration));\n applyAllEntities(display -> {\n Transformation transformation = display.getTransformation();\n transformation.getTranslation().set(movement.getX(), movement.getY(), movement.getZ());\n display.setTransformation(transformation);\n });\n }\n\n public void moveUp() {\n this.textDisplays.forEach(display -> display.teleport(display.getLocation().add(0, LINE_OFFSET, 0)));\n this.paperDisplay.teleport(this.paperLocation.add(0, LINE_OFFSET, 0));\n }\n\n public void newLine() {\n // move every line (+ paper) up to make room for the new one\n this.moveUp();\n\n String line = \"\";\n\n TextDisplay textDisplay = (TextDisplay) this.textLocation.getWorld().spawnEntity(\n this.textLocation, EntityType.TEXT_DISPLAY);\n textDisplay.setAlignment(TextDisplay.TextAlignment.LEFT);\n textDisplay.setText(line);\n textDisplay.setLineWidth(LINE_WIDTH);\n textDisplay.setBackgroundColor(Color.fromARGB(0));\n\n Transformation textTransformation = textDisplay.getTransformation();\n textTransformation.getScale().set(TEXT_SIZE);\n textDisplay.setTransformation(textTransformation);\n\n this.textDisplays.add(textDisplay);\n this.moveLeft(line);\n }\n\n public float getFontOffset(String text) {\n int lineWidth = MinecraftFont.Font.getWidth(text);\n return (TEXT_SIZE / LINE_WIDTH) * lineWidth;\n }\n\n /**\n * Move left to account for the text size growing from the center.\n */\n public void moveLeft(String data) {\n float offset = this.getFontOffset(data);\n TextDisplay currentDisplay = this.textDisplays.get(this.textDisplays.size() - 1);\n\n currentDisplay.teleport(\n Util.getRotatedLocation(\n this.textLocation,\n new Vector(-offset * TEXT_MAGIC, 0, 0),\n currentDisplay.getYaw(),\n 0,\n 0\n ));\n\n float paperOffset = offset * PAPER_MAGIC;\n\n this.paperDisplay.teleport(this.paperLocation.clone().add(Util.getRotatedVector(\n // same with 4.35 here...\n new Vector(paperOffset, 0, 0),\n this.paperLocation.getYaw()\n )));\n\n // every line except the current\n for (int i = 0; i < this.textDisplays.size() - 1; i++) {\n TextDisplay textDisplay = this.textDisplays.get(i);\n\n textDisplay.teleport(\n this.textLocation.clone().add(Util.getRotatedVector(\n new Vector(\n -paperOffset + this.getFontOffset(textDisplay.text().toString())\n * TEXT_MAGIC - 3.34f, // another magic value, sorry\n this.LINE_OFFSET * (this.textDisplays.size() - i - 1),\n 0\n ), // negative because paper is flipped\n textDisplay.getLocation().getYaw()\n ))\n );\n }\n }\n\n public void newData(String data) {\n while (MinecraftFont.Font.getWidth(data) > LINE_WIDTH - 4) { // 4 to provide some padding for large words\n data = data.substring(0, data.length() - 1); // can't have longer lines than the paper\n }\n this.textDisplays.get(this.textDisplays.size() - 1).text(Component.text(data, TEXT_COLOR));\n this.moveLeft(data);\n }\n}" } ]
import com.destroystokyo.paper.profile.PlayerProfile; import com.destroystokyo.paper.profile.ProfileProperty; import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin; import dev.jensderuiter.minecrafttypewriter.Util; import dev.jensderuiter.minecrafttypewriter.typewriter.component.TypeWriterComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.BarTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.BaseTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.CubeTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.casing.MainTypeWriterCasingComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.paper.PaperTypeWriterComponent; import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID;
4,066
package dev.jensderuiter.minecrafttypewriter.typewriter; public abstract class BaseTypeWriter implements TypeWriter { private final int MAX_LINES = 20; protected Location baseLocation; protected Vector playerDirection; protected float playerPitch; protected float playerYaw; protected float oppositeYaw; protected Player player; protected List<String> lines; protected String currentLine; protected List<TypeWriterComponent> components; protected HashMap<String, Vector> keyboardLayout; protected HashMap<String, String> keyboardTextures; protected HashMap<String, BaseTypeWriterButtonComponent> keyboardButtons; @Getter protected PaperTypeWriterComponent paperComponent; public BaseTypeWriter(Player player) { this.player = player; this.playerDirection = this.player.getLocation().getDirection().setY(0); // remove height this.playerPitch = this.player.getLocation().getPitch(); this.playerYaw = this.player.getLocation().getYaw(); this.oppositeYaw = this.playerYaw - 180; this.baseLocation = this.getBaseLocation(); this.components = new ArrayList<>(); this.keyboardLayout = this.getKeyboardLayout(); this.keyboardTextures = this.getKeyboardTextures(); this.keyboardButtons = new HashMap<>(); this.lines = new ArrayList<>(); this.currentLine = ""; TypewriterPlugin.playerWriters.put(player, this); } @Override public void setUp(Location location) { this.keyboardLayout.entrySet().forEach(entry -> { String texture = this.keyboardTextures.get(entry.getKey()); ItemStack skull = this.getSkull(texture); BaseTypeWriterButtonComponent component; if (!entry.getKey().equals(" ")) {
package dev.jensderuiter.minecrafttypewriter.typewriter; public abstract class BaseTypeWriter implements TypeWriter { private final int MAX_LINES = 20; protected Location baseLocation; protected Vector playerDirection; protected float playerPitch; protected float playerYaw; protected float oppositeYaw; protected Player player; protected List<String> lines; protected String currentLine; protected List<TypeWriterComponent> components; protected HashMap<String, Vector> keyboardLayout; protected HashMap<String, String> keyboardTextures; protected HashMap<String, BaseTypeWriterButtonComponent> keyboardButtons; @Getter protected PaperTypeWriterComponent paperComponent; public BaseTypeWriter(Player player) { this.player = player; this.playerDirection = this.player.getLocation().getDirection().setY(0); // remove height this.playerPitch = this.player.getLocation().getPitch(); this.playerYaw = this.player.getLocation().getYaw(); this.oppositeYaw = this.playerYaw - 180; this.baseLocation = this.getBaseLocation(); this.components = new ArrayList<>(); this.keyboardLayout = this.getKeyboardLayout(); this.keyboardTextures = this.getKeyboardTextures(); this.keyboardButtons = new HashMap<>(); this.lines = new ArrayList<>(); this.currentLine = ""; TypewriterPlugin.playerWriters.put(player, this); } @Override public void setUp(Location location) { this.keyboardLayout.entrySet().forEach(entry -> { String texture = this.keyboardTextures.get(entry.getKey()); ItemStack skull = this.getSkull(texture); BaseTypeWriterButtonComponent component; if (!entry.getKey().equals(" ")) {
component = new CubeTypeWriterButtonComponent(skull);
5
2023-11-18 20:44:30+00:00
8k
ZhiQinIsZhen/dubbo-springboot3
dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/controller/user/UserInfoController.java
[ { "identifier": "UserInfoVO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/vo/user/UserInfoVO.java", "snippet": "@Getter\n@Setter\npublic class UserInfoVO implements Serializable {\n @Serial\n private static final long serialVersionUID = 3401036150852744531L;\n\n @Schema(description = \"客户ID\")\n private Long userId;\n\n @Schema(description = \"真实名称\")\n @Desensitization(DesensitizationType.REAL_NAME)\n private String realName;\n\n @Schema(description = \"昵称\")\n private String nickName;\n\n @Desensitization(DesensitizationType.MOBILE)\n @Schema(description = \"手机号码\")\n private String mobile;\n\n @Desensitization(DesensitizationType.EMAIL)\n @Schema(description = \"邮箱地址\")\n private String email;\n\n @Schema(description = \"注册时间\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date registryTime;\n}" }, { "identifier": "UserLoginLogVO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/vo/user/UserLoginLogVO.java", "snippet": "@Getter\n@Setter\npublic class UserLoginLogVO implements Serializable {\n @Serial\n private static final long serialVersionUID = 378737454967076747L;\n\n @Schema(description = \"客户ID\")\n private Long userId;\n\n @Schema(description = \"登出方式(1:手机;2:邮箱)\")\n private Integer loginType;\n\n @Schema(description = \"登出设备(1移动端:;2:网页端)\")\n private Integer device;\n\n @Schema(description = \"登出时间\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date loginTime;\n\n @Schema(description = \"IP地址\")\n private String ip;\n}" }, { "identifier": "UserLogoutLogVO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/vo/user/UserLogoutLogVO.java", "snippet": "@Getter\n@Setter\npublic class UserLogoutLogVO implements Serializable {\n @Serial\n private static final long serialVersionUID = 787994069214271291L;\n\n @Schema(description = \"客户ID\")\n private Long userId;\n\n @Schema(description = \"登录方式(1:手机;2:邮箱)\")\n private Integer type;\n\n @Schema(description = \"登录设备(1移动端:;2:网页端)\")\n private Integer device;\n\n @Schema(description = \"登录时间\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date logoutTime;\n\n @Schema(description = \"IP地址\")\n private String ip;\n}" }, { "identifier": "PageDTO", "path": "dubbo-common/dubbo-common-api-starter/src/main/java/com/liyz/boot3/common/api/dto/PageDTO.java", "snippet": "@Getter\n@Setter\npublic class PageDTO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Schema(description = \"页码\", defaultValue = \"1\")\n @NotNull(groups = {PageQuery.class}, message = \"分页查询页码不能为空\")\n private Long pageNum = 1L;\n\n @Schema(description = \"每页数量\", defaultValue = \"10\")\n @NotNull(groups = {PageQuery.class}, message = \"分页查询每页数量不能为空\")\n private Long pageSize = 10L;\n\n public interface PageQuery {}\n\n public interface Query {}\n}" }, { "identifier": "PageResult", "path": "dubbo-common/dubbo-common-api-starter/src/main/java/com/liyz/boot3/common/api/result/PageResult.java", "snippet": "@Getter\n@Setter\n@JsonPropertyOrder({\"code\", \"message\", \"total\", \"pages\", \"pageNum\", \"pageSize\", \"hasNextPage\", \"data\"})\npublic class PageResult<T> {\n\n public PageResult() {}\n\n public PageResult(String code, String message) {\n this.code = code;\n this.message = message;\n this.total = 0L;\n this.pageNum = 1L;\n this.pageSize = 10L;\n }\n\n public PageResult(IExceptionService codeEnum) {\n this(codeEnum.getCode(), I18nMessageUtil.getMessage(codeEnum.getName(), codeEnum.getMessage(), null));\n }\n\n public PageResult(RemotePage<T> data) {\n this(CommonExceptionCodeEnum.SUCCESS);\n boolean isNull = data == null;\n this.setData(isNull ? List.of() : data.getList());\n this.total = isNull ? 0L : data.getTotal();\n this.pageNum = isNull ? 1 : data.getPageNum();\n this.pageSize = isNull ? 10 : data.getPageSize();\n }\n\n @Schema(description = \"code码\")\n private String code;\n\n @Schema(description = \"消息\")\n private String message;\n\n @Schema(description = \"总数量\")\n private Long total;\n\n @Schema(description = \"页码\")\n private Long pageNum;\n\n @Schema(description = \"每页条数\")\n private Long pageSize;\n\n @Schema(description = \"数据体\")\n private List<T> data;\n\n public static <T> PageResult<T> success(RemotePage<T> data) {\n return new PageResult<>(data);\n }\n\n public static <T> PageResult<T> error(String code, String message) {\n return new PageResult<T>(code, message);\n }\n\n public static <T> PageResult<T> error(IExceptionService codeEnum) {\n return new PageResult<>(codeEnum);\n }\n\n public void setPageNum(long pageNum) {\n this.pageNum = Math.max(1L, pageNum);\n }\n\n public void setPageSize(long pageSize) {\n this.pageSize = Math.max(1L, pageSize);\n }\n\n public long getPages() {\n return this.total % this.pageSize == 0 ? this.total / this.pageSize : this.total / this.pageSize + 1;\n }\n\n public boolean isHasNextPage() {\n return getPages() > pageNum;\n }\n}" }, { "identifier": "Result", "path": "dubbo-common/dubbo-common-api-starter/src/main/java/com/liyz/boot3/common/api/result/Result.java", "snippet": "@Getter\n@Setter\n@JsonPropertyOrder({\"code\", \"message\", \"data\"})\npublic class Result<T> {\n\n public Result(String code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public Result(T data) {\n this(CommonExceptionCodeEnum.SUCCESS);\n this.data = data;\n }\n\n public Result(IExceptionService codeEnum) {\n this(codeEnum.getCode(), I18nMessageUtil.getMessage(codeEnum.getName(), codeEnum.getMessage(), null));\n }\n\n @Schema(description = \"code码\")\n private String code;\n\n @Schema(description = \"消息\")\n private String message;\n\n @Schema(description = \"数据体\")\n private T data;\n\n public static <E> Result<E> success(E data) {\n return new Result<>(data);\n }\n\n public static <E> Result<E> success() {\n return success(null);\n }\n\n public static <E> Result<E> error(IExceptionService codeEnum) {\n return new Result<>(codeEnum);\n }\n\n public static <E> Result<E> error(String code, String message) {\n return new Result<>(code, message);\n }\n}" }, { "identifier": "PageBO", "path": "dubbo-common/dubbo-common-remote/src/main/java/com/liyz/boot3/common/remote/page/PageBO.java", "snippet": "@Getter\n@Setter\npublic class PageBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 页码\n */\n private Long pageNum = 1L;\n\n /**\n * 每页条数\n */\n private Long pageSize = 10L;\n}" }, { "identifier": "RemotePage", "path": "dubbo-common/dubbo-common-remote/src/main/java/com/liyz/boot3/common/remote/page/RemotePage.java", "snippet": "public class RemotePage<T> implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n public static <T> RemotePage<T> of() {\n return new RemotePage<>(List.of(), 0, 1, 10);\n }\n\n public static <T> RemotePage<T> of(List<T> list, long total, long pageNum, long pageSize) {\n return new RemotePage<>(list, total, pageNum, pageSize);\n }\n\n public RemotePage(List<T> list, long total, long pageNum, long pageSize) {\n this.list = list;\n this.total = total;\n this.pageNum = pageNum;\n this.pageSize = pageSize;\n }\n\n /**\n * 结果集\n */\n private List<T> list;\n\n /**\n * 总记录数\n */\n private long total;\n\n /**\n * 当前页\n */\n private long pageNum;\n\n /**\n * 每页的数量\n */\n private long pageSize;\n\n public List<T> getList() {\n return list;\n }\n\n public void setList(List<T> list) {\n this.list = list;\n }\n\n public long getTotal() {\n return total;\n }\n\n public void setTotal(long total) {\n this.total = total;\n }\n\n public long getPageNum() {\n return pageNum;\n }\n\n public void setPageNum(long pageNum) {\n this.pageNum = Math.max(1L, pageNum);\n }\n\n public long getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(long pageSize) {\n this.pageSize = Math.max(1L, pageSize);\n }\n\n public long getPages() {\n return this.total % this.pageSize == 0 ? this.total / this.pageSize : this.total / this.pageSize + 1;\n }\n\n public boolean isHasNextPage() {\n return getPages() > pageNum;\n }\n}" }, { "identifier": "BeanUtil", "path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/util/BeanUtil.java", "snippet": "@UtilityClass\npublic final class BeanUtil {\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @return 目标对象\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier) {\n return copyProperties(source, targetSupplier, null);\n }\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标对象\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (Objects.isNull(source)) {\n return null;\n }\n T target = targetSupplier.get();\n BeanUtils.copyProperties(source, target);\n if (Objects.nonNull(ext)) {\n ext.accept(source, target);\n }\n return target;\n }\n\n /**\n * 数组对象拷贝\n *\n * @param sources 原数组\n * @param targetSupplier 目标对象\n * @return 目标数组\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> List<T> copyList(List<S> sources, Supplier<T> targetSupplier) {\n return copyList(sources, targetSupplier, null);\n }\n\n /**\n * 数组对象拷贝\n *\n * @param sources 原数组\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标数组\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> List<T> copyList(List<S> sources, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (CollectionUtils.isEmpty(sources)) {\n return List.of();\n }\n return sources\n .stream()\n .map(source -> copyProperties(source, targetSupplier, ext))\n .collect(Collectors.toList());\n }\n\n /**\n * 分页对象拷贝\n *\n * @param pageSource 原对象\n * @param targetSupplier 目标对象\n * @return 目标分页\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> RemotePage<T> copyRemotePage(RemotePage<S> pageSource, Supplier<T> targetSupplier) {\n return copyRemotePage(pageSource, targetSupplier, null);\n }\n\n /**\n * 分页对象拷贝\n *\n * @param pageSource 原对象\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标分页\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> RemotePage<T> copyRemotePage(RemotePage<S> pageSource, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (Objects.isNull(pageSource)) {\n return RemotePage.of();\n }\n return new RemotePage<>(\n copyList(pageSource.getList(), targetSupplier, ext),\n pageSource.getTotal(),\n pageSource.getPageNum(),\n pageSource.getPageSize()\n );\n }\n}" }, { "identifier": "AuthContext", "path": "dubbo-common/dubbo-security-client-starter/src/main/java/com/liyz/boot3/security/client/context/AuthContext.java", "snippet": "public class AuthContext implements EnvironmentAware, ApplicationContextAware, InitializingBean {\n\n private static final InheritableThreadLocal<AuthUserBO> innerContext = new InheritableThreadLocal<>();\n\n private static String clientId;\n private static ApplicationContext applicationContext;\n private static AuthenticationManager authenticationManager;\n private static RemoteJwtParseService remoteJwtParseService;\n private static RemoteAuthService remoteAuthService;\n\n /**\n * 获取认证用户\n *\n * @return 认证用户\n */\n public static AuthUserBO getAuthUser() {\n return innerContext.get();\n }\n\n /**\n * 设置认证用户\n *\n * @param authUser 认证用户\n */\n public static void setAuthUser(AuthUserBO authUser) {\n innerContext.set(authUser);\n }\n\n /**\n * 移除认证用户\n */\n public static void remove() {\n innerContext.remove();\n }\n\n /**\n * 认证服务\n */\n public static class AuthService {\n\n /**\n * 用户注册\n *\n * @param authUserRegisterBO 用户注册参数\n * @return 是否注册成功\n */\n public static Boolean registry(AuthUserRegisterBO authUserRegisterBO) {\n authUserRegisterBO.setClientId(clientId);\n return remoteAuthService.registry(authUserRegisterBO);\n }\n\n /**\n * 登录\n *\n * @param authUserLoginBO 登录参数\n * @return 登录用户信息\n */\n public static AuthUserBO login(AuthUserLoginBO authUserLoginBO) {\n authUserLoginBO.setClientId(clientId);\n authUserLoginBO.setDevice(DeviceContext.getDevice(HttpServletContext.getRequest()));\n authUserLoginBO.setLoginType(LoginType.getByType(PatternUtil.checkMobileEmail(authUserLoginBO.getUsername())));\n authUserLoginBO.setIp(HttpServletContext.getIpAddress());\n Authentication authentication = new UsernamePasswordAuthenticationToken(\n Joiner.on(CommonServiceConstant.DEFAULT_JOINER).join(\n authUserLoginBO.getDevice().getType(),\n authUserLoginBO.getClientId(),\n authUserLoginBO.getUsername()),\n authUserLoginBO.getPassword());\n SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(authentication));\n AuthUserDetails authUserDetails = (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n Date checkTime = remoteAuthService.login(\n AuthUserLoginBO.builder()\n .clientId(authUserLoginBO.getClientId())\n .authId(authUserDetails.getAuthUser().getAuthId())\n .loginType(authUserLoginBO.getLoginType())\n .device(authUserLoginBO.getDevice())\n .ip(authUserLoginBO.getIp())\n .build());\n return BeanUtil.copyProperties(authUserDetails.getAuthUser(), AuthUserBO::new, (s, t) -> {\n t.setPassword(null);\n t.setSalt(null);\n s.setCheckTime(checkTime);\n t.setToken(JwtService.generateToken(s));\n });\n }\n\n /**\n * 根据登录名查询用户信息\n *\n * @param username 用户名\n * @return 用户信息\n */\n public static AuthUserBO loadByUsername(String username, Device device) {\n return remoteAuthService.loadByUsername(username, device);\n }\n\n /**\n * 登出\n *\n * @return 是否登出成功\n */\n public static Boolean logout() {\n SecurityContextHolder.clearContext();\n AuthUserBO authUser = getAuthUser();\n if (Objects.isNull(authUser)) {\n return Boolean.FALSE;\n }\n AuthUserLogoutBO authUserLogoutBO = BeanUtil.copyProperties(authUser, AuthUserLogoutBO::new, (s, t) -> {\n t.setLogoutType(s.getLoginType());\n t.setDevice(s.getDevice());\n t.setIp(HttpServletContext.getIpAddress());\n });\n return remoteAuthService.logout(authUserLogoutBO);\n }\n }\n\n /**\n * JWT服务\n */\n public static class JwtService {\n\n /**\n * 解析token\n *\n * @param token jwt\n * @return 用户信息\n */\n public static AuthUserBO parseToken(final String token) {\n return remoteJwtParseService.parseToken(token, clientId);\n }\n\n /**\n * 创建token\n *\n * @param authUser 认证用户信息\n * @return jwt\n */\n public static String generateToken(final AuthUserBO authUser) {\n authUser.setClientId(clientId);\n return remoteJwtParseService.generateToken(authUser);\n }\n\n /**\n * 获取失效时间\n *\n * @param token jwt\n * @return 失效时间戳\n */\n public static Long getExpiration(final String token) {\n return remoteJwtParseService.getExpiration(token);\n }\n }\n\n @Override\n public void afterPropertiesSet() throws Exception {\n remoteAuthService = applicationContext.getBean(SecurityClientConstant.AUTH_SERVICE_BEAN_NAME, RemoteAuthService.class);\n remoteJwtParseService = applicationContext.getBean(SecurityClientConstant.JWT_SERVICE_BEAN_NAME, RemoteJwtParseService.class);\n authenticationManager = applicationContext.getBean(SecurityClientConstant.AUTH_MANAGER_BEAN_NAME, AuthenticationManager.class);\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n AuthContext.applicationContext = applicationContext;\n }\n\n @Override\n public void setEnvironment(Environment environment) {\n clientId = environment.getProperty(SecurityClientConstant.DUBBO_APPLICATION_NAME_PROPERTY);\n }\n}" }, { "identifier": "AuthUserBO", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/bo/AuthUserBO.java", "snippet": "@Getter\n@Setter\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AuthUserBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 6046110472442516409L;\n\n /**\n * 用户id\n */\n private Long authId;\n\n /**\n * 用户名\n */\n private String username;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 加密盐\n */\n private String salt;\n\n /**\n * 客户端ID\n */\n private String clientId;\n\n /**\n * token\n */\n private String token;\n\n /**\n * 登录类型\n * @see com.liyz.boot3.service.auth.enums.LoginType\n */\n private LoginType loginType;\n\n /**\n * 登录设备\n * @see com.liyz.boot3.service.auth.enums.Device\n */\n private Device device;\n\n /**\n * 检查时间\n * 用于是否但设备登录的\n */\n private Date checkTime;\n\n /**\n * 用户角色\n */\n private List<Integer> roleIds;\n\n /**\n * 权限列表\n */\n private List<AuthGrantedAuthorityBO> authorities = new ArrayList<>();\n\n @Getter\n @Setter\n public static class AuthGrantedAuthorityBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 客户端ID\n */\n private String clientId;\n\n /**\n * 权限码\n */\n private String authorityCode;\n }\n}" }, { "identifier": "UserLoginLogBO", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/bo/UserLoginLogBO.java", "snippet": "@Getter\n@Setter\npublic class UserLoginLogBO implements Serializable {\n @Serial\n private static final long serialVersionUID = -8978119199629210583L;\n\n private Long userId;\n\n /**\n * 登录方式:1:手机;2:邮箱\n */\n private Integer loginType;\n\n private Integer device;\n\n private Date loginTime;\n\n private String ip;\n}" }, { "identifier": "UserLogoutLogBO", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/bo/UserLogoutLogBO.java", "snippet": "@Getter\n@Setter\npublic class UserLogoutLogBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 3070437801653890936L;\n\n private Long userId;\n\n /**\n * 登录方式:1:手机;2:邮箱\n */\n private Integer logoutType;\n\n private Integer device;\n\n private Date logoutTime;\n\n private String ip;\n}" }, { "identifier": "RemoteUserInfoService", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/remote/RemoteUserInfoService.java", "snippet": "public interface RemoteUserInfoService {\n\n /**\n * 根据userId获取用户信息\n *\n * @param userId 用户ID\n * @return 用户信息\n */\n UserInfoBO getByUserId(@NotNull(message = \"用户ID不能为空\") Long userId);\n\n /**\n * 分页查询客户信息\n *\n * @param pageBO 分页参数\n * @return 客户信息\n */\n RemotePage<UserInfoBO> page(@NotNull(message = \"分页参数不能为空\") PageBO pageBO);\n}" }, { "identifier": "RemoteUserLoginLogService", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/remote/RemoteUserLoginLogService.java", "snippet": "public interface RemoteUserLoginLogService {\n\n /**\n * 根据userId分页查询登录日志\n *\n * @param userId 用户ID\n * @param pageBO 分页参数\n * @return 用户登录日志\n */\n RemotePage<UserLoginLogBO> page(@NotNull Long userId, @NotNull PageBO pageBO);\n\n /**\n * 根据userId分页流式查询登录日志\n *\n * @param userId 用户ID\n * @param pageBO 分页参数\n * @return 用户登录日志\n */\n RemotePage<UserLoginLogBO> pageStream(@NotNull Long userId, @NotNull PageBO pageBO);\n}" }, { "identifier": "RemoteUserLogoutLogService", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/remote/RemoteUserLogoutLogService.java", "snippet": "public interface RemoteUserLogoutLogService {\n\n /**\n * 根据userId分页查询登出日志\n *\n * @param userId 用户ID\n * @param pageBO 分页参数\n * @return 用户登出日志\n */\n RemotePage<UserLogoutLogBO> page(@NotNull Long userId, @NotNull PageBO pageBO);\n}" } ]
import com.github.xiaoymin.knife4j.annotations.ApiSort; import com.liyz.boot3.api.user.vo.user.UserInfoVO; import com.liyz.boot3.api.user.vo.user.UserLoginLogVO; import com.liyz.boot3.api.user.vo.user.UserLogoutLogVO; import com.liyz.boot3.common.api.dto.PageDTO; import com.liyz.boot3.common.api.result.PageResult; import com.liyz.boot3.common.api.result.Result; import com.liyz.boot3.common.remote.page.PageBO; import com.liyz.boot3.common.remote.page.RemotePage; import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.security.client.context.AuthContext; import com.liyz.boot3.service.auth.bo.AuthUserBO; import com.liyz.boot3.service.user.bo.UserLoginLogBO; import com.liyz.boot3.service.user.bo.UserLogoutLogBO; import com.liyz.boot3.service.user.remote.RemoteUserInfoService; import com.liyz.boot3.service.user.remote.RemoteUserLoginLogService; import com.liyz.boot3.service.user.remote.RemoteUserLogoutLogService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.DubboReference; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Objects;
6,716
package com.liyz.boot3.api.user.controller.user; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/12/6 10:47 */ @ApiSort(3) @Tag(name = "用户信息") @ApiResponses(value = { @ApiResponse(responseCode = "0", description = "成功"), @ApiResponse(responseCode = "1", description = "失败") }) @Slf4j @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) @RestController @RequestMapping("/user") public class UserInfoController { @DubboReference private RemoteUserInfoService remoteUserInfoService; @DubboReference private RemoteUserLoginLogService remoteUserLoginLogService; @DubboReference private RemoteUserLogoutLogService remoteUserLogoutLogService; @Operation(summary = "查询当前登录用户信息") @GetMapping("/current") public Result<UserInfoVO> userInfo() { AuthUserBO authUserBO = AuthContext.getAuthUser(); return Result.success(BeanUtil.copyProperties(remoteUserInfoService.getByUserId(authUserBO.getAuthId()), UserInfoVO::new)); } @Operation(summary = "分页查询用户登录日志") @GetMapping("/loginLogs/page") public PageResult<UserLoginLogVO> pageLoginLogs(PageDTO page) { AuthUserBO authUserBO = AuthContext.getAuthUser(); page = Objects.nonNull(page) ? page : new PageDTO();
package com.liyz.boot3.api.user.controller.user; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/12/6 10:47 */ @ApiSort(3) @Tag(name = "用户信息") @ApiResponses(value = { @ApiResponse(responseCode = "0", description = "成功"), @ApiResponse(responseCode = "1", description = "失败") }) @Slf4j @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) @RestController @RequestMapping("/user") public class UserInfoController { @DubboReference private RemoteUserInfoService remoteUserInfoService; @DubboReference private RemoteUserLoginLogService remoteUserLoginLogService; @DubboReference private RemoteUserLogoutLogService remoteUserLogoutLogService; @Operation(summary = "查询当前登录用户信息") @GetMapping("/current") public Result<UserInfoVO> userInfo() { AuthUserBO authUserBO = AuthContext.getAuthUser(); return Result.success(BeanUtil.copyProperties(remoteUserInfoService.getByUserId(authUserBO.getAuthId()), UserInfoVO::new)); } @Operation(summary = "分页查询用户登录日志") @GetMapping("/loginLogs/page") public PageResult<UserLoginLogVO> pageLoginLogs(PageDTO page) { AuthUserBO authUserBO = AuthContext.getAuthUser(); page = Objects.nonNull(page) ? page : new PageDTO();
RemotePage<UserLoginLogBO> remotePage = remoteUserLoginLogService.page(authUserBO.getAuthId(), BeanUtil.copyProperties(page, PageBO::new));
11
2023-11-13 01:28:21+00:00
8k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/rest/UserController.java
[ { "identifier": "RsaProperties", "path": "dimple-common/src/main/java/com/dimple/config/RsaProperties.java", "snippet": "@Data\n@Component\npublic class RsaProperties {\n\n public static String privateKey;\n\n @Value(\"${rsa.private_key}\")\n public void setPrivateKey(String privateKey) {\n RsaProperties.privateKey = privateKey;\n }\n}" }, { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) {\n super(msg);\n }\n\n public BadRequestException(HttpStatus status, String msg) {\n super(msg);\n this.status = status.value();\n }\n}" }, { "identifier": "User", "path": "dimple-system/src/main/java/com/dimple/modules/system/domain/User.java", "snippet": "@Entity\n@Getter\n@Setter\n@Table(name = \"sys_user\")\npublic class User extends BaseEntity implements Serializable {\n\n @Id\n @Column(name = \"user_id\")\n @NotNull(groups = Update.class)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @ApiModelProperty(value = \"ID\", hidden = true)\n private Long id;\n\n @ManyToMany\n @ApiModelProperty(value = \"用户角色\")\n @JoinTable(name = \"sys_users_roles\",\n joinColumns = {@JoinColumn(name = \"user_id\", referencedColumnName = \"user_id\")},\n inverseJoinColumns = {@JoinColumn(name = \"role_id\", referencedColumnName = \"role_id\")})\n private Set<Role> roles;\n\n @NotBlank\n @Column(unique = true)\n @ApiModelProperty(value = \"用户名称\")\n private String username;\n\n @NotBlank\n @ApiModelProperty(value = \"用户昵称\")\n private String nickName;\n\n @Email\n @NotBlank\n @ApiModelProperty(value = \"邮箱\")\n private String email;\n\n @NotBlank\n @ApiModelProperty(value = \"电话号码\")\n private String phone;\n\n @ApiModelProperty(value = \"用户性别\")\n private String gender;\n\n @ApiModelProperty(value = \"头像真实名称\", hidden = true)\n private String avatarName;\n\n @ApiModelProperty(value = \"头像存储的路径\", hidden = true)\n private String avatarPath;\n\n @ApiModelProperty(value = \"密码\")\n private String password;\n\n @NotNull\n @ApiModelProperty(value = \"是否启用\")\n private Boolean enabled;\n\n @ApiModelProperty(value = \"是否为admin账号\", hidden = true)\n private Boolean isAdmin = false;\n\n @Column(name = \"pwd_reset_time\")\n @ApiModelProperty(value = \"最后修改密码的时间\", hidden = true)\n private Date pwdResetTime;\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n User user = (User) o;\n return Objects.equals(id, user.id) &&\n Objects.equals(username, user.username);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, username);\n }\n}" }, { "identifier": "UserPassVO", "path": "dimple-system/src/main/java/com/dimple/modules/system/domain/vo/UserPassVO.java", "snippet": "@Data\npublic class UserPassVO {\n\n private String oldPass;\n\n private String newPass;\n}" }, { "identifier": "RoleService", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/RoleService.java", "snippet": "public interface RoleService {\n\n /**\n * 查询全部数据\n *\n * @return /\n */\n List<RoleDTO> queryAll();\n\n /**\n * 根据ID查询\n *\n * @param id /\n * @return /\n */\n RoleDTO findById(long id);\n\n /**\n * 创建\n *\n * @param resources /\n */\n void create(Role resources);\n\n /**\n * 编辑\n *\n * @param resources /\n */\n void update(Role resources);\n\n /**\n * 删除\n *\n * @param ids /\n */\n void delete(Set<Long> ids);\n\n /**\n * 根据用户ID查询\n *\n * @param id 用户ID\n * @return /\n */\n List<RoleSmallDTO> findByUsersId(Long id);\n\n /**\n * 根据角色查询角色级别\n *\n * @param roles /\n * @return /\n */\n Integer findByRoles(Set<Role> roles);\n\n /**\n * 修改绑定的菜单\n *\n * @param resources /\n * @param roleDTO /\n */\n void updateMenu(Role resources, RoleDTO roleDTO);\n\n /**\n * 解绑菜单\n *\n * @param id /\n */\n void untiedMenu(Long id);\n\n /**\n * 待条件分页查询\n *\n * @param criteria 条件\n * @param pageable 分页参数\n * @return /\n */\n Object queryAll(RoleQueryCriteria criteria, Pageable pageable);\n\n /**\n * 查询全部\n *\n * @param criteria 条件\n * @return /\n */\n List<RoleDTO> queryAll(RoleQueryCriteria criteria);\n\n /**\n * 导出数据\n *\n * @param queryAll 待导出的数据\n * @param response /\n * @throws IOException /\n */\n void download(List<RoleDTO> queryAll, HttpServletResponse response) throws IOException;\n\n /**\n * 获取用户权限信息\n *\n * @param user 用户信息\n * @return 权限信息\n */\n List<GrantedAuthority> mapToGrantedAuthorities(UserDTO user);\n\n /**\n * 验证是否被用户关联\n *\n * @param ids /\n */\n void verification(Set<Long> ids);\n\n /**\n * 根据菜单Id查询\n *\n * @param menuIds /\n * @return /\n */\n List<Role> findInMenuId(List<Long> menuIds);\n}" }, { "identifier": "UserService", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/UserService.java", "snippet": "public interface UserService {\n\n /**\n * 根据ID查询\n *\n * @param id ID\n * @return /\n */\n UserDTO findById(long id);\n\n /**\n * 新增用户\n *\n * @param resources /\n */\n void create(User resources);\n\n /**\n * 编辑用户\n *\n * @param resources /\n */\n void update(User resources);\n\n /**\n * 删除用户\n *\n * @param ids /\n */\n void delete(Set<Long> ids);\n\n /**\n * 根据用户名查询\n *\n * @param userName /\n * @return /\n */\n UserDTO findByName(String userName);\n\n /**\n * 修改密码\n *\n * @param username 用户名\n * @param encryptPassword 密码\n */\n void updatePass(String username, String encryptPassword);\n\n /**\n * 修改头像\n *\n * @param file 文件\n * @return /\n */\n Map<String, String> updateAvatar(MultipartFile file);\n\n /**\n * 修改邮箱\n *\n * @param username 用户名\n * @param email 邮箱\n */\n void updateEmail(String username, String email);\n\n /**\n * 查询全部\n *\n * @param criteria 条件\n * @param pageable 分页参数\n * @return /\n */\n Object queryAll(UserQueryCriteria criteria, Pageable pageable);\n\n /**\n * 查询全部不分页\n *\n * @param criteria 条件\n * @return /\n */\n List<UserDTO> queryAll(UserQueryCriteria criteria);\n\n /**\n * 导出数据\n *\n * @param queryAll 待导出的数据\n * @param response /\n * @throws IOException /\n */\n void download(List<UserDTO> queryAll, HttpServletResponse response) throws IOException;\n\n /**\n * 用户自助修改资料\n *\n * @param resources /\n */\n void updateCenter(User resources);\n}" }, { "identifier": "VerifyService", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/VerifyService.java", "snippet": "public interface VerifyService {\n\n /**\n * 发送验证码\n *\n * @param email /\n * @param key /\n * @return /\n */\n EmailVO sendEmail(String email, String key);\n\n\n /**\n * 验证\n *\n * @param code /\n * @param key /\n */\n void validated(String key, String code);\n}" }, { "identifier": "RoleSmallDTO", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/dto/RoleSmallDTO.java", "snippet": "@Data\npublic class RoleSmallDTO implements Serializable {\n\n private Long id;\n\n private String name;\n\n private Integer level;\n}" }, { "identifier": "UserDTO", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/dto/UserDTO.java", "snippet": "@Getter\n@Setter\npublic class UserDTO extends BaseDTO implements Serializable {\n\n private Long id;\n\n private Set<RoleSmallDTO> roles;\n\n private Set<JobSmallDto> jobs;\n\n private String username;\n\n private String nickName;\n\n private String email;\n\n private String phone;\n\n private String gender;\n\n private String avatarName;\n\n private String avatarPath;\n\n @JsonIgnore\n private String password;\n\n private Boolean enabled;\n\n @JsonIgnore\n private Boolean isAdmin = false;\n\n private Date pwdResetTime;\n}" }, { "identifier": "UserQueryCriteria", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/dto/UserQueryCriteria.java", "snippet": "@Data\npublic class UserQueryCriteria implements Serializable {\n\n @Query\n private Long id;\n\n @Query(blurry = \"email,username,nickName\")\n private String blurry;\n\n @Query\n private Boolean enabled;\n\n @Query(type = Query.Type.BETWEEN)\n private List<Timestamp> createTime;\n}" }, { "identifier": "RsaUtils", "path": "dimple-common/src/main/java/com/dimple/utils/RsaUtils.java", "snippet": "public class RsaUtils {\n private static final String SRC = \"123456\";\n\n public static void main(String[] args) throws Exception {\n System.out.println(\"\\n\");\n RsaKeyPair keyPair = generateKeyPair();\n System.out.println(\"公钥:\" + keyPair.getPublicKey());\n System.out.println(\"私钥:\" + keyPair.getPrivateKey());\n System.out.println(\"\\n\");\n test1(keyPair);\n System.out.println(\"\\n\");\n test2(keyPair);\n System.out.println(\"\\n\");\n }\n\n /**\n * 公钥加密私钥解密\n */\n private static void test1(RsaKeyPair keyPair) throws Exception {\n System.out.println(\"***************** 公钥加密私钥解密开始 *****************\");\n String text1 = encryptByPublicKey(keyPair.getPublicKey(), RsaUtils.SRC);\n String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1);\n System.out.println(\"加密前:\" + RsaUtils.SRC);\n System.out.println(\"加密后:\" + text1);\n System.out.println(\"解密后:\" + text2);\n if (RsaUtils.SRC.equals(text2)) {\n System.out.println(\"解密字符串和原始字符串一致,解密成功\");\n } else {\n System.out.println(\"解密字符串和原始字符串不一致,解密失败\");\n }\n System.out.println(\"***************** 公钥加密私钥解密结束 *****************\");\n }\n\n /**\n * 私钥加密公钥解密\n *\n * @throws Exception /\n */\n private static void test2(RsaKeyPair keyPair) throws Exception {\n System.out.println(\"***************** 私钥加密公钥解密开始 *****************\");\n String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), RsaUtils.SRC);\n String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);\n System.out.println(\"加密前:\" + RsaUtils.SRC);\n System.out.println(\"加密后:\" + text1);\n System.out.println(\"解密后:\" + text2);\n if (RsaUtils.SRC.equals(text2)) {\n System.out.println(\"解密字符串和原始字符串一致,解密成功\");\n } else {\n System.out.println(\"解密字符串和原始字符串不一致,解密失败\");\n }\n System.out.println(\"***************** 私钥加密公钥解密结束 *****************\");\n }\n\n /**\n * 公钥解密\n *\n * @param publicKeyText 公钥\n * @param text 待解密的信息\n * @return /\n * @throws Exception /\n */\n public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {\n X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);\n Cipher cipher = Cipher.getInstance(\"RSA\");\n cipher.init(Cipher.DECRYPT_MODE, publicKey);\n byte[] result = cipher.doFinal(Base64.decodeBase64(text));\n return new String(result);\n }\n\n /**\n * 私钥加密\n *\n * @param privateKeyText 私钥\n * @param text 待加密的信息\n * @return /\n * @throws Exception /\n */\n public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {\n PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);\n Cipher cipher = Cipher.getInstance(\"RSA\");\n cipher.init(Cipher.ENCRYPT_MODE, privateKey);\n byte[] result = cipher.doFinal(text.getBytes());\n return Base64.encodeBase64String(result);\n }\n\n /**\n * 私钥解密\n *\n * @param privateKeyText 私钥\n * @param text 待解密的文本\n * @return /\n * @throws Exception /\n */\n public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {\n PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);\n Cipher cipher = Cipher.getInstance(\"RSA\");\n cipher.init(Cipher.DECRYPT_MODE, privateKey);\n byte[] result = cipher.doFinal(Base64.decodeBase64(text));\n return new String(result);\n }\n\n /**\n * 公钥加密\n *\n * @param publicKeyText 公钥\n * @param text 待加密的文本\n * @return /\n */\n public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {\n X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);\n Cipher cipher = Cipher.getInstance(\"RSA\");\n cipher.init(Cipher.ENCRYPT_MODE, publicKey);\n byte[] result = cipher.doFinal(text.getBytes());\n return Base64.encodeBase64String(result);\n }\n\n /**\n * 构建RSA密钥对\n *\n * @return /\n * @throws NoSuchAlgorithmException /\n */\n public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {\n KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n keyPairGenerator.initialize(1024);\n KeyPair keyPair = keyPairGenerator.generateKeyPair();\n RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();\n RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();\n String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());\n String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());\n return new RsaKeyPair(publicKeyString, privateKeyString);\n }\n\n\n /**\n * RSA密钥对对象\n */\n public static class RsaKeyPair {\n\n private final String publicKey;\n private final String privateKey;\n\n public RsaKeyPair(String publicKey, String privateKey) {\n this.publicKey = publicKey;\n this.privateKey = privateKey;\n }\n\n public String getPublicKey() {\n return publicKey;\n }\n\n public String getPrivateKey() {\n return privateKey;\n }\n\n }\n}" }, { "identifier": "SecurityUtils", "path": "dimple-common/src/main/java/com/dimple/utils/SecurityUtils.java", "snippet": "@Slf4j\npublic class SecurityUtils {\n\n /**\n * 获取当前登录的用户\n *\n * @return UserDetails\n */\n public static UserDetails getCurrentUser() {\n final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n if (authentication == null) {\n throw new BadRequestException(HttpStatus.UNAUTHORIZED, \"当前登录状态过期\");\n }\n if (authentication.getPrincipal() instanceof UserDetails) {\n UserDetails userDetails = (UserDetails) authentication.getPrincipal();\n UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class);\n return userDetailsService.loadUserByUsername(userDetails.getUsername());\n }\n throw new BadRequestException(HttpStatus.UNAUTHORIZED, \"找不到当前登录的信息\");\n }\n\n /**\n * 获取系统用户名称\n *\n * @return 系统用户名称\n */\n public static String getCurrentUsername() {\n final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n if (authentication == null) {\n throw new BadRequestException(HttpStatus.UNAUTHORIZED, \"当前登录状态过期\");\n }\n UserDetails userDetails = (UserDetails) authentication.getPrincipal();\n return userDetails.getUsername();\n }\n\n /**\n * 获取系统用户ID\n *\n * @return 系统用户ID\n */\n public static Long getCurrentUserId() {\n UserDetails userDetails = getCurrentUser();\n return new JSONObject(new JSONObject(userDetails).get(\"user\")).get(\"id\", Long.class);\n }\n\n}" }, { "identifier": "CodeEnum", "path": "dimple-system/src/main/java/com/dimple/utils/enums/CodeEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CodeEnum {\n\n /* 通过手机号码重置邮箱 */\n PHONE_RESET_EMAIL_CODE(\"phone_reset_email_code_\", \"通过手机号码重置邮箱\"),\n\n /* 通过旧邮箱重置邮箱 */\n EMAIL_RESET_EMAIL_CODE(\"email_reset_email_code_\", \"通过旧邮箱重置邮箱\"),\n\n /* 通过手机号码重置密码 */\n PHONE_RESET_PWD_CODE(\"phone_reset_pwd_code_\", \"通过手机号码重置密码\"),\n\n /* 通过邮箱重置密码 */\n EMAIL_RESET_PWD_CODE(\"email_reset_pwd_code_\", \"通过邮箱重置密码\");\n\n private final String key;\n private final String description;\n}" } ]
import com.dimple.annotation.OLog; import com.dimple.config.RsaProperties; import com.dimple.exception.BadRequestException; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.domain.vo.UserPassVO; import com.dimple.modules.system.service.RoleService; import com.dimple.modules.system.service.UserService; import com.dimple.modules.system.service.VerifyService; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.dto.UserDTO; import com.dimple.modules.system.service.dto.UserQueryCriteria; import com.dimple.utils.RsaUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.enums.CodeEnum; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors;
6,059
package com.dimple.modules.system.rest; /** * @className: UserController * @description: * @author: Dimple * @date: 06/17/20 */ @Api(tags = "系统:用户管理") @RestController @RequestMapping("/api/users") @RequiredArgsConstructor public class UserController { private final PasswordEncoder passwordEncoder; private final UserService userService; private final RoleService roleService; private final VerifyService verificationCodeService; @OLog("导出用户数据") @ApiOperation("导出用户数据") @GetMapping(value = "/download") @PreAuthorize("@ps.check('user:list')") public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { userService.download(userService.queryAll(criteria), response); } @OLog("查询用户") @ApiOperation("查询用户") @GetMapping @PreAuthorize("@ps.check('user:list')") public ResponseEntity<Object> query(UserQueryCriteria criteria, Pageable pageable) { return new ResponseEntity<>(userService.queryAll(criteria, pageable), HttpStatus.OK); } @OLog("新增用户") @ApiOperation("新增用户") @PostMapping @PreAuthorize("@ps.check('user:add')") public ResponseEntity<Object> create(@Validated @RequestBody User resources) { checkLevel(resources); // 默认密码 123456 resources.setPassword(passwordEncoder.encode("123456")); userService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @OLog("修改用户") @ApiOperation("修改用户") @PutMapping @PreAuthorize("@ps.check('user:edit')") public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources) { checkLevel(resources); userService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("修改用户:个人中心") @ApiOperation("修改用户:个人中心") @PutMapping(value = "center") public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources) { if (!resources.getId().equals(SecurityUtils.getCurrentUserId())) { throw new BadRequestException("不能修改他人资料"); } userService.updateCenter(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("删除用户") @ApiOperation("删除用户") @DeleteMapping @PreAuthorize("@ps.check('user:del')") public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) { for (Long id : ids) { Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername()); } } userService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改密码") @PostMapping(value = "/updatePass") public ResponseEntity<Object> updatePass(@RequestBody UserPassVO passVo) throws Exception { String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getOldPass()); String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getNewPass()); UserDTO user = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(oldPass, user.getPassword())) { throw new BadRequestException("修改失败,旧密码错误"); } if (passwordEncoder.matches(newPass, user.getPassword())) { throw new BadRequestException("新密码不能与旧密码相同"); } userService.updatePass(user.getUsername(), passwordEncoder.encode(newPass)); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改头像") @PostMapping(value = "/updateAvatar") public ResponseEntity<Object> updateAvatar(@RequestParam MultipartFile avatar) { return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); } @OLog("修改邮箱") @ApiOperation("修改邮箱") @PostMapping(value = "/updateEmail/{code}") public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword()); UserDTO userDto = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(password, userDto.getPassword())) { throw new BadRequestException("密码错误"); }
package com.dimple.modules.system.rest; /** * @className: UserController * @description: * @author: Dimple * @date: 06/17/20 */ @Api(tags = "系统:用户管理") @RestController @RequestMapping("/api/users") @RequiredArgsConstructor public class UserController { private final PasswordEncoder passwordEncoder; private final UserService userService; private final RoleService roleService; private final VerifyService verificationCodeService; @OLog("导出用户数据") @ApiOperation("导出用户数据") @GetMapping(value = "/download") @PreAuthorize("@ps.check('user:list')") public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { userService.download(userService.queryAll(criteria), response); } @OLog("查询用户") @ApiOperation("查询用户") @GetMapping @PreAuthorize("@ps.check('user:list')") public ResponseEntity<Object> query(UserQueryCriteria criteria, Pageable pageable) { return new ResponseEntity<>(userService.queryAll(criteria, pageable), HttpStatus.OK); } @OLog("新增用户") @ApiOperation("新增用户") @PostMapping @PreAuthorize("@ps.check('user:add')") public ResponseEntity<Object> create(@Validated @RequestBody User resources) { checkLevel(resources); // 默认密码 123456 resources.setPassword(passwordEncoder.encode("123456")); userService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @OLog("修改用户") @ApiOperation("修改用户") @PutMapping @PreAuthorize("@ps.check('user:edit')") public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources) { checkLevel(resources); userService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("修改用户:个人中心") @ApiOperation("修改用户:个人中心") @PutMapping(value = "center") public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources) { if (!resources.getId().equals(SecurityUtils.getCurrentUserId())) { throw new BadRequestException("不能修改他人资料"); } userService.updateCenter(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("删除用户") @ApiOperation("删除用户") @DeleteMapping @PreAuthorize("@ps.check('user:del')") public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) { for (Long id : ids) { Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername()); } } userService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改密码") @PostMapping(value = "/updatePass") public ResponseEntity<Object> updatePass(@RequestBody UserPassVO passVo) throws Exception { String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getOldPass()); String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getNewPass()); UserDTO user = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(oldPass, user.getPassword())) { throw new BadRequestException("修改失败,旧密码错误"); } if (passwordEncoder.matches(newPass, user.getPassword())) { throw new BadRequestException("新密码不能与旧密码相同"); } userService.updatePass(user.getUsername(), passwordEncoder.encode(newPass)); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改头像") @PostMapping(value = "/updateAvatar") public ResponseEntity<Object> updateAvatar(@RequestParam MultipartFile avatar) { return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); } @OLog("修改邮箱") @ApiOperation("修改邮箱") @PostMapping(value = "/updateEmail/{code}") public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword()); UserDTO userDto = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(password, userDto.getPassword())) { throw new BadRequestException("密码错误"); }
verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
12
2023-11-10 03:30:36+00:00
8k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/formatedit/additional/AdditionalInputEditPane.java
[ { "identifier": "AdditionalInfo", "path": "database/src/main/java/com/lazycoder/database/model/AdditionalInfo.java", "snippet": "@Data\npublic class AdditionalInfo extends AbstractFormatInfo {\n\n\tprivate int additionalSerialNumber = 0;\n\n\tpublic AdditionalInfo() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetFormatType(ADDITIONAL_TYPE);\n\t}\n\n}" }, { "identifier": "SysFileStructure", "path": "service/src/main/java/com/lazycoder/service/fileStructure/SysFileStructure.java", "snippet": "public class SysFileStructure {\n\n /**\n * 懒农文件使用后缀\n */\n public static final String PRO_SUFFIX = \".lannong\";\n\n /**\n * sqlite数据库后缀\n */\n public static final String SQLITE_SUFFIX = \".db\";\n\n// /**\n// * 当前程序目录\n// */\n//// public static final String sysDir = System.getProperty(\"user.dir\") + File.separator + \"app\";\n// public static String sysDir = DruidDBConfig.sysDir;\n\n /**\n * 用户使用时添加数据源的文件存放路径\n *\n * @return\n */\n public static File getDataFileFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"fileDataPath\");\n }\n\n /**\n * 根据此文件夹下的文件结构来进行列表显示\n *\n * @return\n */\n public static File getFileListFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"fileListPath\");\n }\n\n /**\n * 系统图片路径\n *\n * @return\n */\n public static File getImageFolder() {\n return LazyCoderBaseConfiguration.getImageFolder();\n }\n\n /**\n * 操作提示的图片路径\n * @param path 相对路径\n * @return\n */\n public static File getOperatingTipImageFolder(String path) {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"operatingTipImage\"+File.separator+path);\n }\n\n /**\n * 用户使用时添加的sqlite数据库的存放路径\n *\n * @return\n */\n public static File getUserDBFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"lannong_db\");\n }\n\n /**\n * 获取对应的sqlite数据库文件\n *\n * @param dataSourceName\n * @return\n */\n public static File getSqliteDBFile(String dataSourceName) {\n return new File(getUserDBFolder().getAbsolutePath() + File.separator + dataSourceName + SQLITE_SUFFIX);\n }\n\n /**\n * 系统数据库存放路径\n *\n * @return\n */\n public static File getSysDBFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"sysdb\");\n }\n\n public static File getSysDataSourceSqlite() {\n return new File(getSysDBFolder().getAbsolutePath() + File.separator + \"sysDataSource.db\");\n }\n\n /**\n * 临时文件夹(用来放一些文件)\n *\n * @return\n */\n protected static File getTempFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"temp\");\n }\n\n\n private static File appCoolFormatDll() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"CoolFormatLib.dll\");\n }\n\n private static File userCoolFormatDll() {\n //return new File(System.getProperty(\"user.dir\") + File.separator + \"CoolFormatLib.dll\");\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"CoolFormatLib.dll\");\n }\n\n\n /**\n * 获取verilog的配置文件\n *\n * @return\n */\n public static File getVerilogSettingFile() {\n //return new File(System.getProperty(\"user.dir\") + File.separator + \"verilog\"+File.separator+\".verilog-format.properties\");\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"verilog\" + File.separator + \".verilog-format.properties\");\n }\n\n /**\n * 生成系统结构\n */\n public static void generateSysFileStrucure() {\n File file = getSysDBFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getUserDBFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getFileListFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getDataFileFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getTempFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n }\n\n /**\n * 复制CoolFormat的dll\n */\n public static void copyCoolFormatDll() {\n if (userCoolFormatDll().exists() == false) {\n if (appCoolFormatDll().exists() == true) {\n try {\n FileUtil.fileCopyNormal(appCoolFormatDll(), userCoolFormatDll());\n FileUtil.setFileHidden(appCoolFormatDll());\n } catch (IOException e) {\n SysService.SYS_SERVICE_SERVICE.log_error( \"复制CoolFormat的dll出错,错误信息:\" + e.getMessage());\n }\n } else {\n SysService.SYS_SERVICE_SERVICE.log_error( \"CoolFormat的dll丢失\");\n }\n }\n }\n\n}" }, { "identifier": "AdditionalMetaModel", "path": "service/src/main/java/com/lazycoder/service/vo/meta/AdditionalMetaModel.java", "snippet": "@Data\n@NoArgsConstructor\npublic class AdditionalMetaModel extends AbstractMetaModel {\n\n\t/**\n\t * 操作模型\n\t */\n\t@JSONField(deserializeUsing = AdditionalOperatingDeserializer.class)\n\tprivate AdditionalOperating operatingModel = new AdditionalOperating();\n\n\t/**\n\t * 默认代码格式\n\t */\n\t@JSONField(deserializeUsing = FormatFileDeserializer.class)\n\tprivate GeneralFileFormat defaultCodeFormat = GeneralFileFormat.createAdditionalFormatFile();\n\n\t/**\n\t * 代码文件模型列表\n\t */\n\t@JSONField(deserializeUsing = FormatFilelListDeserializer.class)\n\tprivate List<GeneralFileFormat> codeModelList = new ArrayList<>();\n\n}" }, { "identifier": "AdditionalFunctionNameInputData", "path": "service/src/main/java/com/lazycoder/service/vo/save/AdditionalFunctionNameInputData.java", "snippet": "@Data\n@NoArgsConstructor\npublic class AdditionalFunctionNameInputData {\n\n private int additionalSerialNumber = 0;\n\n private ArrayList<FunctionNameData> functionNameDataList = new ArrayList<>();\n\n}" }, { "identifier": "AdditionalVariableInputData", "path": "service/src/main/java/com/lazycoder/service/vo/save/AdditionalVariableInputData.java", "snippet": "@Data\n@NoArgsConstructor\npublic class AdditionalVariableInputData {\n\n private int additionalSerialNumber = 0;\n\n private ArrayList<VariableData> variableDataList = new ArrayList<>();\n\n}" }, { "identifier": "AdditionalFormatControlPane", "path": "ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/inputmeta/pane/format/operation/AdditionalFormatControlPane.java", "snippet": "public class AdditionalFormatControlPane extends AbstractFormatControlInputPane {\n\n\t/**\n\t *\n\t */\n\tprivate static final long serialVersionUID = -5890799639415706438L;\n\n\tprivate transient List<OptionDataModel> listTemp;\n\n\t/**\n\t * 可选模板的标识编号\n\t */\n\t@Getter\n\tprivate int additionalSerialNumber = 0;\n\n\tprotected AdditionalFormatControlPane() {\n\t\tsuper();\n\t\tControlCondition condition = new ControlCondition(true, true, true, false);\n\t\tmenuInit(condition);\n\t}\n\n\tpublic AdditionalFormatControlPane(int additionalSerialNumber) {\n\t\tthis();\n\t\tthis.additionalSerialNumber = additionalSerialNumber;\n\t}\n\n\t/**\n\t * 还原\n\t *\n\t * @param additionalMetaModel\n\t * @param formatModel\n\t */\n\tpublic void restore(AdditionalMetaModel additionalMetaModel, FormatModel formatModel) {\n\t\tAdditionalOperating operating = additionalMetaModel.getOperatingModel();\n\t\tLazyCoderFormatControl.buildingOriginalOperatingPane(this, formatModel, operating);// 把操作模型参数写进格式模型\n\t}\n\n\n\t@Override\n\tprotected List<OptionDataModel> getCorrespondingChooseMenuList() {\n\t\tlistTemp = SysService.OPTION_SERVICE.getAdditionalOptionNameList(this.additionalSerialNumber);\n\t\treturn listTemp;\n\t}\n\n\t@Override\n\tprotected List<OptionDataModel> getUpdateChooseMenuList() {\n\t\treturn listTemp;\n\t}\n\n\t@Override\n\tprotected List<OptionDataModel> getDelCorrespondingChooseFromDBMenuList() {\n\t\treturn listTemp;\n\t}\n\n\t@Override\n\tpublic File getImageRootPath() {\n\t\tFile file = DatabaseFileStructure.getAdditionalPictureFolder(SysFileStructure.getDataFileFolder(),\n\t\t\t\tGeneralHolder.currentUserDataSourceLabel.getDataSourceName(), additionalSerialNumber);\n\t\treturn file;\n\t}\n\n\t@Override\n\tpublic File getFileSelectorRootPath() {\n\t\tFile file = DatabaseFileStructure.getAdditionalNeedFileFolder(SysFileStructure.getDataFileFolder(),\n\t\t\t\tGeneralHolder.currentUserDataSourceLabel.getDataSourceName(), additionalSerialNumber);\n\t\treturn file;\n\t}\n\n\t@Override\n\tprotected void addFunctionAddOpratingLabel() {\n\t\tString name = GeneralControl.generateComponentName(model, LabelElementName.FUNCTION_ADD);\n\n\t\tFunctionAddParam functionAddParam = new FunctionAddParam();// 在使用过程中需要的参数\n\t\tfunctionAddParam.setClassName(NotNamed.additional.getClassName());\n\t\tfunctionAddParam.setModuleName(NotNamed.additional.getModuleName());\n\t\tfunctionAddParam.setPaneType(MarkElementName.ADDITIONAL_FORMAT_MARK);\n\n\t\tFunctionAddControlLabel temp = new FunctionAddControlLabel(name, functionAddParam);\n\t\ttemp.setPassingComponentParams(passingComponentParams);\n\t\taddCorrespondingComponentMethod(temp, name, LabelElementName.FUNCTION_ADD, delFunctionAddMenu);\n\t\tLazyCoderFormatControl.addControlLabelAndUpdateCodePaneMenu(model, temp.getControl());\n\t}\n\n\t@Override\n\tprotected FunctionAddControlLabel getFunctionAddControlLabel(FunctionAddControl controlElement) {\n\t\tFunctionAddParam functionAddParam = new FunctionAddParam();// 在使用过程中需要的参数\n\t\tfunctionAddParam.setClassName(NotNamed.additional.getClassName());\n\t\tfunctionAddParam.setModuleName(NotNamed.additional.getModuleName());\n\t\tfunctionAddParam.setPaneType(MarkElementName.ADDITIONAL_FORMAT_MARK);\n\n\t\tFunctionAddControlLabel functionAddControlLabel = new FunctionAddControlLabel(controlElement, functionAddParam);\n\t\treturn functionAddControlLabel;\n\t}\n\n\t@Override\n\tprotected void addInfrequentlyUsedSettingOpratingLabel() {\n\t\tif ((\"\".equals(NotNamed.additional.getClassName()) || \"\".equals(NotNamed.additional.getModuleName())) == false) {\n\t\t\tInfrequentlyUsedSettingParam infrequentlyUsedSettingParam = new InfrequentlyUsedSettingParam();\n\t\t\tinfrequentlyUsedSettingParam.setClassName(NotNamed.additional.getClassName());\n\t\t\tinfrequentlyUsedSettingParam.setModuleName(NotNamed.additional.getModuleName());\n\t\t\tinfrequentlyUsedSettingParam.setPaneType(MarkElementName.ADDITIONAL_FORMAT_MARK);\n\t\t\tinfrequentlyUsedSettingParam.setAdditionalSerialNumber(additionalSerialNumber);\n\n\t\t\tInfrequentlyUsedSettingControlLabel temp = new InfrequentlyUsedSettingControlLabel(model,\n\t\t\t\t\tinfrequentlyUsedSettingParam);\n\t\t\tsuper.addInfrequentlyUsedSettingOpratingLabel(temp);\n\t\t}\n\t}\n\n\t@Override\n\tprotected InfrequentlyUsedSettingControlLabel getInfrequentlyUsedSettingControlLabel(InfrequentlyUsedSettingControl controlElement, AbstractEditContainerModel model) {\n\t\tInfrequentlyUsedSettingParam infrequentlyUsedSettingParam = new InfrequentlyUsedSettingParam();\n\t\tinfrequentlyUsedSettingParam.setPaneType(MarkElementName.ADDITIONAL_FORMAT_MARK);\n\t\tinfrequentlyUsedSettingParam.setClassName(NotNamed.additional.getClassName());\n\t\tinfrequentlyUsedSettingParam.setModuleName(NotNamed.additional.getModuleName());\n\n\t\tInfrequentlyUsedSettingControlLabel infrequentlyUsedSettingControlLabel = new InfrequentlyUsedSettingControlLabel(\n\t\t\t\tcontrolElement, model, infrequentlyUsedSettingParam);\n\t\treturn infrequentlyUsedSettingControlLabel;\n\t}\n\n\t@Override\n\tprotected void clickAddContentChooseMenuItem() {\n\t\tnew ContentChooseFrameAddForBaseControlTextFrame(additionalSerialNumber, this);\n\t}\n\n}" }, { "identifier": "CheckInterface", "path": "ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/moduleedit/CheckInterface.java", "snippet": "public interface CheckInterface {\n\n\t/**\n\t * 检查\n\t *\n\t * @return\n\t */\n\tpublic boolean check();\n\n}" }, { "identifier": "OperatingTipButton", "path": "ui-utils/src/main/java/com/lazycoder/uiutils/component/animatedcarousel/net/codemap/carousel/helpcarousel/OperatingTipButton.java", "snippet": "public class OperatingTipButton extends MyButton {\n\n static ImageIcon questionIcon = new ImageIcon(\n SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + \"my\" + File.separator + \"help\" + File.separator + \"question.png\"),\n questionHoverIcon = new ImageIcon(\n SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + \"my\" + File.separator + \"help\" + File.separator + \"question_hover.png\"),\n questionPressIcon = new ImageIcon(\n SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + \"my\" + File.separator + \"help\" + File.separator + \"question_press.png\");\n\n private String path;\n\n public OperatingTipButton(String path) {\n super(questionIcon);\n this.path = path;\n setBorderPainted(false);\n setContentAreaFilled(false);\n setOpaque(false);\n setSize(questionIcon.getIconWidth(), questionIcon.getIconHeight());\n\n setRolloverIcon(questionHoverIcon);\n setPressedIcon(questionPressIcon);\n addActionListener(actionListener);\n setToolTipText(\"(~ ̄▽ ̄)~ 可看对应操作提示\");\n }\n\n private ActionListener actionListener = new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n OperatingTipAnimatedCarouselPane.creatHelpAnimatedCarouselFrame(path);\n }\n };\n\n}" }, { "identifier": "MyButton", "path": "ui-utils/src/main/java/com/lazycoder/uiutils/mycomponent/MyButton.java", "snippet": "public class MyButton extends JButton {\n\n\t/**\n\t *\n\t */\n\tprivate static final long serialVersionUID = 8262517162910576309L;\n\n\tpublic MyButton() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetFocusPainted(false);\n\t}\n\n\n\tpublic MyButton(String text) {\n\t\t// TODO Auto-generated constructor stub\n\t\tsuper(text);\n\t\tsetFocusPainted(false);\n\t}\n\n\tpublic MyButton(Icon icon) {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetIcon(icon);\n\t\tsetFocusPainted(false);\n\t}\n\n\n\tpublic MyButton(String text, Icon icon) {\n\t\t// TODO Auto-generated constructor stub\n\t\tthis(text);\n\t\tsetIcon(icon);\n\t}\n}" }, { "identifier": "SysUtil", "path": "ui-utils/src/main/java/com/lazycoder/uiutils/utils/SysUtil.java", "snippet": "public class SysUtil {\n\n /**\n * 获取屏幕尺寸\n */\n public static final Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();\n\n /**\n * 获取剪切板\n */\n public static Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();\n\n //任务栏的尺寸参数 摘自 https://www.iteye.com/blog/krs-2042006\n //getScreenInsets是指获得屏幕的 insets\n public static Insets taskbarInsets = Toolkit.getDefaultToolkit().getScreenInsets(new JFrame().getGraphicsConfiguration());\n\n /**\n * 刷新窗口界面\n *\n * @param component\n */\n public static void updateFrameUI(JComponent component) {\n Window window = SwingUtilities.getWindowAncestor(component);\n if (window != null) {\n window.validate();\n }\n }\n\n /***\n * 摘自 https://blog.csdn.net/hw1287789687/article/details/84822840\n * 增加参数后,使滚动条自动定位到底部\n *\n * @param panel_7JS2\n */\n public static void scrollToBottom(JScrollPane panel_7JS2) {\n if (panel_7JS2 != null) {\n int maxHeight = panel_7JS2.getVerticalScrollBar().getMaximum();\n panel_7JS2.getViewport().setViewPosition(new Point(0, maxHeight));\n panel_7JS2.updateUI();\n }\n }\n\n /**\n * 把滑动条自动定位到对应比例的位置\n *\n * @param proportion 该值需要传一个0~1的小数,使滑动条自动定位到对应比例\n */\n public static void scrollToProportion(float proportion, JScrollPane scrollPane) {\n if ((proportion > 0 && proportion < 1) && scrollPane != null) {\n int h = (int) (proportion * scrollPane.getVerticalScrollBar().getMaximum());\n scrollPane.getViewport().setViewPosition(new Point(0, h));\n scrollPane.updateUI();\n }\n }\n\n /**\n * 使滚动条定位到顶部\n *\n * @param scrollPane\n */\n public static void scrollToTop(JScrollPane scrollPane) {\n if (scrollPane != null) {\n scrollPane.getViewport().setViewPosition(new Point(0, 0));\n scrollPane.updateUI();\n }\n }\n\n /**\n * 展示一个Toast\n *\n * @param owner Toast出现的父窗口(DefaultToast必须依赖于JFrame而存在)\n * @param status Toast的状态,INFO,ERROR, SUCCESS\n * @param text 展示的文本\n * @return 创建的Toast\n */\n public static DefaultToast showToast(JFrame owner, ToastStatus status, String text) {\n DefaultToast toast = new DefaultToast(owner, text, status);\n Window frame = toast.getOwner();\n ComponentListener[] listeners = frame.getComponentListeners();\n\n /* 清除过期的listener */\n Optional.ofNullable(listeners).ifPresent((arrays) -> {\n for (ComponentListener listener : arrays) {\n boolean removePredict = (listener instanceof ToastMoveListener)\n && !((ToastMoveListener) listener).isToastShowing();\n if (removePredict) {\n frame.removeComponentListener(listener);\n }\n }\n });\n\n frame.addComponentListener(new ToastMoveListener(toast, Toast.CENTER)); /* 添加一个监听器,使得Toast跟随主窗口移动。 */\n Point toastLocation = Toast.calculateToastLocation(frame.getBounds(), toast.getBounds(), Toast.CENTER);\n toast.setLocation(toastLocation);\n toast.setVisible(true);\n return toast;\n }\n\n public static void setWindowClosingDispose(JFrame frame) {\n frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n frame.addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n frame.dispose();\n }\n });\n }\n\n}" } ]
import com.lazycoder.database.model.AdditionalInfo; import com.lazycoder.service.fileStructure.SysFileStructure; import com.lazycoder.service.vo.meta.AdditionalMetaModel; import com.lazycoder.service.vo.save.AdditionalFunctionNameInputData; import com.lazycoder.service.vo.save.AdditionalVariableInputData; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.format.operation.AdditionalFormatControlPane; import com.lazycoder.uidatasourceedit.moduleedit.CheckInterface; import com.lazycoder.uiutils.component.animatedcarousel.net.codemap.carousel.helpcarousel.OperatingTipButton; import com.lazycoder.uiutils.mycomponent.MyButton; import com.lazycoder.uiutils.utils.SysUtil; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import lombok.Getter;
5,315
package com.lazycoder.uidatasourceedit.formatedit.additional; public class AdditionalInputEditPane extends JPanel implements AdditionalPaneInterface, CheckInterface { /** * */ private static final long serialVersionUID = 8796634939292739650L; private MyButton addVarButton, delVarButton, addFuncitonButton, delFuncitionButton, restoreButton, clearBt; @Getter private AdditionalFormatControlPane additionalFormatControlPane; @Getter private AdditionalVariableTable additionalVariableTable; @Getter private AdditionalFuncitonTable additionalFuncitonTable; private JScrollPane additionalFormatControlScrollPane, additionalVariableTableScrollPane, additionalFuncitonTableScrollPane; private AdditionalFormatPane additionalFormatPane; private JLabel lblNewLabel; private JLabel label1; private OperatingTipButton additionalFormatOperatingTip, additionalVariableOperatingTip, additionalFunctionOperatingTip; /** * Create the panel. */ public AdditionalInputEditPane(int additionalSerialNumber, AdditionalFormatPane additionalFormatPane) { setLayout(null); this.additionalFormatPane = additionalFormatPane; JLabel label = new JLabel("格式:"); label.setBounds(30, 60, 72, 18); add(label); int width = (int) (SysUtil.SCREEN_SIZE.width * 0.27); additionalFormatControlPane = new AdditionalFormatControlPane(additionalSerialNumber); additionalFormatControlScrollPane = new JScrollPane(additionalFormatControlPane); additionalFormatControlPane.setUpdateScrollpane(additionalFormatControlScrollPane); additionalFormatControlScrollPane.setBounds(80, 50, width, 300); add(additionalFormatControlScrollPane); restoreButton = new MyButton("还原"); restoreButton.addActionListener(actionListener); restoreButton.setBounds(100, 360, 80, 30); add(restoreButton); clearBt = new MyButton("清空"); clearBt.setBounds(200, 360, 80, 30); add(clearBt); clearBt.addActionListener(actionListener);
package com.lazycoder.uidatasourceedit.formatedit.additional; public class AdditionalInputEditPane extends JPanel implements AdditionalPaneInterface, CheckInterface { /** * */ private static final long serialVersionUID = 8796634939292739650L; private MyButton addVarButton, delVarButton, addFuncitonButton, delFuncitionButton, restoreButton, clearBt; @Getter private AdditionalFormatControlPane additionalFormatControlPane; @Getter private AdditionalVariableTable additionalVariableTable; @Getter private AdditionalFuncitonTable additionalFuncitonTable; private JScrollPane additionalFormatControlScrollPane, additionalVariableTableScrollPane, additionalFuncitonTableScrollPane; private AdditionalFormatPane additionalFormatPane; private JLabel lblNewLabel; private JLabel label1; private OperatingTipButton additionalFormatOperatingTip, additionalVariableOperatingTip, additionalFunctionOperatingTip; /** * Create the panel. */ public AdditionalInputEditPane(int additionalSerialNumber, AdditionalFormatPane additionalFormatPane) { setLayout(null); this.additionalFormatPane = additionalFormatPane; JLabel label = new JLabel("格式:"); label.setBounds(30, 60, 72, 18); add(label); int width = (int) (SysUtil.SCREEN_SIZE.width * 0.27); additionalFormatControlPane = new AdditionalFormatControlPane(additionalSerialNumber); additionalFormatControlScrollPane = new JScrollPane(additionalFormatControlPane); additionalFormatControlPane.setUpdateScrollpane(additionalFormatControlScrollPane); additionalFormatControlScrollPane.setBounds(80, 50, width, 300); add(additionalFormatControlScrollPane); restoreButton = new MyButton("还原"); restoreButton.addActionListener(actionListener); restoreButton.setBounds(100, 360, 80, 30); add(restoreButton); clearBt = new MyButton("清空"); clearBt.setBounds(200, 360, 80, 30); add(clearBt); clearBt.addActionListener(actionListener);
additionalFormatOperatingTip = new OperatingTipButton(SysFileStructure.getOperatingTipImageFolder(
1
2023-11-16 11:55:06+00:00
8k