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
Feniksovich/RxPubSub
src/main/java/io/github/feniksovich/rxpubsub/event/EventBus.java
[ { "identifier": "PubSubChannel", "path": "src/main/java/io/github/feniksovich/rxpubsub/model/PubSubChannel.java", "snippet": "public class PubSubChannel {\n\n private static final Pattern VALID_IDENTIFIER_REGEX = Pattern.compile(\"[a-z0-9/\\\\-_]*\");\n\n private final String namespace;\n private final String name;\n\n private PubSubChannel(String namespace, String name) {\n this.namespace = namespace;\n this.name = name;\n }\n\n /**\n * Creates a new PubSubChannel instance with the specified namespace and name.\n *\n * @param namespace the namespace of the channel\n * @param name the name of the channel\n * @return a new PubSubChannel instance\n * @throws IllegalArgumentException if the namespace or name is null or empty, or if they are not valid\n */\n public static PubSubChannel from(String namespace, String name) {\n Preconditions.checkArgument(!Strings.isNullOrEmpty(namespace), \"namespace is null or empty\");\n Preconditions.checkArgument(!Strings.isNullOrEmpty(name), \"name is null or empty\");\n Preconditions.checkArgument(\n VALID_IDENTIFIER_REGEX.matcher(namespace).matches(),\n \"namespace is not valid\"\n );\n Preconditions.checkArgument(\n VALID_IDENTIFIER_REGEX.matcher(name).matches(),\n \"name is not valid\"\n );\n return new PubSubChannel(namespace, name);\n }\n\n /**\n * Gets the ID of the pubsub channel.\n *\n * @return the ID of the channel in the format \"namespace:name\"\n */\n public String getId() {\n return namespace + \":\" + name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n PubSubChannel that = (PubSubChannel) o;\n return Objects.equals(namespace, that.namespace) && Objects.equals(name, that.name);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(namespace, name);\n }\n\n @Override\n public String toString() {\n return \"PubSubChannel{\" +\n \"namespace='\" + namespace + '\\'' +\n \", name='\" + name + '\\'' +\n '}';\n }\n}" }, { "identifier": "PubSubMessage", "path": "src/main/java/io/github/feniksovich/rxpubsub/model/PubSubMessage.java", "snippet": "public abstract class PubSubMessage {\n\n @SerializedName(ReservedFields.MESSAGE_ID_FIELD)\n private String messageId = UUID.randomUUID().toString();\n\n @SerializedName(ReservedFields.MESSAGE_RESPONSE_TO_ID_FIELD)\n protected String responseTo;\n\n public String getMessageId() {\n return messageId;\n }\n\n /**\n * Sets a custom message ID of pre-generated one instead.\n * @param messageId ID to set\n */\n public void setMessageId(String messageId) {\n this.messageId = messageId;\n }\n\n /**\n * Returns the source message ID that this message responds to.\n * @return source message ID if present\n */\n public Optional<String> getResponseTo() {\n return Optional.ofNullable(responseTo);\n }\n\n /**\n * Sets the source message ID that this message responds to.\n * @param responseTo source message ID\n */\n public void setResponseTo(String responseTo) {\n this.responseTo = responseTo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n PubSubMessage that = (PubSubMessage) o;\n return Objects.equals(messageId, that.messageId) && Objects.equals(responseTo, that.responseTo);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(messageId, responseTo);\n }\n}" } ]
import io.github.feniksovich.rxpubsub.model.PubSubChannel; import io.github.feniksovich.rxpubsub.model.PubSubMessage; import java.util.function.Consumer; import java.util.function.Function;
1,226
package io.github.feniksovich.rxpubsub.event; /** * The RxPubSub event bus. * Used to listen to the reception of pubsub messages. */ public interface EventBus { /** * Registers a new listener for the specified incoming message. * Provided handler guaranteed to be processed asynchronously in * a dedicated event bus thread pool. * * @param messageClass the pubsub message class * @param handler the reception handler * @return {@link EventBus} instance for chaining purposes */ <T extends PubSubMessage> EventBus registerReceiptListener(Class<T> messageClass, Consumer<T> handler); /** * Registers a new listener for the specified incoming message. * The listener returns a certain {@link PubSubMessage} as a callback * and sends it to the specified channel. * The provided handler is guaranteed to be processed asynchronously * in a dedicated event bus thread pool. * * @param messageClass the pubsub message class * @param channel the channel to send the callback to * @param handler the reception handler that returns {@link PubSubMessage} as a callback * @return {@link EventBus} instance for chaining purposes */
package io.github.feniksovich.rxpubsub.event; /** * The RxPubSub event bus. * Used to listen to the reception of pubsub messages. */ public interface EventBus { /** * Registers a new listener for the specified incoming message. * Provided handler guaranteed to be processed asynchronously in * a dedicated event bus thread pool. * * @param messageClass the pubsub message class * @param handler the reception handler * @return {@link EventBus} instance for chaining purposes */ <T extends PubSubMessage> EventBus registerReceiptListener(Class<T> messageClass, Consumer<T> handler); /** * Registers a new listener for the specified incoming message. * The listener returns a certain {@link PubSubMessage} as a callback * and sends it to the specified channel. * The provided handler is guaranteed to be processed asynchronously * in a dedicated event bus thread pool. * * @param messageClass the pubsub message class * @param channel the channel to send the callback to * @param handler the reception handler that returns {@link PubSubMessage} as a callback * @return {@link EventBus} instance for chaining purposes */
<T extends PubSubMessage> EventBus registerRespondingListener(Class<T> messageClass, PubSubChannel channel, Function<T, PubSubMessage> handler);
0
2023-10-09 19:05:31+00:00
2k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/util/PerformanceCheckUtils.java
[ { "identifier": "LlmProviderFactory", "path": "src/main/java/com/zhongan/devpilot/integrations/llms/LlmProviderFactory.java", "snippet": "@Service\npublic final class LlmProviderFactory {\n\n public LlmProvider getLlmProvider(Project project) {\n var settings = DevPilotLlmSettingsState.getInstance();\n String selectedModel = settings.getSelectedModel();\n ModelServiceEnum modelServiceEnum = ModelServiceEnum.fromName(selectedModel);\n\n switch (modelServiceEnum) {\n case OPENAI:\n return project.getService(OpenAIServiceProvider.class);\n case LLAMA:\n return project.getService(LlamaServiceProvider.class);\n case AIGATEWAY:\n return project.getService(AIGatewayServiceProvider.class);\n }\n\n return project.getService(AIGatewayServiceProvider.class);\n }\n\n}" }, { "identifier": "DevPilotChatCompletionRequest", "path": "src/main/java/com/zhongan/devpilot/integrations/llms/entity/DevPilotChatCompletionRequest.java", "snippet": "public class DevPilotChatCompletionRequest {\n\n String model;\n\n List<DevPilotMessage> messages = new ArrayList<>();\n\n boolean stream = Boolean.FALSE;\n\n public String getModel() {\n return model;\n }\n\n public void setModel(String model) {\n this.model = model;\n }\n\n public List<DevPilotMessage> getMessages() {\n return messages;\n }\n\n public void setMessages(List<DevPilotMessage> messages) {\n this.messages = messages;\n }\n\n public boolean isStream() {\n return stream;\n }\n\n public void setStream(boolean stream) {\n this.stream = stream;\n }\n\n}" }, { "identifier": "DevPilotMessage", "path": "src/main/java/com/zhongan/devpilot/integrations/llms/entity/DevPilotMessage.java", "snippet": "public class DevPilotMessage {\n @JsonIgnore\n private String id;\n\n private String role;\n\n private String content;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n}" }, { "identifier": "PerformanceCheckResponse", "path": "src/main/java/com/zhongan/devpilot/integrations/llms/entity/PerformanceCheckResponse.java", "snippet": "public class PerformanceCheckResponse {\n\n private String rewriteCode;\n\n public String getRewriteCode() {\n return rewriteCode;\n }\n\n public void setRewriteCode(String rewriteCode) {\n this.rewriteCode = rewriteCode;\n }\n\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.intellij.diff.DiffContentFactory; import com.intellij.diff.DiffManager; import com.intellij.diff.contents.DiffContent; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.event.EditorFactoryListener; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.zhongan.devpilot.integrations.llms.LlmProviderFactory; import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionRequest; import com.zhongan.devpilot.integrations.llms.entity.DevPilotMessage; import com.zhongan.devpilot.integrations.llms.entity.PerformanceCheckResponse; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull;
1,217
package com.zhongan.devpilot.util; public class PerformanceCheckUtils { public static final String NO_PERFORMANCE_ISSUES_DESC = "There don't appear to be any performance issues with the given code."; public static final String NO_PERFORMANCE_ISSUES_NULL = "null"; public static final List<String> NO_PERFORMANCE_ISSUES = Lists.newArrayList(NO_PERFORMANCE_ISSUES_DESC, NO_PERFORMANCE_ISSUES_NULL); private final static ObjectMapper objectMapper = new ObjectMapper(); private static final String CUSTOM_PROMPT = "Please optimize the code above for performance. " + "Provide two outputs: one as 'null' indicating no performance issues, " + "and the other as the code after performance optimization, " + "returned in JSON format with the key 'rewriteCode'."; /** * get performance check result * * @param selectedText * @param project * @return */ public static String getChatCompletionResult(String selectedText, Project project) { DevPilotMessage devPilotMessage = new DevPilotMessage(); devPilotMessage.setRole("user"); devPilotMessage.setContent(selectedText + "\n" + CUSTOM_PROMPT); DevPilotChatCompletionRequest request = new DevPilotChatCompletionRequest(); // list content support update request.setMessages(new ArrayList<>() {{ add(devPilotMessage); }});
package com.zhongan.devpilot.util; public class PerformanceCheckUtils { public static final String NO_PERFORMANCE_ISSUES_DESC = "There don't appear to be any performance issues with the given code."; public static final String NO_PERFORMANCE_ISSUES_NULL = "null"; public static final List<String> NO_PERFORMANCE_ISSUES = Lists.newArrayList(NO_PERFORMANCE_ISSUES_DESC, NO_PERFORMANCE_ISSUES_NULL); private final static ObjectMapper objectMapper = new ObjectMapper(); private static final String CUSTOM_PROMPT = "Please optimize the code above for performance. " + "Provide two outputs: one as 'null' indicating no performance issues, " + "and the other as the code after performance optimization, " + "returned in JSON format with the key 'rewriteCode'."; /** * get performance check result * * @param selectedText * @param project * @return */ public static String getChatCompletionResult(String selectedText, Project project) { DevPilotMessage devPilotMessage = new DevPilotMessage(); devPilotMessage.setRole("user"); devPilotMessage.setContent(selectedText + "\n" + CUSTOM_PROMPT); DevPilotChatCompletionRequest request = new DevPilotChatCompletionRequest(); // list content support update request.setMessages(new ArrayList<>() {{ add(devPilotMessage); }});
final String response = new LlmProviderFactory().getLlmProvider(project).chatCompletion(project, request, null);
0
2023-11-29 06:37:51+00:00
2k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/tileprocess/tile/tileset/Tileset.java
[ { "identifier": "ContentInfo", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/ContentInfo.java", "snippet": "@Slf4j\n@Getter\n@Setter\npublic class ContentInfo {\n private String name;\n private String nodeCode;\n private LevelOfDetail lod;\n private List<TileInfo> tileInfos;\n private List<TileInfo> remainTileInfos;\n private GaiaBoundingBox boundingBox;\n private GaiaSet batchedSet;\n\n public void deleteTexture() {\n for (TileInfo tileInfo : tileInfos) {\n GaiaSet set = tileInfo.getSet();\n set.deleteTextures();\n }\n for (TileInfo tileInfo : remainTileInfos) {\n GaiaSet set = tileInfo.getSet();\n if (set != null) {\n set.deleteTextures();\n }\n }\n }\n\n public void clear() {\n this.name = null;\n this.boundingBox = null;\n this.batchedSet = null;\n this.tileInfos.forEach(TileInfo::clear);\n this.tileInfos = null;\n this.remainTileInfos.forEach(TileInfo::clear);\n this.remainTileInfos = null;\n }\n}" }, { "identifier": "Asset", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/tileset/asset/Asset.java", "snippet": "@Getter\n@Setter\npublic class Asset {\n private String version = \"1.0\";\n private Extras extras;\n}" }, { "identifier": "Node", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/tileset/node/Node.java", "snippet": "@Slf4j\n@Getter\n@Setter\npublic class Node {\n @JsonIgnore\n private String nodeCode;\n @JsonIgnore\n private Node parent;\n @JsonIgnore\n private Matrix4d transformMatrix;\n @JsonIgnore\n private Matrix4d transformMatrixAux;\n @JsonIgnore\n private GaiaBoundingBox boundingBox;\n\n private BoundingVolume boundingVolume;\n private RefineType refine = RefineType.ADD;\n private double geometricError = 0.0d;\n private float[] transform;\n private List<Node> children;\n private Content content;\n\n // TransfromMatrix\n public void setTransformMatrix(Matrix4d transformMatrixAux) {\n this.transformMatrixAux = transformMatrixAux;\n if (parent == this) { // root\n this.transformMatrix = transformMatrixAux;\n } else if (parent.getTransformMatrixAux() != null) {\n Matrix4d resultTransfromMatrix = new Matrix4d();\n Matrix4d parentTransformMatrix = parent.getTransformMatrixAux();\n Matrix4d parentTransformMatrixInv = new Matrix4d(parentTransformMatrix).invert();\n\n parentTransformMatrixInv.mul(transformMatrixAux, resultTransfromMatrix);\n\n this.transformMatrix = resultTransfromMatrix;\n this.transformMatrixAux = transformMatrixAux;\n } else {\n this.transformMatrix = transformMatrixAux;\n log.error(\"Error :: Wrong TransformMatrix\");\n }\n\n this.transform = transformMatrix.get(new float[16]);\n\n for (int i = 0; i < transform.length; i++) {\n this.transform[i] = DecimalUtils.cut(this.transform[i]);\n }\n }\n\n public enum RefineType {\n ADD,\n REPLACE,\n }\n\n public List<ContentInfo> findAllContentInfo(List<ContentInfo> contentInfoList) {\n if (content != null) {\n ContentInfo contentInfo = content.getContentInfo();\n if (contentInfo != null) {\n contentInfoList.add(contentInfo);\n }\n }\n for (Node node : children) {\n node.findAllContentInfo(contentInfoList);\n }\n return contentInfoList;\n }\n}" }, { "identifier": "Properties", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/tileset/node/Properties.java", "snippet": "@Getter\n@Setter\npublic class Properties {\n @JsonProperty(\"Height\")\n private Range height;\n\n @JsonProperty(\"Latitude\")\n private Range latitude;\n\n @JsonProperty(\"Longitude\")\n private Range longitude;\n}" } ]
import com.fasterxml.jackson.annotation.JsonIgnore; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.tileset.asset.Asset; import com.gaia3d.process.tileprocess.tile.tileset.node.Node; import com.gaia3d.process.tileprocess.tile.tileset.node.Properties; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List;
1,136
package com.gaia3d.process.tileprocess.tile.tileset; @Getter @Setter public class Tileset { private Asset asset; private double geometricError = 0.0d; private Node root; private Properties properties; @JsonIgnore
package com.gaia3d.process.tileprocess.tile.tileset; @Getter @Setter public class Tileset { private Asset asset; private double geometricError = 0.0d; private Node root; private Properties properties; @JsonIgnore
public List<ContentInfo> findAllContentInfo() {
0
2023-11-30 01:59:44+00:00
2k
xuemingqi/x-cloud
x-work/src/main/java/com/x/work/schedule/service/impl/HelloScheduleServiceImpl.java
[ { "identifier": "ScheduleConstant", "path": "x-work/src/main/java/com/x/work/schedule/constants/ScheduleConstant.java", "snippet": "public interface ScheduleConstant {\n\n /**\n * key 相关\n */\n String COMMON_JOB_KEY = \"COMMON_JOB_\";\n String COMMON_TRIGGER_KEY = \"COMMON_JOB_\";\n String SAY_HELLO_JOB_KEY = \"SAY_HELLO_JOB_\";\n\n String SAY_HELLO_TRIGGER_KEY = \"SAY_HELLO_TRIGGER_\";\n\n /**\n * group相关\n */\n String COMMON_JOB_GROUP = \"COMMON_GROUP_\";\n String SAY_HELLO_JOB_GROUP = \"SAY_HELLO_GROUP_\";\n\n String COMMON_TRIGGER_GROUP = \"COMMON_TRIGGER_\";\n String SAY_HELLO_TRIGGER_GROUP = \"SAY_HELLO_TRIGGER_\";\n\n /**\n * job data相关\n */\n String USER_ID_KEY = \"USER_ID\";\n String COMMON_ID_KEY = \"COMMON_ID\";\n}" }, { "identifier": "HelloJob", "path": "x-work/src/main/java/com/x/work/schedule/job/HelloJob.java", "snippet": "@Slf4j\n@DisallowConcurrentExecution\npublic class HelloJob extends QuartzJobBean {\n\n @Override\n protected void executeInternal(JobExecutionContext context) {\n Long userId = context.getJobDetail().getJobDataMap().getLong(ScheduleConstant.USER_ID_KEY);\n log.info(\"hello! {}\", userId);\n }\n}" }, { "identifier": "HelloScheduleService", "path": "x-work/src/main/java/com/x/work/schedule/service/HelloScheduleService.java", "snippet": "public interface HelloScheduleService {\n\n /**\n * say hello to specific user\n *\n * @param userId user's id\n * @param startTime start time\n */\n void addHelloJob(Long userId, LocalDateTime startTime);\n\n /**\n * say hello to specific user\n *\n * @param userId user's id\n * @param cron cron expressions\n */\n void addHelloJob(Long userId, String cron);\n\n /**\n * delete hello job\n *\n * @param userId user's id\n */\n void deleteHelloJob(Long userId);\n}" } ]
import cn.hutool.core.date.DateTime; import com.x.work.schedule.constants.ScheduleConstant; import com.x.work.schedule.job.HelloJob; import com.x.work.schedule.service.HelloScheduleService; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime;
643
package com.x.work.schedule.service.impl; /** * @author : xuemingqi * @since : 2023/11/28 13:48 */ @Slf4j @Service @RequiredArgsConstructor(onConstructor = @__({@Autowired}))
package com.x.work.schedule.service.impl; /** * @author : xuemingqi * @since : 2023/11/28 13:48 */ @Slf4j @Service @RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class HelloScheduleServiceImpl implements HelloScheduleService {
2
2023-11-27 08:23:38+00:00
2k
okx/OKBund
aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/exception/AAExceptionData.java
[ { "identifier": "CodecUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/CodecUtil.java", "snippet": "public class CodecUtil {\n\n static {\n Brotli4jLoader.ensureAvailability();\n }\n\n public static String abiEncodePacked(Type... parameters) {\n StringBuilder sb = new StringBuilder();\n for (Type parameter : parameters) {\n sb.append(TypeEncoder.encodePacked(parameter));\n }\n return sb.toString();\n }\n\n public static String abiEncode(Type... parameters) {\n return TypeEncoder.encode(new DynamicStruct(parameters));\n }\n\n\n public static List<Type> decodeError(String hexData, Event event) {\n String error = hexData.substring(Web3Constant.METHOD_ID_LENGTH);\n return FunctionReturnDecoder.decode(error, event.getParameters());\n }\n\n public static Tuple decodeFunctionOrError(String input, String methodSig) {\n Function func = Function.parse(methodSig.replace(\" \", \"\"));\n return func.decodeCall(Numeric.hexStringToByteArray(input));\n }\n\n public static byte[] keccak256(String input) {\n return Hash.sha3(Numeric.hexStringToByteArray(input));\n }\n\n public static byte[] keccak256(byte[] input) {\n return Hash.sha3(input);\n }\n\n public static boolean hasValidMethodId(String value) {\n return value.length() >= Web3Constant.METHOD_ID_LENGTH;\n }\n\n public static String buildMethodId(String methodSignature) {\n final byte[] input = methodSignature.getBytes();\n final byte[] hash = keccak256(input);\n return Numeric.toHexString(hash).substring(0, 10);\n }\n\n public static String toHexStringWithPrefix(int n) {\n return Numeric.encodeQuantity(BigInteger.valueOf(n));\n }\n\n public static String toHexStringWithPrefix(long n) {\n return Numeric.encodeQuantity(BigInteger.valueOf(n));\n }\n\n @SneakyThrows\n public static byte[] brotliFastCompress(byte[] bytes) {\n return brotliCompress(bytes, 0, 22);\n }\n\n @SneakyThrows\n public static byte[] brotliCompress(byte[] bytes, int quality, int lgWin) {\n Encoder.Parameters parameters = new Encoder.Parameters();\n parameters.setQuality(quality);\n parameters.setWindow(lgWin);\n parameters.setMode(Encoder.Mode.GENERIC);\n return Encoder.compress(bytes, parameters);\n }\n\n @SneakyThrows\n public static byte[] brotliDecompress(byte[] bytes) {\n DirectDecompress decompress = Decoder.decompress(bytes);\n return decompress.getDecompressedData();\n }\n\n\n public static String create2(byte[] salt, String bytecodeHash, String deployer) {\n byte[] input = Numeric.hexStringToByteArray(\"0xff\" + Numeric.cleanHexPrefix(deployer) + Numeric.toHexStringNoPrefix(salt) + Numeric.cleanHexPrefix(bytecodeHash));\n byte[] addressBytes = Hash.sha3(input);\n return Numeric.toHexString(addressBytes, 12, 20, true);\n }\n\n public static String toChecksumAddress(String address) {\n return Address.toChecksumAddress(address);\n }\n\n\n}" }, { "identifier": "FieldUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/FieldUtil.java", "snippet": "public class FieldUtil {\n\n private static final Pattern PATTERN = Pattern.compile(\"^0x[0-9a-fA-F]*$\");\n\n private static final Pattern PATTERN_ADDRESS = Pattern.compile(\"^0x[0-9a-fA-F]{40,40}$\");\n\n private static final Pattern PATTERN_BYTES32 = Pattern.compile(\"^0x[0-9a-fA-F]{64,64}$\");\n\n public static boolean isValidBytes32(String value) {\n if (!isValidHexPrefix(value)) {\n return false;\n }\n\n return PATTERN_BYTES32.matcher(value).matches();\n }\n\n public static boolean isValidAddress(String value) {\n if (!isValidHexPrefix(value)) {\n return false;\n }\n\n return PATTERN_ADDRESS.matcher(value).matches();\n }\n\n public static boolean isValidHex(String value) {\n if (!isValidHexPrefix(value)) {\n return false;\n }\n\n return PATTERN.matcher(value).matches();\n }\n\n public static boolean isValidHexPrefix(String value) {\n if (value == null) {\n return false;\n }\n\n if (value.length() < 2) {\n return false;\n }\n\n return value.startsWith(Web3Constant.HEX_PREFIX);\n }\n\n public static boolean isEmpty(String field) {\n return !isValidHexPrefix(field) || Web3Constant.HEX_PREFIX.equals(field);\n }\n}" } ]
import com.okcoin.dapp.bundler.infra.chain.CodecUtil; import com.okcoin.dapp.bundler.infra.chain.FieldUtil; import java.util.HashMap;
1,268
package com.okcoin.dapp.bundler.pool.exception; public class AAExceptionData extends HashMap<String, Object> { public AAExceptionData(Object... others) { super(); for (int i = 0; i < others.length / 2; i++) { String k = (String) others[i * 2]; Object v = others[i * 2 + 1];
package com.okcoin.dapp.bundler.pool.exception; public class AAExceptionData extends HashMap<String, Object> { public AAExceptionData(Object... others) { super(); for (int i = 0; i < others.length / 2; i++) { String k = (String) others[i * 2]; Object v = others[i * 2 + 1];
if (v instanceof String && FieldUtil.isValidAddress((String) v)) {
1
2023-11-27 10:54:49+00:00
2k
lidaofu-hub/j_media_server
src/main/java/com/ldf/media/exception/GlobalExceptionHandler.java
[ { "identifier": "Result", "path": "src/main/java/com/ldf/media/api/model/result/Result.java", "snippet": "@Data\n@AllArgsConstructor\npublic class Result<T> {\n /**\n * 状态码\n */\n private Integer code;\n\n /**\n * 信息\n */\n private String msg;\n\n /**\n * 数据\n */\n private T data;\n\n public Result() {\n this.code = ResultEnum.SUCCESS.getCode();\n this.msg = ResultEnum.SUCCESS.getMsg();\n }\n\n public Result(T t) {\n this.code = ResultEnum.SUCCESS.getCode();\n this.msg = ResultEnum.SUCCESS.getMsg();\n this.data = t;\n }\n\n public Result(ResultEnum resultEnum) {\n this.code = resultEnum.getCode();\n this.msg = resultEnum.getMsg();\n }\n\n public Result(ResultEnum resultEnum, T t) {\n this.code = resultEnum.getCode();\n this.msg = resultEnum.getMsg();\n this.data = t;\n }\n\n public Result(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n}" }, { "identifier": "ResultEnum", "path": "src/main/java/com/ldf/media/enums/ResultEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum ResultEnum {\n /**\n * 请求成功\n */\n SUCCESS(0, \"请求成功\"),\n\n /**\n * 请求失败\n */\n ERROR(-1, \"请求成功\"),\n /**\n * 未登录\n */\n NOT_LOGIN(-100, \"未提供有效凭据\"),\n\n /**\n * 无权限\n */\n NOT_POWER(-100, \"无权限\"),\n\n /**\n * 提交限制\n */\n INVALID_ARGS (-300, \"请求过快\"),\n\n /**\n * 请求失败\n */\n EXCEPTION(-400, \"请求或操作失败\"),\n\n\n ;\n\n /**\n * 代码\n */\n private final Integer code;\n\n /**\n * 信息\n */\n private final String msg;\n}" } ]
import cn.hutool.core.util.StrUtil; import com.ldf.media.api.model.result.Result; import com.ldf.media.enums.ResultEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.List;
779
package com.ldf.media.exception; /** * 全局异常处理 * * @author lidaofu * @since 2023/11/29 **/ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 默认全局异常处理 */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(Exception.class)
package com.ldf.media.exception; /** * 全局异常处理 * * @author lidaofu * @since 2023/11/29 **/ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 默认全局异常处理 */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(Exception.class)
public Result<String> handleException(Exception ex, HttpServletRequest request) {
0
2023-11-29 07:47:56+00:00
2k
qdrant/java-client
src/test/java/io/qdrant/client/PointsTest.java
[ { "identifier": "QdrantContainer", "path": "src/test/java/io/qdrant/client/container/QdrantContainer.java", "snippet": "public class QdrantContainer extends GenericContainer<QdrantContainer> {\n\n private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse(\"qdrant/qdrant\");\n private static final String DEFAULT_TAG = System.getProperty(\"qdrantVersion\");\n private static final int GRPC_PORT = 6334;\n private static final int HTTP_PORT = 6333;\n\n public QdrantContainer() {\n this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG));\n }\n\n public QdrantContainer(String dockerImageName) {\n this(DockerImageName.parse(dockerImageName));\n }\n\n public QdrantContainer(final DockerImageName dockerImageName) {\n super(dockerImageName);\n\n addExposedPorts(GRPC_PORT, HTTP_PORT);\n\n setWaitStrategy(new LogMessageWaitStrategy().withRegEx(\".*Actix runtime found; starting in Actix runtime.*\"));\n }\n\n public QdrantContainer withApiKey(String apiKey) {\n return withEnv(\"QDRANT__SERVICE__API_KEY\", apiKey);\n }\n\n public String getGrpcHostAddress() {\n return getHost() + \":\" + getMappedPort(GRPC_PORT);\n }\n\n public String getHttpHostAddress() {\n return getHost() + \":\" + getMappedPort(HTTP_PORT);\n }\n}" }, { "identifier": "hasId", "path": "src/main/java/io/qdrant/client/ConditionFactory.java", "snippet": "public static Condition hasId(PointId id) {\n\treturn Condition.newBuilder()\n\t\t.setHasId(HasIdCondition.newBuilder()\n\t\t\t.addHasId(id)\n\t\t\t.build())\n\t\t.build();\n}" }, { "identifier": "matchKeyword", "path": "src/main/java/io/qdrant/client/ConditionFactory.java", "snippet": "public static Condition matchKeyword(String field, String keyword) {\n\treturn Condition.newBuilder()\n\t\t.setField(FieldCondition.newBuilder()\n\t\t\t.setKey(field)\n\t\t\t.setMatch(Match.newBuilder()\n\t\t\t\t.setKeyword(keyword)\n\t\t\t\t.build())\n\t\t\t.build())\n\t\t.build();\n}" }, { "identifier": "id", "path": "src/main/java/io/qdrant/client/PointIdFactory.java", "snippet": "public static PointId id(long id) {\n\treturn PointId.newBuilder().setNum(id).build();\n}" }, { "identifier": "targetVector", "path": "src/main/java/io/qdrant/client/TargetVectorFactory.java", "snippet": "public static TargetVector targetVector(PointId id) {\n return TargetVector.newBuilder().setSingle(VectorExample.newBuilder().setId(id)).build();\n}" }, { "identifier": "value", "path": "src/main/java/io/qdrant/client/ValueFactory.java", "snippet": "public static Value value(String value) {\n\treturn Value.newBuilder().setStringValue(value).build();\n}" }, { "identifier": "vector", "path": "src/main/java/io/qdrant/client/VectorFactory.java", "snippet": "public static Vector vector(List<Float> values) {\n return Vector.newBuilder().addAllData(values).build();\n}" }, { "identifier": "vectors", "path": "src/main/java/io/qdrant/client/VectorsFactory.java", "snippet": "public static Vectors vectors(List<Float> values) {\n\treturn Vectors.newBuilder()\n\t\t.setVector(vector(values))\n\t\t.build();\n}" } ]
import io.grpc.Grpc; import io.grpc.InsecureChannelCredentials; import io.grpc.ManagedChannel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; import io.qdrant.client.container.QdrantContainer; import io.qdrant.client.grpc.Points.DiscoverPoints; import io.qdrant.client.grpc.Points.PointVectors; import io.qdrant.client.grpc.Points.PointsIdsList; import io.qdrant.client.grpc.Points.PointsSelector; import io.qdrant.client.grpc.Points.PointsUpdateOperation; import io.qdrant.client.grpc.Points.UpdateBatchResponse; import io.qdrant.client.grpc.Points.PointsUpdateOperation.ClearPayload; import io.qdrant.client.grpc.Points.PointsUpdateOperation.UpdateVectors; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static io.qdrant.client.grpc.Collections.CollectionInfo; import static io.qdrant.client.grpc.Collections.CreateCollection; import static io.qdrant.client.grpc.Collections.Distance; import static io.qdrant.client.grpc.Collections.PayloadSchemaType; import static io.qdrant.client.grpc.Collections.VectorParams; import static io.qdrant.client.grpc.Collections.VectorsConfig; import static io.qdrant.client.grpc.Points.BatchResult; import static io.qdrant.client.grpc.Points.Filter; import static io.qdrant.client.grpc.Points.PointGroup; import static io.qdrant.client.grpc.Points.PointStruct; import static io.qdrant.client.grpc.Points.RecommendPointGroups; import static io.qdrant.client.grpc.Points.RecommendPoints; import static io.qdrant.client.grpc.Points.RetrievedPoint; import static io.qdrant.client.grpc.Points.ScoredPoint; import static io.qdrant.client.grpc.Points.ScrollPoints; import static io.qdrant.client.grpc.Points.ScrollResponse; import static io.qdrant.client.grpc.Points.SearchPointGroups; import static io.qdrant.client.grpc.Points.SearchPoints; import static io.qdrant.client.grpc.Points.UpdateResult; import static io.qdrant.client.grpc.Points.UpdateStatus; import static io.qdrant.client.grpc.Points.Vectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static io.qdrant.client.ConditionFactory.hasId; import static io.qdrant.client.ConditionFactory.matchKeyword; import static io.qdrant.client.PointIdFactory.id; import static io.qdrant.client.TargetVectorFactory.targetVector; import static io.qdrant.client.ValueFactory.value; import static io.qdrant.client.VectorFactory.vector; import static io.qdrant.client.VectorsFactory.vectors;
1,575
package io.qdrant.client; @Testcontainers class PointsTest { @Container private static final QdrantContainer QDRANT_CONTAINER = new QdrantContainer(); private QdrantClient client; private ManagedChannel channel; private String testName; @BeforeEach public void setup(TestInfo testInfo) { testName = testInfo.getDisplayName().replace("()", ""); channel = Grpc.newChannelBuilder( QDRANT_CONTAINER.getGrpcHostAddress(), InsecureChannelCredentials.create()) .build(); QdrantGrpcClient grpcClient = QdrantGrpcClient.newBuilder(channel).build(); client = new QdrantClient(grpcClient); } @AfterEach public void teardown() throws Exception { List<String> collectionNames = client.listCollectionsAsync().get(); for (String collectionName : collectionNames) { client.deleteCollectionAsync(collectionName).get(); } client.close(); channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } @Test public void retrieve() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<RetrievedPoint> points = client.retrieveAsync( testName,
package io.qdrant.client; @Testcontainers class PointsTest { @Container private static final QdrantContainer QDRANT_CONTAINER = new QdrantContainer(); private QdrantClient client; private ManagedChannel channel; private String testName; @BeforeEach public void setup(TestInfo testInfo) { testName = testInfo.getDisplayName().replace("()", ""); channel = Grpc.newChannelBuilder( QDRANT_CONTAINER.getGrpcHostAddress(), InsecureChannelCredentials.create()) .build(); QdrantGrpcClient grpcClient = QdrantGrpcClient.newBuilder(channel).build(); client = new QdrantClient(grpcClient); } @AfterEach public void teardown() throws Exception { List<String> collectionNames = client.listCollectionsAsync().get(); for (String collectionName : collectionNames) { client.deleteCollectionAsync(collectionName).get(); } client.close(); channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } @Test public void retrieve() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<RetrievedPoint> points = client.retrieveAsync( testName,
id(9),
3
2023-11-30 10:21:23+00:00
2k
miliariadnane/herb-classifier-api
src/main/java/dev/nano/herbclassifier/service/ImageClassificationService.java
[ { "identifier": "InvalidFileException", "path": "src/main/java/dev/nano/herbclassifier/common/exception/domain/InvalidFileException.java", "snippet": "public class InvalidFileException extends RuntimeException {\n public InvalidFileException(String message) {\n super(message);\n }\n}" }, { "identifier": "NotAnImageFileException", "path": "src/main/java/dev/nano/herbclassifier/common/exception/domain/NotAnImageFileException.java", "snippet": "public class NotAnImageFileException extends RuntimeException {\n public NotAnImageFileException(String message) {\n super(message);\n }\n}" } ]
import dev.nano.herbclassifier.common.exception.domain.InvalidFileException; import dev.nano.herbclassifier.common.exception.domain.NotAnImageFileException; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.datavec.image.loader.NativeImageLoader; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.util.ModelSerializer; import org.nd4j.common.io.ClassPathResource; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler; import org.nd4j.linalg.factory.Nd4j; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import static org.apache.http.entity.ContentType.IMAGE_GIF; import static org.apache.http.entity.ContentType.IMAGE_JPEG; import static org.apache.http.entity.ContentType.IMAGE_PNG;
652
package dev.nano.herbclassifier.service; @Service @Slf4j @RequiredArgsConstructor public class ImageClassificationService { private static final String[] LABELS = {"Coriander", "Parsley", "Not sure"}; private static final String MODEL_FILE_PATH = "model/herb_model.zip"; private static final double CERTAINTY_THRESHOLD = 0.9; private MultiLayerNetwork model; @PostConstruct public void init() { log.info("Initializing ImageClassificationService..."); try { InputStream modelInputStream = new ClassPathResource(MODEL_FILE_PATH).getInputStream(); model = ModelSerializer.restoreMultiLayerNetwork(modelInputStream); log.info("Model loaded from {}", MODEL_FILE_PATH); } catch (IOException e) { log.error("Failed to load model from {}", MODEL_FILE_PATH, e); throw new IllegalStateException("Failed to load model", e); } } public String getHerbClassification(MultipartFile file) { log.info("Validating file..."); validateFile(file); try { INDArray image = convertFileToINDArray(file); log.info("Classifying image..."); String label = classifyImage(image); log.info("Image classified as {}", label); return label; } catch (IOException e) { log.error("Failed to process image", e); throw new IllegalStateException("Failed to process image", e); } } private void validateFile(MultipartFile file) { if (file.isEmpty()) {
package dev.nano.herbclassifier.service; @Service @Slf4j @RequiredArgsConstructor public class ImageClassificationService { private static final String[] LABELS = {"Coriander", "Parsley", "Not sure"}; private static final String MODEL_FILE_PATH = "model/herb_model.zip"; private static final double CERTAINTY_THRESHOLD = 0.9; private MultiLayerNetwork model; @PostConstruct public void init() { log.info("Initializing ImageClassificationService..."); try { InputStream modelInputStream = new ClassPathResource(MODEL_FILE_PATH).getInputStream(); model = ModelSerializer.restoreMultiLayerNetwork(modelInputStream); log.info("Model loaded from {}", MODEL_FILE_PATH); } catch (IOException e) { log.error("Failed to load model from {}", MODEL_FILE_PATH, e); throw new IllegalStateException("Failed to load model", e); } } public String getHerbClassification(MultipartFile file) { log.info("Validating file..."); validateFile(file); try { INDArray image = convertFileToINDArray(file); log.info("Classifying image..."); String label = classifyImage(image); log.info("Image classified as {}", label); return label; } catch (IOException e) { log.error("Failed to process image", e); throw new IllegalStateException("Failed to process image", e); } } private void validateFile(MultipartFile file) { if (file.isEmpty()) {
throw new InvalidFileException("Invalid file");
0
2023-12-04 20:24:16+00:00
2k
Elb1to/FFA
src/main/java/me/elb1to/ffa/user/command/UserProfileDebugCommand.java
[ { "identifier": "FfaPlugin", "path": "src/main/java/me/elb1to/ffa/FfaPlugin.java", "snippet": "@Getter\npublic class FfaPlugin extends JavaPlugin {\n\n\tprivate MongoSrv mongoSrv;\n\n\tprivate MapManager mapManager;\n\tprivate KitManager kitManager;\n\tprivate FfaManager ffaManager;\n\n\tprivate UserProfileManager userProfileManager;\n\tprivate LeaderboardManager leaderboardManager;\n\n\tprivate CommandManager commandManager;\n\n\t@Override\n\tpublic void onEnable() {\n\t\tsaveDefaultConfig();\n\n\t\tmongoSrv = new MongoSrv(this, getConfig().getConfigurationSection(\"mongo\"));\n\n\t\tmapManager = new MapManager(this, getConfig().getConfigurationSection(\"maps\"));\n\t\tkitManager = new KitManager(this, getConfig().getConfigurationSection(\"kits\"));\n\t\tffaManager = new FfaManager(this);\n\n\t\tuserProfileManager = new UserProfileManager(this);\n\t\tleaderboardManager = new LeaderboardManager(this);\n\t\tcommandManager = new CommandManager(this);\n\n\t\tgetServer().getPluginManager().registerEvents(new FfaListener(this), this);\n\t\tgetServer().getPluginManager().registerEvents(new ButtonListener(this), this);\n\t\tgetServer().getPluginManager().registerEvents(new UserProfileListener(this), this);\n\n\t\tgetServer().getScheduler().runTaskLater(this, () -> {\n\t\t\tfor (FfaMap ffaMap : mapManager.getMaps()) {\n\t\t\t\tffaMap.setWorld(Bukkit.getWorld(ffaMap.getName()));\n\t\t\t\tCuboid cuboid = new Cuboid(ffaMap.getMin().toBukkitLocation(), ffaMap.getMax().toBukkitLocation());\n\t\t\t\tffaMap.setCuboid(cuboid);\n\t\t\t}\n\n\t\t\tleaderboardManager.updateLeaderboards();\n\t\t}, 100L);\n\n\t\tgetServer().getScheduler().runTaskTimerAsynchronously(this, new ItemRemovalTask(this), 1L, 1L);\n\n\t\tAssemble assemble = new Assemble(this, new ScoreboardLayout(this));\n\t\tassemble.setAssembleStyle(AssembleStyle.CUSTOM);\n\t\tassemble.setTicks(20);\n\t}\n\n\t@Override\n\tpublic void onDisable() {\n\t\tkitManager.save();\n\t\tmapManager.save();\n\n\t\tfor (UserProfile userProfile : userProfileManager.getAllProfiles()) {\n\t\t\tuserProfileManager.save(userProfile);\n\t\t}\n\n\t\tfor (World world : Bukkit.getWorlds()) {\n\t\t\tfor (Entity entity : world.getEntities()) {\n\t\t\t\tif (!(entity.getType() == EntityType.PAINTING || entity.getType() == EntityType.ITEM_FRAME)) {\n\t\t\t\t\tentity.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tmongoSrv.disconnect();\n\t}\n}" }, { "identifier": "UserProfile", "path": "src/main/java/me/elb1to/ffa/user/UserProfile.java", "snippet": "@Data\npublic class UserProfile {\n\n\tprivate final UUID uniqueId;\n\n\tprivate boolean loaded;\n\n\tprivate String name;\n\n\tprivate Map<String, Integer> kills = new ConcurrentHashMap<>();\n\tprivate Map<String, Integer> deaths = new ConcurrentHashMap<>();\n\n\tprivate UserSettings settings = new UserSettings();\n\n\tprivate FfaMap map;\n\tprivate FfaInstance ffa;\n\tprivate State state = State.SPAWN;\n\n\tpublic UserProfile(UUID uniqueId) {\n\t\tthis.uniqueId = uniqueId;\n\t}\n\n\tpublic UserProfile(UUID uniqueId, String name, Map<String, Integer> kills, Map<String, Integer> deaths) {\n\t\tthis.uniqueId = uniqueId;\n\t\tthis.name = name;\n\t\tthis.kills = kills;\n\t\tthis.deaths = deaths;\n\t}\n\n\tpublic int getKills(String kitName) {\n\t\treturn this.kills.getOrDefault(kitName, 0);\n\t}\n\n\tpublic int getDeaths(String kitName) {\n\t\treturn this.deaths.getOrDefault(kitName, 0);\n\t}\n\n\tpublic int getTotalKills() {\n\t\treturn this.kills.values().stream().mapToInt(Integer::intValue).sum();\n\t}\n\n\tpublic int getTotalDeaths() {\n\t\treturn this.deaths.values().stream().mapToInt(Integer::intValue).sum();\n\t}\n\n\tpublic void increaseKills(String kitName) {\n\t\tthis.kills.put(kitName, this.kills.getOrDefault(kitName, 0) + 1);\n\t}\n\n\tpublic void increaseDeaths(String kitName) {\n\t\tthis.deaths.put(kitName, this.deaths.getOrDefault(kitName, 0) + 1);\n\t}\n\n\tpublic enum State {\n\t\tSPAWN, PLAYING, SPECTATING\n\t}\n}" } ]
import co.aikar.commands.BaseCommand; import co.aikar.commands.annotation.CommandAlias; import co.aikar.commands.annotation.CommandPermission; import co.aikar.commands.annotation.Dependency; import co.aikar.commands.bukkit.contexts.OnlinePlayer; import me.elb1to.ffa.FfaPlugin; import me.elb1to.ffa.user.UserProfile; import org.bukkit.entity.Player;
1,260
package me.elb1to.ffa.user.command; /** * @author Elb1to * @since 11/27/2023 */ public class UserProfileDebugCommand extends BaseCommand { @Dependency private FfaPlugin plugin; @CommandAlias("userdebug") @CommandPermission("ffa.admin") public void onCommand(Player player, OnlinePlayer target) {
package me.elb1to.ffa.user.command; /** * @author Elb1to * @since 11/27/2023 */ public class UserProfileDebugCommand extends BaseCommand { @Dependency private FfaPlugin plugin; @CommandAlias("userdebug") @CommandPermission("ffa.admin") public void onCommand(Player player, OnlinePlayer target) {
UserProfile profile = plugin.getUserProfileManager().getByUuid(target.getPlayer().getUniqueId());
1
2023-11-28 16:53:29+00:00
2k
ItsThosea/BadOptimizations
common/src/main/java/me/thosea/badoptimizations/mixin/MixinDataTracker.java
[ { "identifier": "DummyLock", "path": "common/src/main/java/me/thosea/badoptimizations/DummyLock.java", "snippet": "public final class DummyLock implements ReadWriteLock {\n\tpublic static final DummyLock INSTANCE = new DummyLock();\n\n\tprivate DummyLock() {}\n\n\tprivate final Condition dummyCondition = new Condition() {\n\t\t@Override\n\t\tpublic void await() {}\n\t\t@Override\n\t\tpublic void awaitUninterruptibly() {}\n\t\t@Override\n\t\tpublic long awaitNanos(long nanosTimeout) {return 0;}\n\t\t@Override\n\t\tpublic boolean await(long time, TimeUnit unit) {return true;}\n\t\t@Override\n\t\tpublic boolean awaitUntil(Date deadline) {return true;}\n\t\t@Override\n\t\tpublic void signal() {}\n\t\t@Override\n\t\tpublic void signalAll() {}\n\t};\n\tprivate final Lock dummyLock = new Lock() {\n\t\t@Override\n\t\tpublic void lock() {}\n\t\t@Override\n\t\tpublic void lockInterruptibly() {}\n\t\t@Override\n\t\tpublic boolean tryLock() {return true;}\n\t\t@Override\n\t\tpublic boolean tryLock(long time, @NotNull TimeUnit unit) {return true;}\n\t\t@Override\n\t\tpublic void unlock() {}\n\t\t@NotNull\n\t\t@Override\n\t\tpublic Condition newCondition() {\n\t\t\treturn dummyCondition;\n\t\t}\n\t};\n\n\t@NotNull\n\t@Override\n\tpublic Lock readLock() {\n\t\treturn dummyLock;\n\t}\n\t@NotNull\n\t@Override\n\tpublic Lock writeLock() {\n\t\treturn dummyLock;\n\t}\n}" }, { "identifier": "EntityAccessor", "path": "common/src/main/java/me/thosea/badoptimizations/EntityAccessor.java", "snippet": "public interface EntityAccessor {\n\tvoid badoptimizations$refreshEntityData(TrackedData<?> data);\n}" } ]
import me.thosea.badoptimizations.DummyLock; import me.thosea.badoptimizations.EntityAccessor; import net.minecraft.entity.Entity; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.DataTracker.Entry; import net.minecraft.entity.data.DataTracker.SerializedEntry; import net.minecraft.entity.data.TrackedData; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; 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.At.Shift; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.concurrent.locks.ReadWriteLock;
675
package me.thosea.badoptimizations.mixin; @Mixin(DataTracker.class) public abstract class MixinDataTracker { @Shadow @Final @Mutable private ReadWriteLock lock; @Unique private EntityAccessor entityAccessor; @Inject(method = "<init>", at = @At("TAIL")) private void replaceLock(Entity trackedEntity, CallbackInfo ci) {
package me.thosea.badoptimizations.mixin; @Mixin(DataTracker.class) public abstract class MixinDataTracker { @Shadow @Final @Mutable private ReadWriteLock lock; @Unique private EntityAccessor entityAccessor; @Inject(method = "<init>", at = @At("TAIL")) private void replaceLock(Entity trackedEntity, CallbackInfo ci) {
this.lock = DummyLock.INSTANCE;
0
2023-12-04 00:25:02+00:00
2k
google/watchface
play-validations/memory-footprint/src/main/java/com/google/wear/watchface/dfx/memory/OptimizationEstimator.java
[ { "identifier": "findBitmapFontsNode", "path": "play-validations/memory-footprint/src/main/java/com/google/wear/watchface/dfx/memory/WatchFaceDocuments.java", "snippet": "static Node findBitmapFontsNode(Document document) {\n NodeList nodeList = document.getElementsByTagName(\"BitmapFonts\");\n if (nodeList == null) {\n return null;\n }\n return nodeList.item(0);\n}" }, { "identifier": "findSceneNode", "path": "play-validations/memory-footprint/src/main/java/com/google/wear/watchface/dfx/memory/WatchFaceDocuments.java", "snippet": "static Node findSceneNode(Document document) {\n return document.getElementsByTagName(\"Scene\").item(0);\n}" }, { "identifier": "getNodeAttribute", "path": "play-validations/memory-footprint/src/main/java/com/google/wear/watchface/dfx/memory/WatchFaceDocuments.java", "snippet": "static Optional<String> getNodeAttribute(Node currentNode, String attribute) {\n NamedNodeMap attributes = currentNode.getAttributes();\n if (attributes == null) {\n // A node might have no attributes\n return Optional.empty();\n }\n Node namedItem = attributes.getNamedItem(attribute);\n if (namedItem == null) {\n // A node might not have the required attribute\n return Optional.empty();\n }\n return Optional.of(namedItem.getNodeValue());\n}" } ]
import java.util.Map; import java.util.Optional; import java.util.Set; import static com.google.wear.watchface.dfx.memory.WatchFaceDocuments.findBitmapFontsNode; import static com.google.wear.watchface.dfx.memory.WatchFaceDocuments.findSceneNode; import static com.google.wear.watchface.dfx.memory.WatchFaceDocuments.getNodeAttribute; import static java.lang.Math.ceil; import static java.lang.Math.floor; import static java.lang.Math.max; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.HashMap; import java.util.HashSet;
793
/* * Copyright 2023 Google LLC * * 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.google.wear.watchface.dfx.memory; /** Estimates the effects of optimizing the DWF. */ class OptimizationEstimator { private final Document document; private final Map<String, DrawableResourceDetails> resourceMemoryMap; private final EvaluationSettings evaluationSettings; OptimizationEstimator( Document document, Map<String, DrawableResourceDetails> resourceMemoryMap, EvaluationSettings evaluationSettings) { this.document = document; this.resourceMemoryMap = resourceMemoryMap; this.evaluationSettings = evaluationSettings; } private class Metadata { final Map<DrawableResourceDetails, HashSet<Node>> resourceToImageNodesMap = new HashMap<>(); final Map<String, HashSet<Node>> bitmapFontFamilyToNodesMap = new HashMap<>(); } /** * Analyzes the DWF, looking for optimizations. Size changes ro images are written to * DrawableResourceDetails in memory, but the actual optimizations are not applied. */ void estimateOptimizations() { try { // Initially collect metadata about the scene, linking drawables and bitmap font // families to the nodes that are using them. Metadata metadata = new Metadata();
/* * Copyright 2023 Google LLC * * 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.google.wear.watchface.dfx.memory; /** Estimates the effects of optimizing the DWF. */ class OptimizationEstimator { private final Document document; private final Map<String, DrawableResourceDetails> resourceMemoryMap; private final EvaluationSettings evaluationSettings; OptimizationEstimator( Document document, Map<String, DrawableResourceDetails> resourceMemoryMap, EvaluationSettings evaluationSettings) { this.document = document; this.resourceMemoryMap = resourceMemoryMap; this.evaluationSettings = evaluationSettings; } private class Metadata { final Map<DrawableResourceDetails, HashSet<Node>> resourceToImageNodesMap = new HashMap<>(); final Map<String, HashSet<Node>> bitmapFontFamilyToNodesMap = new HashMap<>(); } /** * Analyzes the DWF, looking for optimizations. Size changes ro images are written to * DrawableResourceDetails in memory, but the actual optimizations are not applied. */ void estimateOptimizations() { try { // Initially collect metadata about the scene, linking drawables and bitmap font // families to the nodes that are using them. Metadata metadata = new Metadata();
collectMetadata(findSceneNode(document), metadata);
1
2023-12-02 22:51:58+00:00
2k
daironpf/SocialSeed
Backend/src/test/java/com/social/seed/repository/PostRepositoryTest.java
[ { "identifier": "HashTag", "path": "Backend/src/main/java/com/social/seed/model/HashTag.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Node\npublic class HashTag{\n\n @Id\n @GeneratedValue(UUIDStringGenerator.class)\n @Property(\"identifier\")\n private String id;\n\n private String name;\n private int socialUserInterestIn;\n private int postTaggedIn;\n}" }, { "identifier": "Post", "path": "Backend/src/main/java/com/social/seed/model/Post.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Node(\"Post\")\npublic class Post {\n\n @Id\n @GeneratedValue(UUIDStringGenerator.class)\n @Property(\"identifier\")\n private String id;\n\n private String content;\n private LocalDateTime updateDate;\n private String imageUrl;\n\n private Boolean isActive;\n\n private int likedCount;\n\n @Relationship(type = \"POSTED_BY\")\n private PostedByRelationship author;\n\n @Relationship(type = \"TAGGED_WITH\")\n private List<HashTag> hashTags;\n}" }, { "identifier": "SocialUser", "path": "Backend/src/main/java/com/social/seed/model/SocialUser.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Node\npublic class SocialUser {\n\n @Id\n @GeneratedValue(UUIDStringGenerator.class)\n @Property(\"identifier\")\n private String id;\n\n private LocalDateTime dateBorn;\n private LocalDateTime registrationDate;\n\n private String fullName;\n private String userName;\n private String email;\n private String language;\n\n private Boolean onVacation;\n private Boolean isActive;\n private Boolean isDeleted;\n\n private Integer friendCount;\n private Integer followersCount;\n private Integer followingCount;\n private Integer friendRequestCount;\n\n @Relationship(type = \"INTERESTED_IN_HASHTAG\")\n private List<SocialUserInterestInHashTagRelationShip> hashTags;\n}" } ]
import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.social.seed.model.HashTag; import com.social.seed.model.Post; import com.social.seed.model.SocialUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import java.time.LocalDateTime; import java.util.*;
895
/* * Copyright 2011-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.social.seed.repository; /** * Unit tests for the {@link PostRepository}, focusing on testing individual methods and functionalities * in isolation for managing {@link Post}. * <p> * The tests use the {@code @DataNeo4jTest} annotation to provide an embedded Neo4j environment * for the repository layer. * <p> * @author Dairon Pérez Frías * @since 2023-12-25 */ @DataNeo4jTest class PostRepositoryTest { //region dependencies @Autowired private PostRepository underTest; @Autowired private HashTagRepository hashTagRepository; @Autowired private SocialUserRepository socialUserRepository; //endregion //region variables private SocialUser user1;
/* * Copyright 2011-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.social.seed.repository; /** * Unit tests for the {@link PostRepository}, focusing on testing individual methods and functionalities * in isolation for managing {@link Post}. * <p> * The tests use the {@code @DataNeo4jTest} annotation to provide an embedded Neo4j environment * for the repository layer. * <p> * @author Dairon Pérez Frías * @since 2023-12-25 */ @DataNeo4jTest class PostRepositoryTest { //region dependencies @Autowired private PostRepository underTest; @Autowired private HashTagRepository hashTagRepository; @Autowired private SocialUserRepository socialUserRepository; //endregion //region variables private SocialUser user1;
private Post post1;
1
2023-12-04 21:47:54+00:00
2k
lunasaw/zlm-spring-boot-starter
src/main/java/io/github/lunasaw/zlm/node/impl/WeightRandomLoadBalancer.java
[ { "identifier": "ZlmNode", "path": "src/main/java/io/github/lunasaw/zlm/config/ZlmNode.java", "snippet": "@Data\npublic class ZlmNode {\n\n /**\n * The id of this node.\n */\n private String serverId = \"zlm\";\n\n /**\n * The host of this node. eg: <a href=\"http://127.0.0.1:9092\">node</a>\n */\n private String host = \"http://127.0.0.1:9092\";\n\n /**\n * The secret of this host.\n */\n private String secret;\n\n /**\n * Whether enable this host.\n */\n private boolean enabled = true;\n\n /**\n * Whether enable hook.\n */\n private boolean hookEnabled = true;\n\n /**\n * The weight of this host.\n */\n private int weight = 100;\n}" }, { "identifier": "ZlmProperties", "path": "src/main/java/io/github/lunasaw/zlm/config/ZlmProperties.java", "snippet": "@ConfigurationProperties(prefix = \"zlm\")\n@Data\npublic class ZlmProperties implements InitializingBean {\n\n /**\n * 对外NodeMap\n */\n public static Map<String, ZlmNode> nodeMap = new ConcurrentHashMap<>();\n\n public static List<ZlmNode> nodes = new CopyOnWriteArrayList<>();\n\n private boolean enable = true;\n\n private LoadBalancerEnums balance = LoadBalancerEnums.ROUND_ROBIN;\n\n public static void addNode(ZlmNode zlmNode) {\n if (zlmNode != null) {\n nodes.add(zlmNode);\n nodeMap.put(zlmNode.getServerId(), zlmNode);\n }\n }\n\n public Map<String, ZlmNode> getNodeMap() {\n return nodeMap;\n }\n\n public List<ZlmNode> getNodes() {\n return nodes;\n }\n\n @Override\n public void afterPropertiesSet() {\n nodeMap = nodes.stream().filter(ZlmNode::isEnabled).collect(Collectors.toMap(ZlmNode::getServerId, node -> node));\n }\n}" }, { "identifier": "LoadBalancerEnums", "path": "src/main/java/io/github/lunasaw/zlm/enums/LoadBalancerEnums.java", "snippet": "@Getter\npublic enum LoadBalancerEnums {\n RANDOM(1, \"Random\"),\n\n ROUND_ROBIN(2, \"RoundRobin\"),\n\n CONSISTENT_HASHING(3, \"ConsistentHashing\"),\n\n WEIGHT_ROUND_ROBIN(4, \"WeightRoundRobin\"),\n\n WEIGHT_RANDOM(5, \"WeightRandom\");\n\n private int code;\n private String type;\n\n private LoadBalancerEnums(int code, String type) {\n this.code = code;\n this.type = type;\n }\n\n}" }, { "identifier": "LoadBalancer", "path": "src/main/java/io/github/lunasaw/zlm/node/LoadBalancer.java", "snippet": "public interface LoadBalancer {\n\n ZlmNode selectNode(String key);\n\n String getType();\n}" } ]
import io.github.lunasaw.zlm.config.ZlmNode; import io.github.lunasaw.zlm.config.ZlmProperties; import io.github.lunasaw.zlm.enums.LoadBalancerEnums; import io.github.lunasaw.zlm.node.LoadBalancer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger;
941
package io.github.lunasaw.zlm.node.impl; /** * @author luna * @date 2024/1/5 */ public class WeightRandomLoadBalancer implements LoadBalancer { static final AtomicInteger TOTAL_WEIGHT = new AtomicInteger(0); static final Map<String, Integer> WEIGHT_MAP = new ConcurrentHashMap<>(); static final Random RANDOM = new Random(); public WeightRandomLoadBalancer() { init(); } public static void init() { List<String> nodeList = new ArrayList<>(ZlmProperties.nodeMap.keySet()); int size = nodeList.size(); if (size > 0) { for (String nodeName : nodeList) {
package io.github.lunasaw.zlm.node.impl; /** * @author luna * @date 2024/1/5 */ public class WeightRandomLoadBalancer implements LoadBalancer { static final AtomicInteger TOTAL_WEIGHT = new AtomicInteger(0); static final Map<String, Integer> WEIGHT_MAP = new ConcurrentHashMap<>(); static final Random RANDOM = new Random(); public WeightRandomLoadBalancer() { init(); } public static void init() { List<String> nodeList = new ArrayList<>(ZlmProperties.nodeMap.keySet()); int size = nodeList.size(); if (size > 0) { for (String nodeName : nodeList) {
ZlmNode nodeConfig = ZlmProperties.nodeMap.get(nodeName);
0
2023-12-02 08:25:38+00:00
2k
Tofaa2/EntityLib
src/main/java/me/tofaa/entitylib/meta/mobs/monster/GhastMeta.java
[ { "identifier": "Metadata", "path": "src/main/java/me/tofaa/entitylib/meta/Metadata.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class Metadata {\n\n private final Map<Byte, EntityData> metadataMap = new ConcurrentHashMap<>();\n private final int entityId;\n\n public Metadata(int entityId) {\n this.entityId = entityId;\n }\n\n public <T> T getIndex(byte index, @Nullable T defaultValue) {\n EntityData entityData = metadataMap.get(index);\n if (entityData == null) return defaultValue;\n if (entityData.getValue() == null) return defaultValue;\n return (T) entityData.getValue();\n }\n\n public <T> void setIndex(byte index, @NotNull EntityDataType<T> dataType, T value) {\n EntityData data = new EntityData(index, dataType, value);\n this.metadataMap.put(index, data);\n WrapperEntity e = EntityLib.getEntity(entityId);\n if (e != null && e.hasSpawned()) {\n e.sendPacketToViewers(\n new WrapperPlayServerEntityMetadata(\n entityId,\n getEntries()\n )\n );\n }\n }\n\n @NotNull List<EntityData> getEntries() {\n return new ArrayList<>(metadataMap.values());\n }\n\n public WrapperPlayServerEntityMetadata createPacket() {\n return new WrapperPlayServerEntityMetadata(entityId, getEntries());\n }\n\n}" }, { "identifier": "MobMeta", "path": "src/main/java/me/tofaa/entitylib/meta/types/MobMeta.java", "snippet": "public class MobMeta extends LivingEntityMeta {\n\n public static final byte OFFSET = LivingEntityMeta.MAX_OFFSET;\n public static final byte MAX_OFFSET = OFFSET + 1;\n\n private final static byte NO_AI_BIT = 0x01;\n private final static byte IS_LEFT_HANDED_BIT = 0x02;\n private final static byte IS_AGGRESSIVE_BIT = 0x04;\n\n\n public MobMeta(int entityId, Metadata metadata) {\n super(entityId, metadata);\n }\n\n public boolean isNoAi() {\n return getMaskBit(OFFSET, NO_AI_BIT);\n }\n\n public void setNoAi(boolean value) {\n setMaskBit(OFFSET, NO_AI_BIT, value);\n }\n\n public boolean isLeftHanded() {\n EntityMeta.isVersionNewer(ServerVersion.V_1_9);\n return getMaskBit(OFFSET, IS_LEFT_HANDED_BIT);\n }\n\n public void setLeftHanded(boolean value) {\n EntityMeta.isVersionNewer(ServerVersion.V_1_9);\n setMaskBit(OFFSET, IS_LEFT_HANDED_BIT, value);\n }\n\n public boolean isAggressive() {\n EntityMeta.isVersionNewer(ServerVersion.V_1_14);\n return getMaskBit(OFFSET, IS_AGGRESSIVE_BIT);\n }\n\n public void setAggressive(boolean value) {\n EntityMeta.isVersionNewer(ServerVersion.V_1_14);\n setMaskBit(OFFSET, IS_AGGRESSIVE_BIT, value);\n }\n\n}" } ]
import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes; import me.tofaa.entitylib.meta.Metadata; import me.tofaa.entitylib.meta.types.MobMeta;
830
package me.tofaa.entitylib.meta.mobs.monster; public class GhastMeta extends MobMeta { public static final byte OFFSET = MobMeta.MAX_OFFSET; public static final byte MAX_OFFSET = OFFSET + 1;
package me.tofaa.entitylib.meta.mobs.monster; public class GhastMeta extends MobMeta { public static final byte OFFSET = MobMeta.MAX_OFFSET; public static final byte MAX_OFFSET = OFFSET + 1;
public GhastMeta(int entityId, Metadata metadata) {
0
2023-11-27 02:17:41+00:00
2k
minlwin/onestop-batch6
s02-backend/member-api/src/main/java/com/jdc/shop/api/member/MemberPurchaseApi.java
[ { "identifier": "PurchaseSearch", "path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/member/input/PurchaseSearch.java", "snippet": "@Data\npublic class PurchaseSearch {\n\n\tprivate LocalDate from;\n\tprivate LocalDate to;\n\n\tpublic Predicate where(CriteriaBuilder cb, Root<Sale> root) {\n\t\tvar list = new ArrayList<Predicate>();\n\t\t\n\t\tif(null != from) {\n\t\t\tlist.add(cb.greaterThanOrEqualTo(root.get(Sale_.saleAt), from.atStartOfDay()));\n\t\t}\n\t\t\n\t\tif(null != to) {\n\t\t\tlist.add(cb.lessThan(root.get(Sale_.saleAt), to.plusDays(1).atStartOfDay()));\n\t\t}\n\t\t\n\t\treturn cb.and(list.toArray(i -> new Predicate[i]));\n\t}\n}" }, { "identifier": "PurchaseDetailsDto", "path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/member/output/PurchaseDetailsDto.java", "snippet": "@Data\npublic class PurchaseDetailsDto {\n\t\n\tprivate PurchaseDto purchase;\n\tprivate List<PurchaseItem> items;\n\t\n\tpublic static PurchaseDetailsDto from(Sale entity) {\n\t\tvar dto = new PurchaseDetailsDto();\n\t\tdto.setPurchase(PurchaseDto.from(entity));\n\t\tdto.setItems(entity.getItems().stream().map(PurchaseItem::from).toList());\n\t\treturn dto;\n\t}\n\n}" }, { "identifier": "PurchaseDto", "path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/member/output/PurchaseDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PurchaseDto {\n\n\tprivate SalePk id;\n\tprivate LocalDateTime saleAt;\n\tprivate String saleBy;\n\tprivate BigDecimal salePrice;\n\tprivate BigDecimal discount;\n\t\n\tpublic static PurchaseDto from(Sale entity) {\n\t\tvar dto = new PurchaseDto();\n\t\tdto.setId(entity.getId());\n\t\tdto.setSaleBy(entity.getSellBy().getName());\n\t\tdto.setSaleAt(entity.getSaleAt());\n\t\tdto.setSalePrice(entity.getSalePrice());\n\t\tdto.setDiscount(entity.getDiscount());\n\t\treturn dto;\n\t}\n\n\tpublic static void select(CriteriaQuery<PurchaseDto> cq, Root<Sale> root) {\n\t\tcq.multiselect(\n\t\t\troot.get(Sale_.id),\n\t\t\troot.get(Sale_.saleAt),\n\t\t\troot.get(Sale_.sellBy).get(Employee_.name),\n\t\t\troot.get(Sale_.salePrice),\n\t\t\troot.get(Sale_.discount)\n\t\t);\n\t}\t\n}" }, { "identifier": "PurchaseService", "path": "s02-backend/member-api/src/main/java/com/jdc/shop/model/service/PurchaseService.java", "snippet": "@Service\n@Transactional(readOnly = true)\npublic class PurchaseService {\n\t\n\t@Autowired\n\tprivate SaleRepo repo;\n\n\tpublic Page<PurchaseDto> search(PurchaseSearch form, int page, int size) {\n\t\tFunction<CriteriaBuilder, CriteriaQuery<Long>> countFunc = cb -> {\n\t\t\tvar cq = cb.createQuery(Long.class);\n\t\t\tvar root = cq.from(Sale.class);\n\t\t\tcq.select(cb.count(root.get(Sale_.id)));\n\t\t\t\n\t\t\tcq.where(form.where(cb, root));\n\t\t\treturn cq;\n\t\t};\n\t\t\n\t\tFunction<CriteriaBuilder, CriteriaQuery<PurchaseDto>> queryFunc = cb -> {\n\t\t\tvar cq = cb.createQuery(PurchaseDto.class);\n\t\t\tvar root = cq.from(Sale.class);\n\t\t\tPurchaseDto.select(cq, root);\n\t\t\tcq.where(form.where(cb, root));\n\t\t\t\n\t\t\tcq.orderBy(cb.desc(root.get(Sale_.saleAt)));\n\t\t\t\n\t\t\treturn cq;\n\t\t};\n\n\t\treturn repo.search(queryFunc, countFunc, page, size);\t\n\t}\n\n\tpublic PurchaseDetailsDto findById(String invoiceNumber) {\n\t\tvar id = SalePk.from(invoiceNumber);\n\t\treturn repo.findById(id).map(PurchaseDetailsDto::from)\n\t\t\t\t.orElseThrow(() -> new ApiBusinessException(\"Invalid invoice number.\"));\n\t}\n\n\tpublic List<PurchaseDto> findByMemberId(int id) {\n\t\treturn repo.search(cb -> {\n\t\t\tvar cq = cb.createQuery(PurchaseDto.class);\n\t\t\tvar root = cq.from(Sale.class);\n\t\t\tPurchaseDto.select(cq, root);\n\t\t\tcq.where(cb.equal(root.get(Sale_.customer).get(Member_.id), id));\n\t\t\tcq.orderBy(cb.desc(root.get(Sale_.saleAt)));\n\t\t\treturn cq;\n\t\t});\n\t}\n\n}" }, { "identifier": "ApiResponse", "path": "s02-backend/member-api/src/main/java/com/jdc/shop/utils/io/ApiResponse.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ApiResponse<T> {\n\n\tprivate Status status;\n\tprivate LocalDateTime issueAt;\n\tprivate T payload;\n\t\n\tpublic static <T> ApiResponse<T> success(T data) {\n\t\treturn new ApiResponse<T>(Status.Success, LocalDateTime.now(), data);\n\t}\n\n\tpublic static <T> ApiResponse<T> validationError(T data) {\n\t\treturn new ApiResponse<T>(Status.ValidationError, LocalDateTime.now(), data);\n\t}\n\n\tpublic static <T> ApiResponse<T> businessError(T data) {\n\t\treturn new ApiResponse<T>(Status.BusinessError, LocalDateTime.now(), data);\n\t}\n\n\tpublic static <T> ApiResponse<T> platformError(T data) {\n\t\treturn new ApiResponse<T>(Status.PlatformError, LocalDateTime.now(), data);\n\t}\n\n\tpublic static <T> ApiResponse<T> securityError(T data) {\n\t\treturn new ApiResponse<T>(Status.SecurityError, LocalDateTime.now(), data);\n\t}\n\n\tpublic enum Status {\n\t\tSuccess,\n\t\tValidationError,\n\t\tBusinessError,\n\t\tSecurityError,\n\t\tPlatformError\n\t}\n\t\n}" } ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.jdc.shop.api.member.input.PurchaseSearch; import com.jdc.shop.api.member.output.PurchaseDetailsDto; import com.jdc.shop.api.member.output.PurchaseDto; import com.jdc.shop.model.service.PurchaseService; import com.jdc.shop.utils.io.ApiResponse;
1,521
package com.jdc.shop.api.member; @RestController @RequestMapping("member/purchase") public class MemberPurchaseApi { @Autowired private PurchaseService service; @GetMapping public ApiResponse<Page<PurchaseDto>> search(PurchaseSearch form, @RequestParam(required = false, defaultValue = "0") int page, @RequestParam(required = false, defaultValue = "10") int size) { return ApiResponse.success(service.search(form, page, size)); } @GetMapping("{id}")
package com.jdc.shop.api.member; @RestController @RequestMapping("member/purchase") public class MemberPurchaseApi { @Autowired private PurchaseService service; @GetMapping public ApiResponse<Page<PurchaseDto>> search(PurchaseSearch form, @RequestParam(required = false, defaultValue = "0") int page, @RequestParam(required = false, defaultValue = "10") int size) { return ApiResponse.success(service.search(form, page, size)); } @GetMapping("{id}")
public ApiResponse<PurchaseDetailsDto> showDetails(@PathVariable String id) {
1
2023-12-04 06:59:55+00:00
2k
LYEmerald/Festival
src/main/java/net/endlight/festival/command/PluginCommand.java
[ { "identifier": "Festival", "path": "src/main/java/net/endlight/festival/Festival.java", "snippet": "public class Festival extends PluginBase {\r\n\r\n public static final String VERSION = \"1.0.0\";\r\n\r\n public static final Random RANDOM = new Random();\r\n\r\n private static Festival plugin;\r\n\r\n public static Festival getInstance() {\r\n return plugin;\r\n }\r\n\r\n @Override\r\n public void onLoad() {\r\n this.getLogger().info(TextFormat.BLUE + \"Festival启动中,感谢您的下载与使用!\");\r\n }\r\n\r\n @Override\r\n public void onEnable() {\r\n plugin = this;\r\n this.saveDefaultConfig();\r\n PluginThread pluginThread = new PluginThread(this.getConfig());\r\n if (this.getConfig().getBoolean(\"AutoStart\")) {\r\n pluginThread.start();\r\n this.getLogger().info(TextFormat.GREEN + \"线程启动成功!\");\r\n }\r\n this.getServer().getCommandMap().register(\"festival\",new PluginCommand());\r\n this.getServer().getPluginManager().registerEvents(new PluginListener(), this);\r\n this.getLogger().info(TextFormat.GREEN + \"Festival v\"+ VERSION +\" 加载成功\");\r\n }\r\n\r\n}\r" }, { "identifier": "Utils", "path": "src/main/java/net/endlight/festival/utils/Utils.java", "snippet": "public class Utils {\r\n\r\n public static int MENU = 0xd3f3ba9;\r\n public static int SETTING = 0xfed0ee8;\r\n\r\n /**\r\n * 倒计时格式\r\n */\r\n public static String addZero(long i) {\r\n if (i < 10) {\r\n return \"0\" + i;\r\n }\r\n return \"\" + i;\r\n }\r\n\r\n /**\r\n * 播放音效\r\n */\r\n public static void playSound(Player player, Sound sound,Float pitch) {\r\n PlaySoundPacket packet = new PlaySoundPacket();\r\n packet.name = sound.getSound();\r\n packet.volume = 1.0F;\r\n packet.pitch = pitch;\r\n packet.x = player.getFloorX();\r\n packet.y = player.getFloorY();\r\n packet.z = player.getFloorZ();\r\n player.dataPacket(packet);\r\n }\r\n\r\n /**\r\n * 放烟花\r\n * 参考:https://github.com/PetteriM1/FireworkShow\r\n */\r\n public static void spawnFirework(Vector3 pos,Level level) {\r\n ItemFirework item = new ItemFirework();\r\n CompoundTag tag = new CompoundTag();\r\n CompoundTag ex = new CompoundTag()\r\n .putByteArray(\"FireworkColor\", new byte[]{(byte) DyeColor.values()[Festival.RANDOM.nextInt(ItemFirework.FireworkExplosion.ExplosionType.values().length)].getDyeData()})\r\n .putByteArray(\"FireworkFade\", new byte[]{})\r\n .putBoolean(\"FireworkFlicker\", Festival.RANDOM.nextBoolean())\r\n .putBoolean(\"FireworkTrail\", Festival.RANDOM.nextBoolean())\r\n .putByte(\"FireworkType\", ItemFirework.FireworkExplosion.ExplosionType.values()[Festival.RANDOM.nextInt(ItemFirework.FireworkExplosion.ExplosionType.values().length)].ordinal());\r\n tag.putCompound(\"Fireworks\", new CompoundTag(\"Fireworks\")\r\n .putList(new ListTag<CompoundTag>(\"Explosions\").add(ex))\r\n .putByte(\"Flight\", 1));\r\n item.setNamedTag(tag);\r\n CompoundTag nbt = new CompoundTag()\r\n .putList(new ListTag<DoubleTag>(\"Pos\")\r\n .add(new DoubleTag(\"\", pos.x + 0.5))\r\n .add(new DoubleTag(\"\", pos.y + 0.5))\r\n .add(new DoubleTag(\"\", pos.z + 0.5)))\r\n .putList(new ListTag<DoubleTag>(\"Motion\")\r\n .add(new DoubleTag(\"\", 0))\r\n .add(new DoubleTag(\"\", 0))\r\n .add(new DoubleTag(\"\", 0)))\r\n .putList(new ListTag<FloatTag>(\"Rotation\")\r\n .add(new FloatTag(\"\", 0))\r\n .add(new FloatTag(\"\", 0)))\r\n .putCompound(\"FireworkItem\", NBTIO.putItemHelper(item));\r\n\r\n FullChunk chunk = level.getChunkIfLoaded(pos.getChunkX(), pos.getChunkZ());\r\n if (chunk != null) {\r\n new EntityFirework(chunk, nbt).spawnToAll();\r\n }\r\n }\r\n\r\n /**\r\n * 插件表单\r\n */\r\n public static void sendMainMenu(Player player){\r\n FormWindowSimple simple = new FormWindowSimple(\"§l§cFestival\",\"\");\r\n simple.addButton(new ElementButton(\"启动线程\"));\r\n simple.addButton(new ElementButton(\"编辑参数\"));\r\n player.showFormWindow(simple,MENU);\r\n }\r\n\r\n public static void sendSettingMenu(Player player){\r\n FormWindowCustom custom = new FormWindowCustom(\"参数设置\");\r\n custom.addElement(new ElementInput(\"年\",\"\",Festival.getInstance().getConfig().getString(\"Calendar.Year\")));\r\n custom.addElement(new ElementInput(\"月\",\"\",Festival.getInstance().getConfig().getString(\"Calendar.Month\")));\r\n custom.addElement(new ElementInput(\"日\",\"\",Festival.getInstance().getConfig().getString(\"Calendar.Day\")));\r\n custom.addElement(new ElementInput(\"时\",\"\",Festival.getInstance().getConfig().getString(\"Calendar.Hour\")));\r\n custom.addElement(new ElementInput(\"分\",\"\",Festival.getInstance().getConfig().getString(\"Calendar.Minute\")));\r\n custom.addElement(new ElementInput(\"秒\",\"\",Festival.getInstance().getConfig().getString(\"Calendar.Second\")));\r\n player.showFormWindow(custom,SETTING);\r\n }\r\n\r\n /**\r\n * 启动线程\r\n */\r\n public static void startThread(){\r\n PluginThread pluginThread = new PluginThread(Festival.getInstance().getConfig());\r\n pluginThread.start();\r\n }\r\n\r\n /**\r\n * 设置参数\r\n */\r\n public static void setConfig(int year, int month, int day, int hour, int minute, int second){\r\n Festival.getInstance().getConfig().set(\"Calendar.Year\", year);\r\n Festival.getInstance().getConfig().set(\"Calendar.Month\", month);\r\n Festival.getInstance().getConfig().set(\"Calendar.Day\", day);\r\n Festival.getInstance().getConfig().set(\"Calendar.Hour\", hour);\r\n Festival.getInstance().getConfig().set(\"Calendar.Minute\", minute);\r\n Festival.getInstance().getConfig().set(\"Calendar.Second\", second);\r\n Festival.getInstance().getConfig().save();\r\n }\r\n}\r" } ]
import cn.nukkit.Player; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.utils.TextFormat; import net.endlight.festival.Festival; import net.endlight.festival.utils.Utils;
1,591
package net.endlight.festival.command; public class PluginCommand extends Command { public PluginCommand() { super("festival", "Festival节日倒计时插件"); } public boolean execute(CommandSender commandSender, String s, String[] strings) { if (commandSender instanceof Player) { Player player = (Player) commandSender; if (player.isOp()) {
package net.endlight.festival.command; public class PluginCommand extends Command { public PluginCommand() { super("festival", "Festival节日倒计时插件"); } public boolean execute(CommandSender commandSender, String s, String[] strings) { if (commandSender instanceof Player) { Player player = (Player) commandSender; if (player.isOp()) {
Utils.sendMainMenu(player);
1
2023-11-30 07:05:55+00:00
2k
Mohamed-code-13/Simple-Paint
paint-backend/src/main/java/com/mohamedcode13/paintbackend/controllers/PaintController.java
[ { "identifier": "Action", "path": "paint-backend/src/main/java/com/mohamedcode13/paintbackend/models/actions/Action.java", "snippet": "public class Action {\n private final ActionType actionType;\n private List<AbstractShape> before;\n private List<AbstractShape> after;\n\n public Action(ActionType actionType) {\n this.actionType = actionType;\n this.before = new ArrayList<>();\n this.after = new ArrayList<>();\n }\n\n public ActionType getActionType() {\n return actionType;\n }\n\n public List<AbstractShape> getBefore() {\n return before;\n }\n\n public void setBefore(List<AbstractShape> before) {\n this.before = before;\n }\n\n public List<AbstractShape> getAfter() {\n return after;\n }\n\n public void setAfter(List<AbstractShape> after) {\n this.after = after;\n }\n\n public void addBefore(AbstractShape shape) {\n before.add(shape);\n }\n\n public void addAfter(AbstractShape shape) {\n after.add(shape);\n }\n\n public Action reversedCopy() {\n ActionType reversedActionType = getReversedActionType();\n Action reversedAction = new Action(reversedActionType);\n\n reversedAction.setBefore(this.after);\n reversedAction.setAfter(this.before);\n\n return reversedAction;\n }\n\n private ActionType getReversedActionType() {\n switch (this.actionType) {\n case ChangeAllShapes:\n return ActionType.ChangeAllShapes;\n case ChangeOneShape:\n return ActionType.ChangeOneShape;\n case AddShape:\n return ActionType.DeleteShape;\n case DeleteShape:\n return ActionType.AddShape;\n default:\n throw new IllegalArgumentException(\"Invalid ActionType\");\n }\n }\n}" }, { "identifier": "ActionType", "path": "paint-backend/src/main/java/com/mohamedcode13/paintbackend/models/actions/ActionType.java", "snippet": "public enum ActionType {\n ChangeAllShapes,\n ChangeOneShape,\n AddShape,\n DeleteShape\n}" }, { "identifier": "SaveLoadJSON", "path": "paint-backend/src/main/java/com/mohamedcode13/paintbackend/service/SaveLoadJSON.java", "snippet": "@Service\npublic class SaveLoadJSON {\n public String saveJson(List<AbstractShape> shapes) {\n ObjectMapper objectMapper = new ObjectMapper();\n StringWriter writer = new StringWriter();\n\n try {\n objectMapper.writeValue(writer, shapes);\n return writer.toString();\n } catch (Exception e) {\n return null;\n }\n }\n\n public List<AbstractShape> loadJson(String jsonData) {\n ObjectMapper objectMapper = new ObjectMapper();\n\n try {\n return objectMapper.readValue(jsonData, objectMapper.getTypeFactory().constructCollectionType(List.class, AbstractShape.class));\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n}" }, { "identifier": "SaveLoadXML", "path": "paint-backend/src/main/java/com/mohamedcode13/paintbackend/service/SaveLoadXML.java", "snippet": "@Service\npublic class SaveLoadXML {\n public String saveXML(List<AbstractShape> shapes) {\n try {\n\n JAXBContext ctx = JAXBContext.newInstance(AbstractShapeWrapper.class,\n AbstractShape.class, Circle.class,\n Ellipse.class, Line.class,\n Rectangle.class, Square.class, Triangle.class);\n\n Marshaller marshaller = ctx.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n\n StringWriter writer = new StringWriter();\n AbstractShapeWrapper wrapper = new AbstractShapeWrapper(shapes);\n\n marshaller.marshal(wrapper, writer);\n\n return writer.toString();\n\n } catch (JAXBException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public List<AbstractShape> loadXml(String xmlData) {\n try {\n\n JAXBContext ctx = JAXBContext.newInstance(AbstractShapeWrapper.class,\n AbstractShape.class, Circle.class,\n Ellipse.class, Line.class,\n Rectangle.class, Square.class, Triangle.class);\n Unmarshaller unmarshaller = ctx.createUnmarshaller();\n\n StringReader reader = new StringReader(xmlData);\n AbstractShapeWrapper wrapper = (AbstractShapeWrapper) unmarshaller.unmarshal(reader);\n\n return wrapper.getShapes();\n\n } catch (JAXBException e) {\n e.printStackTrace();\n }\n return null;\n }\n}" } ]
import com.mohamedcode13.paintbackend.models.actions.Action; import com.mohamedcode13.paintbackend.models.*; import com.mohamedcode13.paintbackend.models.actions.ActionType; import com.mohamedcode13.paintbackend.service.SaveLoadJSON; import com.mohamedcode13.paintbackend.service.SaveLoadXML; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Stack;
1,186
package com.mohamedcode13.paintbackend.controllers; @RestController @RequestMapping("/") @CrossOrigin() public class PaintController { private int id = 0; @Autowired private ShapeFactory shapeFactory; @Autowired
package com.mohamedcode13.paintbackend.controllers; @RestController @RequestMapping("/") @CrossOrigin() public class PaintController { private int id = 0; @Autowired private ShapeFactory shapeFactory; @Autowired
private SaveLoadXML saveLoadXML;
3
2023-11-29 00:47:23+00:00
2k
ismail2ov/upgrade-ecommerce-cross-selling-to-spring-boot-3
src/main/java/com/github/ismail2ov/ecommerce/infrastructure/controller/BasketController.java
[ { "identifier": "BasketService", "path": "src/main/java/com/github/ismail2ov/ecommerce/application/BasketService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class BasketService {\n\n private final BasketRepository basketRepository;\n\n public Basket getBy(Long userId) {\n return basketRepository.getByUserId(userId).orElseThrow(BasketNotFoundException::new);\n }\n\n public Basket addProductToBasket(Long userId, Product product) {\n Optional<Basket> optBasket = basketRepository.getByUserId(userId);\n Basket basket;\n if (optBasket.isPresent()) {\n basket = optBasket.get();\n } else {\n basket = new Basket();\n basket.setUserId(userId);\n }\n\n basket.addItem(product);\n\n return basketRepository.save(basket);\n }\n}" }, { "identifier": "Basket", "path": "src/main/java/com/github/ismail2ov/ecommerce/domain/Basket.java", "snippet": "@Convert(attributeName = \"jsonb\", converter = JsonBinaryType.class)\n@Entity\n@Table(name = \"baskets\")\n@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Basket {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private Long userId;\n\n @JdbcTypeCode(SqlTypes.JSON)\n @Column(columnDefinition = \"jsonb\")\n private Items items = new Items();\n\n public void addItem(Product product) {\n items.addItem(product);\n }\n}" }, { "identifier": "Product", "path": "src/main/java/com/github/ismail2ov/ecommerce/domain/Product.java", "snippet": "@Entity\n@Table(name = \"products\")\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String name;\n\n private String price;\n\n public Product(String name, String price) {\n this.name = name;\n this.price = price;\n }\n}" }, { "identifier": "BasketMapper", "path": "src/main/java/com/github/ismail2ov/ecommerce/infrastructure/controller/mapper/BasketMapper.java", "snippet": "@Mapper\npublic interface BasketMapper {\n\n BasketRDTO basketRDTOFrom(Basket basket);\n}" }, { "identifier": "ProductMapper", "path": "src/main/java/com/github/ismail2ov/ecommerce/infrastructure/controller/mapper/ProductMapper.java", "snippet": "@Mapper\npublic interface ProductMapper {\n\n List<ProductRDTO> productRDTOFrom(List<Product> products);\n\n ProductPageRDTO productPageRDTOFrom(ProductPageDTO productPageDTO);\n\n Product productFrom(ProductRDTO productRDTO);\n}" } ]
import com.github.ismail2ov.ecommerce.application.BasketService; import com.github.ismail2ov.ecommerce.domain.Basket; import com.github.ismail2ov.ecommerce.domain.Product; import com.github.ismail2ov.ecommerce.infrastructure.controller.api.UsersApi; import com.github.ismail2ov.ecommerce.infrastructure.controller.mapper.BasketMapper; import com.github.ismail2ov.ecommerce.infrastructure.controller.mapper.ProductMapper; import com.github.ismail2ov.ecommerce.infrastructure.controller.model.BasketRDTO; import com.github.ismail2ov.ecommerce.infrastructure.controller.model.ProductRDTO; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController;
826
package com.github.ismail2ov.ecommerce.infrastructure.controller; @RestController @RequiredArgsConstructor public class BasketController implements UsersApi { private final BasketService basketService; private final ProductMapper productMapper;
package com.github.ismail2ov.ecommerce.infrastructure.controller; @RestController @RequiredArgsConstructor public class BasketController implements UsersApi { private final BasketService basketService; private final ProductMapper productMapper;
private final BasketMapper basketMapper;
3
2023-11-27 22:47:18+00:00
2k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/command/UserListTabCompletable.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, UserListProvider, CommandProvider,\n BrokerProvider, TextValidator, AudiencesProvider, BlockProvider, MetaProvider, EventDispatcher, HookProvider {\n\n /**\n * Initialize all plugin systems\n *\n * @since 1.0\n */\n default void initialize() {\n log(Level.INFO, String.format(\"Initializing HuskClaims v%s...\", getPluginVersion()));\n try {\n loadSettings();\n loadServer();\n loadTrustLevels();\n loadLocales();\n loadDatabase();\n loadClaimWorlds();\n loadClaimHighlighter();\n loadUserGroups();\n loadTrustTags();\n loadBroker();\n loadCommands();\n loadListeners();\n loadClaimBlockScheduler();\n loadHooks();\n loadAPI();\n loadMetrics();\n } catch (Throwable e) {\n log(Level.SEVERE, \"An error occurred whilst initializing HuskClaims\", e);\n disablePlugin();\n return;\n }\n log(Level.INFO, String.format(\"Successfully initialized HuskClaims v%s\", getPluginVersion()));\n checkForUpdates();\n }\n\n /**\n * Shutdown plugin subsystems\n *\n * @since 1.0\n */\n default void shutdown() {\n log(Level.INFO, String.format(\"Disabling HuskClaims v%s...\", getPluginVersion()));\n try {\n unloadHooks();\n closeBroker();\n closeDatabase();\n cancelTasks();\n unloadAPI();\n } catch (Throwable e) {\n log(Level.SEVERE, \"An error occurred whilst disabling HuskClaims\", e);\n }\n log(Level.INFO, String.format(\"Successfully disabled HuskClaims v%s\", getPluginVersion()));\n }\n\n /**\n * Register the API instance\n *\n * @since 1.0\n */\n void loadAPI();\n\n /**\n * Unregister the API instance\n *\n * @since 1.0\n */\n default void unloadAPI() {\n HuskClaimsAPI.unregister();\n }\n\n /**\n * Load plugin metrics\n *\n * @since 1.0\n */\n void loadMetrics();\n\n /**\n * Disable the plugin\n *\n * @since 1.0\n */\n void disablePlugin();\n\n /**\n * Get a list of all {@link OnlineUser online users} on this server\n *\n * @return A list of {@link OnlineUser}s\n * @since 1.0\n */\n List<? extends OnlineUser> getOnlineUsers();\n\n /**\n * Log a message to the console.\n *\n * @param level the level to log at\n * @param message the message to log\n * @param exceptions any exceptions to log\n * @since 1.0\n */\n void log(@NotNull Level level, @NotNull String message, Throwable... exceptions);\n\n /**\n * Get a {@link Key} for the plugin\n *\n * @param value the value of the key\n * @return the key\n */\n @NotNull\n default Key getKey(@NotNull String... value) {\n @Subst(\"bar\") String text = String.join(\"/\", value);\n return Key.key(\"huskclaims\", text);\n }\n\n /**\n * Get the plugin instance\n *\n * @return the plugin instance\n * @since 1.0\n */\n @NotNull\n default HuskClaims getPlugin() {\n return this;\n }\n\n}" }, { "identifier": "CommandUser", "path": "common/src/main/java/net/william278/huskclaims/user/CommandUser.java", "snippet": "public interface CommandUser {\n\n @NotNull\n Audience getAudience();\n\n boolean hasPermission(@NotNull String permission, boolean isDefault);\n\n boolean hasPermission(@NotNull String permission);\n\n default void sendMessage(@NotNull Component component) {\n getAudience().sendMessage(component);\n }\n\n default void sendMessage(@NotNull MineDown mineDown) {\n this.sendMessage(mineDown.toComponent());\n }\n\n}" }, { "identifier": "User", "path": "common/src/main/java/net/william278/huskclaims/user/User.java", "snippet": "@Getter\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@AllArgsConstructor(access = AccessLevel.PROTECTED)\npublic class User implements Trustable, Comparable<User> {\n\n @Expose\n @NotNull\n private String name;\n @Expose\n @NotNull\n private UUID uuid;\n\n @NotNull\n public static User of(@NotNull UUID uuid, @NotNull String name) {\n return new User(name, uuid);\n }\n\n @NotNull\n @Override\n public String getTrustIdentifier(@NotNull HuskClaims plugin) {\n return name;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof User user)) {\n return false;\n }\n return user.getUuid().equals(uuid);\n }\n\n @Override\n public int compareTo(@NotNull User o) {\n return name.compareTo(o.getName());\n }\n}" } ]
import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.user.CommandUser; import net.william278.huskclaims.user.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List;
1,573
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <[email protected]> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.william278.huskclaims.command; public interface UserListTabCompletable extends TabCompletable { @Override @Nullable default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <[email protected]> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.william278.huskclaims.command; public interface UserListTabCompletable extends TabCompletable { @Override @Nullable default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
return getPlugin().getUserList().stream().map(User::getName).toList();
2
2023-11-28 01:09:43+00:00
2k
Speccy42/AZClientAPI
src/main/java/fr/speccy/azclientapi/bukkit/packets/PacketEntityMeta.java
[ { "identifier": "AZClientPlugin", "path": "src/main/java/fr/speccy/azclientapi/bukkit/AZClientPlugin.java", "snippet": "public final class AZClientPlugin extends JavaPlugin {\n public static AZClientPlugin main;\n private static AZManager AZManager;\n\n @Override\n public void onEnable() {\n AZManager = new AZManager((Plugin)this);\n getServer().getPluginManager().registerEvents(new PacketWindow(this), (Plugin)this);\n main = this;\n }\n\n @Override\n public void onDisable() {\n }\n\n public AZManager getAZManager() {\n return AZManager;\n }\n}" }, { "identifier": "AZManager", "path": "src/main/java/fr/speccy/azclientapi/bukkit/AZManager.java", "snippet": "public class AZManager implements Listener, Closeable {\n private final Plugin plugin;\n private final int serverVersion;\n private static final String PLSP_CHANNEL = \"PLSP\";\n private final Map<UUID, AZPlayer> players;\n\n public AZManager(final Plugin plugin) {\n this.players = new HashMap<UUID, AZPlayer>();\n this.plugin = plugin;\n this.serverVersion = BukkitUtil.findServerVersion();\n plugin.getServer().getPluginManager().registerEvents((Listener)this, plugin);\n plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, \"PLSP\");\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n public void onPlayerLogin(final PlayerLoginEvent event) {\n event.getPlayer().setMetadata(\"AZClientPlugin:hostname\", (MetadataValue)new FixedMetadataValue(this.plugin, (Object)event.getHostname()));\n final AZPlayer AZPlayer;\n this.players.put(event.getPlayer().getUniqueId(), AZPlayer = new AZPlayer(this, event.getPlayer()));\n AZPlayer.init();\n }\n\n @EventHandler(priority = EventPriority.MONITOR)\n public void onPlayerLoginMonitor(final PlayerLoginEvent event) {\n if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) {\n this.playerQuit(event.getPlayer());\n }\n }\n\n @EventHandler\n public void onPlayerJoin(final PlayerJoinEvent event) {\n final AZPlayer AZPlayer = this.getPlayer(event.getPlayer());\n AZPlayer.join();\n }\n\n public AZPlayer getPlayer(final Player player) {\n return this.players.get(player.getUniqueId());\n }\n\n @EventHandler(priority = EventPriority.HIGHEST)\n public void onPlayerQuit(final PlayerQuitEvent event) {\n this.playerQuit(event.getPlayer());\n }\n\n private void playerQuit(final Player player) {\n final AZPlayer AZPlayer = this.players.remove(player.getUniqueId());\n if (AZPlayer != null) {\n AZPlayer.free(true);\n }\n }\n\n public void sendPLSPMessage(final Player player, final PLSPPacket<PLSPPacketHandler.ClientHandler> message) {\n try {\n final PacketOutBuffer buf = new PacketOutBuffer();\n final PLSPProtocol.PacketData<?> packetData = (PLSPProtocol.PacketData<?>)PLSPProtocol.getClientPacketByClass((Class)message.getClass());\n NotchianPacketUtil.writeString((NotchianPacketBuffer)buf, packetData.getId(), 32767);\n message.write((NotchianPacketBuffer)buf);\n player.sendPluginMessage(this.plugin, \"PLSP\", buf.toBytes());\n }\n catch (Exception e) {\n this.plugin.getLogger().log(Level.WARNING, \"Exception sending PLSP message to \" + ((player != null) ? player.getName() : \"null\") + \":\", e);\n }\n }\n\n public void close() throws IOException {\n HandlerList.unregisterAll((Listener)this);\n this.plugin.getServer().getMessenger().unregisterOutgoingPluginChannel(this.plugin, \"PLSP\");\n }\n\n public Plugin getPlugin() {\n return this.plugin;\n }\n\n public int getServerVersion() {\n return this.serverVersion;\n }\n\n public static Integer getColor(final String hexColor) {\n String hexValue = \"0xFF\" + hexColor;\n long longValue = Long.parseLong(hexValue.substring(2), 16);\n return (int) longValue;\n }\n}" } ]
import fr.speccy.azclientapi.bukkit.AZClientPlugin; import fr.speccy.azclientapi.bukkit.AZManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import pactify.client.api.plprotocol.metadata.PactifyScaleMetadata; import pactify.client.api.plprotocol.metadata.PactifyTagMetadata; import pactify.client.api.plsp.packet.client.PLSPPacketEntityMeta;
1,133
package fr.speccy.azclientapi.bukkit.packets; public class PacketEntityMeta { public static void setPlayerScale(Player player, Float BboxH, Float BboxW, Float RenderD, Float RenderH, Float RenderW, Boolean ScaleItems) {
package fr.speccy.azclientapi.bukkit.packets; public class PacketEntityMeta { public static void setPlayerScale(Player player, Float BboxH, Float BboxW, Float RenderD, Float RenderH, Float RenderW, Boolean ScaleItems) {
AZManager azManager = AZClientPlugin.main.getAZManager();
0
2023-11-27 12:23:57+00:00
2k
realgpp/aem-cdn-cache-invalidator
core/src/main/java/com/baglio/autocdninvalidator/core/service/impl/AkamaiInvalidationServiceImpl.java
[ { "identifier": "CONFIGURATION_ID", "path": "core/src/main/java/com/baglio/autocdninvalidator/core/utils/Constants.java", "snippet": "public static final String CONFIGURATION_ID = \"configurationID\";" }, { "identifier": "LoggingHelper", "path": "core/src/main/java/com/baglio/autocdninvalidator/core/helpers/LoggingHelper.java", "snippet": "public class LoggingHelper {\n\n private final Logger logger;\n\n /**\n * Construct helper for the given class to log messages to. This will create a Logger named after the class.\n *\n * @param clazz the class to name the logger after\n */\n public LoggingHelper(final Class clazz) {\n this.logger = LoggerFactory.getLogger(clazz);\n }\n\n /**\n * Log a debug message if debug logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void debug(final String message, final Object... args) {\n if (logger.isDebugEnabled()) {\n logger.debug(message, args);\n }\n }\n\n /**\n * Log an info message if info logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void info(final String message, final Object... args) {\n if (logger.isInfoEnabled()) {\n logger.info(message, args);\n }\n }\n\n /**\n * Log a warn message if warn logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void warn(final String message, final Object... args) {\n if (logger.isWarnEnabled()) {\n logger.warn(message, args);\n }\n }\n\n /**\n * Log a trace message if trace logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void trace(final String message, final Object... args) {\n if (logger.isTraceEnabled()) {\n logger.trace(message, args);\n }\n }\n\n /**\n * Log an error message if error logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void error(final String message, final Object... args) {\n if (logger.isErrorEnabled()) {\n logger.error(message, args);\n }\n }\n}" }, { "identifier": "CdnInvalidationService", "path": "core/src/main/java/com/baglio/autocdninvalidator/core/service/CdnInvalidationService.java", "snippet": "public interface CdnInvalidationService {\n\n /**\n * Purge CDN content on the selected set of cache tags.\n *\n * @param tags An array of cache tag strings you want to purge.\n * @return true if invalidation succeed, false otherwise.\n */\n boolean purgeByTag(Set<String> tags);\n\n /**\n * Purges CDN content on the selected CP code.\n *\n * @param codes An array of the CP codes you want to purge.\n * @return true if invalidation succeed, false otherwise.\n */\n boolean purgeByCode(Set<String> codes);\n\n /**\n * Purges CDN content on the selected URL.\n *\n * @param urls Lists URLs or ARLs to purge.\n * @return true if invalidation succeed, false otherwise.\n */\n boolean purgeByURLs(Set<String> urls);\n}" }, { "identifier": "HttpClientService", "path": "core/src/main/java/com/baglio/autocdninvalidator/core/service/HttpClientService.java", "snippet": "public interface HttpClientService {\n\n /**\n * Gets a closeable HTTP client that is configured with the desired properties.\n *\n * <p>The client is configured with:\n *\n * <ul>\n * <li>Custom accepting trust strategy to allow all certificates\n * <li>HTTP and HTTPS socket factories\n * <li>Connection pool with max total and default max per route connections\n * <li>Request configuration with connect, socket and request timeouts\n * </ul>\n *\n * <p>The client is lazily initialized on first call to this method.\n *\n * @return a closeable HttpClient instance\n */\n CloseableHttpClient getConfiguredHttpClient();\n}" }, { "identifier": "UtilityService", "path": "core/src/main/java/com/baglio/autocdninvalidator/core/service/UtilityService.java", "snippet": "public interface UtilityService {\n <T> T getService(Class<T> tClass, String serviceId);\n}" } ]
import static com.baglio.autocdninvalidator.core.utils.Constants.CONFIGURATION_ID; import com.akamai.edgegrid.signer.ClientCredential; import com.akamai.edgegrid.signer.EdgeGridV1Signer; import com.akamai.edgegrid.signer.Request; import com.akamai.edgegrid.signer.exceptions.RequestSigningException; import com.baglio.autocdninvalidator.core.helpers.LoggingHelper; import com.baglio.autocdninvalidator.core.service.CdnInvalidationService; import com.baglio.autocdninvalidator.core.service.HttpClientService; import com.baglio.autocdninvalidator.core.service.UtilityService; import com.google.gson.Gson; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.AttributeType; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.service.metatype.annotations.Option;
1,476
package com.baglio.autocdninvalidator.core.service.impl; @Designate(ocd = AkamaiInvalidationServiceImpl.Config.class) @Component(service = CdnInvalidationService.class, immediate = true) public class AkamaiInvalidationServiceImpl implements CdnInvalidationService {
package com.baglio.autocdninvalidator.core.service.impl; @Designate(ocd = AkamaiInvalidationServiceImpl.Config.class) @Component(service = CdnInvalidationService.class, immediate = true) public class AkamaiInvalidationServiceImpl implements CdnInvalidationService {
private static final LoggingHelper LOGGER = new LoggingHelper(AkamaiInvalidationServiceImpl.class);
1
2023-11-27 14:47:45+00:00
2k
Max6468/ClimateEvents
src/main/java/org/max6468/climateevents/ClimateEvents.java
[ { "identifier": "MainCommand", "path": "src/main/java/org/max6468/climateevents/commands/MainCommand.java", "snippet": "public class MainCommand implements CommandExecutor {\n\n private final ClimateUtils climateUtils;\n\n\n\n public MainCommand(ClimateEvents plugin) {\n this.climateUtils = new ClimateUtils(plugin);\n this.plugin = plugin;\n }\n private ClimateEvents plugin;\n\n @Override\n public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) {\n FileConfiguration config = plugin.getConfig();\n if (commandSender.hasPermission(\"climateevents.admin\")){\n if (args.length >= 1) {\n switch (args.length) {\n case 1:\n switch (args[0]){\n case \"list\":\n climateUtils.climateList(commandSender);\n break;\n case \"help\":\n climateUtils.help(commandSender);\n break;\n }\n break;\n case 2:\n switch (args[0]) {\n case \"create\":\n climateUtils.climateCreate(commandSender, command, s, args);\n break;\n case \"delete\":\n climateUtils.borrarClimaPreguntar(commandSender, command, s, args);\n break;\n case \"accept\":\n climateUtils.acceptBorrarClima(commandSender, command, s, args);\n break;\n case \"decline\":\n climateUtils.declineBorrarClima(commandSender, command, s, args);\n break;\n\n }\n break;\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n if (args[0].equals(\"edit\")) {\n\n switch (args[2]) {\n case \"frequency\":\n climateUtils.climateEditFrequency(args);\n break;\n case \"duration\":\n climateUtils.climateEditDuration(args);\n break;\n case \"effects\":\n climateUtils.climateEditEffects(args);\n break;\n case \"save\":\n climateUtils.climateSave();\n break;\n }\n }\n break;\n\n default:\n\n }\n }\n }else{\n commandSender.sendMessage(MessageUtils.getColoredMessage(config.getString(\"config.permission_denied\")));\n }\n\n return true;\n }\n}" }, { "identifier": "MessageUtils", "path": "src/main/java/org/max6468/climateevents/utils/MessageUtils.java", "snippet": "public class MessageUtils {\n public static String getColoredMessage(String message) {\n return ChatColor.translateAlternateColorCodes('&', message);\n }\n}" } ]
import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import org.max6468.climateevents.commands.MainCommand; import org.max6468.climateevents.utils.MessageUtils; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.util.Map;
824
package org.max6468.climateevents; public final class ClimateEvents extends JavaPlugin { public static String prefix = "&0&l[&dClimate&9Events&0&l]"; private final String version = getDescription().getVersion(); FileConfiguration config = this.getConfig(); public void onEnable() { registerCommands(); Bukkit.getConsoleSender().sendMessage("");
package org.max6468.climateevents; public final class ClimateEvents extends JavaPlugin { public static String prefix = "&0&l[&dClimate&9Events&0&l]"; private final String version = getDescription().getVersion(); FileConfiguration config = this.getConfig(); public void onEnable() { registerCommands(); Bukkit.getConsoleSender().sendMessage("");
Bukkit.getConsoleSender().sendMessage(MessageUtils.getColoredMessage("&l&6======================================"));
1
2023-11-28 07:39:19+00:00
2k
Manzzx/multi-channel-message-reach
metax-web/src/main/java/com/metax/web/util/aliyun/AlibabaCloudSMSReceiptPullUtils.java
[ { "identifier": "AlibabaCloudSmsConfig", "path": "metax-web/src/main/java/com/metax/web/domain/aliyun/AlibabaCloudSmsConfig.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AlibabaCloudSmsConfig {\n\n /**\n * regionId\n */\n private String regionId;\n\n /**\n * accessKeyId\n */\n private String accessKeyId;\n\n /**\n * accessSecret\n */\n private String accessSecret;\n\n /**\n * 模板code\n */\n private String templateCode;\n\n /**\n * 签名\n */\n private String signName;\n\n\n /**\n * 第三方服务名称\n */\n private String serviceName;\n\n}" }, { "identifier": "QueryAlibabaCloudSMSReceiptParam", "path": "metax-web/src/main/java/com/metax/web/domain/aliyun/QueryAlibabaCloudSMSReceiptParam.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class QueryAlibabaCloudSMSReceiptParam {\n\n /**\n * 手机号 必选\n */\n private String phone;\n\n /**\n * 流水号 可选\n */\n private String bizId;\n\n\n /**\n * 发送日期 格式:yyyyMMdd 必选\n */\n private String sendDate;\n\n /**\n * 查询页大小 必选\n */\n private long pageSize;\n\n /**\n * 当前页数 必选\n */\n private long pageNum;\n}" }, { "identifier": "SmsRecord", "path": "metax-web/src/main/java/com/metax/web/vo/SmsRecord.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class SmsRecord {\n\n /**\n * 请求id\n */\n private String requestId;\n\n /**\n * 短信渠道服务商名称\n */\n private String channelName;\n\n /**\n * 短信流水号\n */\n private String serialId;\n\n /**\n * 发送状态\n */\n private String status;\n\n /**\n * 接受者手机号\n */\n private String phone;\n\n /**\n * 短信模板名称\n */\n private String template;\n\n /**\n * 消息内容\n */\n private String content;\n\n /**\n * 短信发送时间\n */\n private LocalDateTime sendDate;\n\n /**\n * 接受时间\n */\n private LocalDateTime receiveDate;\n\n /**\n * 查询时间\n */\n private LocalDateTime queryDate;\n\n /**\n * 返回日志/备注\n */\n private String log;\n\n}" }, { "identifier": "SmsRecordPage", "path": "metax-web/src/main/java/com/metax/web/vo/SmsRecordPage.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class SmsRecordPage {\n\n private List<SmsRecord> smsRecords;\n\n private long total;\n\n}" }, { "identifier": "DAY_FORMAT_Y_M_D_H_M_S", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/MetaxDataConstants.java", "snippet": "public static final String DAY_FORMAT_Y_M_D_H_M_S = \"yyyy-MM-dd HH:mm:ss\";" }, { "identifier": "REDIS_DAY_KEY_FORMAT", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/MetaxDataConstants.java", "snippet": "public static final String REDIS_DAY_KEY_FORMAT = \"yyyyMMdd\";" } ]
import cn.hutool.core.util.StrUtil; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.metax.web.domain.aliyun.AlibabaCloudSmsConfig; import com.metax.web.domain.aliyun.QueryAlibabaCloudSMSReceiptParam; import com.metax.web.vo.SmsRecord; import com.metax.web.vo.SmsRecordPage; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import static com.metax.common.core.constant.MetaxDataConstants.DAY_FORMAT_Y_M_D_H_M_S; import static com.metax.common.core.constant.MetaxDataConstants.REDIS_DAY_KEY_FORMAT;
1,594
package com.metax.web.util.aliyun; /** * 阿里云短信回执拉取 * * @Author: hanabi * @DateTime: 2023/10/29 19:36 **/ public class AlibabaCloudSMSReceiptPullUtils { //产品名称:云通信短信API产品,开发者无需替换 static final String product = "Dysmsapi"; //产品域名,开发者无需替换 static final String domain = "dysmsapi.aliyuncs.com"; /** * 查询短信详情 * * @param config * @param param * @return * @throws ClientException */ public static QuerySendDetailsResponse querySendDetails(AlibabaCloudSmsConfig config, QueryAlibabaCloudSMSReceiptParam param) throws ClientException { //可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", config.getAccessKeyId(), config.getAccessSecret()); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); //组装请求对象 QuerySendDetailsRequest request = new QuerySendDetailsRequest(); //必填-号码 request.setPhoneNumber(param.getPhone()); //可选-流水号 if (StrUtil.isNotBlank(param.getBizId())) { request.setBizId(param.getBizId()); } //必填-发送日期 支持30天内记录查询,格式yyyyMMdd SimpleDateFormat ft = new SimpleDateFormat(REDIS_DAY_KEY_FORMAT); request.setSendDate(ft.format(new Date())); //必填-页大小 request.setPageSize(param.getPageSize()); //必填-当前页码 request.setCurrentPage(param.getPageNum()); //hint 此处可能会抛出异常,注意catch QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request); return querySendDetailsResponse; }
package com.metax.web.util.aliyun; /** * 阿里云短信回执拉取 * * @Author: hanabi * @DateTime: 2023/10/29 19:36 **/ public class AlibabaCloudSMSReceiptPullUtils { //产品名称:云通信短信API产品,开发者无需替换 static final String product = "Dysmsapi"; //产品域名,开发者无需替换 static final String domain = "dysmsapi.aliyuncs.com"; /** * 查询短信详情 * * @param config * @param param * @return * @throws ClientException */ public static QuerySendDetailsResponse querySendDetails(AlibabaCloudSmsConfig config, QueryAlibabaCloudSMSReceiptParam param) throws ClientException { //可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", config.getAccessKeyId(), config.getAccessSecret()); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); //组装请求对象 QuerySendDetailsRequest request = new QuerySendDetailsRequest(); //必填-号码 request.setPhoneNumber(param.getPhone()); //可选-流水号 if (StrUtil.isNotBlank(param.getBizId())) { request.setBizId(param.getBizId()); } //必填-发送日期 支持30天内记录查询,格式yyyyMMdd SimpleDateFormat ft = new SimpleDateFormat(REDIS_DAY_KEY_FORMAT); request.setSendDate(ft.format(new Date())); //必填-页大小 request.setPageSize(param.getPageSize()); //必填-当前页码 request.setCurrentPage(param.getPageNum()); //hint 此处可能会抛出异常,注意catch QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request); return querySendDetailsResponse; }
public static SmsRecordPage pull(AlibabaCloudSmsConfig config, QueryAlibabaCloudSMSReceiptParam param) {
3
2023-12-04 05:10:13+00:00
2k
ydb-platform/yoj-project
repository/src/main/java/tech/ydb/yoj/repository/db/projection/RoProjectionCache.java
[ { "identifier": "Entity", "path": "repository/src/main/java/tech/ydb/yoj/repository/db/Entity.java", "snippet": "public interface Entity<E extends Entity<E>> extends Table.ViewId<E> {\n @Override\n Id<E> getId();\n\n @SuppressWarnings(\"unchecked\")\n default E postLoad() {\n return (E) this;\n }\n\n @SuppressWarnings(\"unchecked\")\n default E preSave() {\n return (E) this;\n }\n\n default List<Entity<?>> createProjections() {\n return List.of();\n }\n\n interface Id<E extends Entity<E>> {\n\n /**\n * @deprecated Use {@link Table#find(Entity.Id)} instead.\n */\n @CheckForNull\n @Deprecated\n default E resolve() {\n return Tx.Current.get().getRepositoryTransaction().table(getType()).find(this);\n }\n\n /**\n * @deprecated Use {@link Table#find(Entity.Id, Supplier)} instead.\n */\n @NonNull\n @Deprecated\n default <EXCEPTION extends Exception> E resolve(\n Supplier<? extends EXCEPTION> throwIfAbsent\n ) throws EXCEPTION {\n return Tx.Current.get().getRepositoryTransaction().table(getType()).find(this, throwIfAbsent);\n }\n\n @SuppressWarnings(\"unchecked\")\n default Class<E> getType() {\n return (Class<E>) new TypeToken<E>(getClass()) {\n }.getRawType();\n }\n\n default boolean isPartial() {\n var schema = EntitySchema.of(getType()).getIdSchema();\n var columns = schema.flattenFields();\n var nonNullFields = schema.flatten(this);\n return columns.size() > nonNullFields.size();\n }\n }\n}" }, { "identifier": "RepositoryTransaction", "path": "repository/src/main/java/tech/ydb/yoj/repository/db/RepositoryTransaction.java", "snippet": "public interface RepositoryTransaction {\n <T extends Entity<T>> Table<T> table(Class<T> c);\n\n /**\n * Commits the transaction or throws exception. Note that this method is not expected to be called, if the last\n * transaction statement has thrown an exception, because it means that transaction didn't 'execute normally'.\n *\n * @throws OptimisticLockException if the transaction's optimistic attempt has failed and it ought to be started over\n */\n void commit() throws OptimisticLockException;\n\n /**\n * Rollbacks that transaction. This method <i>must</i> be called in the end unless {@link #commit()} method was chosen for calling.\n * If this method throws an exception, the transaction consistency is not confirmed and none of its results can be used\n * (you may very well be inside a catch clause right now, having caught an exception from your transaction and calling the rollback method\n * on this occasion; even so, your exception is a <i>result</i> of your transaction and it must be disregarded, because the\n * consistency couldn't be confirmed).\n * If the thrown exception is {@link OptimisticLockException}, the transaction is certainly inconsistent and ought to\n * be started over. Otherwise it's at your discretion whether to restart the transaction or simply to fail the operation.\n * <p>\n * (Note, that consistency is only checked if the transaction has 'executed normally', i.e. the last statement didn't throw an exception.\n * Otherwise this method always completes normally.)\n */\n void rollback() throws OptimisticLockException;\n\n TransactionLocal getTransactionLocal();\n\n TxOptions getOptions();\n}" } ]
import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.RepositoryTransaction;
871
package tech.ydb.yoj.repository.db.projection; public class RoProjectionCache implements ProjectionCache { @Override
package tech.ydb.yoj.repository.db.projection; public class RoProjectionCache implements ProjectionCache { @Override
public void load(Entity<?> entity) {
0
2023-12-05 15:57:58+00:00
2k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/VersionSelectorDialog.java
[ { "identifier": "getValue", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraCore.java", "snippet": "public static Object getValue(String key){\n return getInstance().mValueMap.get(key);\n}" }, { "identifier": "JMinecraftVersionList", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/JMinecraftVersionList.java", "snippet": "@Keep\n@SuppressWarnings(\"unused\") // all unused fields here are parts of JSON structures\npublic class JMinecraftVersionList {\n public Map<String, String> latest;\n public Version[] versions;\n\n @Keep\n public static class FileProperties {\n public String id, sha1, url;\n public long size;\n }\n\n @Keep\n public static class Version extends FileProperties {\n // Since 1.13, so it's one of ways to check\n public Arguments arguments;\n public AssetIndex assetIndex;\n\n public String assets;\n public Map<String, MinecraftClientInfo> downloads;\n public String inheritsFrom;\n public JavaVersionInfo javaVersion;\n public DependentLibrary[] libraries;\n public LoggingConfig logging;\n public String mainClass;\n public String minecraftArguments;\n public int minimumLauncherVersion;\n public String releaseTime;\n public String time;\n public String type;\n }\n @Keep\n public static class JavaVersionInfo {\n public String component;\n public int majorVersion;\n public int version; // parameter used by LabyMod 4\n }\n @Keep\n public static class LoggingConfig {\n public LoggingClientConfig client;\n\n @Keep\n public static class LoggingClientConfig {\n public String argument;\n public FileProperties file;\n public String type;\n }\n }\n // Since 1.13\n @Keep\n public static class Arguments {\n public Object[] game;\n public Object[] jvm;\n\n @Keep\n public static class ArgValue {\n public ArgRules[] rules;\n public String value;\n\n // TLauncher styled argument...\n public String[] values;\n\n @Keep\n public static class ArgRules {\n public String action;\n public String features;\n public ArgOS os;\n\n @Keep\n public static class ArgOS {\n public String name;\n public String version;\n }\n }\n }\n }\n @Keep\n public static class AssetIndex extends FileProperties {\n public long totalSize;\n }\n}" }, { "identifier": "ExtraConstants", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraConstants.java", "snippet": "public class ExtraConstants {\n /* ExtraCore constant: a HashMap for converting values such as latest-snapshot or latest-release to actual game version names */\n public static final String RELEASE_TABLE = \"release_table\";\n /* ExtraCore constant: Serpent's back button tracking thing */\n public static final String BACK_PREFERENCE = \"back_preference\";\n /* ExtraCore constant: The OPENGL version that should be exposed */\n public static final String OPEN_GL_VERSION = \"open_gl_version\";\n /* ExtraCore constant: When the microsoft authentication via webview is done */\n public static final String MICROSOFT_LOGIN_TODO = \"webview_login_done\";\n /* ExtraCore constant: Mojang or \"local\" authentication to perform */\n public static final String MOJANG_LOGIN_TODO = \"mojang_login_todo\";\n /* ExtraCore constant: Add minecraft account procedure, the user has to select between mojang or microsoft */\n public static final String SELECT_AUTH_METHOD = \"start_login_procedure\";\n /* ExtraCore constant: Selected file or folder, as a String */\n public static final String FILE_SELECTOR = \"file_selector\";\n /* ExtraCore constant: Need to refresh the version spinner, selecting the uuid at the same time. Can be DELETED_PROFILE */\n public static final String REFRESH_VERSION_SPINNER = \"refresh_version\";\n /* ExtraCore Constant: When we want to launch the game */\n public static final String LAUNCH_GAME = \"launch_game\";\n /* ExtraCore Constant:Other login methods */\n public static final String OTHER_LOGIN_TODO = \"other_login_todo\";\n\n}" } ]
import static net.kdt.pojavlaunch.extra.ExtraCore.getValue; import android.content.Context; import android.view.LayoutInflater; import android.widget.ExpandableListView; import androidx.appcompat.app.AlertDialog; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.extra.ExtraConstants;
1,138
package net.kdt.pojavlaunch.profiles; public class VersionSelectorDialog { public static void open(Context context, boolean hideCustomVersions, VersionSelectorListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); ExpandableListView expandableListView = (ExpandableListView) LayoutInflater.from(context) .inflate(R.layout.dialog_expendable_list_view , null);
package net.kdt.pojavlaunch.profiles; public class VersionSelectorDialog { public static void open(Context context, boolean hideCustomVersions, VersionSelectorListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); ExpandableListView expandableListView = (ExpandableListView) LayoutInflater.from(context) .inflate(R.layout.dialog_expendable_list_view , null);
JMinecraftVersionList jMinecraftVersionList = (JMinecraftVersionList) getValue(ExtraConstants.RELEASE_TABLE);
0
2023-12-01 16:16:12+00:00
2k
SuperMagicican/elegent-security
elegent-security-verifier-gateway/src/main/java/cn/elegent/security/verifier/gateway/config/GatewayVeriferConfigurer.java
[ { "identifier": "LoginStrategyService", "path": "elegent-security-common/src/main/java/cn/elegent/security/common/core/LoginStrategyService.java", "snippet": "public interface LoginStrategyService {\n\n /**\n * 获取全部的登录策略\n * @return\n */\n Map<String, LoginStrategy> getLoginStrategy();\n\n}" }, { "identifier": "GatewayTokenAcquirer", "path": "elegent-security-verifier-gateway/src/main/java/cn/elegent/security/verifier/gateway/acquirer/GatewayTokenAcquirer.java", "snippet": "@Builder\npublic class GatewayTokenAcquirer implements TokenAcquirer<ServerHttpRequest> {\n\n private HeaderProperties headerProperties;\n\n private LoginStrategyService loginStrategyService;\n\n @Override\n public TokenDetails getToken(ServerHttpRequest request) {\n\n TokenDetails tokenDetails=new TokenDetails();\n\n List<String> headers = request.getHeaders().get(headerProperties.getTokenHeader());\n if(headers==null) return null;\n String token =headers.get(0);\n if(token==null ) return null;\n tokenDetails.setAccessToken(token);\n\n List<String> types = request.getHeaders().get(headerProperties.getTypeHeader());\n String type=\"default\";\n if(types!=null && types.size()>0){\n type= types.get(0);\n }\n tokenDetails.setType(type);\n\n return tokenDetails;\n\n }\n}" }, { "identifier": "GatewayUrlAcquirer", "path": "elegent-security-verifier-gateway/src/main/java/cn/elegent/security/verifier/gateway/acquirer/GatewayUrlAcquirer.java", "snippet": "@Builder\npublic class GatewayUrlAcquirer implements UrlAcquirer<ServerHttpRequest>{\n @Override\n public String getUrl(ServerHttpRequest request) {\n\n HttpMethod method = request.getMethod();\n String url = request.getURI().getPath();\n return method.name() + url;\n\n }\n}" }, { "identifier": "GatewayAccessDeniedHandler", "path": "elegent-security-verifier-gateway/src/main/java/cn/elegent/security/verifier/gateway/handler/GatewayAccessDeniedHandler.java", "snippet": "public class GatewayAccessDeniedHandler implements AccessDeniedHandler<ServerHttpRequest, ServerHttpResponse> {\n @Override\n public void handle(ServerHttpRequest request, ServerHttpResponse response) {\n response.setStatusCode(HttpStatus.FORBIDDEN);\n }\n}" }, { "identifier": "GatewayAuthenticationEntryPoint", "path": "elegent-security-verifier-gateway/src/main/java/cn/elegent/security/verifier/gateway/handler/GatewayAuthenticationEntryPoint.java", "snippet": "public class GatewayAuthenticationEntryPoint implements AuthenticationEntryPoint<ServerHttpRequest, ServerHttpResponse> {\n @Override\n public void commence(ServerHttpRequest request, ServerHttpResponse response) {\n response.setStatusCode(HttpStatus.UNAUTHORIZED);\n }\n}" }, { "identifier": "DefaultAccessDeniedHandler", "path": "elegent-security-verifier/src/main/java/cn/elegent/security/verifier/handler/DefaultAccessDeniedHandler.java", "snippet": "public class DefaultAccessDeniedHandler implements AccessDeniedHandler<HttpServletRequest,HttpServletResponse> {\n @Override\n public void handle(HttpServletRequest request, HttpServletResponse response) {\n response.setStatus(HttpStatus.FORBIDDEN.value());\n }\n}" }, { "identifier": "DefaultAuthenticationEntryPoint", "path": "elegent-security-verifier/src/main/java/cn/elegent/security/verifier/handler/DefaultAuthenticationEntryPoint.java", "snippet": "public class DefaultAuthenticationEntryPoint implements AuthenticationEntryPoint<HttpServletRequest,HttpServletResponse> {\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response) {\n response.setStatus(HttpStatus.UNAUTHORIZED.value());\n }\n}" }, { "identifier": "HeaderProperties", "path": "elegent-security-verifier/src/main/java/cn/elegent/security/verifier/properties/HeaderProperties.java", "snippet": "@Data\n@Configuration\npublic class HeaderProperties implements Serializable {\n\n\n /**\n * 获取请求头的名字( 登录类型)\n */\n @Value(\"${elegent.security.verifier.header.type:login-type}\")\n private String typeHeader;\n\n /**\n * 获取请求头的名字( 登录类型)\n */\n @Value(\"${elegent.security.verifier.header.token:user-token}\")\n private String tokenHeader;\n\n}" } ]
import cn.elegent.security.common.core.LoginStrategyService; import cn.elegent.security.verifier.core.*; import cn.elegent.security.verifier.gateway.acquirer.GatewayTokenAcquirer; import cn.elegent.security.verifier.gateway.acquirer.GatewayUrlAcquirer; import cn.elegent.security.verifier.gateway.handler.GatewayAccessDeniedHandler; import cn.elegent.security.verifier.gateway.handler.GatewayAuthenticationEntryPoint; import cn.elegent.security.verifier.handler.DefaultAccessDeniedHandler; import cn.elegent.security.verifier.handler.DefaultAuthenticationEntryPoint; import cn.elegent.security.verifier.properties.HeaderProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.server.reactive.ServerHttpRequest;
1,231
package cn.elegent.security.verifier.gateway.config; @Configuration public class GatewayVeriferConfigurer { @Autowired private HeaderProperties headerProperties; @Autowired private LoginStrategyService loginStrategyService; /** * 令牌获取器(覆盖默认的令牌获取器) * return */ @Bean public TokenAcquirer tokenAcquirer(){ return GatewayTokenAcquirer.builder() .loginStrategyService(loginStrategyService) .headerProperties(headerProperties).build(); } /** * 地址获取器(覆盖默认的地址获取器) * return */ @Bean public UrlAcquirer urlAcquirer(){
package cn.elegent.security.verifier.gateway.config; @Configuration public class GatewayVeriferConfigurer { @Autowired private HeaderProperties headerProperties; @Autowired private LoginStrategyService loginStrategyService; /** * 令牌获取器(覆盖默认的令牌获取器) * return */ @Bean public TokenAcquirer tokenAcquirer(){ return GatewayTokenAcquirer.builder() .loginStrategyService(loginStrategyService) .headerProperties(headerProperties).build(); } /** * 地址获取器(覆盖默认的地址获取器) * return */ @Bean public UrlAcquirer urlAcquirer(){
return GatewayUrlAcquirer.builder()
2
2023-12-02 12:13:30+00:00
2k
kawashirov/distant-horizons
fabric/src/main/java/com/seibel/distanthorizons/fabric/FabricClientMain.java
[ { "identifier": "LodCommonMain", "path": "common/src/main/java/com/seibel/distanthorizons/common/LodCommonMain.java", "snippet": "public class LodCommonMain\n{\n\tpublic static boolean forge = false;\n\tpublic static LodForgeMethodCaller forgeMethodCaller;\n\t\n\t\n\t\n\tpublic static void startup(LodForgeMethodCaller forgeMethodCaller)\n\t{\n\t\tif (forgeMethodCaller != null)\n\t\t{\n\t\t\tLodCommonMain.forge = true;\n\t\t\tLodCommonMain.forgeMethodCaller = forgeMethodCaller;\n\t\t}\n\t\t\n\t\tDependencySetup.createSharedBindings();\n\t\tSharedApi.init();\n// if (!serverSided) {\n// new NetworkReceiver().register_Client();\n// } else {\n// new NetworkReceiver().register_Server();\n// }\n\t}\n\t\n\tpublic static void initConfig()\n\t{\n\t\tConfigBase.INSTANCE = new ConfigBase(ModInfo.ID, ModInfo.NAME, Config.class, 2);\n\t\tConfig.completeDelayedSetup();\n\t}\n\t\n}" }, { "identifier": "DependencySetup", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/DependencySetup.java", "snippet": "public class DependencySetup\n{\n\t\n\tpublic static void createSharedBindings()\n\t{\n\t\tSingletonInjector.INSTANCE.bind(ILangWrapper.class, LangWrapper.INSTANCE);\n\t\tSingletonInjector.INSTANCE.bind(IVersionConstants.class, VersionConstants.INSTANCE);\n\t\tSingletonInjector.INSTANCE.bind(IWrapperFactory.class, WrapperFactory.INSTANCE);\n\t\tSingletonInjector.INSTANCE.bind(IKeyedClientLevelManager.class, KeyedClientLevelManager.INSTANCE);\n\t\tDependencySetupDoneCheck.isDone = true;\n\t}\n\t\n\t//@Environment(EnvType.SERVER)\n\tpublic static void createServerBindings()\n\t{\n\t\tSingletonInjector.INSTANCE.bind(IMinecraftSharedWrapper.class, MinecraftDedicatedServerWrapper.INSTANCE);\n\t}\n\t\n\t//@Environment(EnvType.CLIENT)\n\tpublic static void createClientBindings()\n\t{\n\t\tSingletonInjector.INSTANCE.bind(IMinecraftClientWrapper.class, MinecraftClientWrapper.INSTANCE);\n\t\tSingletonInjector.INSTANCE.bind(IMinecraftSharedWrapper.class, MinecraftClientWrapper.INSTANCE);\n\t\tSingletonInjector.INSTANCE.bind(IMinecraftRenderWrapper.class, MinecraftRenderWrapper.INSTANCE);\n\t\tSingletonInjector.INSTANCE.bind(IConfigGui.class, ClassicConfigGUI.CONFIG_CORE_INTERFACE);\n\t}\n\t\n}" } ]
import com.seibel.distanthorizons.common.LodCommonMain; import com.seibel.distanthorizons.common.wrappers.DependencySetup; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
705
package com.seibel.distanthorizons.fabric; @Environment(EnvType.CLIENT) public class FabricClientMain implements ClientModInitializer { public static FabricClientProxy client_proxy; public static FabricServerProxy server_proxy; // Do if implements ClientModInitializer // This loads the mod before minecraft loads which causes a lot of issues @Override public void onInitializeClient() {
package com.seibel.distanthorizons.fabric; @Environment(EnvType.CLIENT) public class FabricClientMain implements ClientModInitializer { public static FabricClientProxy client_proxy; public static FabricServerProxy server_proxy; // Do if implements ClientModInitializer // This loads the mod before minecraft loads which causes a lot of issues @Override public void onInitializeClient() {
DependencySetup.createClientBindings();
1
2023-12-04 11:41:46+00:00
2k
aws-observability/application-signals-demo
spring-petclinic-vets-service/src/test/java/org/springframework/samples/petclinic/vets/web/VetResourceTest.java
[ { "identifier": "S3Service", "path": "spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/aws/S3Service.java", "snippet": "@Component\npublic class S3Service {\n private S3Client s3Client;\n private static final String ENV_TRACE_BUCKET = \"TRACE_DATA_BUCKET\";\n private static final String ENV_TRACE_S3_KEY = \"TRACE_DATA_S3_KEY\";\n\n public S3Service(){\n\n // AWS web identity is set for EKS clusters, if these are not set then use default credentials\n if (System.getenv(\"AWS_WEB_IDENTITY_TOKEN_FILE\") == null && System.getProperty(\"aws.webIdentityTokenFile\") == null) {\n s3Client = S3Client.builder()\n .region(Region.US_EAST_1)\n .build();\n }\n else {\n s3Client = S3Client.builder()\n .region(Region.US_EAST_1)\n .credentialsProvider(WebIdentityTokenFileCredentialsProvider.create())\n .build();\n }\n }\n\n public void listBuckets() {\n s3Client.listBuckets();\n }\n}" }, { "identifier": "Vet", "path": "spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/Vet.java", "snippet": "@Entity\n@Table(name = \"vets\")\npublic class Vet {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Getter\n @Setter\n private Integer id;\n\n @Column(name = \"first_name\")\n @NotBlank\n @Getter\n @Setter\n private String firstName;\n\n @Column(name = \"last_name\")\n @NotBlank\n @Getter\n @Setter\n private String lastName;\n\n @ManyToMany(fetch = FetchType.EAGER)\n @JoinTable(name = \"vet_specialties\", joinColumns = @JoinColumn(name = \"vet_id\"),\n inverseJoinColumns = @JoinColumn(name = \"specialty_id\"))\n private Set<Specialty> specialties;\n\n protected Set<Specialty> getSpecialtiesInternal() {\n if (this.specialties == null) {\n this.specialties = new HashSet<>();\n }\n return this.specialties;\n }\n\n @XmlElement\n public List<Specialty> getSpecialties() {\n List<Specialty> sortedSpecs = new ArrayList<>(getSpecialtiesInternal());\n PropertyComparator.sort(sortedSpecs, new MutableSortDefinition(\"name\", true, true));\n return Collections.unmodifiableList(sortedSpecs);\n }\n\n public int getNrOfSpecialties() {\n return getSpecialtiesInternal().size();\n }\n\n public void addSpecialty(Specialty specialty) {\n getSpecialtiesInternal().add(specialty);\n }\n\n}" }, { "identifier": "VetRepository", "path": "spring-petclinic-vets-service/src/main/java/org/springframework/samples/petclinic/vets/model/VetRepository.java", "snippet": "public interface VetRepository extends JpaRepository<Vet, Integer> {\n}" } ]
import static java.util.Arrays.asList; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.samples.petclinic.vets.aws.S3Service; import org.springframework.samples.petclinic.vets.model.Vet; import org.springframework.samples.petclinic.vets.model.VetRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc;
1,156
/* * Copyright 2002-2021 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 * * 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. * * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package org.springframework.samples.petclinic.vets.web; /** * @author Maciej Szarlinski */ @ExtendWith(SpringExtension.class) @WebMvcTest(VetResource.class) @ActiveProfiles("test") class VetResourceTest { @Autowired MockMvc mvc; @MockBean VetRepository vetRepository; @MockBean S3Service s3Service; @Test void shouldGetAListOfVets() throws Exception {
/* * Copyright 2002-2021 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 * * 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. * * Modifications Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package org.springframework.samples.petclinic.vets.web; /** * @author Maciej Szarlinski */ @ExtendWith(SpringExtension.class) @WebMvcTest(VetResource.class) @ActiveProfiles("test") class VetResourceTest { @Autowired MockMvc mvc; @MockBean VetRepository vetRepository; @MockBean S3Service s3Service; @Test void shouldGetAListOfVets() throws Exception {
Vet vet = new Vet();
1
2023-11-28 22:56:17+00:00
2k
gaojindeng/netty-spring-boot-starter
netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/AbstractNetty.java
[ { "identifier": "BaseChannelHandlerManager", "path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/channel/BaseChannelHandlerManager.java", "snippet": "public abstract class BaseChannelHandlerManager extends ChannelInitializer<Channel> {\n\n private final List<ChannelHandler> sharableHandlers = new ArrayList<>();\n\n private final List<Supplier<ChannelHandler>> noSharableHandlers = new ArrayList<>();\n\n public void add(ChannelHandler channelHandler) {\n sharableHandlers.add(channelHandler);\n }\n\n public void add(Supplier<ChannelHandler> supplier) {\n noSharableHandlers.add(supplier);\n }\n\n @Override\n protected void initChannel(Channel channel) throws Exception {\n ChannelPipeline pipeline = channel.pipeline();\n beforeHandlers().forEach(pipeline::addLast);\n\n // 添加自定义不可共享处理器\n noSharableHandlers.forEach(s -> pipeline.addLast(s.get()));\n\n // 添加自定义可共享处理器\n sharableHandlers.forEach(pipeline::addLast);\n\n afterHandlers().forEach(pipeline::addLast);\n }\n\n abstract List<ChannelHandler> beforeHandlers();\n\n abstract List<ChannelHandler> afterHandlers();\n}" }, { "identifier": "RequestMessageConverter", "path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/convert/RequestMessageConverter.java", "snippet": "public interface RequestMessageConverter<T, K> extends MessageConverter<T, K> {\n}" }, { "identifier": "ResponseMessageConverter", "path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/convert/ResponseMessageConverter.java", "snippet": "public interface ResponseMessageConverter<T, K> extends MessageConverter<T, K> {\n}" }, { "identifier": "AbstractProperties", "path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/properties/AbstractProperties.java", "snippet": "public class AbstractProperties {\n private Integer port;\n private List<LoadClass> sharableHandlers = new ArrayList<>();\n private List<LoadClass> noSharableHandlers = new ArrayList<>();\n private int readerIdleSeconds = 0;\n private int writerIdleSeconds = 0;\n private int allIdleSeconds = 0;\n private int maxConn = 1000;\n /**\n * 对应netty的worker线程数\n */\n private int ioThreads = 0;\n\n public static class LoadClass {\n private String className;\n private List<ParamClass> params;\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public List<ParamClass> getParams() {\n return params;\n }\n\n public void setParams(List<ParamClass> params) {\n this.params = params;\n }\n }\n\n public static class ParamClass {\n private String className;\n private Object value;\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public Object getValue() {\n return value;\n }\n\n public void setValue(Object value) {\n this.value = value;\n }\n }\n\n public Integer getPort() {\n return port;\n }\n\n public void setPort(Integer port) {\n this.port = port;\n }\n\n public List<LoadClass> getSharableHandlers() {\n return sharableHandlers;\n }\n\n public void setSharableHandlers(List<LoadClass> sharableHandlers) {\n this.sharableHandlers = sharableHandlers;\n }\n\n public List<LoadClass> getNoSharableHandlers() {\n return noSharableHandlers;\n }\n\n public void setNoSharableHandlers(List<LoadClass> noSharableHandlers) {\n this.noSharableHandlers = noSharableHandlers;\n }\n\n public int getReaderIdleSeconds() {\n return readerIdleSeconds;\n }\n\n public void setReaderIdleSeconds(int readerIdleSeconds) {\n this.readerIdleSeconds = readerIdleSeconds;\n }\n\n public int getWriterIdleSeconds() {\n return writerIdleSeconds;\n }\n\n public void setWriterIdleSeconds(int writerIdleSeconds) {\n this.writerIdleSeconds = writerIdleSeconds;\n }\n\n public int getAllIdleSeconds() {\n return allIdleSeconds;\n }\n\n public void setAllIdleSeconds(int allIdleSeconds) {\n this.allIdleSeconds = allIdleSeconds;\n }\n\n public int getMaxConn() {\n return maxConn;\n }\n\n public void setMaxConn(int maxConn) {\n this.maxConn = maxConn;\n }\n\n public int getIoThreads() {\n return ioThreads;\n }\n\n public void setIoThreads(int ioThreads) {\n this.ioThreads = ioThreads;\n }\n}" } ]
import io.github.gaojindeng.netty.channel.BaseChannelHandlerManager; import io.github.gaojindeng.netty.convert.RequestMessageConverter; import io.github.gaojindeng.netty.convert.ResponseMessageConverter; import io.github.gaojindeng.netty.properties.AbstractProperties; import io.netty.channel.ChannelHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import java.lang.reflect.Constructor; import java.util.List;
1,360
package io.github.gaojindeng.netty; /** * @author gjd */ public abstract class AbstractNetty { private static final Logger log = LoggerFactory.getLogger(AbstractNetty.class); private String name = "default"; protected int port; protected BaseChannelHandlerManager channelInitializer; protected AbstractProperties nettyProperties; private RequestMessageConverter requestMessageConverter;
package io.github.gaojindeng.netty; /** * @author gjd */ public abstract class AbstractNetty { private static final Logger log = LoggerFactory.getLogger(AbstractNetty.class); private String name = "default"; protected int port; protected BaseChannelHandlerManager channelInitializer; protected AbstractProperties nettyProperties; private RequestMessageConverter requestMessageConverter;
private ResponseMessageConverter responseMessageConverter;
2
2023-12-03 13:11:09+00:00
2k
binance/binance-sbe-java-sample-app
src/main/java/com/binance/sbe/sbesampleapp/RateLimit.java
[ { "identifier": "RateLimitInterval", "path": "src/main/java/spot_sbe/RateLimitInterval.java", "snippet": "@SuppressWarnings(\"all\")\npublic enum RateLimitInterval\n{\n Second((short)0),\n\n Minute((short)1),\n\n Hour((short)2),\n\n Day((short)3),\n\n /**\n * To be used to represent not present or null.\n */\n NULL_VAL((short)255);\n\n private final short value;\n\n RateLimitInterval(final short value)\n {\n this.value = value;\n }\n\n /**\n * The raw encoded value in the Java type representation.\n *\n * @return the raw value encoded.\n */\n public short value()\n {\n return value;\n }\n\n /**\n * Lookup the enum value representing the value.\n *\n * @param value encoded to be looked up.\n * @return the enum value representing the value.\n */\n public static RateLimitInterval get(final short value)\n {\n switch (value)\n {\n case 0: return Second;\n case 1: return Minute;\n case 2: return Hour;\n case 3: return Day;\n case 255: return NULL_VAL;\n }\n\n throw new IllegalArgumentException(\"Unknown value: \" + value);\n }\n}" }, { "identifier": "RateLimitType", "path": "src/main/java/spot_sbe/RateLimitType.java", "snippet": "@SuppressWarnings(\"all\")\npublic enum RateLimitType\n{\n RawRequests((short)0),\n\n RequestWeight((short)2),\n\n Orders((short)3),\n\n /**\n * To be used to represent not present or null.\n */\n NULL_VAL((short)255);\n\n private final short value;\n\n RateLimitType(final short value)\n {\n this.value = value;\n }\n\n /**\n * The raw encoded value in the Java type representation.\n *\n * @return the raw value encoded.\n */\n public short value()\n {\n return value;\n }\n\n /**\n * Lookup the enum value representing the value.\n *\n * @param value encoded to be looked up.\n * @return the enum value representing the value.\n */\n public static RateLimitType get(final short value)\n {\n switch (value)\n {\n case 0: return RawRequests;\n case 2: return RequestWeight;\n case 3: return Orders;\n case 255: return NULL_VAL;\n }\n\n throw new IllegalArgumentException(\"Unknown value: \" + value);\n }\n}" } ]
import spot_sbe.RateLimitInterval; import spot_sbe.RateLimitType;
693
package com.binance.sbe.sbesampleapp; public class RateLimit { public final RateLimitType rateLimitType;
package com.binance.sbe.sbesampleapp; public class RateLimit { public final RateLimitType rateLimitType;
public final RateLimitInterval interval;
0
2023-11-27 09:46:42+00:00
2k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/entity/jurorresponse/AbstractJurorResponse.java
[ { "identifier": "Constants", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/Constants.java", "snippet": "public class Constants {\n\n public static final String PHONE_REGEX = \"^(\\\\+44|0)7\\\\d{9}$\";\n public static final String NOTES_REGEX = \"[A-Za-z0-9]{10,501}\";\n public static final String ADDRESS_LINE_1_REGEX = \"[0-9]{0,9} [A-Z]{5,15} (Road|Lane|Gate|Close|Avenue|Street|Way|Drive|Gardens|Crescent|\"\n + \"Terrace|Place|Hill|Park|View|Court|Square|Walk|Lane|Grove|Gardens|Hill|Hillside|Hilltop|Hollow|\"\n + \"House|Housing|Hurst|Industrial|Ings|Island|Islands|Isle|Isles|Junction|Keep|Kings|Knapp|Knoll|\"\n + \"Knolls|Lair|Lake|Lakes|Landing|Lane|Lanes|Lawn|Lawns|Lea|Leas|Lee|Lees|Line|Link|Little|Lodge|\"\n + \"Loft|Loggia|Long|Lowlands|Main|Manor|Mansion|Manse|Mead|Meadow|Meadows|Meander|Mews|Mill|Mission|\"\n + \"Moor|Moorings|Moorland|Mount|Mountain|Mountains|Mound|Mounts|Neuk|Nook|Orchard|Oval|Overlook|\"\n + \"Park|Parklands|Parkway|Parade|Paradise|Parc|Parks|Part|Passage|Path|Pathway|Pike|Pines|Place|\"\n + \"Plain|Plains|Plaza|Point|Points|Port|Ports|Prairie|Quadrant|Quay|Quays|Ramble|Ramp|Ranch|Rapids|\"\n + \"Reach|Reserve|Rest|Retreat|Ridge|Ridges|Rise|River|Rivers|Road|Roads|Route|Row|Rue|Run|Shoal|\"\n + \"Shoals|Shore|Shores|Skyline|Slope|Slopes|Spur|Square|Squares|Stairs|Stead|Strand|Stream|Street|\"\n + \"Streets|Summit|Terrace|Throughway|Trace|Track|Trafficway|Trail|Trailer|Tunnel|Turnpike|Underpass|\"\n + \"Union|Unions|Valley|Valleys|Viaduct|View|Views|Village|Villages|Ville|Vista|Walk|Wall|Way|Ways|\";\n public static final String ADDRESS_LINE_2_REGEX = \"(Apartment|Suite|Room|Floor|Box) Number [0-9]{1,3}\";\n\n public static final Map<PoolRequestGeneratorUtil.CourtType, Integer> POOL_REQUEST_WEIGHT_MAP;\n\n static {\n POOL_REQUEST_WEIGHT_MAP = Map.of(\n PoolRequestGeneratorUtil.CourtType.CIVIL, 145,\n PoolRequestGeneratorUtil.CourtType.CRIMINAL, 4,\n PoolRequestGeneratorUtil.CourtType.CROWN, 62_156,\n PoolRequestGeneratorUtil.CourtType.HIGH, 15,\n PoolRequestGeneratorUtil.CourtType.CORONER, 1\n );\n }\n}" }, { "identifier": "ProcessingStatus", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/ProcessingStatus.java", "snippet": "@Getter\npublic enum ProcessingStatus {\n TODO(\"To Do\"),\n\n AWAITING_CONTACT(\"Awaiting Juror\"),\n AWAITING_COURT_REPLY(\"Awaiting Court\"),\n AWAITING_TRANSLATION(\"Awaiting Translation\"),\n\n @Deprecated\n REFERRED_TO_TEAM_LEADER(\"Referred to Team Leader\"), // no longer used in code, but may be in db\n\n CLOSED(\"Closed\");\n\n private final String description;\n\n ProcessingStatus(String description) {\n this.description = description;\n }\n\n}" } ]
import jakarta.persistence.Column; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; import uk.gov.hmcts.juror.support.generation.generators.code.GenerateGenerationConfig; import uk.gov.hmcts.juror.support.generation.generators.value.DateFilter; import uk.gov.hmcts.juror.support.generation.generators.value.EmailGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.FirstNameGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.FixedValueGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.LastNameGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.LocalDateGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.NullValueGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromFileGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.RegexGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.SequenceGenerator; import uk.gov.hmcts.juror.support.generation.generators.value.StringSequenceGenerator; import uk.gov.hmcts.juror.support.sql.Constants; import uk.gov.hmcts.juror.support.sql.entity.ProcessingStatus; import java.io.Serializable; import java.time.LocalDate; import java.time.temporal.ChronoUnit;
1,574
package uk.gov.hmcts.juror.support.sql.entity.jurorresponse; @MappedSuperclass @Table(name = "juror_response", schema = "juror_mod") @Getter @Setter @GenerateGenerationConfig public abstract class AbstractJurorResponse extends Address implements Serializable { @Id @Column(name = "juror_number") @StringSequenceGenerator(format = "%09d", sequenceGenerator = @SequenceGenerator(id = "juror_number", start = 1) ) private String jurorNumber; @Column(name = "date_received") @LocalDateGenerator( minInclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 100, unit = ChronoUnit.DAYS), maxExclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 0, unit = ChronoUnit.DAYS) ) private LocalDate dateReceived; @Column(name = "title") @RandomFromFileGenerator(file = "data/titles.txt") private String title; @Column(name = "first_name") @FirstNameGenerator private String firstName; @Column(name = "last_name") @LastNameGenerator private String lastName; @Column(name = "processing_status") @Enumerated(EnumType.STRING) @FixedValueGenerator("uk.gov.hmcts.juror.support.sql.entity.ProcessingStatus.TODO")
package uk.gov.hmcts.juror.support.sql.entity.jurorresponse; @MappedSuperclass @Table(name = "juror_response", schema = "juror_mod") @Getter @Setter @GenerateGenerationConfig public abstract class AbstractJurorResponse extends Address implements Serializable { @Id @Column(name = "juror_number") @StringSequenceGenerator(format = "%09d", sequenceGenerator = @SequenceGenerator(id = "juror_number", start = 1) ) private String jurorNumber; @Column(name = "date_received") @LocalDateGenerator( minInclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 100, unit = ChronoUnit.DAYS), maxExclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 0, unit = ChronoUnit.DAYS) ) private LocalDate dateReceived; @Column(name = "title") @RandomFromFileGenerator(file = "data/titles.txt") private String title; @Column(name = "first_name") @FirstNameGenerator private String firstName; @Column(name = "last_name") @LastNameGenerator private String lastName; @Column(name = "processing_status") @Enumerated(EnumType.STRING) @FixedValueGenerator("uk.gov.hmcts.juror.support.sql.entity.ProcessingStatus.TODO")
private ProcessingStatus processingStatus = ProcessingStatus.TODO;
1
2023-12-01 11:38:42+00:00
2k
vvbbnn00/JavaWeb-CanteenSystem
JavaBackend/src/main/java/cn/vvbbnn00/canteen/filter/role_check/RoleCheckRestfulFilter.java
[ { "identifier": "User", "path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/model/User.java", "snippet": "@Data\n@JavaBean\npublic class User implements Serializable {\n private Integer userId;\n\n @Pattern(regexp = \"^[a-zA-Z0-9_]{4,16}$\", message = \"用户名只能包含字母、数字和下划线,长度为4-16位\")\n private String username;\n\n // 此处的密码是加密后的密码\n @Pattern(regexp = \"^\\\\S{6,16}$\", message = \"密码不能包含空格,长度为6-16位\")\n private String password;\n private String name;\n private String employeeId;\n @Min(value = 0, message = \"level不能小于0\")\n @Max(value = 20, message = \"level不能大于20\")\n private Integer level;\n @Min(value = 0, message = \"point不能小于0\")\n private Long point;\n private Boolean available;\n\n @Enumerated(EnumType.STRING)\n private Role role;\n private Boolean isVerified;\n\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime createdAt;\n\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime updatedAt;\n\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime lastLoginAt;\n\n @Email(message = \"邮箱格式不正确\")\n private String email;\n\n public String getAvatar() {\n return StringUtils.getAvatarUrl(this.email);\n }\n\n public enum Role {\n user, canteen_admin, admin\n }\n}" }, { "identifier": "GsonFactory", "path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/util/GsonFactory.java", "snippet": "public class GsonFactory {\n /**\n * 获取Gson对象,该对象已经注册了必要的适配器\n *\n * @return Gson对象\n */\n public static Gson getGson() {\n return new GsonBuilder()\n .setPrettyPrinting()\n .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())\n .create();\n }\n\n\n /**\n * 将对象转换为 JSON 格式。\n *\n * @param obj 需要被转换为 JSON 的对象。\n * @return 对象的 JSON 字符串表示形式。\n */\n public static String toJson(Object obj) {\n return getGson().toJson(obj);\n }\n\n /**\n * 生成错误响应\n *\n * @param response HttpServletResponse对象\n * @param code 响应码\n * @param message 响应信息\n */\n public static void makeErrorResponse(HttpServletResponse response, int code, String message) throws IOException {\n response.setStatus(code);\n response.setContentType(\"application/json;charset=utf-8\");\n response.getWriter().println(GsonFactory.getGson().toJson(new BasicResponse(code, message)));\n }\n\n /**\n * 生成成功响应\n *\n * @param response HttpServletResponse对象\n * @param message 响应信息\n */\n public static void makeSuccessResponse(HttpServletResponse response, String message) throws IOException {\n makeErrorResponse(response, 200, message);\n }\n\n /**\n * 生成错误响应\n *\n * @param code 响应码\n * @param message 响应信息\n * @return 响应字符串\n */\n public static Response generateErrorResponse(int code, String message) {\n Response.ResponseBuilder builder = Response.status(code);\n builder.entity(GsonFactory.getGson().toJson(new BasicResponse(code, message)));\n return builder.build();\n }\n\n /**\n * 生成成功响应\n *\n * @param message 响应信息\n * @return 响应字符串\n */\n public static Response generateSuccessResponse(String message) {\n return generateErrorResponse(200, message);\n }\n}" } ]
import cn.vvbbnn00.canteen.annotation.CheckRole; import cn.vvbbnn00.canteen.model.User; import cn.vvbbnn00.canteen.util.GsonFactory; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.Context; import java.lang.reflect.Method;
1,242
package cn.vvbbnn00.canteen.filter.role_check; public class RoleCheckRestfulFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Context private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) { HttpSession session = request.getSession(); // 获取资源类和方法 Method method = resourceInfo.getResourceMethod(); // 检查是否存在 CheckPermission 注解 if (method.isAnnotationPresent(CheckRole.class)) { CheckRole permission = method.getAnnotation(CheckRole.class); String requiredRole = permission.value(); User user = (User) session.getAttribute("user"); switch (RoleCheckFilter.checkRole(user, requiredRole)) { case -1:
package cn.vvbbnn00.canteen.filter.role_check; public class RoleCheckRestfulFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Context private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) { HttpSession session = request.getSession(); // 获取资源类和方法 Method method = resourceInfo.getResourceMethod(); // 检查是否存在 CheckPermission 注解 if (method.isAnnotationPresent(CheckRole.class)) { CheckRole permission = method.getAnnotation(CheckRole.class); String requiredRole = permission.value(); User user = (User) session.getAttribute("user"); switch (RoleCheckFilter.checkRole(user, requiredRole)) { case -1:
requestContext.abortWith(GsonFactory.generateErrorResponse(401, "Unauthorized"));
1
2023-12-01 04:55:12+00:00
2k
JamJestJerzy/AoTT
src/main/java/dev/j3rzy/aott/Aott.java
[ { "identifier": "Scheduled", "path": "src/main/java/dev/j3rzy/aott/events/Scheduled.java", "snippet": "public class Scheduled {\n BukkitScheduler scheduler = Bukkit.getServer().getScheduler();\n\n /**\n * Excecuted once every 2 seconds\n */\n public static void onceEveryTwoSeconds() {\n new java.util.Timer().schedule(new java.util.TimerTask(){@Override public void run(){\n onceEveryTwoSeconds();\n }},2000);\n\n /* Regen mana and health */\n for (Player player : Players.INSTANCE.getPlayers()) {\n player.heal((player.getMaxHealth() * 0.01) + 1.5);\n player.regenMana(player.getMaxMana() * 0.02);\n }\n /* Regen mana and health */\n }\n\n /**\n * Executed once every second\n */\n public static void onceASecond() {\n new java.util.Timer().schedule(new java.util.TimerTask(){@Override public void run(){\n onceASecond();\n }},1000);\n }\n\n /**\n * Executed once 1/4th of a second\n */\n public static void onceOneForthOfASecond() {\n new java.util.Timer().schedule(new java.util.TimerTask() {\n @Override\n public void run() {\n onceOneForthOfASecond();\n }\n }, 250);\n\n /* Display stats above hotbar */\n for (Player player : Players.INSTANCE.getPlayers()) {\n PlayerUtils.updateActionBarStats(player); // Shows stats above hotbar\n player.getPlayer().setFoodLevel(20);\n }\n /* Display stats above hotbar */\n\n for (Player player : Players.INSTANCE.getPlayers()) {\n org.bukkit.entity.Player bukkitPlayer = player.getPlayer();\n bukkitPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(player.getMaxHealth()/5);\n }\n }\n\n /**\n * Executed once per gameTick\n */\n int taskId = scheduler.scheduleSyncRepeatingTask(plugin, () -> {\n\n }, 0L, 1L);\n}" }, { "identifier": "log", "path": "src/main/java/dev/j3rzy/aott/utils/Utils.java", "snippet": "public static Logger log = Logger.getLogger(\"AOTT\");" }, { "identifier": "pm", "path": "src/main/java/dev/j3rzy/aott/utils/Utils.java", "snippet": "public static PluginManager pm = plugin.getServer().getPluginManager();" } ]
import static dev.j3rzy.aott.events.Scheduled.*; import static dev.j3rzy.aott.utils.Utils.log; import static dev.j3rzy.aott.utils.Utils.pm; import dev.j3rzy.aott.commands.*; import dev.j3rzy.aott.events.*; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scoreboard.*; import java.util.Objects;
849
package dev.j3rzy.aott; public final class Aott extends JavaPlugin { @Override public void onEnable() { /* Register events */ pm.registerEvents(new PlayerInteract(), this); pm.registerEvents(new PlayerJoin(), this); pm.registerEvents(new EntityDamageByEntity(), this); pm.registerEvents(new EntityDamage(), this); pm.registerEvents(new EntityDamageByBlock(), this); pm.registerEvents(new PlayerRespawn(), this); /* Register commands */ Objects.requireNonNull(this.getCommand("aote")).setExecutor(new aote()); Objects.requireNonNull(this.getCommand("hyperion")).setExecutor(new hyperion()); Objects.requireNonNull(this.getCommand("stick")).setExecutor(new stick()); Objects.requireNonNull(this.getCommand("fish")).setExecutor(new fish()); Objects.requireNonNull(this.getCommand("gigarion")).setExecutor(new gigarion()); onceEveryTwoSeconds(); onceASecond(); onceOneForthOfASecond();
package dev.j3rzy.aott; public final class Aott extends JavaPlugin { @Override public void onEnable() { /* Register events */ pm.registerEvents(new PlayerInteract(), this); pm.registerEvents(new PlayerJoin(), this); pm.registerEvents(new EntityDamageByEntity(), this); pm.registerEvents(new EntityDamage(), this); pm.registerEvents(new EntityDamageByBlock(), this); pm.registerEvents(new PlayerRespawn(), this); /* Register commands */ Objects.requireNonNull(this.getCommand("aote")).setExecutor(new aote()); Objects.requireNonNull(this.getCommand("hyperion")).setExecutor(new hyperion()); Objects.requireNonNull(this.getCommand("stick")).setExecutor(new stick()); Objects.requireNonNull(this.getCommand("fish")).setExecutor(new fish()); Objects.requireNonNull(this.getCommand("gigarion")).setExecutor(new gigarion()); onceEveryTwoSeconds(); onceASecond(); onceOneForthOfASecond();
log.info("Plugin got enabled!");
1
2023-11-28 21:20:59+00:00
2k
SuperMagicican/elegent-idem
elegent-idem-core/src/main/java/cn/elegent/idem/core/aspect/ElegentIdemAspect.java
[ { "identifier": "Checker", "path": "elegent-idem-core/src/main/java/cn/elegent/idem/core/Checker.java", "snippet": "public interface Checker {\n\n\n /**\n * 检查方法\n * @param uniqueID\n * @return\n */\n boolean check(String uniqueID);\n\n /**\n * 执行成功后要做的事情\n * @param uniqueID\n * @return\n */\n void afterSuccess(String uniqueID);\n\n}" }, { "identifier": "CheckerLoader", "path": "elegent-idem-core/src/main/java/cn/elegent/idem/core/CheckerLoader.java", "snippet": "@Component\npublic class CheckerLoader implements ApplicationContextAware {\n\n private static Map<String, Checker> elegentCheckerMap = new HashMap<>();\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n\n //加载所有检查器\n Collection<Checker> checkers = applicationContext.getBeansOfType(Checker.class).values();\n checkers.stream().forEach(checker->{\n //通过反射拿到类上的平台注解\n CheckerName annotation = checker.getClass().getAnnotation(CheckerName.class);\n if (annotation != null) {\n elegentCheckerMap.put(annotation.value(), checker);\n }\n });\n\n }\n\n\n /**\n * 查询检查器\n * @param name 名称\n * @return\n */\n public static Checker getChecker(String name){\n Checker checker = elegentCheckerMap.get(name);\n if(checker!=null){\n return checker;\n }else{\n throw new RuntimeException(\"未找到\"+ name+\"检查器\");\n }\n }\n\n\n}" }, { "identifier": "ExceptionManager", "path": "elegent-idem-core/src/main/java/cn/elegent/idem/core/ExceptionManager.java", "snippet": "public interface ExceptionManager {\n\n\n /**\n * 当出现重复请求的时候的异常处理\n */\n void errorHandler();\n\n}" }, { "identifier": "UniqueID", "path": "elegent-idem-core/src/main/java/cn/elegent/idem/core/UniqueID.java", "snippet": "public interface UniqueID {\n\n /**\n * 获取唯一id的方法\n * @return\n */\n String getUniqueID(String name);\n}" } ]
import cn.elegent.idem.annotation.ElegentIdem; import cn.elegent.idem.core.Checker; import cn.elegent.idem.core.CheckerLoader; import cn.elegent.idem.core.ExceptionManager; import cn.elegent.idem.core.UniqueID; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
1,036
package cn.elegent.idem.core.aspect; /** * InterfaceIdempotenceTableAspect * @description 接口幂等表的方式实现接口幂等性 * @author WGL * @date 2022/11/11 20:33 */ @Aspect @Component @Slf4j public class ElegentIdemAspect { @Autowired private ExceptionManager exceptionManager; @Autowired private UniqueID uniqueID; //唯一标识获取器 /** * 织入点 */ // @Pointcut("@annotation(cn.elegent.idem.annotation.ElegentIdem)") // public void elegentIdem() { // } /** * 接口幂等性操作流程 * 1)首先判断每个请求id是否存在 * 2)如果不存在直接存入redis -> key:requestid value:PROC * 3) 如果存在则判断状态是否存在如果存在 则拒绝 * 4)业务逻辑执行完 删除对应的requestId */ @Around("@annotation(elegentIdem)") public Object methodBefore(ProceedingJoinPoint point , ElegentIdem elegentIdem) { //请求id由接口获取,目的是提高拓展性 String uniqueID = this.uniqueID.getUniqueID(elegentIdem.name()); log.info("elegent-iu 框架 uniqueID:{}",uniqueID); Object proceed = null;
package cn.elegent.idem.core.aspect; /** * InterfaceIdempotenceTableAspect * @description 接口幂等表的方式实现接口幂等性 * @author WGL * @date 2022/11/11 20:33 */ @Aspect @Component @Slf4j public class ElegentIdemAspect { @Autowired private ExceptionManager exceptionManager; @Autowired private UniqueID uniqueID; //唯一标识获取器 /** * 织入点 */ // @Pointcut("@annotation(cn.elegent.idem.annotation.ElegentIdem)") // public void elegentIdem() { // } /** * 接口幂等性操作流程 * 1)首先判断每个请求id是否存在 * 2)如果不存在直接存入redis -> key:requestid value:PROC * 3) 如果存在则判断状态是否存在如果存在 则拒绝 * 4)业务逻辑执行完 删除对应的requestId */ @Around("@annotation(elegentIdem)") public Object methodBefore(ProceedingJoinPoint point , ElegentIdem elegentIdem) { //请求id由接口获取,目的是提高拓展性 String uniqueID = this.uniqueID.getUniqueID(elegentIdem.name()); log.info("elegent-iu 框架 uniqueID:{}",uniqueID); Object proceed = null;
Checker checker = CheckerLoader.getChecker(elegentIdem.type()); //根据类型匹配检查器
1
2023-12-02 12:24:38+00:00
2k
aosolorzano/city-tasks-aws-fullstack
apis/city-events-function/src/main/java/com/hiperium/city/events/function/functions/CreateEventFunction.java
[ { "identifier": "EventBridgeCustomEvent", "path": "apis/city-events-function/src/main/java/com/hiperium/city/events/function/models/EventBridgeCustomEvent.java", "snippet": "@Data\npublic class EventBridgeCustomEvent {\n\n @NotEmpty\n private String version;\n\n @NotEmpty\n private String id;\n\n @NotEmpty\n @ToString.Exclude\n private String account;\n\n @NotEmpty\n private String source;\n\n @NotEmpty\n private String region;\n\n @NotNull\n private Instant time;\n\n private List<String> resources;\n\n @JsonProperty(\"detail-type\")\n private String detailType;\n\n @NotNull\n private TaskEventDetail detail;\n}" }, { "identifier": "EventsResponse", "path": "apis/city-events-function/src/main/java/com/hiperium/city/events/function/models/EventsResponse.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class EventsResponse {\n\n private int statusCode;\n private Map<String, String> headers;\n private String body;\n}" }, { "identifier": "EventService", "path": "apis/city-events-function/src/main/java/com/hiperium/city/events/function/services/EventService.java", "snippet": "@Service\npublic class EventService {\n\n private final DynamoDbClient dynamoDbClient;\n\n @Setter(onMethod_ = @Autowired)\n private EventMapper eventMapper;\n\n @Value(\"${\" + PropertiesUtil.TIME_ZONE_ID_PROPERTY + \"}\")\n private String zoneId;\n\n public EventService(DynamoDbClient dynamoDbClient) {\n this.dynamoDbClient = dynamoDbClient;\n }\n\n public void createEvent(EventBridgeCustomEvent eventBridgeCustomEvent) {\n BeansValidationUtil.validateBean(eventBridgeCustomEvent.getDetail());\n\n Event event = this.eventMapper.fromCustomEvent(eventBridgeCustomEvent, this.zoneId);\n var putItemRequest = PutItemRequest.builder()\n .item(\n Map.of(Event.ID_FIELD, AttributeValue.fromS(UUID.randomUUID().toString()),\n Event.DEVICE_ID_FIELD, AttributeValue.fromS(eventBridgeCustomEvent.getDetail().getDeviceId()),\n Event.TASK_ID_FIELD, AttributeValue.fromN(eventBridgeCustomEvent.getDetail().getTaskId().toString()),\n Event.OPERATION_FIELD, AttributeValue.fromS(eventBridgeCustomEvent.getDetail().getDeviceOperation().name()),\n Event.EXECUTION_DATE_FIELD, AttributeValue.fromS(event.getExecutionDate()),\n Event.EXECUTION_INSTANT_FIELD, AttributeValue.fromN(event.getExecutionInstant().toString())\n )\n )\n .tableName(Event.TABLE_NAME)\n .build();\n this.dynamoDbClient.putItem(putItemRequest);\n }\n}" }, { "identifier": "BeansValidationUtil", "path": "apis/city-events-function/src/main/java/com/hiperium/city/events/function/utils/BeansValidationUtil.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class BeansValidationUtil {\n\n public static void validateBean(EventBridgeCustomEvent customEvent) {\n try (ValidatorFactory factory = buildDefaultValidatorFactory()) {\n Validator validator = factory.getValidator();\n Set<ConstraintViolation<EventBridgeCustomEvent>> violations = validator.validate(customEvent);\n if (!violations.isEmpty()) {\n violations.stream()\n .findFirst()\n .ifPresent(BeansValidationUtil::throwValidationTaskDtoException);\n }\n }\n }\n\n public static void validateBean(TaskEventDetail taskEventDetail) {\n try (ValidatorFactory factory = buildDefaultValidatorFactory()) {\n Validator validator = factory.getValidator();\n Set<ConstraintViolation<TaskEventDetail>> violations = validator.validate(taskEventDetail);\n if (!violations.isEmpty()) {\n violations.stream()\n .findFirst()\n .ifPresent(BeansValidationUtil::throwValidationTaskCriteriaDtoException);\n }\n }\n }\n\n private static void throwValidationTaskDtoException(ConstraintViolation<EventBridgeCustomEvent> constraintViolation) {\n throw new ValidationException(constraintViolation.getMessage());\n }\n\n private static void throwValidationTaskCriteriaDtoException(ConstraintViolation<TaskEventDetail> constraintViolation) {\n throw new ValidationException(constraintViolation.getMessage());\n }\n}" }, { "identifier": "FunctionsUtil", "path": "apis/city-events-function/src/main/java/com/hiperium/city/events/function/utils/FunctionsUtil.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class FunctionsUtil {\n\n private static final Map<String, String> HEADERS = new HashMap<>();\n\n static {\n HEADERS.put(\"Content-Type\", \"application/json\");\n HEADERS.put(\"X-Custom-Header\", \"application/json\");\n }\n\n private static final ObjectMapper MAPPER = new ObjectMapper()\n .findAndRegisterModules()\n .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);\n\n public static <T> T unmarshal(byte[] jsonBytes, Class<T> type) {\n try {\n return MAPPER.readValue(jsonBytes, type);\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Error unmarshalling the <\" + type.getSimpleName() + \"> object: \"\n + e.getMessage());\n }\n }\n\n public static EventsResponse getSuccessResponse() {\n return EventsResponse.builder()\n .statusCode(201)\n .headers(HEADERS)\n .body(\"{}\")\n .build();\n }\n}" } ]
import com.hiperium.city.events.function.models.EventBridgeCustomEvent; import com.hiperium.city.events.function.models.EventsResponse; import com.hiperium.city.events.function.services.EventService; import com.hiperium.city.events.function.utils.BeansValidationUtil; import com.hiperium.city.events.function.utils.FunctionsUtil; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.util.function.Function;
1,409
package com.hiperium.city.events.function.functions; @Slf4j @Component public class CreateEventFunction implements Function<EventBridgeCustomEvent, EventsResponse> { private final EventService eventService; public CreateEventFunction(EventService eventService) { this.eventService = eventService; } @Override public EventsResponse apply(EventBridgeCustomEvent event) { log.debug("handleRequest(): {}", event);
package com.hiperium.city.events.function.functions; @Slf4j @Component public class CreateEventFunction implements Function<EventBridgeCustomEvent, EventsResponse> { private final EventService eventService; public CreateEventFunction(EventService eventService) { this.eventService = eventService; } @Override public EventsResponse apply(EventBridgeCustomEvent event) { log.debug("handleRequest(): {}", event);
BeansValidationUtil.validateBean(event);
3
2023-11-28 16:35:22+00:00
2k
christophermontero/fluxifyuserverse
infrastructure/driven-adapters/redis/src/main/java/co/com/giocom/redis/template/RedisReactiveAdapter.java
[ { "identifier": "User", "path": "domain/model/src/main/java/co/com/giocom/model/user/User.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder(toBuilder = true)\npublic class User {\n \n Long id;\n String firstName;\n String lastName;\n String email;\n String avatar;\n}" }, { "identifier": "UserCacheGateway", "path": "domain/model/src/main/java/co/com/giocom/model/user/gateways/UserCacheGateway.java", "snippet": "public interface UserCacheGateway {\r\n\r\n Mono<User> getById(Long id);\r\n\r\n Mono<User> save(User user);\r\n}\r" }, { "identifier": "ReactiveTemplateAdapterOperations", "path": "infrastructure/driven-adapters/redis/src/main/java/co/com/giocom/redis/template/helper/ReactiveTemplateAdapterOperations.java", "snippet": "public abstract class ReactiveTemplateAdapterOperations<E, K, V> {\n private final ReactiveRedisTemplate<K, V> template;\n private final Class<V> dataClass;\n private final Function<V, E> toEntityFn;\n protected ObjectMapper mapper;\n\n @SuppressWarnings(\"unchecked\")\n protected ReactiveTemplateAdapterOperations(\n ReactiveRedisConnectionFactory connectionFactory,\n ObjectMapper mapper, Function<V, E> toEntityFn) {\n this.mapper = mapper;\n ParameterizedType genericSuperclass = (ParameterizedType) this.getClass()\n .getGenericSuperclass();\n this.dataClass = (Class<V>) genericSuperclass.getActualTypeArguments()[2];\n this.toEntityFn = toEntityFn;\n\n RedisSerializationContext<K, V> serializationContext = RedisSerializationContext.<K, V> newSerializationContext(\n new Jackson2JsonRedisSerializer<>(dataClass)).build();\n\n template = new ReactiveRedisTemplate<>(connectionFactory,\n serializationContext);\n }\n\n public Mono<E> save(K key, E entity) {\n return Mono.just(entity).map(this::toValue)\n .flatMap(value -> template.opsForValue().set(key, value))\n .thenReturn(entity);\n }\n\n public Mono<E> save(K key, E entity, long expirationMillis) {\n return save(key, entity).flatMap(\n v -> template.expire(key, Duration.ofMillis(expirationMillis))\n .thenReturn(v));\n }\n\n public Mono<E> findById(K key) {\n return template.opsForValue().get(key).map(this::toEntity);\n }\n\n protected V toValue(E entity) {\n return mapper.map(entity, dataClass);\n }\n\n protected E toEntity(V data) {\n return data != null ? toEntityFn.apply(data) : null;\n }\n\n}" }, { "identifier": "UserCacheDAO", "path": "infrastructure/driven-adapters/redis/src/main/java/co/com/giocom/redis/template/model/UserCacheDAO.java", "snippet": "@Data\r\n@AllArgsConstructor\r\n@NoArgsConstructor\r\n@Builder(toBuilder = true)\r\npublic class UserCacheDAO {\r\n\r\n Long id;\r\n String firstName;\r\n String lastName;\r\n String email;\r\n String avatar;\r\n}\r" } ]
import co.com.giocom.model.user.User; import co.com.giocom.model.user.gateways.UserCacheGateway; import co.com.giocom.redis.template.helper.ReactiveTemplateAdapterOperations; import co.com.giocom.redis.template.model.UserCacheDAO; import lombok.extern.slf4j.Slf4j; import org.reactivecommons.utils.ObjectMapper; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import java.util.Map;
813
package co.com.giocom.redis.template; @Slf4j @Component public class RedisReactiveAdapter
package co.com.giocom.redis.template; @Slf4j @Component public class RedisReactiveAdapter
extends ReactiveTemplateAdapterOperations<User, String, UserCacheDAO>
3
2023-12-03 01:00:15+00:00
2k
RabbitHareLu/K-Tools
warehouse/src/main/java/com/ktools/warehouse/manager/uid/IdGenerator.java
[ { "identifier": "MybatisContext", "path": "warehouse/src/main/java/com/ktools/warehouse/mybatis/MybatisContext.java", "snippet": "@Slf4j\npublic class MybatisContext {\n\n private final MybatisFlexBootstrap bootstrap;\n\n public MybatisContext(DataSource dataSource) {\n FlexGlobalConfig.getDefaultConfig().setPrintBanner(false);\n this.bootstrap = MybatisFlexBootstrap.getInstance()\n .addDataSource(SysDataSource.DATASOURCE_NAME, dataSource)\n .addMapper(PropMapper.class)\n .addMapper(TreeMapper.class)\n .start();\n\n // 修改impala方言\n DialectFactory.registerDialect(DbType.IMPALA, new CommonsDialectImpl(KeywordWrap.BACK_QUOTE, LimitOffsetProcessor.POSTGRESQL));\n }\n\n public <T> T getMapper(Class<T> tClass) {\n return bootstrap.getMapper(tClass);\n }\n\n public Properties loadAllProperties() {\n List<PropEntity> propEntities = this.getMapper(PropMapper.class).selectAll();\n Properties properties = new Properties();\n propEntities.forEach(prop -> properties.put(prop.getKey(), prop.getValue()));\n return properties;\n }\n\n public void addDataSource(String key, DataSource dataSource) {\n FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();\n flexDataSource.addDataSource(key, dataSource);\n }\n\n public void removeDataSource(String key) {\n FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();\n HikariDataSource dataSource = (HikariDataSource) flexDataSource.getDataSourceMap().get(key);\n dataSource.close();\n flexDataSource.removeDatasource(key);\n }\n\n public boolean existDataSource(String key) {\n FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();\n return flexDataSource.getDataSourceMap().containsKey(key);\n }\n\n public DataSource getDataSource(String key) throws KToolException {\n FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();\n if (!flexDataSource.getDataSourceMap().containsKey(key)) {\n throw new KToolException(\"数据源不存在!\");\n }\n return flexDataSource.getDataSourceMap().get(key);\n }\n\n public void showdown() {\n FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();\n ArrayList<String> keys = new ArrayList<>(flexDataSource.getDataSourceMap().keySet());\n keys.forEach(key -> {\n HikariDataSource dataSource = (HikariDataSource) flexDataSource.getDataSourceMap().get(key);\n dataSource.close();\n flexDataSource.removeDatasource(key);\n });\n }\n}" }, { "identifier": "PropEntity", "path": "warehouse/src/main/java/com/ktools/warehouse/mybatis/entity/PropEntity.java", "snippet": "@Data\n@Table(value = \"PROP\", dataSource = SysDataSource.DATASOURCE_NAME)\npublic class PropEntity {\n\n @Id(\"ID\")\n private Integer id;\n\n @Column(\"KEY\")\n private String key;\n\n @Column(\"VALUE\")\n private String value;\n\n}" }, { "identifier": "PropMapper", "path": "warehouse/src/main/java/com/ktools/warehouse/mybatis/mapper/PropMapper.java", "snippet": "public interface PropMapper extends BaseMapper<PropEntity> {\n\n}" } ]
import com.ktools.warehouse.mybatis.MybatisContext; import com.ktools.warehouse.mybatis.entity.PropEntity; import com.ktools.warehouse.mybatis.mapper.PropMapper; import com.mybatisflex.core.query.QueryChain; import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.update.UpdateChain; import java.util.ArrayList; import java.util.List;
867
package com.ktools.warehouse.manager.uid; /** * ID生成器 * * @author WCG */ public class IdGenerator { private static final String ID_PROP_PRE = "K_TOOLS.ID.K_";
package com.ktools.warehouse.manager.uid; /** * ID生成器 * * @author WCG */ public class IdGenerator { private static final String ID_PROP_PRE = "K_TOOLS.ID.K_";
private final PropMapper propMapper;
2
2023-11-30 03:26:25+00:00
2k
ChrisGenti/VPL
velocity/src/main/java/com/github/chrisgenti/vpl/velocity/listeners/disconnect/DisconnectListener.java
[ { "identifier": "VPLPlugin", "path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/VPLPlugin.java", "snippet": "@Plugin(\n id = \"vpl\",\n name = \"VPL\",\n version = \"1.0.0\",\n description = \"\",\n authors = {\"ChrisGenti\"}\n) @Getter\npublic class VPLPlugin {\n public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create(\"vpl\", \"main\");\n public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier(\"vpl:main\");\n\n @Inject private ProxyServer proxy;\n @Inject private Logger logger;\n @Inject private EventManager eventManager;\n @Inject @DataDirectory Path directory;\n\n private ConfigFile configFile;\n private LanguageFile languageFile;\n\n private PlayerManager playerManager;\n private ServerManager serverManager;\n private DataProvider provider;\n\n private PluginTask registerTask;\n\n @Subscribe\n public void onInitialization(ProxyInitializeEvent event) {\n /*\n * FILES\n */\n this.configFile = new ConfigFile(directory.toFile(), \"config.toml\");\n this.languageFile = new LanguageFile(new File(directory.toFile(), \"lang\"), configFile.LANGUAGE);\n\n /*\n * SETUP MESSAGE\n */\n this.sendMessage(\n \"<reset>\", \"<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>\"\n );\n\n /*\n * MANAGERS\n */\n this.playerManager = new PlayerManager();\n this.serverManager = new ServerManager(this);\n\n /*\n * PROVIDERS\n */\n this.provider = new MySQLProvider(this, configFile.CREDENTIALS);\n this.provider.init();\n\n /*\n * COMMANDS\n */\n this.registerCommands(\n new VPLCommand(this), new PremiumCommand(this)\n );\n\n /*\n * LISTENERS\n */\n this.registerListeners(\n new PluginMessageListener(this),\n new ChatListener(this), new CommandListener(this), new TabCompleteListener(this),\n new PreLoginListener(this), new ProfileRequestListener(this), new InitialServerListener(this), new PostLoginListener(this), new DisconnectListener(this)\n );\n\n /*\n * TASKS\n */\n this.registerTask = new RegisterTask(this);\n this.registerTask.run();\n\n /*\n * CHANNELS\n */\n this.registerPluginChannels();\n }\n\n @Subscribe\n public void onShutdown(ProxyShutdownEvent event) {\n /*\n * TASKS\n */\n this.registerTask.stop();\n\n /*\n * CHANNELS\n */\n this.unregisterPluginChannels();\n }\n\n public void debug(String message) {\n if (configFile.DEBUG)\n logger.info(\"[DEBUG] {}\", message);\n }\n\n public void sendMessage(CommandSource source, String message) {\n if (!message.isEmpty())\n source.sendMessage(MiniMessage.miniMessage().deserialize(message));\n }\n\n public void sendMessage(String... messages) {\n CommandSource source = proxy.getConsoleCommandSource();\n Arrays.stream(messages).forEach(message -> this.sendMessage(source, message));\n }\n\n private void registerCommands(PluginCommand... commands) {\n CommandManager manager = proxy.getCommandManager();\n\n Arrays.stream(commands).forEach(command -> {\n CommandMeta commandMeta = manager.metaBuilder(command.name())\n .plugin(this)\n .build();\n manager.register(commandMeta, command);\n });\n }\n\n private void registerListeners(Listener<?>... listeners) {\n Arrays.stream(listeners).forEach(Listener::register);\n }\n\n private void registerPluginChannels() {\n this.proxy.getChannelRegistrar().register(MODERN_CHANNEL, LEGACY_CHANNEL);\n }\n\n private void unregisterPluginChannels() {\n this.proxy.getChannelRegistrar().unregister(MODERN_CHANNEL, LEGACY_CHANNEL);\n }\n}" }, { "identifier": "Listener", "path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/listeners/Listener.java", "snippet": "public interface Listener<E> extends AwaitingEventExecutor<E> {\n void register();\n}" }, { "identifier": "PlayerManager", "path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/players/PlayerManager.java", "snippet": "@Getter\npublic class PlayerManager {\n private final Set<UUID> loggedPlayers = ConcurrentHashMap.newKeySet();\n private final Set<UUID> premiumPlayers = ConcurrentHashMap.newKeySet();\n private final Set<UUID> confirmationPlayers = ConcurrentHashMap.newKeySet();\n private final Map<UUID, Long> awaitingPlayers = Maps.newHashMap();\n\n public boolean presentInLogin(UUID uniqueID) {\n return this.loggedPlayers.contains(uniqueID);\n }\n\n public void addLogin(UUID uniqueID) {\n this.loggedPlayers.add(uniqueID);\n }\n\n public void removeLogin(UUID uniqueID) {\n this.loggedPlayers.remove(uniqueID);\n }\n\n public boolean presentInPremium(UUID uniqueID) {\n return this.premiumPlayers.contains(uniqueID);\n }\n\n public void addPremium(UUID uniqueID) {\n this.premiumPlayers.add(uniqueID);\n }\n\n public void removePremium(UUID uniqueID) {\n this.premiumPlayers.remove(uniqueID);\n }\n\n public boolean presentInConfirmation(UUID uniqueID) {\n return this.confirmationPlayers.contains(uniqueID);\n }\n\n public void addConfirmation(UUID uniqueID) {\n this.confirmationPlayers.add(uniqueID);\n }\n\n public void removeConfirmation(UUID uniqueID) {\n this.confirmationPlayers.remove(uniqueID);\n }\n\n public boolean presentInAwaiting(UUID uniqueID) {\n return this.awaitingPlayers.containsKey(uniqueID);\n }\n\n public void addAwaiting(UUID uniqueID) {\n this.awaitingPlayers.put(uniqueID, System.currentTimeMillis());\n }\n\n public void removeAwaiting(UUID uniqueID) {\n this.awaitingPlayers.remove(uniqueID);\n }\n}" } ]
import com.github.chrisgenti.vpl.velocity.VPLPlugin; import com.github.chrisgenti.vpl.velocity.listeners.Listener; import com.github.chrisgenti.vpl.velocity.players.PlayerManager; import com.velocitypowered.api.event.EventManager; import com.velocitypowered.api.event.EventTask; import com.velocitypowered.api.event.connection.DisconnectEvent; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.UUID;
1,543
package com.github.chrisgenti.vpl.velocity.listeners.disconnect; public class DisconnectListener implements Listener<DisconnectEvent> { private final VPLPlugin plugin; private final EventManager eventManager;
package com.github.chrisgenti.vpl.velocity.listeners.disconnect; public class DisconnectListener implements Listener<DisconnectEvent> { private final VPLPlugin plugin; private final EventManager eventManager;
private final PlayerManager playerManager;
2
2023-11-28 10:12:04+00:00
2k
Ethylene9160/Chess
src/chess/web/MoveServer.java
[ { "identifier": "ServerThread", "path": "src/chess/threads/ServerThread.java", "snippet": "public class ServerThread implements Runnable{\n\n private String name;\n\n public ServerThread(String name) {\n this.name = name;\n }\n\n @Override\n public void run() {\n JFrame frame = new JFrame();\n JTextField textField = new JTextField(name + \"服务器启动\");\n textField.setEditable(false);\n frame.setSize(120,100);\n frame.setLocationRelativeTo(null);\n JPanel panel = new JPanel();\n panel.add(textField);\n frame.add(panel);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n}" }, { "identifier": "Constants", "path": "src/chess/util/Constants.java", "snippet": "public class Constants {\n public static final int FRAME_LENGTH = 1080,\n FRAME_HEIGHT = 720;\n public static final String SAVE_BUTTON = \"SAVE\", LOAD_BUTTON = \"LOAD\", REGRET_BUTTON = \"REGRET\", RESTART_BUTTON = \"RESTART\",\n APPLY_BUTTON = \"APPLY\", PREPARE_BUTTON = \"PREP\", CONFIRM_BUTTON = \"CFR\", FORGET_BUTTON = \"FGB\", SIGN_BUTTON = \"SetS\",\n YOUR_EMO = \"Yem\";\n\n public final static String BASE_PATH = \"D:\\\\resource\\\\WChess\\\\statics\", //这里设置资源文件根目录\n LIBRARY_PATH = BASE_PATH + \"\\\\Library\",\n IMAGE_PATH = BASE_PATH + File.separator + \"image\",\n EMO_PATH = IMAGE_PATH + File.separator +\"emo\",\n HEAD_PATH = IMAGE_PATH + File.separator + \"head\",\n STYLE_PATH = IMAGE_PATH + File.separator + \"style\";\n\n public final static String REGISTER_PATH = BASE_PATH + File.separator + \"register\\\\reg.ethy\";\n public final static String CHESS_REGIST = BASE_PATH + File.separator + \"register\\\\chessReg.ethy\";\n public final static int PANEL_WEIGHT = PanelBase.BOARD_WEIGHT + 200;\n public final static String[] HEADERS = new File(HEAD_PATH).list(),\n EMOS = new File(EMO_PATH).list();\n public static final Font LITTLE_BLACK = new Font(\"微软雅黑\", Font.BOLD, 16),\n LARGE_BLACK = new Font(\"微软雅黑\", Font.BOLD, 50);\n\n //在这里修改网络\n public static final int PORT = 8888;//port\n public static final String HOST = \"127.0.0.1\";//IP\n\n\n private static String[] getHead(){\n return new File(HEAD_PATH).list();\n }\n}" }, { "identifier": "RegisterUtil", "path": "src/chess/util/RegisterUtil.java", "snippet": "public class RegisterUtil {\n public static HashMap<Integer, Registers> getRegisters(String fileName){\n HashMap<Integer, Registers> registers = new HashMap<>();\n File file = new File(fileName);\n StringBuilder sb = new StringBuilder();\n sb.setLength(0);\n// String sb = \"\";\n try{\n Scanner input = new Scanner(new File(fileName));\n while(input.hasNext()){\n sb.append(input.next());\n }\n sb.setLength(sb.length()-1);\n// sb.deleteCharAt(0);\n //获取每一个用户的信息\n String[] infos = sb.toString().split(\"#\");\n for(String info : infos){\n String baseInfo[] = info.split(\"&\");\n// System.out.println(Arrays.toString(baseInfo));\n registers.put(Integer.parseInt(baseInfo[0]),\n new Registers(\n Integer.parseInt(baseInfo[0]),//ID\n Integer.parseInt(baseInfo[1]),//all times\n Integer.parseInt(baseInfo[2]),//win times\n baseInfo[3], baseInfo[4], baseInfo[5], baseInfo[6], baseInfo[7],baseInfo[8],\n Integer.parseInt(baseInfo[9]), Integer.parseInt(baseInfo[10]))\n );\n }\n }catch(Exception e){\n System.out.println(\"ERROR!\");\n e.printStackTrace();\n return null;\n }\n System.out.println(registers);\n return registers;\n }\n\n public static void writeRegisters(String fileName, Map<Integer, Registers> registers){\n File file = new File(fileName + \"1\");\n String registerInfos = \"\";\n System.out.println(registers);\n for(Integer key : registers.keySet()){\n registerInfos = registerInfos + registers.get(key).toString();\n }\n System.out.println(registerInfos);\n try{\n BufferedWriter writer = new BufferedWriter(new FileWriter(fileName+ \"1\"));\n writer.write(registerInfos);\n writer.close();\n }catch(Exception e){\n e.printStackTrace();\n }\n }\n\n}" } ]
import chess.threads.ServerThread; import chess.util.Constants; import chess.util.RegisterUtil; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map;
1,250
package chess.web; /** * 游戏操作端的server * 通过构建channel数组,实现多线程转发消息。 */ public class MoveServer { //创建集合对象,从而实现“群发 //public static List<MoveChannel> list = new ArrayList<MoveChannel>(); public static Map<Integer, MoveChannel> listMap = new HashMap<>(); public static int webID; public static Map<Integer,Registers> registers; // public static Map<Integer,Registers> registers = new HashMap<>(); public static void main(String[] args) throws IOException { new Thread(new ServerThread("Reversi")).start();
package chess.web; /** * 游戏操作端的server * 通过构建channel数组,实现多线程转发消息。 */ public class MoveServer { //创建集合对象,从而实现“群发 //public static List<MoveChannel> list = new ArrayList<MoveChannel>(); public static Map<Integer, MoveChannel> listMap = new HashMap<>(); public static int webID; public static Map<Integer,Registers> registers; // public static Map<Integer,Registers> registers = new HashMap<>(); public static void main(String[] args) throws IOException { new Thread(new ServerThread("Reversi")).start();
registers = RegisterUtil.getRegisters(Constants.REGISTER_PATH);
2
2023-12-01 02:33:32+00:00
2k
thunkware/virtual-threads-backport
src/main/java/io/github/thunkware/ThreadProvider8.java
[ { "identifier": "OfPlatform", "path": "src/main/java/io/github/thunkware/ThreadTool.java", "snippet": "interface OfPlatform extends Builder {\n\n /**\n * Sets the thread group.\n * @param group the thread group\n * @return this builder\n */\n OfPlatform group(ThreadGroup group);\n\n /**\n * Sets the daemon status.\n * @param on {@code true} to create daemon threads\n * @return this builder\n */\n OfPlatform daemon(boolean on);\n\n /**\n * Sets the daemon status to {@code true}.\n * @return this builder\n */\n default OfPlatform daemon() {\n return daemon(true);\n }\n\n /**\n * Sets the thread priority.\n * @param priority priority\n * @return this builder\n * @throws IllegalArgumentException if the priority is less than\n * {@link Thread#MIN_PRIORITY} or greater than {@link Thread#MAX_PRIORITY}\n */\n OfPlatform priority(int priority);\n\n /**\n * Sets the desired stack size.\n *\n * <p> The stack size is the approximate number of bytes of address space\n * that the Java virtual machine is to allocate for the thread's stack. The\n * effect is highly platform dependent and the Java virtual machine is free\n * to treat the {@code stackSize} parameter as a \"suggestion\". If the value\n * is unreasonably low for the platform then a platform specific minimum\n * may be used. If the value is unreasonably high then a platform specific\n * maximum may be used. A value of zero is always ignored.\n *\n * @param stackSize the desired stack size\n * @return this builder\n * @throws IllegalArgumentException if the stack size is negative\n */\n OfPlatform stackSize(long stackSize);\n}" }, { "identifier": "OfVirtual", "path": "src/main/java/io/github/thunkware/ThreadTool.java", "snippet": "interface OfVirtual extends Builder {\n}" } ]
import io.github.thunkware.ThreadTool.Builder.OfPlatform; import io.github.thunkware.ThreadTool.Builder.OfVirtual; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import static io.github.thunkware.ThreadFeature.HAS_VIRTUAL_THREADS; import static io.github.thunkware.ThreadFeature.IS_VIRTUAL; import static io.github.thunkware.ThreadFeature.NEW_THREAD_PER_TASK_EXECUTOR; import static io.github.thunkware.ThreadFeature.NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR; import static io.github.thunkware.ThreadFeature.OF_PLATFORM; import static io.github.thunkware.ThreadFeature.OF_VIRTUAL; import static io.github.thunkware.ThreadFeature.START_VIRTUAL_THREAD; import static io.github.thunkware.ThreadFeature.UNSTARTED_VIRTUAL_THREAD;
958
package io.github.thunkware; final class ThreadProvider8 implements ThreadProvider { private final ThreadProviderConfig config = new ThreadProviderConfig(); @Override public ThreadProviderConfig getConfig() { return config; } @Override public boolean hasVirtualThreads() { config.enforceCompatibilityPolicy(HAS_VIRTUAL_THREADS); return false; } @Override public boolean isVirtual(final Thread thread) { config.enforceCompatibilityPolicy(IS_VIRTUAL); return false; } @Override public Thread startVirtualThread(final Runnable task) { config.enforceCompatibilityPolicy(START_VIRTUAL_THREAD); Thread thread = unstartedVirtualThread(task); thread.start(); return thread; } @Override public Thread unstartedVirtualThread(Runnable task) { config.enforceCompatibilityPolicy(UNSTARTED_VIRTUAL_THREAD); return new Thread(task); } @Override public ExecutorService newThreadPerTaskExecutor(final ThreadFactory threadFactory) { config.enforceCompatibilityPolicy(NEW_THREAD_PER_TASK_EXECUTOR); return new ThreadPerTaskExecutor(threadFactory); } @Override public ExecutorService newVirtualThreadPerTaskExecutor() { config.enforceCompatibilityPolicy(NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR); return newThreadPerTaskExecutor(task -> { Thread thread = new Thread(task); thread.setDaemon(true); return thread; }); } @Override
package io.github.thunkware; final class ThreadProvider8 implements ThreadProvider { private final ThreadProviderConfig config = new ThreadProviderConfig(); @Override public ThreadProviderConfig getConfig() { return config; } @Override public boolean hasVirtualThreads() { config.enforceCompatibilityPolicy(HAS_VIRTUAL_THREADS); return false; } @Override public boolean isVirtual(final Thread thread) { config.enforceCompatibilityPolicy(IS_VIRTUAL); return false; } @Override public Thread startVirtualThread(final Runnable task) { config.enforceCompatibilityPolicy(START_VIRTUAL_THREAD); Thread thread = unstartedVirtualThread(task); thread.start(); return thread; } @Override public Thread unstartedVirtualThread(Runnable task) { config.enforceCompatibilityPolicy(UNSTARTED_VIRTUAL_THREAD); return new Thread(task); } @Override public ExecutorService newThreadPerTaskExecutor(final ThreadFactory threadFactory) { config.enforceCompatibilityPolicy(NEW_THREAD_PER_TASK_EXECUTOR); return new ThreadPerTaskExecutor(threadFactory); } @Override public ExecutorService newVirtualThreadPerTaskExecutor() { config.enforceCompatibilityPolicy(NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR); return newThreadPerTaskExecutor(task -> { Thread thread = new Thread(task); thread.setDaemon(true); return thread; }); } @Override
public OfPlatform ofPlatform() {
0
2023-12-03 07:04:02+00:00
2k
dnslin/cloud189
src/main/java/in/dnsl/logic/UserSign.java
[ { "identifier": "SessionDTO", "path": "src/main/java/in/dnsl/domain/dto/SessionDTO.java", "snippet": "@NoArgsConstructor\n@Data\npublic class SessionDTO {\n\n @JsonProperty(\"res_code\")\n private Integer resCode;\n\n @JsonProperty(\"res_message\")\n private String resMessage;\n\n @JsonProperty(\"accessToken\")\n private String accessToken;\n\n @JsonProperty(\"familySessionKey\")\n private String familySessionKey;\n\n @JsonProperty(\"familySessionSecret\")\n private String familySessionSecret;\n\n @JsonProperty(\"getFileDiffSpan\")\n private Integer getFileDiffSpan;\n\n @JsonProperty(\"getUserInfoSpan\")\n private Integer getUserInfoSpan;\n\n @JsonProperty(\"isSaveName\")\n private String isSaveName;\n\n @JsonProperty(\"keepAlive\")\n private Integer keepAlive;\n\n @JsonProperty(\"loginName\")\n private String loginName;\n\n @JsonProperty(\"refreshToken\")\n private String refreshToken;\n\n @JsonProperty(\"sessionKey\")\n private String sessionKey;\n\n @JsonProperty(\"sessionSecret\")\n private String sessionSecret;\n\n private AccessTokenDTO accessTokenDTO;\n\n}" }, { "identifier": "UserSignResult", "path": "src/main/java/in/dnsl/domain/result/UserSignResult.java", "snippet": "@Data\n@NoArgsConstructor\n@XStreamAlias(\"userSignResult\")\npublic class UserSignResult {\n private int result;\n private String resultTip;\n private int activityFlag;\n private String prizeListUrl;\n private String buttonTip;\n private String buttonUrl;\n private String activityTip;\n}" }, { "identifier": "SignatureUtils", "path": "src/main/java/in/dnsl/utils/SignatureUtils.java", "snippet": "public class SignatureUtils {\n\n public static String signatureOfMd5(Map<String, String> params) {\n List<String> keys = new ArrayList<>();\n for (Map.Entry<String, String> entry : params.entrySet()) {\n keys.add(entry.getKey() + \"=\" + entry.getValue());\n }\n\n Collections.sort(keys);\n String signStr = String.join(\"&\", keys);\n\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(signStr.getBytes());\n byte[] digest = md.digest();\n return bytesToHex(digest).toLowerCase();\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"MD5算法不可用\", e);\n }\n }\n\n private static String bytesToHex(byte[] bytes) {\n StringBuilder hexString = new StringBuilder();\n for (byte b : bytes) {\n String hex = Integer.toHexString(0xff & b);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n return hexString.toString();\n }\n\n @SneakyThrows\n public static String signatureOfHmac(String secretKey, String sessionKey, String operate, String urlString, String dateOfGmt) {\n try {\n URI url = new URI(urlString);\n String requestUri = url.getPath();\n\n String plainStr = String.format(\"SessionKey=%s&Operate=%s&RequestURI=%s&Date=%s\",\n sessionKey, operate, requestUri, dateOfGmt);\n\n SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), \"HmacSHA1\");\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(keySpec);\n byte[] result = mac.doFinal(plainStr.getBytes(StandardCharsets.UTF_8));\n return bytesToHex(result).toUpperCase();\n } catch (NoSuchAlgorithmException | InvalidKeyException e) {\n throw new RuntimeException(\"Error while calculating HMAC\", e);\n }\n }\n\n}" }, { "identifier": "XmlUtils", "path": "src/main/java/in/dnsl/utils/XmlUtils.java", "snippet": "@Slf4j\npublic class XmlUtils {\n private static final XStream xstream = new XStream();\n\n static {\n // 设置 XStream 安全性,允许任何类被序列化或反序列化\n xstream.addPermission(AnyTypePermission.ANY);\n }\n\n // 将XML转换为Java对象\n public static <T> T xmlToObject(String xml, Class<T> clazz) {\n xstream.processAnnotations(clazz);\n return clazz.cast(xstream.fromXML(xml));\n }\n\n // 将Java对象转换为XML字符串\n public static String objectToXml(Object obj) {\n xstream.processAnnotations(obj.getClass());\n return xstream.toXML(obj);\n }\n\n}" }, { "identifier": "API_URL", "path": "src/main/java/in/dnsl/constant/ApiConstant.java", "snippet": "public static final String API_URL = \"https://api.cloud.189.cn\";" }, { "identifier": "dateOfGmtStr", "path": "src/main/java/in/dnsl/utils/ApiUtils.java", "snippet": "public static String dateOfGmtStr() {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n Date currentDate = new Date();\n return dateFormat.format(currentDate);\n}" }, { "identifier": "uuidUpper", "path": "src/main/java/in/dnsl/utils/ApiUtils.java", "snippet": "public static String uuidUpper() {\n return uuidDash().toUpperCase();\n}" }, { "identifier": "uuidDash", "path": "src/main/java/in/dnsl/utils/StringGenerator.java", "snippet": "public static String uuidDash() {\n return randomUUID().toString();\n}" } ]
import in.dnsl.domain.dto.SessionDTO; import in.dnsl.domain.result.UserSignResult; import in.dnsl.utils.SignatureUtils; import in.dnsl.utils.XmlUtils; import lombok.extern.slf4j.Slf4j; import me.kuku.utils.OkHttpUtils; import okhttp3.Headers; import java.util.HashMap; import java.util.Map; import static in.dnsl.constant.ApiConstant.API_URL; import static in.dnsl.utils.ApiUtils.dateOfGmtStr; import static in.dnsl.utils.ApiUtils.uuidUpper; import static in.dnsl.utils.StringGenerator.uuidDash;
1,536
package in.dnsl.logic; @Slf4j public class UserSign { public static void appUserSign(SessionDTO dto){ var fullUrl = "%s/mkt/userSign.action?clientType=TELEIPHONE&version=8.9.4&model=iPhone&osFamily=iOS&osVersion=13.7&clientSn=%s"; fullUrl = String.format(fullUrl, API_URL, uuidDash()); var headers = Map.ofEntries( Map.entry("Date", dateOfGmtStr()), Map.entry("SessionKey",dto.getSessionKey()), Map.entry("Signature", SignatureUtils.signatureOfHmac(dto.getSessionSecret(),dto.getSessionKey(),"POST",fullUrl,dateOfGmtStr())),
package in.dnsl.logic; @Slf4j public class UserSign { public static void appUserSign(SessionDTO dto){ var fullUrl = "%s/mkt/userSign.action?clientType=TELEIPHONE&version=8.9.4&model=iPhone&osFamily=iOS&osVersion=13.7&clientSn=%s"; fullUrl = String.format(fullUrl, API_URL, uuidDash()); var headers = Map.ofEntries( Map.entry("Date", dateOfGmtStr()), Map.entry("SessionKey",dto.getSessionKey()), Map.entry("Signature", SignatureUtils.signatureOfHmac(dto.getSessionSecret(),dto.getSessionKey(),"POST",fullUrl,dateOfGmtStr())),
Map.entry("X-Request-ID", uuidUpper()),
6
2023-12-02 17:02:16+00:00
2k
anndiak/StarChat
src/main/java/com/starchat/controller/ChatController.java
[ { "identifier": "ChatRoom", "path": "src/main/java/com/starchat/model/ChatRoom.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Getter\n@Setter\n@ToString\npublic class ChatRoom {\n private Long id;\n private String topic;\n private LocalDateTime created_at = LocalDateTime.now();\n private LocalDateTime updated_at = LocalDateTime.now();\n}" }, { "identifier": "Message", "path": "src/main/java/com/starchat/model/Message.java", "snippet": "@NoArgsConstructor @AllArgsConstructor @Getter @Setter @ToString\npublic class Message {\n private Long id;\n private Long chatRoomId;\n private Long toUserId;\n private Long fromUserId;\n private String text;\n private LocalDateTime createdAt = LocalDateTime.now();\n\n public Message(Long chatRoomId, Long toUserId, Long fromUserId, String text) {\n this.chatRoomId = chatRoomId;\n this.toUserId = toUserId;\n this.fromUserId = fromUserId;\n this.text = text;\n }\n}" }, { "identifier": "MessageDto", "path": "src/main/java/com/starchat/model/dto/MessageDto.java", "snippet": "@Data\npublic class MessageDto {\n\n @JsonProperty(\"chatId\")\n private Long chatId;\n\n @JsonProperty(\"text\")\n private String text;\n\n @JsonProperty(\"senderEmail\")\n private String senderEmail;\n\n @JsonProperty(\"receiverEmail\")\n private String receiverEmail;\n\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss\")\n private LocalDateTime createdAt;\n\n @JsonProperty(\"files\")\n private List<UploadedFileDto> files;\n}" }, { "identifier": "UploadedFileDto", "path": "src/main/java/com/starchat/model/dto/UploadedFileDto.java", "snippet": "@Data\npublic class UploadedFileDto {\n private Long id;\n private String fileName;\n private String fileType;\n private long fileSize;\n private LocalDateTime uploadedAt;\n}" }, { "identifier": "ChatRoomRepository", "path": "src/main/java/com/starchat/repository/ChatRoomRepository.java", "snippet": "public interface ChatRoomRepository {\n\n ChatRoom getChatRoomById(Long id);\n\n ChatRoom addChatRoom(ChatRoom chatRoom);\n\n void deleteChatRoomById (Long id);\n\n List<ChatRoom> getAllChatRooms();\n\n void updateUpdatedAtById(Long id, LocalDateTime updatedAt);\n}" }, { "identifier": "FileRepository", "path": "src/main/java/com/starchat/repository/FileRepository.java", "snippet": "public interface FileRepository {\n\n UploadedFile addFile(UploadedFile file);\n\n UploadedFile getFileById(Long id);\n\n List<UploadedFile> getFilesByMessageId(Long messageId);\n\n void assignFileToMessage(Long id, Long messageId);\n}" }, { "identifier": "MessageRepository", "path": "src/main/java/com/starchat/repository/MessageRepository.java", "snippet": "public interface MessageRepository {\n\n Message getMessageById(Long id);\n\n Message addMessage(Message message);\n\n List<Message> getAllMessagesByChatRoomId(Long id);\n\n List<Long> getUserChatIds(Long id);\n}" }, { "identifier": "UserRepository", "path": "src/main/java/com/starchat/repository/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository {\n\n User getUserById(Long id);\n\n User getUserByEmail(String email);\n\n List<User> getAllUsers();\n\n Long getUserIdByEmail(String email);\n\n void addUser(User user);\n void deleteUserById (Long id);\n}" } ]
import com.intersystems.jdbc.IRIS; import com.starchat.model.ChatRoom; import com.starchat.model.Message; import com.starchat.model.dto.MessageDto; import com.starchat.model.dto.UploadedFileDto; import com.starchat.repository.ChatRoomRepository; import com.starchat.repository.FileRepository; import com.starchat.repository.MessageRepository; import com.starchat.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalDateTime; import java.util.List;
955
package com.starchat.controller; @Controller public class ChatController { @Autowired
package com.starchat.controller; @Controller public class ChatController { @Autowired
private MessageRepository messageRepository;
6
2023-11-27 02:41:17+00:00
2k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/ast/LiteralExpression.java
[ { "identifier": "BaseType", "path": "compiler/src/main/java/org/vectorlang/compiler/compiler/BaseType.java", "snippet": "public enum BaseType {\n INT(4), FLOAT(8), BOOL(1), CHAR(1);\n\n private int width;\n\n private BaseType(int width) {\n this.width = width;\n }\n\n public int getWidth() {\n return width;\n }\n}" }, { "identifier": "Type", "path": "compiler/src/main/java/org/vectorlang/compiler/compiler/Type.java", "snippet": "public class Type {\n private int[] shape;\n private BaseType baseType;\n private boolean constant;\n\n public Type(BaseType baseType, int[] shape, boolean constant) {\n this.shape = shape;\n this.baseType = baseType;\n this.constant = constant;\n }\n\n public Type vectorize(int length) {\n int[] newShape = new int[shape.length + 1];\n newShape[0] = length;\n for (int i = 0; i < shape.length; i++) {\n newShape[i + 1] = shape[i];\n }\n return new Type(baseType, newShape, constant);\n }\n\n public Type indexed() {\n if (shape.length > 0) {\n int[] newShape = new int[shape.length - 1];\n for (int i = 0; i < newShape.length; i++) {\n newShape[i] = shape[i + 1];\n }\n return new Type(baseType, newShape, constant);\n } else {\n return null;\n }\n }\n\n public Type concat(Type type) {\n int[] newShape = new int[shape.length];\n shape[0] = shape[0] + type.shape[0];\n for (int i = 1; i < shape.length; i++) {\n newShape[i] = shape[i];\n }\n return new Type(baseType, newShape, constant);\n }\n\n public int getSize() {\n int size = 1; /*switch (baseType) {\n case BOOL -> 1;\n case CHAR -> 1;\n case FLOAT -> 8;\n case INT -> 4;\n };*/\n for (int dimension : shape) {\n size *= dimension; \n }\n return size;\n }\n\n public int[] getShape() {\n return shape;\n }\n\n public BaseType getBaseType() {\n return baseType;\n }\n\n public Type constant() {\n return new Type(baseType, shape, true);\n }\n\n @Override\n public boolean equals(Object object) {\n if (object instanceof Type) {\n return Arrays.equals(shape, ((Type) object).shape)\n && baseType.equals(((Type) object).baseType);\n }\n return false;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(switch(baseType) {\n case BOOL -> \"bool\";\n case CHAR -> \"char\";\n case FLOAT -> \"float\";\n case INT -> \"int\";\n });\n for (int i : shape) {\n builder.append('[').append(i).append(']');\n }\n return builder.toString();\n }\n}" } ]
import org.vectorlang.compiler.compiler.BaseType; import org.vectorlang.compiler.compiler.Type;
849
package org.vectorlang.compiler.ast; public class LiteralExpression extends Expression { private final int intValue; private final boolean boolValue; private final double floatValue; private final int type; public LiteralExpression(int value) {
package org.vectorlang.compiler.ast; public class LiteralExpression extends Expression { private final int intValue; private final boolean boolValue; private final double floatValue; private final int type; public LiteralExpression(int value) {
super(new Type(BaseType.INT, new int[0], true));
0
2023-11-30 04:22:36+00:00
2k
Tabbleman/oesm
backend/oesm/src/main/java/org/tabbleman/oesm/controller/ExamController.java
[ { "identifier": "Exam", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/entity/Exam.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\npublic class Exam {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long examId;\n private String examName;\n\n private Long examQuestionCount = 10L;\n\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Timestamp examStartTimeStamp;\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Timestamp examEndTimeStamp;\n\n}" }, { "identifier": "Question", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/entity/Question.java", "snippet": "@Data\n@Entity\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Question {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long questionId;\n /**\n * single\n * multiple\n * truefalse\n */\n private String questionType;\n private String questionName;\n /**\n * answer is the content of the choices.\n * e\n */\n private String questionAnswer;\n /**\n * choice splict format:\n * \"[]$[]$[]$[]\"\n * \"T$F\"\n */\n private String questionChoices = \"hello world$goodgood$fucn u$test\";\n// private Long subjectId;\n public Question(String questionType, String questionName, String questionAnswer, String questionChoices) {\n this.questionType = questionType;\n this.questionName = questionName;\n this.questionAnswer = questionAnswer;\n this.questionChoices = questionChoices;\n }\n}" }, { "identifier": "ExamService", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/service/ExamService.java", "snippet": "public interface ExamService {\n // for student:\n public List<Long> getUserExamsId(UserExamsQo userExamsQo);\n\n public List<ExamCardDisplayVo> getUserFinishedExams(UserExamsQo userExamsQo);\n public List<Exam> getUserAllExams(UserExamsQo userExamsQo);\n public List<Exam> getUserUnfinishedExams(UserExamsQo userExamsQo);\n\n public Exam getExamByExamId(Long examId);\n\n public List<Question> generateQuestionsByExamId(Long examId);\n\n\n public Exam createExam(ExamConfigDto configDto);\n\n public Long judgeExam(QuestionAnswerSheetDto answerSheet);\n\n}" }, { "identifier": "QuestionService", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/service/QuestionService.java", "snippet": "public interface QuestionService {\n public List<Question> getAllQuestions();\n\n public List<Question> getAllSingleQuestions();\n\n public List<Question> getAllMultipleQuestions();\n\n public List<Question> getAllTfQuestions();\n\n public String uploadQuestion(MultipartFile questionCsv);\n}" }, { "identifier": "ExamConfigDto", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/utils/dto/ExamConfigDto.java", "snippet": "@Data\npublic class ExamConfigDto {\n// private Long subjectId;\n private String examName;\n private Long classId;\n private Long examQuestionCount;\n private Long singleCount;\n private Long singleScore;\n private Long multipleCount;\n private Long multipleScore;\n private Long truefalseCount;\n private Long truefalseScore;\n\n private String examStartTimeStamp;\n\n private String examEndTimeStamp;\n}" }, { "identifier": "QuestionAnswerSheetDto", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/utils/dto/QuestionAnswerSheetDto.java", "snippet": "@Data\npublic class QuestionAnswerSheetDto {\n\n private Long userId;\n private Long examId;\n\n private List<MetaQuestionAnswer> questionAnswers;\n}" }, { "identifier": "UserExamsQo", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/utils/qo/UserExamsQo.java", "snippet": "@Data\npublic class UserExamsQo {\n private Long userId;\n}" }, { "identifier": "ExamCardDisplayVo", "path": "backend/oesm/src/main/java/org/tabbleman/oesm/utils/vo/ExamCardDisplayVo.java", "snippet": "@Data\npublic class ExamCardDisplayVo {\n private String examName;\n private Long userScore;\n// private Long totalScore;\n\n}" } ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.tabbleman.oesm.entity.Exam; import org.tabbleman.oesm.entity.Question; import org.tabbleman.oesm.service.ExamService; import org.tabbleman.oesm.service.QuestionService; import org.tabbleman.oesm.utils.dto.ExamConfigDto; import org.tabbleman.oesm.utils.dto.QuestionAnswerSheetDto; import org.tabbleman.oesm.utils.qo.UserExamsQo; import org.tabbleman.oesm.utils.vo.ExamCardDisplayVo; import java.util.ArrayList; import java.util.List;
1,397
package org.tabbleman.oesm.controller; /** * todo: * Exam controller * functions Actor Descriptions * * @Get getAllExams student * getAllQuestions Teacher * getAllSingleQuestions Teacher * getAllMultipleQuestion Teacher * getAllTFQuestion Teacher * @Post updateExam Student * addNewQuestion Teacher * createExam Teacher need pick different number of different type of question * finishExam Student */ @CrossOrigin @RestController @RequestMapping("/api/exam") public class ExamController { Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired private ExamService examService; @Autowired private QuestionService questionService; /** * for login user to view their task * * @param userExamsQo * @return */ @PostMapping("/user/exams/unfinished")
package org.tabbleman.oesm.controller; /** * todo: * Exam controller * functions Actor Descriptions * * @Get getAllExams student * getAllQuestions Teacher * getAllSingleQuestions Teacher * getAllMultipleQuestion Teacher * getAllTFQuestion Teacher * @Post updateExam Student * addNewQuestion Teacher * createExam Teacher need pick different number of different type of question * finishExam Student */ @CrossOrigin @RestController @RequestMapping("/api/exam") public class ExamController { Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired private ExamService examService; @Autowired private QuestionService questionService; /** * for login user to view their task * * @param userExamsQo * @return */ @PostMapping("/user/exams/unfinished")
ResponseEntity<List<Exam>> getUserUnfinishedExams(@RequestBody UserExamsQo userExamsQo) {
0
2023-12-04 08:50:19+00:00
2k
SuperMagicican/elegent-AC
elegent-AC-mqtt/src/main/java/cn/elegent/ac/mqtt/MqttCallback.java
[ { "identifier": "ACACKHandler", "path": "elegent-AC-core/src/main/java/cn/elegent/ac/ACACKHandler.java", "snippet": "public interface ACACKHandler<T> {\n\n\n public void deliveryComplete(String topic,T params);\n\n}" }, { "identifier": "ACDistributer", "path": "elegent-AC-core/src/main/java/cn/elegent/ac/core/ACDistributer.java", "snippet": "public interface ACDistributer {\n\n\n void distribute(String topic,String msgContent);\n\n}" }, { "identifier": "CoreData", "path": "elegent-AC-core/src/main/java/cn/elegent/ac/core/CoreData.java", "snippet": "public class CoreData {\n\n\n /**\n * 消息处理类map\n */\n public static Map<String, ACHandler> handlerMap = new HashMap<String,ACHandler>();//key:主题 value:消息处理类\n\n /**\n * 主题列表\n */\n //public static Set<Topic> topicList=new HashSet<>();\n\n\n private static Chains chains = new Chains();\n\n static {\n chains.addGetHandler(new HashGetHandler())\n .addGetHandler(new TopicWildcardGetHandler())\n .addGetHandler(new MapKeyWildcardGetHandler())\n ;\n }\n\n public static Object get(String topic) {\n return chains.get(topic);\n }\n\n}" }, { "identifier": "MqttBeans", "path": "elegent-AC-mqtt/src/main/java/cn/elegent/ac/mqtt/config/MqttBeans.java", "snippet": "@Configuration\n@Component\n@Data\n@Slf4j\npublic class MqttBeans {\n\n @Autowired\n private ACConfig acConfig;\n\n @Autowired\n private MqttCallback mqttCallback;\n\n @Bean\n public MqttClient mqttClient() {\n String serverURI=\"tcp://\"+ acConfig.getHost()+\":\"+acConfig.getPort();\n try {\n MqttClient client = new MqttClient(\n serverURI,\n acConfig.getClientId(),\n new MemoryPersistence());\n client.setManualAcks(true); //设置手动消息接收确认\n //===================\n client.setCallback(mqttCallback);\n //====================\n client.connect(mqttConnectOptions());\n return client;\n } catch (MqttException e) {\n log.error(\"MQTT无法连接!!!!\",e);\n return null;\n }\n }\n\n private MqttConnectOptions mqttConnectOptions() {\n MqttConnectOptions options = new MqttConnectOptions();\n options.setUserName(acConfig.getUsername());\n options.setPassword(acConfig.getPassword().toCharArray());\n options.setAutomaticReconnect(true);//是否自动重新连接\n options.setCleanSession(true);//是否清除之前的连接信息\n options.setConnectionTimeout(acConfig.getConnectionTimeout());//连接超时时间\n options.setKeepAliveInterval(acConfig.getKeepAliveInterval());//心跳\n options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);//设置mqtt版本\n return options;\n }\n\n}" } ]
import cn.elegent.ac.ACACKHandler; import cn.elegent.ac.core.ACDistributer; import cn.elegent.ac.core.CoreData; import cn.elegent.ac.mqtt.config.MqttBeans; import lombok.extern.slf4j.Slf4j; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component;
963
package cn.elegent.ac.mqtt; /** * 基于Eclipse paho设置事件 * @author wgl */ @Component @Slf4j public class MqttCallback implements MqttCallbackExtended{ @Autowired private ACDistributer acDistributer;//消息分发处理器 @Autowired @Lazy private MqttClient mqttClient; @Autowired @Lazy private ACACKHandler acackHandler; @Autowired
package cn.elegent.ac.mqtt; /** * 基于Eclipse paho设置事件 * @author wgl */ @Component @Slf4j public class MqttCallback implements MqttCallbackExtended{ @Autowired private ACDistributer acDistributer;//消息分发处理器 @Autowired @Lazy private MqttClient mqttClient; @Autowired @Lazy private ACACKHandler acackHandler; @Autowired
private MqttBeans mqttBeans;
3
2023-12-02 11:40:04+00:00
2k
igna-778/CarpetSuppresion
src/main/java/igna778/carpetsuppresion/utils/ClientCarpetSuppresion.java
[ { "identifier": "BlockEventQueueLogger", "path": "src/main/java/igna778/carpetsuppresion/BlockEventQueueLogger.java", "snippet": "public class BlockEventQueueLogger extends HUDLogger {\r\n public static BlockEventQueueLogger create() {\r\n try {\r\n return new BlockEventQueueLogger(CarpetSuppresion.class.getDeclaredField(\"__blockEvents\"), \"blockEventQueue\", \"all\", new String[]{\"all\", \"total\", \"overworld\", \"nether\", \"end\"}, false);\r\n } catch (NoSuchFieldException e) {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n public BlockEventQueueLogger(Field field, String logName, String def, String[] options, boolean strictOptions) {\r\n super(field, logName, def, options, strictOptions);\r\n }\r\n}" }, { "identifier": "CarpetSuppresion", "path": "src/main/java/igna778/carpetsuppresion/CarpetSuppresion.java", "snippet": "public class CarpetSuppresion implements ModInitializer, CarpetExtension {\r\n public static boolean __blockEvents;\r\n @SuppressWarnings(\"DataFlowIssue\")\r\n @Override\r\n public void onInitialize() {\r\n CarpetServer.manageExtension(this);\r\n HUDController.register(server -> {\r\n if (!CarpetSuppresion.__blockEvents) return;\r\n int total = 0;\r\n int ow = ((ServerWorldAccessor) server.getWorld(World.OVERWORLD)).getSyncedBlockEventQueue().size();\r\n int ne = ((ServerWorldAccessor) server.getWorld(World.NETHER)).getSyncedBlockEventQueue().size();\r\n int end = ((ServerWorldAccessor) server.getWorld(World.END)).getSyncedBlockEventQueue().size();\r\n for (ServerWorld world : server.getWorlds()) {\r\n total += ((ServerWorldAccessor) world).getSyncedBlockEventQueue().size();\r\n }\r\n int finalTotal = total;\r\n LoggerRegistry.getLogger(\"blockEventQueue\").log(option -> mapOptions(option, finalTotal, ow, ne, end));\r\n });\r\n }\r\n\r\n public void onGameStarted()\r\n {\r\n CarpetServer.settingsManager.parseSettingsClass(CSSettings.class);\r\n }\r\n\r\n private static Text[] mapOptions(String selected, int total, int ow, int ne, int end) {\r\n List<String> builder = new ArrayList<>();\r\n if (selected.equals(\"all\") || selected.equals(\"total\")) builder.add(\"T: \" + total);\r\n if (selected.equals(\"all\") || selected.equals(\"overworld\")) builder.add(\"OW: \" + ow);\r\n if (selected.equals(\"all\") || selected.equals(\"nether\")) builder.add(\"NE: \" + ne);\r\n if (selected.equals(\"all\") || selected.equals(\"end\")) builder.add(\"END: \" + end);\r\n return new Text[]{Text.of(String.join(\"; \", builder.toArray(new String[]{})))};\r\n }\r\n\r\n @Override\r\n public void registerLoggers() {\r\n LoggerRegistry.registerLogger(\"blockEventQueue\", BlockEventQueueLogger.create());\r\n }\r\n\r\n}" }, { "identifier": "ServerWorldAccessor", "path": "src/main/java/igna778/carpetsuppresion/mixins/ServerWorldAccessor.java", "snippet": "@Mixin(ServerWorld.class)\r\npublic interface ServerWorldAccessor {\r\n @Accessor\r\n ObjectLinkedOpenHashSet<BlockEvent> getSyncedBlockEventQueue();\r\n}" } ]
import carpet.CarpetExtension; import carpet.CarpetServer; import carpet.logging.HUDController; import carpet.logging.LoggerRegistry; import igna778.carpetsuppresion.BlockEventQueueLogger; import igna778.carpetsuppresion.CarpetSuppresion; import igna778.carpetsuppresion.mixins.ServerWorldAccessor; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ModInitializer; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.Text; import net.minecraft.world.World; import java.util.ArrayList; import java.util.List;
1,263
package igna778.carpetsuppresion.utils; public class ClientCarpetSuppresion implements ClientModInitializer, CarpetExtension { public void onInitializeClient() { CarpetServer.manageExtension(this); HUDController.register(server -> { if (!CarpetSuppresion.__blockEvents) return; int total = 0; int ow = ((ServerWorldAccessor) server.getWorld(World.OVERWORLD)).getSyncedBlockEventQueue().size(); int ne = ((ServerWorldAccessor) server.getWorld(World.NETHER)).getSyncedBlockEventQueue().size(); int end = ((ServerWorldAccessor) server.getWorld(World.END)).getSyncedBlockEventQueue().size(); for (ServerWorld world : server.getWorlds()) { total += ((ServerWorldAccessor) world).getSyncedBlockEventQueue().size(); } int finalTotal = total; LoggerRegistry.getLogger("blockEventQueue").log(option -> mapOptions(option, finalTotal, ow, ne, end)); }); } public void onGameStarted() { CarpetServer.settingsManager.parseSettingsClass(CSSettings.class); } private static Text[] mapOptions(String selected, int total, int ow, int ne, int end) { List<String> builder = new ArrayList<>(); if (selected.equals("all") || selected.equals("total")) builder.add("T: " + total); if (selected.equals("all") || selected.equals("overworld")) builder.add("OW: " + ow); if (selected.equals("all") || selected.equals("nether")) builder.add("NE: " + ne); if (selected.equals("all") || selected.equals("end")) builder.add("END: " + end); return new Text[]{Text.of(String.join("; ", builder.toArray(new String[]{})))}; } @Override public void registerLoggers() {
package igna778.carpetsuppresion.utils; public class ClientCarpetSuppresion implements ClientModInitializer, CarpetExtension { public void onInitializeClient() { CarpetServer.manageExtension(this); HUDController.register(server -> { if (!CarpetSuppresion.__blockEvents) return; int total = 0; int ow = ((ServerWorldAccessor) server.getWorld(World.OVERWORLD)).getSyncedBlockEventQueue().size(); int ne = ((ServerWorldAccessor) server.getWorld(World.NETHER)).getSyncedBlockEventQueue().size(); int end = ((ServerWorldAccessor) server.getWorld(World.END)).getSyncedBlockEventQueue().size(); for (ServerWorld world : server.getWorlds()) { total += ((ServerWorldAccessor) world).getSyncedBlockEventQueue().size(); } int finalTotal = total; LoggerRegistry.getLogger("blockEventQueue").log(option -> mapOptions(option, finalTotal, ow, ne, end)); }); } public void onGameStarted() { CarpetServer.settingsManager.parseSettingsClass(CSSettings.class); } private static Text[] mapOptions(String selected, int total, int ow, int ne, int end) { List<String> builder = new ArrayList<>(); if (selected.equals("all") || selected.equals("total")) builder.add("T: " + total); if (selected.equals("all") || selected.equals("overworld")) builder.add("OW: " + ow); if (selected.equals("all") || selected.equals("nether")) builder.add("NE: " + ne); if (selected.equals("all") || selected.equals("end")) builder.add("END: " + end); return new Text[]{Text.of(String.join("; ", builder.toArray(new String[]{})))}; } @Override public void registerLoggers() {
LoggerRegistry.registerLogger("blockEventQueue", BlockEventQueueLogger.create());
0
2023-11-30 14:06:16+00:00
2k
greeta-eshop-01/eshop-api
graphql-gateway-service/src/main/java/com/eshop/gqlgateway/api/datafetchers/LineItemDatafetcher.java
[ { "identifier": "NodeType", "path": "graphql-gateway-service/src/main/java/com/eshop/gqlgateway/api/NodeType.java", "snippet": "@RequiredArgsConstructor\n@Getter\npublic enum NodeType {\n Basket(\"Basket\"),\n Order(\"Order\"),\n Product(\"Product\"),\n User(\"User\"),\n BasketLineItem(\"BasketLineItem\"),\n OrderLineItem(\"OrderLineItem\"),\n Brand(\"Brand\"),\n Category(\"Category\");\n\n @Getter\n private final String name;\n\n public static NodeType of(@NonNull String nodeType) {\n return Stream.of(values()).filter(n -> n.getName().equals(nodeType))\n .findFirst()\n .orElseThrow(() -> new IllegalArgumentException(\"Invalid node type: %s\".formatted(nodeType)));\n }\n\n}" }, { "identifier": "ToBasketLineItemConverter", "path": "graphql-gateway-service/src/main/java/com/eshop/gqlgateway/api/converters/ToBasketLineItemConverter.java", "snippet": "@Component\npublic class ToBasketLineItemConverter {\n public LineItem convert(BasketItemDto basketItem) {\n return LineItem.newBuilder()\n .id(generateId(NodeType.BasketLineItem, basketItem.id()))\n .name(basketItem.productName())\n .image(basketItem.pictureUrl())\n .unitPrice(basketItem.unitPrice())\n .quantity(basketItem.quantity())\n .price(basketItem.quantity() * basketItem.unitPrice())\n .build();\n }\n}" }, { "identifier": "ToOrderLineItemConverter", "path": "graphql-gateway-service/src/main/java/com/eshop/gqlgateway/api/converters/ToOrderLineItemConverter.java", "snippet": "@Component\npublic class ToOrderLineItemConverter {\n\n public LineItem convert(OrderItemDto orderItem) {\n return LineItem.newBuilder()\n .id(generateId(NodeType.OrderLineItem, orderItem.id()))\n .name(orderItem.productName())\n .image(orderItem.pictureUrl())\n .unitPrice(orderItem.unitPrice())\n .quantity(orderItem.units())\n .build();\n }\n}" }, { "identifier": "BasketApiService", "path": "graphql-gateway-service/src/main/java/com/eshop/gqlgateway/services/BasketApiService.java", "snippet": "public interface BasketApiService {\n Optional<BasketDto> findByUserId(String userId);\n\n Optional<BasketDto> findById(UUID id);\n\n Optional<BasketItemDto> findBasketItemById(UUID id);\n\n Optional<BasketDto> update(BasketDto basket);\n\n void checkout(BasketCheckoutDto basketCheckout);\n}" }, { "identifier": "OrderApiService", "path": "graphql-gateway-service/src/main/java/com/eshop/gqlgateway/services/OrderApiService.java", "snippet": "public interface OrderApiService {\n Optional<OrderDto> findById(UUID id);\n\n List<OrderDto> userOrders();\n\n List<OrderDto> allOrders();\n\n Optional<OrderItemDto> findOrderItemById(UUID id);\n}" }, { "identifier": "fromString", "path": "graphql-gateway-service/src/main/java/com/eshop/gqlgateway/api/util/IdUtils.java", "snippet": "public static NodeId fromString(String encodedId) {\n final var decodedBytes = Base64.getDecoder().decode(encodedId);\n final var decodedString = new String(decodedBytes);\n final var parts = decodedString.split(\"_\");\n\n if (parts.length != 2) throw new IllegalArgumentException(\"Invalid node id\");\n\n return new NodeId(\n UUID.fromString(parts[1]),\n NodeType.of(parts[0]),\n encodedId\n );\n}" } ]
import com.eshop.gqlgateway.DgsConstants; import com.eshop.gqlgateway.api.NodeType; import com.eshop.gqlgateway.api.converters.ToBasketLineItemConverter; import com.eshop.gqlgateway.api.converters.ToOrderLineItemConverter; import com.eshop.gqlgateway.services.BasketApiService; import com.eshop.gqlgateway.services.OrderApiService; import com.eshop.gqlgateway.types.LineItem; import com.eshop.gqlgateway.types.Product; import com.netflix.graphql.dgs.DgsComponent; import com.netflix.graphql.dgs.DgsData; import com.netflix.graphql.dgs.DgsQuery; import com.netflix.graphql.dgs.exceptions.DgsEntityNotFoundException; import graphql.execution.DataFetcherResult; import graphql.schema.DataFetchingEnvironment; import lombok.RequiredArgsConstructor; import org.dataloader.DataLoader; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import static com.eshop.gqlgateway.api.dataloaders.DataLoaders.PRODUCTS; import static com.eshop.gqlgateway.api.util.IdUtils.fromString;
1,133
package com.eshop.gqlgateway.api.datafetchers; /** * Datafetcher for {@link LineItem}. */ @RequiredArgsConstructor @DgsComponent public class LineItemDatafetcher { private final OrderApiService orderApiService; private final BasketApiService basketApiService; private final ToOrderLineItemConverter toOrderLineItemConverter; private final ToBasketLineItemConverter toBasketLineItemConverter; @DgsQuery public DataFetcherResult<LineItem> lineItem(String lineItemId) {
package com.eshop.gqlgateway.api.datafetchers; /** * Datafetcher for {@link LineItem}. */ @RequiredArgsConstructor @DgsComponent public class LineItemDatafetcher { private final OrderApiService orderApiService; private final BasketApiService basketApiService; private final ToOrderLineItemConverter toOrderLineItemConverter; private final ToBasketLineItemConverter toBasketLineItemConverter; @DgsQuery public DataFetcherResult<LineItem> lineItem(String lineItemId) {
var nodeId = fromString(lineItemId);
5
2023-11-29 10:00:27+00:00
2k
Moerfiane/liftoff-cranberry-code-crunchers-api
src/main/java/com/launchcode/munchincrunch/controllers/RestaurantsController.java
[ { "identifier": "Restaurant", "path": "src/main/java/com/launchcode/munchincrunch/models/Restaurant.java", "snippet": "public class Restaurant implements Serializable {\n\n private String name;\n private String image_url;\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 getImage_url() {\n return image_url;\n }\n\n public void setImage_url(String image_url) {\n this.image_url = image_url;\n }\n\n public Address getLocation() {\n return location;\n }\n\n public void setLocation(Address location) {\n this.location = location;\n }\n\n private Address location;\n}" }, { "identifier": "Restaurants", "path": "src/main/java/com/launchcode/munchincrunch/models/Restaurants.java", "snippet": "public class Restaurants {\n public List<Restaurant> getBusinesses() {\n return businesses;\n }\n\n public void setBusinesses(List<Restaurant> businesses) {\n this.businesses = businesses;\n }\n\n private List<Restaurant> businesses;\n}" }, { "identifier": "RestaurantsService", "path": "src/main/java/com/launchcode/munchincrunch/services/RestaurantsService.java", "snippet": "@Service\npublic class RestaurantsService {\n\n @Value(\"${api_key}\")\n private String apiKey;\n\n @Value(\"${yelp_api_url}\")\n private String yelpApiUrl;\n\n public List<Restaurant> searchRestaurants(@PathVariable String location){\n RestTemplate restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.set(\"Authorization\", \"Bearer \" + apiKey);\n HttpEntity<?> httpEntity = new HttpEntity<>(headers);\n ResponseEntity<Restaurants> response = restTemplate.exchange(yelpApiUrl+\"?location=\"+location, HttpMethod.GET,httpEntity,Restaurants.class);\n if( response.getBody()!=null){\n return response.getBody().getBusinesses();\n }\n return new ArrayList<>();\n }\n\n}" } ]
import com.launchcode.munchincrunch.models.Restaurant; import com.launchcode.munchincrunch.models.Restaurants; import com.launchcode.munchincrunch.services.RestaurantsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List;
647
package com.launchcode.munchincrunch.controllers; @RestController @CrossOrigin(origins = "http://localhost:3000") public class RestaurantsController { @Autowired private RestaurantsService restaurantsService; @GetMapping("/restaurants/{location}")
package com.launchcode.munchincrunch.controllers; @RestController @CrossOrigin(origins = "http://localhost:3000") public class RestaurantsController { @Autowired private RestaurantsService restaurantsService; @GetMapping("/restaurants/{location}")
public List<Restaurant> searchRestaurants(@PathVariable String location) {
0
2023-11-28 01:15:10+00:00
2k
SuperMagicican/elegent-pay
elegent-pay-core/src/main/java/cn/elegent/pay/core/CallbackWatch.java
[ { "identifier": "CallBackService", "path": "elegent-pay-core/src/main/java/cn/elegent/pay/CallBackService.java", "snippet": "public interface CallBackService {\n\n /**\n * 成功支付--处理业务逻辑\n * @param orderSn 订单号\n */\n void successPay(String orderSn);\n\n /**\n * 失败支付-处理业务逻辑\n * @param orderSn 订单号\n */\n void failPay(String orderSn);\n\n /**\n * 退款成功-处理业务逻辑\n * @param orderSn 订单号\n */\n void successRefund(String orderSn);\n\n /**\n * 退款失败-处理业务逻辑\n * @param orderSn 订单号\n */\n void failRefund(String orderSn);\n\n}" }, { "identifier": "ElegentPay", "path": "elegent-pay-core/src/main/java/cn/elegent/pay/ElegentPay.java", "snippet": "public interface ElegentPay {\n\n\n PayResponse requestPay(PayRequest payRequest,String tradeType,String platform) throws TradeException;\n\n\n Boolean closePay(String orderSn, String platform) throws TradeException;\n\n\n Boolean refund(RefundRequest refundRequest,String platform) throws TradeException;\n\n\n QueryResponse queryTradingOrderNo(String orderSn , String platform) throws TradeException;\n\n\n\n QueryRefundResponse queryRefundTrading(String orderSn , String platform) throws TradeException;\n\n\n /**\n * 获得openID\n * @param code\n * @return\n */\n String getOpenid(String code, String platform);\n\n}" }, { "identifier": "CallbackConfig", "path": "elegent-pay-core/src/main/java/cn/elegent/pay/config/CallbackConfig.java", "snippet": "@Component\n@ConfigurationProperties(\"elegent.pay.callback\")\n@Data\npublic class CallbackConfig {\n\n private String domain; //回调域名\n\n @Value(\"${elegent.pay.callback.watch:false}\")\n private boolean watch; //是否开启监听\n\n @Value(\"${elegent.pay.callback.cycle:10}\")\n private int cycle;//检查周期\n\n\n}" }, { "identifier": "QueryRefundResponse", "path": "elegent-pay-core/src/main/java/cn/elegent/pay/dto/QueryRefundResponse.java", "snippet": "@Data\npublic class QueryRefundResponse extends QueryResponse{\n\n\n private String refund_id; //微信支付退款单号\n\n private String out_refund_no;//商户退款单号\n\n private String channel;//退款渠道\n\n private String user_received_account;//退款账号\n\n private String success_time;//退款成功时间\n\n private String status;//退款状态\n\n private int refund;//退款金额\n\n\n}" }, { "identifier": "QueryResponse", "path": "elegent-pay-core/src/main/java/cn/elegent/pay/dto/QueryResponse.java", "snippet": "@Data\npublic class QueryResponse {\n\n private String openid;//用户id\n\n private String trade_state;//交易状态\n\n private String order_sn;//订单号\n\n private String transaction_id;//交易单号\n\n private int total;//金额\n\n private Map expand;//扩展(全部的返回数据)\n\n}" }, { "identifier": "WatchDTO", "path": "elegent-pay-core/src/main/java/cn/elegent/pay/dto/WatchDTO.java", "snippet": "@Data\npublic class WatchDTO {\n\n private String orderSn; //订单号\n\n private String platform;//平台\n\n}" } ]
import cn.elegent.pay.CallBackService; import cn.elegent.pay.ElegentPay; import cn.elegent.pay.config.CallbackConfig; import cn.elegent.pay.dto.QueryRefundResponse; import cn.elegent.pay.dto.QueryResponse; import cn.elegent.pay.dto.WatchDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import java.util.Timer; import java.util.TimerTask;
1,196
package cn.elegent.pay.core; @Component @ConditionalOnProperty(prefix = "elegent.pay.callback",name = "watch",havingValue = "true") @Slf4j public class CallbackWatch { @Autowired private CallBackService callBackService; @Autowired private CallbackConfig callbackConfig; @Autowired private ElegentPay elegentPay; @PostConstruct public void queryWatch(){ if(callbackConfig.getCycle()<=0){ return; } log.info("开启支付结果定期巡检"); Timer timer = new Timer(); // 2、创建 TimerTask 任务线程 TimerTask task=new TimerTask() { @Override public void run() { try{ //查询支付状态 log.info("支付状态定期巡检,{}",WatchList.payList); for( WatchDTO watchDTO: WatchList.payList ){ //查询订单是否支付成功
package cn.elegent.pay.core; @Component @ConditionalOnProperty(prefix = "elegent.pay.callback",name = "watch",havingValue = "true") @Slf4j public class CallbackWatch { @Autowired private CallBackService callBackService; @Autowired private CallbackConfig callbackConfig; @Autowired private ElegentPay elegentPay; @PostConstruct public void queryWatch(){ if(callbackConfig.getCycle()<=0){ return; } log.info("开启支付结果定期巡检"); Timer timer = new Timer(); // 2、创建 TimerTask 任务线程 TimerTask task=new TimerTask() { @Override public void run() { try{ //查询支付状态 log.info("支付状态定期巡检,{}",WatchList.payList); for( WatchDTO watchDTO: WatchList.payList ){ //查询订单是否支付成功
QueryResponse queryResponse = elegentPay.queryTradingOrderNo(watchDTO.getOrderSn(),watchDTO.getPlatform());
4
2023-12-02 08:25:08+00:00
2k
ExternalService/sft
src/main/java/com/nbnw/sft/config/ModConfig.java
[ { "identifier": "ConfigSyncPacket", "path": "src/main/java/com/nbnw/sft/network/ConfigSyncPacket.java", "snippet": "public class ConfigSyncPacket implements IMessage {\n @Override\n public void fromBytes(ByteBuf buf) {\n }\n @Override\n public void toBytes(ByteBuf buf) {\n }\n\n}" }, { "identifier": "ModEntry", "path": "src/main/java/com/nbnw/sft/ModEntry.java", "snippet": "@Mod(modid = ModEntry.MODID)\npublic class ModEntry\n{\n public static final String MODID = \"sft\";\n public static final String VERSION = \"1.4.0\";\n @Mod.Metadata\n public static ModMetadata metadata;\n // 指定客户端和服务器代理类的路径\n// @SidedProxy(clientSide = \"com.nbnw.sft.proxy.ClientProxy\", serverSide = \"com.nbnw.sft.proxy.ServerProxy\")\n// public static CommonProxy proxy;\n\n public static SimpleNetworkWrapper network;\n\n @EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n event.registerServerCommand(new CommandSFT()); // 注册玩家指令\n }\n\n @EventHandler\n public void preInit(FMLPreInitializationEvent event)\n {\n ModConfig.getInstance().init(event);\n MinecraftForge.EVENT_BUS.register(ModConfig.getInstance());\n // 创建代理实例\n// if (event.getSide().isClient()) {\n// proxy = new ClientProxy();\n// } else {\n// proxy = new CommonProxy();\n// }\n// proxy.init();\n\n // 初始化网络通道\n network = NetworkRegistry.INSTANCE.newSimpleChannel(MODID);\n\n // 注册数据包和处理器 0和1是该数据包通道的唯一标识 每个不同类型的数据包都应该有它唯一的标识\n // 四个参数:1 消息处理器类 2 数据包类 3 数据包通道 4 该数据包该在哪一边处理\n network.registerMessage(NetworkMessageDispatcher.class, CommonMessagePacket.class, 0, Side.CLIENT);\n network.registerMessage(NetworkMessageDispatcher.class, CommonMessagePacket.class, 1, Side.SERVER);\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event)\n {\n ModConfig.getInstance().checkAndResetConfigIfNeeded(); // 检查配置文件版本号并根据需要重置配置文件\n MinecraftForge.EVENT_BUS.register(ScreenMessageHandler.getInstance()); // 注册屏幕显示信息事件实例\n MinecraftForge.EVENT_BUS.register(ShowSleepPlayerCount.getInstance()); // 注册睡眠统计显示信息事件实例\n FMLCommonHandler.instance().bus().register(new PlayerLoginEventHandler()); // 玩家登陆事件\n MinecraftForge.EVENT_BUS.register(new PlayerLoginEventHandler()); // 玩家登陆事件\n MinecraftForge.EVENT_BUS.register(new PlayerSleepEventHandler()); // 玩家睡觉事件\n FMLCommonHandler.instance().bus().register(new PlayerBedStateHandler()); // 显示睡觉玩家比例\n }\n}" } ]
import com.nbnw.sft.network.ConfigSyncPacket; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.common.config.Configuration; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import java.io.File; import com.nbnw.sft.ModEntry;
1,197
package com.nbnw.sft.config; public class ModConfig { private static final String LANGUAGE = "language"; private static final String SEVERAL_PLAYER_SLEEP = "several_player_sleep"; private static final String CONFIG_VERSION = "config_version"; private static final String SPS_THRESHOLD = "sps_threshold"; private static final String LOGIN_MESSAGE = "login_message"; private static final int MESSAGE_COLOR = 0xE367E9; private Configuration config; // 保存单例实例 private static ModConfig instance; // 私有构造器 private ModConfig() { } public static ModConfig getInstance() { if (instance == null) { instance = new ModConfig(); } return instance; } public Configuration getConfig() { return this.config; } public void init(FMLPreInitializationEvent event) { File modConfigDir = new File(event.getModConfigurationDirectory(), ModEntry.metadata.modId); modConfigDir.mkdirs(); File configFile = new File(modConfigDir, "sft_config.cfg"); // create mod config file this.config = new Configuration(configFile); loadAndSyncConfig(); } // 加载和同步配置 public void loadAndSyncConfig() { // 加载配置 loadConfiguration(); // 同步到所有客户端 syncConfigToClients(); } // TODO 将配置数据同步到所有客户端 private void syncConfigToClients() { // 封装配置数据并发送到所有客户端 // 使用Forge网络包系统进行通信 } // TODO 客户端接收配置数据后,调用此方法同步配置
package com.nbnw.sft.config; public class ModConfig { private static final String LANGUAGE = "language"; private static final String SEVERAL_PLAYER_SLEEP = "several_player_sleep"; private static final String CONFIG_VERSION = "config_version"; private static final String SPS_THRESHOLD = "sps_threshold"; private static final String LOGIN_MESSAGE = "login_message"; private static final int MESSAGE_COLOR = 0xE367E9; private Configuration config; // 保存单例实例 private static ModConfig instance; // 私有构造器 private ModConfig() { } public static ModConfig getInstance() { if (instance == null) { instance = new ModConfig(); } return instance; } public Configuration getConfig() { return this.config; } public void init(FMLPreInitializationEvent event) { File modConfigDir = new File(event.getModConfigurationDirectory(), ModEntry.metadata.modId); modConfigDir.mkdirs(); File configFile = new File(modConfigDir, "sft_config.cfg"); // create mod config file this.config = new Configuration(configFile); loadAndSyncConfig(); } // 加载和同步配置 public void loadAndSyncConfig() { // 加载配置 loadConfiguration(); // 同步到所有客户端 syncConfigToClients(); } // TODO 将配置数据同步到所有客户端 private void syncConfigToClients() { // 封装配置数据并发送到所有客户端 // 使用Forge网络包系统进行通信 } // TODO 客户端接收配置数据后,调用此方法同步配置
public void onConfigSyncPacketReceived(ConfigSyncPacket packet) {
0
2023-11-29 15:20:07+00:00
2k
id681ilyg316/jsp_medicine_jxc
源码/jsp_medicine_jxc/src/com/medicine/action/AdminAction.java
[ { "identifier": "AdminDao", "path": "源码/jsp_medicine_jxc/src/com/medicine/dao/AdminDao.java", "snippet": "public class AdminDao {\r\n\r\n\t/**\r\n\t * ¹ÜÀíÔ±µÇ½\r\n\t * @throws Exception \r\n\t * */\r\n\tpublic Admin login(Admin admin,Connection con) throws Exception{\r\n\t\tAdmin resultAdmin = null;\r\n\t\tString sql = \"select * from t_admin where adminName=? and password=?\";\r\n\t\tPreparedStatement pstmt = con.prepareStatement(sql);\r\n\t\tpstmt.setString(1, admin.getAdminName());\r\n\t\tpstmt.setString(2, admin.getPassword());\r\n\t\tResultSet rs = pstmt.executeQuery();\r\n\t\twhile(rs.next()){\r\n\t\t\tresultAdmin = new Admin();\r\n\t\t\tresultAdmin.setAdminId(rs.getInt(\"adminId\"));\r\n\t\t\tresultAdmin.setAdminName(rs.getString(\"adminName\"));\r\n\t\t\tresultAdmin.setPassword(rs.getString(\"password\"));\r\n\t\t}\r\n\t\treturn resultAdmin;\t\r\n\t}\r\n\t/**\r\n\t * ÐÞ¸ÄÃÜÂë\r\n\t * */\r\n\tpublic int modifyPassword(Connection con,Admin admin)throws Exception{\r\n\t\tString sql=\"update t_admin set password=? where adminId=?\";\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sql);\r\n\t\tpstmt.setString(1, admin.getPassword());\r\n\t\tpstmt.setInt(2, admin.getAdminId());\r\n\t\treturn pstmt.executeUpdate();\r\n\t}\r\n}\r" }, { "identifier": "Admin", "path": "源码/jsp_medicine_jxc/src/com/medicine/model/Admin.java", "snippet": "public class Admin {\r\n\r\n\tprivate int adminId;\r\n\tprivate String adminName;\r\n\tprivate String password;\r\n\tpublic int getAdminId() {\r\n\t\treturn adminId;\r\n\t}\r\n\tpublic void setAdminId(int adminId) {\r\n\t\tthis.adminId = adminId;\r\n\t}\r\n\tpublic String getAdminName() {\r\n\t\treturn adminName;\r\n\t}\r\n\tpublic void setAdminName(String adminName) {\r\n\t\tthis.adminName = adminName;\r\n\t}\r\n\tpublic String getPassword() {\r\n\t\treturn password;\r\n\t}\r\n\tpublic void setPassword(String password) {\r\n\t\tthis.password = password;\r\n\t}\r\n\t\r\n\t\r\n}\r" }, { "identifier": "DbUtil", "path": "源码/jsp_medicine_jxc/src/com/medicine/util/DbUtil.java", "snippet": "public class DbUtil {\r\n\r\n\tpublic Connection getCon()throws Exception{\r\n\t\tClass.forName(PropertiesUtil.getValue(\"jdbcName\"));\r\n\t\tConnection con=DriverManager.getConnection(PropertiesUtil.getValue(\"dbUrl\"), PropertiesUtil.getValue(\"dbUserName\"), PropertiesUtil.getValue(\"dbPassword\"));\r\n\t\treturn con;\r\n\t}\r\n\t\r\n\tpublic void closeCon(Connection con)throws Exception{\r\n\t\tif(con!=null){\r\n\t\t\tcon.close();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\tDbUtil dbUtil=new DbUtil();\r\n\t\ttry {\r\n\t\t\tdbUtil.getCon();\r\n\t\t\tSystem.out.println(\"数据库连接成功\");\r\n\t\t} catch (Exception e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.out.println(\"数据库连接失败\");\r\n\t\t}\r\n\t}\r\n}\r" }, { "identifier": "NavUtil", "path": "源码/jsp_medicine_jxc/src/com/medicine/util/NavUtil.java", "snippet": "public class NavUtil {\r\n\r\n\tpublic static String getNavgation(String mainMenu,String subMenu){\r\n\t\tStringBuffer navCode=new StringBuffer();\r\n\t\tnavCode.append(\"µ±Ç°Î»Öãº&nbsp;&nbsp;\");\r\n\t\tnavCode.append(\"<a href='\"+PropertiesUtil.getValue(\"projectName\")+\"/main.jsp'>Ö÷Ò³</a>&nbsp;&nbsp;>&nbsp;&nbsp;\");\r\n\t\tnavCode.append(\"<a href='#'>\"+mainMenu+\"</a>&nbsp;&nbsp;>&nbsp;&nbsp;\");\r\n\t\tnavCode.append(\"<a href='#'>\"+subMenu+\"</a>\");\r\n\t\treturn navCode.toString();\r\n\t}\r\n}\r" }, { "identifier": "ResponseUtil", "path": "源码/jsp_medicine_jxc/src/com/medicine/util/ResponseUtil.java", "snippet": "public class ResponseUtil {\r\n\r\n\tpublic static void write(Object o,HttpServletResponse response)throws Exception{\r\n\t\tresponse.setContentType(\"text/html;charset=utf-8\");\r\n\t\tPrintWriter out=response.getWriter();\r\n\t\tout.println(o.toString());\r\n\t\tout.flush();\r\n\t\tout.close();\r\n\t}\r\n}\r" }, { "identifier": "StringUtil", "path": "源码/jsp_medicine_jxc/src/com/medicine/util/StringUtil.java", "snippet": "public class StringUtil {\r\n\r\n\t/**\r\n\t * 判断是否是空\r\n\t * @param str\r\n\t * @return\r\n\t */\r\n\tpublic static boolean isEmpty(String str){\r\n\t\tif(\"\".equals(str)|| str==null){\r\n\t\t\treturn true;\r\n\t\t}else{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * 判断是否不是空\r\n\t * @param str\r\n\t * @return\r\n\t */\r\n\tpublic static boolean isNotEmpty(String str){\r\n\t\tif(!\"\".equals(str)&&str!=null){\r\n\t\t\treturn true;\r\n\t\t}else{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n}\r" } ]
import java.sql.Connection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import com.medicine.dao.AdminDao; import com.medicine.model.Admin; import com.medicine.util.DbUtil; import com.medicine.util.NavUtil; import com.medicine.util.ResponseUtil; import com.medicine.util.StringUtil; import com.opensymphony.xwork2.ActionSupport; import net.sf.json.JSONObject;
1,573
package com.medicine.action; public class AdminAction extends ActionSupport implements ServletRequestAware { /** * */ private static final long serialVersionUID = 1L; private HttpServletRequest request; private Admin admin; private String error; private String imageCode; private int adminId; private String password; private String mainPage; private String navCode; public String getMainPage() { return mainPage; } public void setMainPage(String mainPage) { this.mainPage = mainPage; } public String getNavCode() { return navCode; } public void setNavCode(String navCode) { this.navCode = navCode; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAdminId() { return adminId; } public void setAdminId(int adminId) { this.adminId = adminId; } public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getImageCode() { return imageCode; } public void setImageCode(String imageCode) { this.imageCode = imageCode; } private AdminDao adminDao = new AdminDao() ;
package com.medicine.action; public class AdminAction extends ActionSupport implements ServletRequestAware { /** * */ private static final long serialVersionUID = 1L; private HttpServletRequest request; private Admin admin; private String error; private String imageCode; private int adminId; private String password; private String mainPage; private String navCode; public String getMainPage() { return mainPage; } public void setMainPage(String mainPage) { this.mainPage = mainPage; } public String getNavCode() { return navCode; } public void setNavCode(String navCode) { this.navCode = navCode; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAdminId() { return adminId; } public void setAdminId(int adminId) { this.adminId = adminId; } public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getImageCode() { return imageCode; } public void setImageCode(String imageCode) { this.imageCode = imageCode; } private AdminDao adminDao = new AdminDao() ;
private DbUtil dbUtil=new DbUtil();
2
2023-11-29 14:18:23+00:00
2k
PajangForever/pjfmod
src/main/java/name/pjfmod/zhuCeXiangMu/ShiTiZhuCe.java
[ { "identifier": "Pjfmod", "path": "src/main/java/name/pjfmod/Pjfmod.java", "snippet": "public class Pjfmod implements ModInitializer {\n\t// This logger is used to write text to the console and the log file.\n\t// It is considered best practice to use your mod id as the logger's name.\n\t// That way, it's clear which mod wrote info, warnings, and errors.\n\tpublic static final String MOD_ID = \"pjfmod\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"pjfmod\");\n\n\tpublic static final StatusEffect EXP = new ExpStatusEffect();\n\tpublic static FlowableFluid STILL_SLIVER;\n\tpublic static FlowableFluid FLOWING_SLIVER;\n\tpublic static Block FLUID_SLIVER_BLOCK;\n\n\t@Override\n\tpublic void onInitialize() {\n\t\t// This code runs as soon as Minecraft is in a mod-load-ready state.\n\t\t// However, some things (like resources) may still be uninitialized.\n\t\t// Proceed with mild caution.\n\n\t\tLOGGER.info(\"Hello Pajang! It's Fabric world!\");\n\n\t\tSTILL_SLIVER = Registry.register(Registries.FLUID, new Identifier(Pjfmod.MOD_ID, \"fluid_sliver\"), new SliverFluid.Still());\n\t\tFLOWING_SLIVER = Registry.register(Registries.FLUID, new Identifier(Pjfmod.MOD_ID, \"flowing_fluid_sliver\"), new SliverFluid.Flowing());\n\t\tFLUID_SLIVER_BLOCK = Registry.register(Registries.BLOCK, new Identifier(Pjfmod.MOD_ID,\"fluid_sliver_block\"), new FluidBlock(STILL_SLIVER, FabricBlockSettings.copy(Blocks.WATER)){});\n\n\t\tScreenHandlerZhuCe.zhuCeSuoYouScreenHandlers();\n\t\tWuPinZuZhuCe.zhuCeSuoYouWuPinZu();\n\t\tWuPinZhuCe.zhuCeSuoYouWuPin();\n\t\tFangKuaiZhuCe.zhuCeSuoYouFangKuai();\n\t\tDiWuZhuCe.zhuCeSuoYouDiWu();\n\t\tTianJiaDiWu.tianJiaSuoYouiDiWu();\n\t\tFangKuaiShiTiZhuCe.zhuCeSuoYouFangKuaiShiTi();\n\t\tFuMoZhuCe.zhuCeSuoYouFuMo();\n\t\tShiTiZhuCe.zhuCeSuoYouShiTi();\n\n\t\tRegistry.register(Registries.STATUS_EFFECT, new Identifier(Pjfmod.MOD_ID, \"exp\"), EXP);\n\n\t}\n}" }, { "identifier": "SliverCubeEntity", "path": "src/main/java/name/pjfmod/ziDingYi/SliverCubeEntity.java", "snippet": "public class SliverCubeEntity extends PathAwareEntity {\n public SliverCubeEntity(EntityType<? extends PathAwareEntity> entityType, World world) {\n super(entityType, world);\n }\n}" } ]
import name.pjfmod.Pjfmod; import name.pjfmod.ziDingYi.SliverCubeEntity; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricDefaultAttributeRegistry; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder; import net.minecraft.entity.*; import net.minecraft.entity.mob.PathAwareEntity; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier;
897
package name.pjfmod.zhuCeXiangMu; public class ShiTiZhuCe { public static final EntityType<SliverCubeEntity> SLIVER_CUBE = registerEntity("sliver_cube",SpawnGroup.CREATURE,SliverCubeEntity::new, 1.00f,1.25f); public static <T extends PathAwareEntity> EntityType<T> registerEntity(String name, SpawnGroup spawnGroup, EntityType.EntityFactory<T> factory, Float width, Float height){ EntityType<T> registeredEntity = Registry.register(Registries.ENTITY_TYPE,
package name.pjfmod.zhuCeXiangMu; public class ShiTiZhuCe { public static final EntityType<SliverCubeEntity> SLIVER_CUBE = registerEntity("sliver_cube",SpawnGroup.CREATURE,SliverCubeEntity::new, 1.00f,1.25f); public static <T extends PathAwareEntity> EntityType<T> registerEntity(String name, SpawnGroup spawnGroup, EntityType.EntityFactory<T> factory, Float width, Float height){ EntityType<T> registeredEntity = Registry.register(Registries.ENTITY_TYPE,
new Identifier(Pjfmod.MOD_ID, name),
0
2023-11-30 11:00:39+00:00
2k
AaronsonRossita/user-login-service
src/main/java/com/userLogin/service/AuthenticationServiceImpl.java
[ { "identifier": "CustomUserDetailsService", "path": "src/main/java/com/userLogin/security/CustomUserDetailsService.java", "snippet": "@Service\npublic class CustomUserDetailsService implements UserDetailsService {\n\n @Autowired\n private UserService userService;\n\n @Override\n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n CustomUser customUser = userService.findUserByUsername(username);\n\n if(customUser == null){\n throw new UsernameNotFoundException(\"The provided username can't be found\");\n }\n return User.withDefaultPasswordEncoder().username(customUser.getUsername()).password(customUser.getPassword()).roles().build();\n }\n}" }, { "identifier": "AuthenticationRequest", "path": "src/main/java/com/userLogin/security/model/AuthenticationRequest.java", "snippet": "public class AuthenticationRequest implements Serializable {\n\n private String username;\n private String password;\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n //need default constructor for JSON Parsing\n public AuthenticationRequest() {}\n\n public AuthenticationRequest(String username, String password) {\n this.setUsername(username);\n this.setPassword(password);\n }\n}" }, { "identifier": "AuthenticationResponse", "path": "src/main/java/com/userLogin/security/model/AuthenticationResponse.java", "snippet": "public class AuthenticationResponse implements Serializable {\n\n private final String jwt;\n\n public AuthenticationResponse(String jwt) {\n this.jwt = jwt;\n }\n\n public String getJwt() {\n return jwt;\n }\n}" }, { "identifier": "JwtUtil", "path": "src/main/java/com/userLogin/utils/JwtUtil.java", "snippet": "@Component\npublic class JwtUtil {\n\n private final String SECRET_KEY = \"secret\";\n\n public String extractUsername(String token) {\n return extractClaim(token, Claims::getSubject);\n }\n\n public Date extractExpiration(String token) {\n return extractClaim(token, Claims::getExpiration);\n }\n\n public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {\n final Claims claims = extractAllClaims(token);\n return claimsResolver.apply(claims);\n }\n private Claims extractAllClaims(String token) {\n return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();\n }\n\n private Boolean isTokenExpired(String token) {\n return extractExpiration(token).before(new Date());\n }\n\n public String generateToken(UserDetails userDetails) {\n Map<String, Object> claims = new HashMap<>();\n return createToken(claims, userDetails.getUsername());\n }\n\n private String createToken(Map<String, Object> claims, String subject) {\n\n return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))\n .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))\n .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();\n }\n\n public Boolean validateToken(String token, UserDetails userDetails) {\n final String username = extractUsername(token);\n return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));\n }\n}" } ]
import com.userLogin.security.CustomUserDetailsService; import com.userLogin.security.model.AuthenticationRequest; import com.userLogin.security.model.AuthenticationResponse; import com.userLogin.utils.JwtUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service;
861
package com.userLogin.service; @Service public class AuthenticationServiceImpl implements AuthenticationService { @Autowired
package com.userLogin.service; @Service public class AuthenticationServiceImpl implements AuthenticationService { @Autowired
private CustomUserDetailsService myUserDetailsService;
0
2023-11-27 15:31:37+00:00
2k
NerdyPuzzle/Configuration-files-plugin-MCreator
src/main/java/net/nerdypuzzle/configurationfiles/element/types/entries/JConfigVariablesList.java
[ { "identifier": "Config", "path": "src/main/java/net/nerdypuzzle/configurationfiles/element/types/Config.java", "snippet": "public class Config extends NamespacedGeneratableElement {\n\tpublic List<Config.Pool> pools;\n\tpublic String file;\n\tpublic int configType;\n\tpublic Config(ModElement element) {\n\t\tsuper(element);\n\t}\n\n\tpublic static class Pool {\n\t\tpublic String category;\n\t\tpublic List<Config.Pool.Entry> entries;\n\n\t\tpublic Pool() {\n\t\t}\n\n\t\tpublic static class Entry {\n\t\t\tpublic MItemBlock item;\n\t\t\tpublic int silkTouchMode;\n\t\t\tpublic MItemBlock block;\n\t\t\tpublic int logicField;\n\t\t\tpublic double numberField;\n\t\t\tpublic String textDefault;\n\t\t\tpublic String comment;\n\t\t\tpublic String vardisplay;\n\t\t\tpublic String varname;\n\t\t\tpublic Boolean enablecomment;\n\t\t\tpublic Boolean onlyComment;\n\n\t\t\tpublic String entityType;\n\t\t\tpublic Entry() {\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "JConfigVariable", "path": "src/main/java/net/nerdypuzzle/configurationfiles/element/types/entries/lists/JConfigVariable.java", "snippet": "public class JConfigVariable extends JEntriesList {\n\n private final VTextField category = new VTextField(13);\n private final List<JVariableEntry> entryList = new ArrayList();\n private final JPanel entries = new JPanel(new GridLayout(0, 1, 5, 5));\n\n public JConfigVariable(MCreator mcreator, IHelpContext gui, JPanel parent, List<JConfigVariable> pollList) {\n super(mcreator, new BorderLayout(), gui);\n this.setOpaque(false);\n JComponent container = PanelUtils.expandHorizontally(this);\n parent.add(container);\n pollList.add(this);\n this.setBackground(((Color)UIManager.get(\"MCreatorLAF.DARK_ACCENT\")).brighter());\n JPanel topbar = new JPanel(new FlowLayout(0));\n topbar.setOpaque(false);\n topbar.add(L10N.label(\"elementgui.config.categoryname\", new Object[0]));\n topbar.add(this.category);\n topbar.add(Box.createHorizontalGlue());\n JButton add = new JButton(UIRES.get(\"16px.add.gif\"));\n add.setText(L10N.t(\"elementgui.config.new_variable\", new Object[0]));\n JButton remove = new JButton(UIRES.get(\"16px.clear\"));\n remove.setText(L10N.t(\"elementgui.config.remove_category\", new Object[0]));\n remove.addActionListener((e) -> {\n pollList.remove(this);\n parent.remove(container);\n parent.revalidate();\n parent.repaint();\n });\n JComponent component = PanelUtils.centerAndEastElement(topbar, PanelUtils.join(2, new Component[]{add, remove}));\n component.setOpaque(true);\n component.setBackground(((Color)UIManager.get(\"MCreatorLAF.DARK_ACCENT\")).brighter());\n this.add(\"North\", component);\n this.entries.setOpaque(false);\n add.addActionListener((e) -> {\n JVariableEntry entry = new JVariableEntry(mcreator, this.entries, this.entryList);\n this.registerEntryUI(entry);\n });\n this.add(\"Center\", this.entries);\n this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder((Color)UIManager.get(\"MCreatorLAF.BRIGHT_COLOR\"), 1), L10N.t(\"elementgui.config.configcategory\", new Object[0]), 0, 0, this.getFont().deriveFont(12.0F), (Color)UIManager.get(\"MCreatorLAF.BRIGHT_COLOR\")));\n parent.revalidate();\n parent.repaint();\n }\n\n public void reloadDataLists() {\n this.entryList.forEach(JVariableEntry::reloadDataLists);\n }\n\n protected AggregatedValidationResult validatePage(int page) {\n return new AggregatedValidationResult(new IValidable[]{this.category});\n }\n\n public Config.Pool getPool() {\n Config.Pool pool = new Config.Pool();\n pool.category = this.category.getText();\n pool.entries = this.entryList.stream().map(JVariableEntry::getEntry).filter(Objects::nonNull).toList();\n return pool.entries.isEmpty() ? null : pool;\n }\n\n public void setPool(Config.Pool pool) {\n this.category.setText(pool.category);\n if (pool.entries != null) {\n pool.entries.forEach((e) -> {\n JVariableEntry entry = new JVariableEntry(this.mcreator, this.entries, this.entryList);\n this.registerEntryUI(entry);\n entry.setEntry(e);\n });\n }\n\n }\n}" } ]
import net.mcreator.ui.MCreator; import net.mcreator.ui.component.util.PanelUtils; import net.mcreator.ui.help.IHelpContext; import net.mcreator.ui.init.L10N; import net.mcreator.ui.minecraft.JEntriesList; import net.nerdypuzzle.configurationfiles.element.types.Config; import net.nerdypuzzle.configurationfiles.element.types.entries.lists.JConfigVariable; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Objects;
1,541
package net.nerdypuzzle.configurationfiles.element.types.entries; public class JConfigVariablesList extends JEntriesList { private final List<JConfigVariable> poolList = new ArrayList(); private final JPanel pools = new JPanel(new GridLayout(0, 1, 5, 5)); public JConfigVariablesList(MCreator mcreator, IHelpContext gui) { super(mcreator, new BorderLayout(), gui); this.setOpaque(false); this.pools.setOpaque(false); JToolBar bar = new JToolBar(); bar.setFloatable(false); this.add.setText(L10N.t("elementgui.config.new_category", new Object[0])); this.add.addActionListener((e) -> { JConfigVariable pool = new JConfigVariable(mcreator, gui, this.pools, this.poolList); this.registerEntryUI(pool); }); bar.add(this.add); this.add("North", bar); JScrollPane sp = new JScrollPane(PanelUtils.pullElementUp(this.pools)) { protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g.create(); g2d.setColor((Color)UIManager.get("MCreatorLAF.LIGHT_ACCENT")); g2d.setComposite(AlphaComposite.SrcOver.derive(0.45F)); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); g2d.dispose(); super.paintComponent(g); } }; sp.setOpaque(false); sp.getViewport().setOpaque(false); sp.getVerticalScrollBar().setUnitIncrement(11); sp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.add("Center", sp); } public void reloadDataLists() { this.poolList.forEach(JConfigVariable::reloadDataLists); }
package net.nerdypuzzle.configurationfiles.element.types.entries; public class JConfigVariablesList extends JEntriesList { private final List<JConfigVariable> poolList = new ArrayList(); private final JPanel pools = new JPanel(new GridLayout(0, 1, 5, 5)); public JConfigVariablesList(MCreator mcreator, IHelpContext gui) { super(mcreator, new BorderLayout(), gui); this.setOpaque(false); this.pools.setOpaque(false); JToolBar bar = new JToolBar(); bar.setFloatable(false); this.add.setText(L10N.t("elementgui.config.new_category", new Object[0])); this.add.addActionListener((e) -> { JConfigVariable pool = new JConfigVariable(mcreator, gui, this.pools, this.poolList); this.registerEntryUI(pool); }); bar.add(this.add); this.add("North", bar); JScrollPane sp = new JScrollPane(PanelUtils.pullElementUp(this.pools)) { protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g.create(); g2d.setColor((Color)UIManager.get("MCreatorLAF.LIGHT_ACCENT")); g2d.setComposite(AlphaComposite.SrcOver.derive(0.45F)); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); g2d.dispose(); super.paintComponent(g); } }; sp.setOpaque(false); sp.getViewport().setOpaque(false); sp.getVerticalScrollBar().setUnitIncrement(11); sp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.add("Center", sp); } public void reloadDataLists() { this.poolList.forEach(JConfigVariable::reloadDataLists); }
public List<Config.Pool> getPools() {
0
2023-12-01 10:17:08+00:00
2k
godheaven/klib-data-jdbc
src/test/java/cl/kanopus/jdbc/example/entity/TestViewData.java
[ { "identifier": "Mapping", "path": "src/main/java/cl/kanopus/jdbc/entity/Mapping.java", "snippet": "public abstract class Mapping implements Serializable {\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(Mapping.class);\r\n\r\n @Override\r\n public String toString() {\r\n\r\n Class<?> clase = this.getClass();\r\n Method[] methods = clase.getMethods();\r\n String result;\r\n Method method;\r\n\r\n StringBuilder aux = new StringBuilder(\"Class : [\" + this.getClass().getName() + \"]\\n\");\r\n Object obj;\r\n for (int i = 0; i < methods.length; i++) {\r\n if (methods[i].getName().startsWith(\"get\") && !methods[i].getName().equals(\"getClass\")) {\r\n try {\r\n method = methods[i];\r\n obj = method.invoke(this, (Object[]) null);\r\n if (obj != null) {\r\n result = obj.toString();\r\n } else {\r\n result = null;\r\n }\r\n aux.append(method.getName().substring(3)).append(\" : [\").append(result).append(\"]\\n\");\r\n\r\n } catch (SecurityException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) {\r\n LOGGER.error(ex.getMessage(), ex);\r\n }\r\n }\r\n }\r\n\r\n return aux.toString();\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "Status", "path": "src/test/java/cl/kanopus/jdbc/example/entity/enums/Status.java", "snippet": "public enum Status implements EnumIdentifiable<String>{\r\n ERROR,\r\n SUCCESS;\r\n\r\n @Override\r\n public String getId() {\r\n return this.name();\r\n }\r\n\r\n}\r" }, { "identifier": "Color", "path": "src/test/java/cl/kanopus/jdbc/example/entity/enums/Color.java", "snippet": "public enum Color implements EnumIdentifiable<Integer> {\r\n\r\n RED(1),\r\n BLACK(2);\r\n\r\n private int id;\r\n\r\n Color(int id) {\r\n this.id = id;\r\n }\r\n\r\n @Override\r\n public Integer getId() {\r\n return id;\r\n }\r\n\r\n}\r" }, { "identifier": "EnumParser", "path": "src/main/java/cl/kanopus/jdbc/util/parser/EnumParser.java", "snippet": "public abstract class EnumParser {\r\n\r\n private EnumParser() {\r\n throw new IllegalStateException(\"Utility class\");\r\n }\r\n\r\n public static <T extends Enum<T> & EnumIdentifiable<S>, S> T parse(Class<T> type, S id) {\r\n for (T t : type.getEnumConstants()) {\r\n if (t.getId().equals(id)) {\r\n return t;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n}\r" }, { "identifier": "JsonListParser", "path": "src/main/java/cl/kanopus/jdbc/util/parser/JsonListParser.java", "snippet": "public abstract class JsonListParser {\r\n\r\n private JsonListParser() {\r\n throw new IllegalStateException(\"Utility class\");\r\n }\r\n\r\n public static <T extends List<T>> T parse(Class<T> type, String json) {\r\n Type type2 = TypeToken.getParameterized(ArrayList.class, type).getType();\r\n return GsonUtils.custom.fromJson(json, type2);\r\n }\r\n\r\n}\r" }, { "identifier": "JsonParser", "path": "src/main/java/cl/kanopus/jdbc/util/parser/JsonParser.java", "snippet": "public abstract class JsonParser {\r\n\r\n private JsonParser() {\r\n }\r\n\r\n public static <T> T parse(Class<T> type, String json) {\r\n return GsonUtils.custom.fromJson(json, type);\r\n }\r\n\r\n}\r" } ]
import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.example.entity.enums.Status; import cl.kanopus.jdbc.example.entity.enums.Color; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.View; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import java.util.List;
1,059
package cl.kanopus.jdbc.example.entity; /** * @author Pablo Diaz Saavedra * @email [email protected] * */ @View("SELECT * FROM tmp_test_data") public class TestViewData extends Mapping { @Column(name = "pk_test_data", serial = true) private long id; @Column(name = "td_system_id") private long systemId; @Column(name = "td_login_id", length = 10) private String loginId; @Column(name = "td_date") private Date date; @Column(name = "td_local_date") private LocalDate localDate; @Column(name = "td_local_date_time") private LocalDateTime localDateTime;
package cl.kanopus.jdbc.example.entity; /** * @author Pablo Diaz Saavedra * @email [email protected] * */ @View("SELECT * FROM tmp_test_data") public class TestViewData extends Mapping { @Column(name = "pk_test_data", serial = true) private long id; @Column(name = "td_system_id") private long systemId; @Column(name = "td_login_id", length = 10) private String loginId; @Column(name = "td_date") private Date date; @Column(name = "td_local_date") private LocalDate localDate; @Column(name = "td_local_date_time") private LocalDateTime localDateTime;
@Column(name = "td_status", parser = EnumParser.class, parserResult = Status.class)
3
2023-11-27 18:25:00+00:00
2k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/renderer/HudRenderer.java
[ { "identifier": "ClientState", "path": "src/client/java/me/andre111/voxedit/client/ClientState.java", "snippet": "@Environment(value=EnvType.CLIENT)\npublic class ClientState {\n\tpublic static ClientPlayerEntity player;\n\tpublic static ToolItem.Data active;\n\tpublic static BlockHitResult target;\n\t\n\tpublic static Set<BlockPos> positions;\n\t\n\tpublic static float cameraSpeed = 2f;\n}" }, { "identifier": "ToolSettingsScreen", "path": "src/client/java/me/andre111/voxedit/client/gui/screen/ToolSettingsScreen.java", "snippet": "@Environment(value=EnvType.CLIENT)\npublic class ToolSettingsScreen extends Screen {\n\tprivate int contentWidth = 100;\n\tprivate int contentHeight = 96;\n\tprivate int padding = 2;\n\t\n\tprivate TextWidget toolName;\n\tprivate List<ToolSettingWidget<?, ?, ?>> toolSettingWidgets;\n\tprivate Tool<?, ?> lastTool = null;\n\n\tpublic ToolSettingsScreen() {\n\t\tsuper(Text.translatable(\"voxedit.screen.toolSettings\"));\n\t\trebuild();\n\t}\n\t\n\tpublic void rebuild() {\n\t\tif(ClientState.active == null) return;\n\t\tif(lastTool != ClientState.active.selected().tool()) {\n\t\t\tlastTool = ClientState.active.selected().tool();\n\t\t\tinit(MinecraftClient.getInstance(), MinecraftClient.getInstance().getWindow().getScaledWidth(), MinecraftClient.getInstance().getWindow().getScaledHeight());\n\t\t} else {\n\t\t\treload();\n\t\t}\n\t}\n\t\n\tprivate void reload() {\n\t\tif(ClientState.active == null) return;\n\n\t\t// (re)load name display\n\t\tMutableText name = Text.translatable(\"voxedit.tool\").copy().append(\": \").append(ClientState.active.selected().tool().asText());\n\t\tif(ClientState.active.size() > 1) {\n\t\t\tname = name.append(\" (\"+(ClientState.active.selectedIndex()+1)+\"/\"+ClientState.active.size()+\")\");\n\t\t}\n\t\ttoolName.setMessage(name);\n\t\t\n\t\t// reload settings\n\t\tfor(var setting : toolSettingWidgets) {\n\t\t\tsetting.reload();\n\t\t}\n\t}\n\t\t\n\n\t@Override\n\tprotected void init() {\n\t\tcontentWidth = 100;\n\t\tcontentHeight = 8+12;\n\t\tif(ClientState.active == null) return;\n\n\t\ttoolSettingWidgets = new ArrayList<>();\n\t\tfor(var toolSetting : ClientState.active.selected().config().settings().get()) {\n\t\t\ttoolSettingWidgets.add(ToolSettingWidget.of(toolSetting));\n\t\t}\n\t\tcontentHeight += (toolSettingWidgets.size()+1) * 22;\n\t\t\n\t\tint x = 2+padding;\n\t\tint y = (height-contentHeight-padding*2) / 2;\n\t\t\n\t\t// title\n\t\tint currentY = y;\n\t\taddDrawableChild(new TextWidget(x, currentY, contentWidth, 14, Text.translatable(\"voxedit.screen.toolSettings\"), textRenderer).alignCenter());\n\t\tcurrentY += 12;\n\t\taddDrawableChild(toolName = new TextWidget(x, currentY, contentWidth, 14, Text.empty(), textRenderer).alignCenter());\n\t\tcurrentY += 12;\n\t\t\n\t\t// change tool button\n\t\taddDrawableChild(ButtonWidget.builder(Text.translatable(\"voxedit.screen.toolSettings.changeTool\"), (button) -> {\n\t\t\tInputScreen.getSelector(this, Text.translatable(\"voxedit.screen.toolSettings.changeToolTitle\"), Text.translatable(\"voxedit.tool\"), ClientState.active.selected().tool(), VoxEdit.TOOL_REGISTRY.stream().toList(), Tool::asText, (newTool) -> {\n\t\t\t\tClientNetworking.setTool(newTool.getDefault());\n\t\t\t});\n\t\t}).dimensions(x, currentY, contentWidth, 20).build());\n\t\tcurrentY += 22;\n\t\t\n\t\t// tool settings\n\t\tfor(var setting : toolSettingWidgets) {\n\t\t\tfor(var e : setting.create(this, x, currentY, contentWidth, 20)) {\n\t\t\t\taddDrawableChild(e);\n\t\t\t}\n\t\t\tcurrentY += 22;\n\t\t}\n\t\t\n\t\treload();\n\t}\n\t\n\t@Override\n\tpublic void renderInGameBackground(DrawContext context) {\n\t\tint x = 2;\n\t\tint y = (context.getScaledWindowHeight()-contentHeight-padding*2) / 2;\n context.fillGradient(x, y, x + contentWidth + padding * 2, y + contentHeight + padding * 2, -1072689136, -804253680);\n }\n\t\n\t@Override\n\tpublic void close() {\n\t\tsetFocused(null);\n\t\tsuper.close();\n\t}\n}" } ]
import me.andre111.voxedit.client.ClientState; import me.andre111.voxedit.client.gui.screen.ToolSettingsScreen; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext;
1,514
/* * Copyright (c) 2023 André Schweiger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.andre111.voxedit.client.renderer; @Environment(value=EnvType.CLIENT) public class HudRenderer implements HudRenderCallback { private static ToolSettingsScreen TOOL_SETTINGS; public static void init() { HudRenderCallback.EVENT.register(new HudRenderer()); } public static ToolSettingsScreen getToolSettingsScreen() { if(TOOL_SETTINGS == null) TOOL_SETTINGS = new ToolSettingsScreen(); return TOOL_SETTINGS; } @Override public void onHudRender(DrawContext drawContext, float tickDelta) { var currentScreen = MinecraftClient.getInstance().currentScreen; if(currentScreen != null) { if(currentScreen == getToolSettingsScreen()) { int width = MinecraftClient.getInstance().getWindow().getScaledWidth(); int height = MinecraftClient.getInstance().getWindow().getScaledHeight(); drawContext.fillGradient(0, 0, width, height, 0xA0101010, 0xB0101010); drawContext.drawCenteredTextWithShadow(MinecraftClient.getInstance().textRenderer, "<- Edit Tool Settings", width/2, height/2, 0xFFFFFFFF); } return; }
/* * Copyright (c) 2023 André Schweiger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.andre111.voxedit.client.renderer; @Environment(value=EnvType.CLIENT) public class HudRenderer implements HudRenderCallback { private static ToolSettingsScreen TOOL_SETTINGS; public static void init() { HudRenderCallback.EVENT.register(new HudRenderer()); } public static ToolSettingsScreen getToolSettingsScreen() { if(TOOL_SETTINGS == null) TOOL_SETTINGS = new ToolSettingsScreen(); return TOOL_SETTINGS; } @Override public void onHudRender(DrawContext drawContext, float tickDelta) { var currentScreen = MinecraftClient.getInstance().currentScreen; if(currentScreen != null) { if(currentScreen == getToolSettingsScreen()) { int width = MinecraftClient.getInstance().getWindow().getScaledWidth(); int height = MinecraftClient.getInstance().getWindow().getScaledHeight(); drawContext.fillGradient(0, 0, width, height, 0xA0101010, 0xB0101010); drawContext.drawCenteredTextWithShadow(MinecraftClient.getInstance().textRenderer, "<- Edit Tool Settings", width/2, height/2, 0xFFFFFFFF); } return; }
if(ClientState.active == null) return;
0
2023-12-01 15:12:26+00:00
2k
sammierosado/liftoff-group-1
VenuApp/src/main/java/infinitycodecrew/VenuApp/controllers/EventController.java
[ { "identifier": "Event", "path": "VenuApp/src/main/java/infinitycodecrew/VenuApp/models/Event.java", "snippet": "@Entity\npublic class Event extends AbstractEntity {\n\n private String eventName;\n\n private double price;\n\n @ManyToOne\n @JoinColumn(name=\"artist_id\")\n private Artist artist;\n\n @ManyToOne\n @JoinColumn(name=\"venue_id\")\n private Venue venue;\n\n @Lob\n @Column(name = \"flyer_image\", columnDefinition = \"LONGBLOB\")\n private byte[] flyerImage;\n\n @Column(name = \"flyer_content_type\")\n private String flyerContentType;\n\n\n @DateTimeFormat(pattern = \"MM-dd-yyyy\")\n private LocalDate date;\n\n public Event() {\n\n }\n// public Event(String eventName, double price, LocalDate date) {\n// this.eventName = eventName;\n// this.price = price;\n// this.date = date;\n// }\n\n public Event(String eventName, double price, Artist artist, Venue venue, LocalDate date) {\n this.eventName = eventName;\n this.price = price;\n this.artist = artist;\n this.venue = venue;\n this.date = date;\n }\n\n public String getEventName() {\n return eventName;\n }\n\n public void setEventName(String eventName) {\n this.eventName = eventName;\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 LocalDate getDate() {\n return date;\n }\n\n public void setDate(LocalDate date) {\n this.date = date;\n }\n\n public Artist getArtist() {\n return artist;\n }\n\n public void setArtist(Artist artist) {\n this.artist = artist;\n }\n\n public Venue getVenue() {\n return venue;\n }\n\n public void setVenue(Venue venue) {\n this.venue = venue;\n }\n\n public byte[] getFlyerImage() {\n return flyerImage;\n }\n\n public void setFlyerImage(byte[] flyerImage) {\n this.flyerImage = flyerImage;\n }\n\n public String getFlyerContentType() {\n return flyerContentType;\n }\n\n public void setFlyerContentType(String flyerContentType) {\n this.flyerContentType = flyerContentType;\n }\n}" }, { "identifier": "ArtistRepository", "path": "VenuApp/src/main/java/infinitycodecrew/VenuApp/models/data/ArtistRepository.java", "snippet": "public interface ArtistRepository extends CrudRepository<Artist, Integer> {\n}" }, { "identifier": "EventRepository", "path": "VenuApp/src/main/java/infinitycodecrew/VenuApp/models/data/EventRepository.java", "snippet": "public interface EventRepository extends CrudRepository<Event, Integer> {\n}" }, { "identifier": "VenueRepository", "path": "VenuApp/src/main/java/infinitycodecrew/VenuApp/models/data/VenueRepository.java", "snippet": "public interface VenueRepository extends CrudRepository<Venue, Integer>{\n}" } ]
import infinitycodecrew.VenuApp.models.Event; import infinitycodecrew.VenuApp.models.data.ArtistRepository; import infinitycodecrew.VenuApp.models.data.EventRepository; import infinitycodecrew.VenuApp.models.data.VenueRepository; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException;
906
package infinitycodecrew.VenuApp.controllers; @Controller @RequestMapping("/events") public class EventController { @Autowired private EventRepository eventRepository; @Autowired
package infinitycodecrew.VenuApp.controllers; @Controller @RequestMapping("/events") public class EventController { @Autowired private EventRepository eventRepository; @Autowired
private ArtistRepository artistRepository;
1
2023-11-27 21:16:19+00:00
2k
litongjava/java-ee-t-io-study
tio-websocket-showcase/src/main/java/org/tio/showcase/Starter.java
[ { "identifier": "HttpServerInit", "path": "tio-websocket-showcase/src/main/java/org/tio/showcase/http/init/HttpServerInit.java", "snippet": "public class HttpServerInit {\n\t@SuppressWarnings(\"unused\")\n\tprivate static Logger log = LoggerFactory.getLogger(HttpServerInit.class);\n\n\tpublic static HttpConfig httpConfig;\n\n\tpublic static HttpRequestHandler requestHandler;\n\n\tpublic static HttpServerStarter httpServerStarter;\n\n\tpublic static ServerTioConfig serverTioConfig;\n\n\tpublic static void init() throws Exception {\n\t\t//\t\tlong start = SystemTimer.currTime;\n\n\t\tint port = P.getInt(\"http.port\");//启动端口\n\t\tString pageRoot = P.get(\"http.page\");//html/css/js等的根目录,支持classpath:,也支持绝对路径\n\t\thttpConfig = new HttpConfig(port, null, null, null);\n\t\thttpConfig.setPageRoot(pageRoot);\n\t\thttpConfig.setMaxLiveTimeOfStaticRes(P.getInt(\"http.maxLiveTimeOfStaticRes\"));\n\t\thttpConfig.setPage404(P.get(\"http.404\"));\n\t\thttpConfig.setPage500(P.get(\"http.500\"));\n\t\thttpConfig.setUseSession(false);\n\t\thttpConfig.setCheckHost(false);\n\n\t\trequestHandler = new DefaultHttpRequestHandler(httpConfig, HttpServerShowcaseStarter.class);//第二个参数也可以是数组\n\n\t\thttpServerStarter = new HttpServerStarter(httpConfig, requestHandler);\n\t\tserverTioConfig = httpServerStarter.getServerTioConfig();\n\t\thttpServerStarter.start(); //启动http服务器\n\n//\t\tString protocol = SslUtils.isSsl(serverTioConfig) ? \"https\" : \"http\";\n\n\t\t//\t\tlong end = SystemTimer.currTime;\n\t\t//\t\tlong iv = end - start;\n\t\t//\t\tif (log.isInfoEnabled()) {\n\t\t//\t\t\tlog.info(\"\\r\\nTio Http Server启动完毕,耗时:{}ms\\r\\n访问地址:{}://127.0.0.1:{}\", iv, protocol, port);\n\t\t//\t\t} else {\n\t\t//\t\t\tSystem.out.println(\"\\r\\nTio Http Server启动完毕,耗时:\" + iv + \"ms,\\r\\n访问地址:\" + protocol + \"://127.0.0.1:\" + port);\n\t\t//\t\t}\n\t}\n\n}" }, { "identifier": "ShowcaseWebsocketStarter", "path": "tio-websocket-showcase/src/main/java/org/tio/showcase/websocket/server/ShowcaseWebsocketStarter.java", "snippet": "public class ShowcaseWebsocketStarter {\n\n\tprivate WsServerStarter wsServerStarter;\n\tprivate ServerTioConfig serverTioConfig;\n\n\t/**\n\t *\n\t * @author tanyaowu\n\t */\n\tpublic ShowcaseWebsocketStarter(int port, ShowcaseWsMsgHandler wsMsgHandler) throws Exception {\n\t\twsServerStarter = new WsServerStarter(port, wsMsgHandler);\n\n\t\tserverTioConfig = wsServerStarter.getServerTioConfig();\n\t\tserverTioConfig.setName(ShowcaseServerConfig.PROTOCOL_NAME);\n\t\tserverTioConfig.setServerAioListener(ShowcaseServerAioListener.me);\n\n\t\t//设置ip监控\n\t\tserverTioConfig.setIpStatListener(ShowcaseIpStatListener.me);\n\t\t//设置ip统计时间段\n\t\tserverTioConfig.ipStats.addDurations(ShowcaseServerConfig.IpStatDuration.IPSTAT_DURATIONS);\n\t\t\n\t\t//设置心跳超时时间\n\t\tserverTioConfig.setHeartbeatTimeout(ShowcaseServerConfig.HEARTBEAT_TIMEOUT);\n\t\t\n\t\tif (P.getInt(\"ws.use.ssl\", 1) == 1) {\n\t\t\t//如果你希望通过wss来访问,就加上下面的代码吧,不过首先你得有SSL证书(证书必须和域名相匹配,否则可能访问不了ssl)\n//\t\t\tString keyStoreFile = \"classpath:config/ssl/keystore.jks\";\n//\t\t\tString trustStoreFile = \"classpath:config/ssl/keystore.jks\";\n//\t\t\tString keyStorePwd = \"214323428310224\";\n\t\t\t\n\t\t\t\n\t\t\tString keyStoreFile = P.get(\"ssl.keystore\", null);\n\t\t\tString trustStoreFile = P.get(\"ssl.truststore\", null);\n\t\t\tString keyStorePwd = P.get(\"ssl.pwd\", null);\n\t\t\tserverTioConfig.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);\n\t\t}\n\t}\n\n\t/**\n\t * @param args\n\t * @author tanyaowu\n\t * @throws IOException\n\t */\n\tpublic static void start() throws Exception {\n\t\tShowcaseWebsocketStarter appStarter = new ShowcaseWebsocketStarter(ShowcaseServerConfig.SERVER_PORT, ShowcaseWsMsgHandler.me);\n\t\tappStarter.wsServerStarter.start();\n\t}\n\n\t/**\n\t * @return the serverTioConfig\n\t */\n\tpublic ServerTioConfig getServerTioConfig() {\n\t\treturn serverTioConfig;\n\t}\n\n\tpublic WsServerStarter getWsServerStarter() {\n\t\treturn wsServerStarter;\n\t}\n\t\n\tpublic static void main(String[] args) throws Exception {\n\t\t//启动http server,这个步骤不是必须的,但是为了用页面演示websocket,所以先启动http\n\t\tP.use(\"app.properties\");\n\t\t\n\t\t\n\t\tif (P.getInt(\"start.http\", 1) == 1) {\n\t\t\tHttpServerInit.init();\n\t\t}\n\t\t\n\t\t//启动websocket server\n\t\tstart();\n\t}\n\n}" } ]
import org.tio.showcase.http.init.HttpServerInit; import org.tio.showcase.websocket.server.ShowcaseWebsocketStarter; import org.tio.utils.jfinal.P;
1,519
package org.tio.showcase; /** * @author tanyaowu */ public class Starter { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //加载属性文件 P.use("app.properties"); //启动http server,这个步骤不是必须的,但是为了用页面演示websocket,所以先启动http if (P.getInt("start.http", 1) == 1) {
package org.tio.showcase; /** * @author tanyaowu */ public class Starter { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //加载属性文件 P.use("app.properties"); //启动http server,这个步骤不是必须的,但是为了用页面演示websocket,所以先启动http if (P.getInt("start.http", 1) == 1) {
HttpServerInit.init();
0
2023-12-01 16:23:37+00:00
2k
victor-vilar/coleta
backend/src/main/java/com/victorvilar/projetoempresa/mappers/ApplicationUserMapper.java
[ { "identifier": "ApplicationUser", "path": "backend/src/main/java/com/victorvilar/projetoempresa/domain/ApplicationUser.java", "snippet": "@Entity\n@Table(name=\"application_users\")\npublic class ApplicationUser implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String username;\n private String password;\n private String profilePhotoUrl;\n\n public String getProfilePhotoUrl() {\n return profilePhotoUrl;\n }\n\n public void setProfilePhotoUrl(String profilePhotoUrl) {\n this.profilePhotoUrl = profilePhotoUrl;\n }\n\n @ManyToMany\n @JoinTable(name=\"users_roles\", joinColumns = @JoinColumn(name=\"application_user_id\"),inverseJoinColumns = @JoinColumn(name=\"role_id\"))\n private Set<ApplicationUserRole> applicationUserRoles = new HashSet<>();\n\n\n public ApplicationUser() {\n }\n\n public ApplicationUser(Long id, String username, String password, Set<ApplicationUserRole> applicationUserRoles) {\n this.id = id;\n this.username = username;\n this.password = password;\n this.applicationUserRoles = applicationUserRoles;\n }\n\n public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getUsername() {\n return username;\n }\n public void setUsername(String username) {\n this.username = username;\n }\n\n\n @Override\n public String getPassword() {\n return this.password;\n }\n public void setPassword(String password){this.password = password;}\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return this.applicationUserRoles;\n }\n public void setRoles(Set<ApplicationUserRole> roles){\n this.applicationUserRoles = roles;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n @Override\n public boolean isEnabled() {\n return true;\n }\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 ApplicationUser that = (ApplicationUser) o;\n return Objects.equals(id, that.id) && Objects.equals(username, that.username) && Objects.equals(password, that.password) && Objects.equals(applicationUserRoles, that.applicationUserRoles);\n }\n\n}" }, { "identifier": "ApplicationUserDto", "path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/applicationuser/ApplicationUserDto.java", "snippet": "public class ApplicationUserDto {\n\n\n @NotNull(message = \"The user must have a username\")\n private String username;\n @NotNull(message = \"the user must have a password\")\n private String password;\n @NotNull(message=\"the user must have at least one role\")\n private Set<String> roles = new HashSet<>();\n\n private String profilePhotoUrl;\n\n public String getProfilePhotoUrl() {\n return profilePhotoUrl;\n }\n\n public void setProfilePhotoUrl(String profilePhotoUrl) {\n this.profilePhotoUrl = profilePhotoUrl;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Set<String> getRoles() {\n return roles;\n }\n\n public void setRoles(List<String> roles) {\n roles.forEach(role -> this.roles.add(role));\n\n }\n}" }, { "identifier": "ApplicationUserResponseDto", "path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/applicationuser/ApplicationUserResponseDto.java", "snippet": "public class ApplicationUserResponseDto {\n\n\n private String username;\n private Set<String> roles = new HashSet<>();\n private String profilePhotoUrl;\n\n\n\n public String getProfilePhotoUrl(){\n return this.profilePhotoUrl;\n }\n\n public void setProfilePhotoUrl(String url){\n this.profilePhotoUrl = url;\n }\n\n\n public String getUsername() {\n return username;\n }\n public void setUsername(String username) {\n this.username = username;\n }\n public Set<String> getRoles() {\n return roles;\n }\n public void setRoles(Set<String> roles) {\n this.roles = roles;\n }\n\n public ApplicationUserResponseDto(){\n\n }\n\n public static ApplicationUserResponseDtoBuilder builder(){\n return new ApplicationUserResponseDtoBuilder();\n }\n\n public static class ApplicationUserResponseDtoBuilder{\n\n private String username;\n private Set<String> roles = new HashSet<>();\n private String perfilPhotoUrl;\n\n public ApplicationUserResponseDtoBuilder username(String username){\n this.username =username;\n return this;\n }\n\n public ApplicationUserResponseDtoBuilder roles(Collection<? extends GrantedAuthority> roles){\n this.roles = (Set<String>)roles.stream().map(role -> role.getAuthority()).collect(Collectors.toSet());\n return this;\n }\n\n public ApplicationUserResponseDtoBuilder perfilPhotoUrl(String url){\n this.perfilPhotoUrl = url;\n return this;\n }\n\n public ApplicationUserResponseDto build(){\n ApplicationUserResponseDto responseDto = new ApplicationUserResponseDto();\n responseDto.setUsername(this.username);\n responseDto.setRoles(this.roles);\n responseDto.setProfilePhotoUrl(this.perfilPhotoUrl);\n return responseDto;\n }\n\n }\n}" } ]
import com.victorvilar.projetoempresa.domain.ApplicationUser; import com.victorvilar.projetoempresa.dto.applicationuser.ApplicationUserDto; import com.victorvilar.projetoempresa.dto.applicationuser.ApplicationUserResponseDto; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Component; import java.util.stream.Collectors;
1,496
package com.victorvilar.projetoempresa.mappers; @Component public class ApplicationUserMapper { private final ModelMapper mapper; public ApplicationUserMapper(ModelMapper mapper){ this.mapper=mapper; }
package com.victorvilar.projetoempresa.mappers; @Component public class ApplicationUserMapper { private final ModelMapper mapper; public ApplicationUserMapper(ModelMapper mapper){ this.mapper=mapper; }
public ApplicationUser toApplicationUser(ApplicationUserDto userDto){
1
2023-12-02 21:29:33+00:00
2k
aliyun/aliyun-pairec-config-java-sdk
src/main/java/com/aliyun/openservices/pairec/api/ParamApi.java
[ { "identifier": "Constants", "path": "src/main/java/com/aliyun/openservices/pairec/common/Constants.java", "snippet": "public class Constants {\n public static final String CODE_OK = \"OK\";\n public static final String Environment_Daily_Desc = \"daily\";\n public static final String Environment_Prepub_Desc = \"prepub\";\n\n public static final String Environment_Product_Desc = \"product\";\n\n public static int ExpRoom_Status_Offline = 1;\n public static int ExpRoom_Status_Online = 2;\n\n public static int ExpGroup_Status_Offline = 1;\n public static int ExpGroup_Status_Online = 2;\n\n public static final int ExpGroup_Distribution_Type_User = 1;\n\n public static final int ExpGroup_Distribution_Type_TimeDuration = 2;\n\n public static int Experiment_Status_Offline = 1;\n public static int Experiment_Status_Online = 2;\n\n public static int Bucket_Type_UID = 1;\n public static int Bucket_Type_UID_HASH = 2;\n public static int Bucket_Type_Custom = 3;\n public static int Bucket_Type_Filter = 4;\n\n public static int ExpRoom_Type_Base = 1;\n public static int ExpRoom_Type_Normal = 2;\n\n public static final int Experiment_Type_Base = 1;\n public static final int Experiment_Type_Test = 2;\n public static final int Experiment_Type_Default = 3;\n\n public static String environmentDesc2OpenApiString(String environment) {\n if (environment.equals(Environment_Daily_Desc)) {\n return \"Daily\";\n } else if (environment.equals(Environment_Prepub_Desc)) {\n return \"Pre\";\n } else if (environment.equals(Environment_Product_Desc)) {\n return \"Prod\";\n }\n\n return \"\";\n }\n\n}" }, { "identifier": "Param", "path": "src/main/java/com/aliyun/openservices/pairec/model/Param.java", "snippet": "public class Param {\n @SerializedName(\"param_id\")\n private Long paramId = null;\n\n @SerializedName(\"scene_id\")\n private Long sceneId = null;\n\n @SerializedName(\"param_name\")\n private String paramName = null;\n\n @SerializedName(\"param_value\")\n private String paramValue = null;\n\n @SerializedName(\"environment\")\n private String environment = null;\n\n public Param paramId(Long paramId) {\n this.paramId = paramId;\n return this;\n }\n\n /**\n * Get paramId\n * @return paramId\n **/\n public Long getParamId() {\n return paramId;\n }\n\n public void setParamId(Long paramId) {\n this.paramId = paramId;\n }\n\n public Param sceneId(Long sceneId) {\n this.sceneId = sceneId;\n return this;\n }\n\n /**\n * Get sceneId\n * @return sceneId\n **/\n public Long getSceneId() {\n return sceneId;\n }\n\n public void setSceneId(Long sceneId) {\n this.sceneId = sceneId;\n }\n\n public Param paramName(String paramName) {\n this.paramName = paramName;\n return this;\n }\n\n /**\n * Get paramName\n * @return paramName\n **/\n public String getParamName() {\n return paramName;\n }\n\n public void setParamName(String paramName) {\n this.paramName = paramName;\n }\n\n public Param paramValue(String paramValue) {\n this.paramValue = paramValue;\n return this;\n }\n\n /**\n * Get paramValue\n * @return paramValue\n **/\n public String getParamValue() {\n return paramValue;\n }\n\n public void setParamValue(String paramValue) {\n this.paramValue = paramValue;\n }\n\n public Param environment(String environment) {\n this.environment = environment;\n return this;\n }\n\n /**\n * Get environment\n * @return environment\n **/\n public String getEnvironment() {\n return environment;\n }\n\n public void setEnvironment(String environment) {\n this.environment = environment;\n }\n\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Param param = (Param) o;\n return Objects.equals(this.paramId, param.paramId) &&\n Objects.equals(this.sceneId, param.sceneId) &&\n Objects.equals(this.paramName, param.paramName) &&\n Objects.equals(this.paramValue, param.paramValue) &&\n Objects.equals(this.environment, param.environment);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(paramId, sceneId, paramName, paramValue, environment);\n }\n\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Param {\\n\");\n \n sb.append(\" paramId: \").append(toIndentedString(paramId)).append(\"\\n\");\n sb.append(\" sceneId: \").append(toIndentedString(sceneId)).append(\"\\n\");\n sb.append(\" paramName: \").append(toIndentedString(paramName)).append(\"\\n\");\n sb.append(\" paramValue: \").append(toIndentedString(paramValue)).append(\"\\n\");\n sb.append(\" environment: \").append(toIndentedString(environment)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n\n}" } ]
import com.aliyun.openservices.pairec.common.Constants; import com.aliyun.openservices.pairec.model.Param; import com.aliyun.pairecservice20221213.models.ListParamsRequest; import com.aliyun.pairecservice20221213.models.ListParamsResponse; import com.aliyun.pairecservice20221213.models.ListParamsResponseBody; import java.util.ArrayList; import java.util.List;
1,550
package com.aliyun.openservices.pairec.api; public class ParamApi extends BaseApi { public ParamApi(ApiClient apiClient) { super(apiClient); }
package com.aliyun.openservices.pairec.api; public class ParamApi extends BaseApi { public ParamApi(ApiClient apiClient) { super(apiClient); }
public List<Param> getParam(Long sceneId, String environment, Long paramId, String paramName) throws Exception {
1
2023-11-29 06:27:36+00:00
2k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/mods/minetweaker/CTILiquidStackExpansion.java
[ { "identifier": "IMaterialData", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterialData.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterialData\")\npublic interface IMaterialData {\n\t@ZenMethod\n\tpublic static IMaterialData association(IItemStack item) {\n\t\tOreDictItemData data = OreDictManager.INSTANCE.getAssociation(MineTweakerMC.getItemStack(item), F);\n\t\tif (data != null) return new CTMaterialData(data);\n\t\tMineTweakerAPI.logError(item + \" dose not have a GT Association!\");\n\t\treturn null;\n\t}\n\n\t@ZenMethod\n\tpublic static IMaterialData association(ILiquidStack iLiquidStack) {\n\t\tOreDictMaterialStack stack = OreDictMaterial.FLUID_MAP.get(MineTweakerMC.getLiquidStack(iLiquidStack).getFluid().getName());\n\t\tif (stack != null) {\n\t\t\tOreDictItemData data = new OreDictItemData(stack);\n\t\t\treturn new CTMaterialData(data);\n\t\t}\n\t\tMineTweakerAPI.logError(iLiquidStack + \" dose not have a GT Association!\");\n\t\treturn null;\n\t}\n\n\t@ZenMethod\n\tpublic static IMaterialData association(IOreDictEntry ore) {\n\t\tOreDictItemData data = OreDictManager.INSTANCE.getAutomaticItemData(ore.getName());\n\t\tif (data != null) return new CTMaterialData(data);\n\t\tMineTweakerAPI.logError(ore + \" dose not have a GT Association!\");\n\t\treturn null;\n\t}\n\n\t@ZenGetter\n\tIMaterialStack material();\n\n\t@ZenGetter\n\tIPrefix prefix();\n\n\t@ZenGetter\n\tList<IMaterialStack> byProducts();\n\n\t@ZenGetter\n\tList<IMaterialStack> materials();\n}" }, { "identifier": "CTMaterialData", "path": "src/main/java/mods/bio/gttweaker/mods/gregtech/oredict/CTMaterialData.java", "snippet": "public class CTMaterialData implements mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData {\n\tpublic final OreDictItemData backingData;\n\t@Override\n\t@ZenGetter\n\tpublic IMaterialStack material(){\n\t\tif(backingData.mMaterial != null) return new CTMaterialStack(backingData.mMaterial);\n\t\tMineTweakerAPI.logError(this + \" dose not have any Main Material\");\n\t\treturn null;\n\t}\n\t@Override\n\t@ZenGetter\n\tpublic IPrefix prefix(){\n\t\tif(backingData.mPrefix != null) return new CTPrefix(backingData.mPrefix);\n\t\tMineTweakerAPI.logError(this + \" dose not have any GT prefix\");\n\t\treturn null;\n\t}\n\t@Override\n\tpublic List<IMaterialStack> byProducts(){\n\t\tif(backingData.mByProducts.length < 1) {\n\t\t\tMineTweakerAPI.logError(this + \" dose not have any GT byproduct\");\n\t\t\treturn new ArrayList<>();\n\t\t}\n\t\treturn Arrays.stream(backingData.mByProducts).map(CTMaterialStack::new).collect(Collectors.toList());\n\t}\n\t@Override\n\t@ZenGetter\n\tpublic List<IMaterialStack> materials(){\n\t\tList<IMaterialStack> list = new ArrayList<>();\n\t\tlist.add(material());\n\t\tlist.addAll(byProducts());\n\t\treturn list;\n\t}\n\n\tpublic CTMaterialData(OreDictItemData backingData) {\n\t\tthis.backingData = backingData;\n\t\tif(backingData==null) {\n\t\t\tMineTweakerAPI.logError(\"Material Data cannot be null\",new NullPointerException(\"Not a valid Material Data.\"));\n\t\t}\n\t}\n\n\t/**\n\t * @return a very JSON like CTMaterialData Representation tough it's not ready for json parsing at all\n\t * but is human readable.\n\t * {\n\t * MainMaterial: <material:name> * amount U ,\n\t * ByProducts: [\n\t * 1: <material:name> * amount U,\n\t * 2 :<material:name> * amount U,\n\t * 3: <material:name> * amount U\n\t * ]\n\t * }\n\t *\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tif(material() != null) builder.append(\"{MainMaterial:\").append(material());\n\t\telse builder.append(\"{NULL\");\n\t\tList<IMaterialStack> list = byProducts();\n\t\tif(!list.isEmpty()) builder.append(\",ByProducts:[\");\n\t\tlist.forEach(s->builder.append(String.format(\"%d: %s,\",list.indexOf(s),s)));\n\t\tif (!list.isEmpty()) builder.reverse().deleteCharAt(0).reverse().append(\"]}\");\n\t\treturn builder.toString();\n\t}\n}" } ]
import minetweaker.api.liquid.ILiquidStack; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.mods.gregtech.oredict.CTMaterialData; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenGetter;
1,255
package mods.bio.gttweaker.mods.minetweaker; @ZenClass("minetweaker.item.ILiquidStack") public class CTILiquidStackExpansion { @ZenGetter
package mods.bio.gttweaker.mods.minetweaker; @ZenClass("minetweaker.item.ILiquidStack") public class CTILiquidStackExpansion { @ZenGetter
public static IMaterialData association(ILiquidStack iLiquidStack) {
0
2023-12-03 11:55:49+00:00
2k
rensatopc/WhistleMod
src/main/java/io/ren778/github/rensato_whistle/main/WhistleMod.java
[ { "identifier": "WhistleModBlocks", "path": "src/main/java/io/ren778/github/rensato_whistle/registers/WhistleModBlocks.java", "snippet": "public class WhistleModBlocks {\n public static final DeferredRegister<Block> MOD_BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, WhistleMod.MOD_ID);\n\n public static final RegistryObject<Block> WHISTLE_BLOCK = MOD_BLOCKS.register(\"whistle_block\", BlockWhistle::new);\n}" }, { "identifier": "WhistleModItems", "path": "src/main/java/io/ren778/github/rensato_whistle/registers/WhistleModItems.java", "snippet": "public class WhistleModItems {\n\n public static final DeferredRegister<Item> MOD_ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, WhistleMod.MOD_ID);\n public static final RegistryObject<Item> WHISTLE = MOD_ITEMS.register(\"whistle\", ItemWhistle::new);\n}" }, { "identifier": "WhistleModSounds", "path": "src/main/java/io/ren778/github/rensato_whistle/registers/WhistleModSounds.java", "snippet": "public class WhistleModSounds {\n public static final DeferredRegister<SoundEvent> MOD_SOUNDEVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, WhistleMod.MOD_ID);\n\n public static final RegistryObject<SoundEvent> WHISTLE_CLICK = registerSoundEvent(\"whistle_click\");\n\n public static RegistryObject<SoundEvent> registerSoundEvent(String name) {\n return MOD_SOUNDEVENTS.register(name, () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(WhistleMod.MOD_ID, name)));\n }\n}" }, { "identifier": "WhistleModTabs", "path": "src/main/java/io/ren778/github/rensato_whistle/registers/tab/WhistleModTabs.java", "snippet": "public class WhistleModTabs {\n public static final DeferredRegister<CreativeModeTab> MOD_TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, WhistleMod.MOD_ID);\n public static final RegistryObject<CreativeModeTab> MAINTAB = MOD_TABS.register(\"whistle_main\", () -> {\n return CreativeModeTab.builder()\n .icon(() -> new ItemStack(WhistleModItems.WHISTLE.get()))\n .title(Component.translatable(\"itemGroup.whistle_main\"))\n .displayItems((param, output) -> {\n for (Item item:WhistleModMainTab.items) {\n output.accept(item);\n }\n })\n .build();\n });\n}" } ]
import io.ren778.github.rensato_whistle.registers.WhistleModBlocks; import io.ren778.github.rensato_whistle.registers.WhistleModItems; import io.ren778.github.rensato_whistle.registers.WhistleModSounds; import io.ren778.github.rensato_whistle.registers.tab.WhistleModTabs; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
740
package io.ren778.github.rensato_whistle.main; @Mod(WhistleMod.MOD_ID) public class WhistleMod { public static final String MOD_ID = "rensato_whistle"; public WhistleMod() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); WhistleModItems.MOD_ITEMS.register(bus); WhistleModTabs.MOD_TABS.register(bus);
package io.ren778.github.rensato_whistle.main; @Mod(WhistleMod.MOD_ID) public class WhistleMod { public static final String MOD_ID = "rensato_whistle"; public WhistleMod() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); WhistleModItems.MOD_ITEMS.register(bus); WhistleModTabs.MOD_TABS.register(bus);
WhistleModSounds.MOD_SOUNDEVENTS.register(bus);
2
2023-12-03 10:03:35+00:00
2k
ariel-mitchell/404-found
server/src/main/java/org/launchcode/fourohfourfound/finalproject/repositories/CharacterRepository.java
[ { "identifier": "Character", "path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/models/Character.java", "snippet": "@Entity\n@Table(name = \"characters\")\npublic class Character extends AbstractIdentifiableModel{\n @ManyToOne\n @JoinColumn(name = \"owner_id\")\n private User owner;\n private String characterName;\n private String alignment;\n private String characterClass;\n private String race;\n private String background;\n private String armorChoice;\n private String magicArmor;\n private String weapon;\n private String magicWeapon;\n private String equipment;\n private String treasure;\n private String proficiencyOne;\n private String proficiencyTwo;\n private String spellOne;\n private String spellTwo;\n\n public Character() {\n }\n\n public Character(User owner, String characterName,String alignment, String aBackground,String armorChoice,\n String magicArmor, String weapon, String magicWeapon, String equipment, String treasure,\n String aClass, String aRace, String proficiencyOne, String proficiencyTwo,\n String spellOne, String spellTwo) {\n super();\n this.owner = owner;\n this.characterName = characterName;\n this.alignment = alignment;\n this.background = aBackground;\n this.armorChoice = armorChoice;\n this.magicArmor = magicArmor;\n this.weapon = weapon;\n this.magicWeapon = magicWeapon;\n this.equipment = equipment;\n this.treasure = treasure;\n this.characterClass = aClass;\n this.race = aRace;\n this.proficiencyOne = proficiencyOne;\n this.proficiencyTwo = proficiencyTwo;\n this.spellOne = spellOne;\n this.spellTwo = spellTwo;\n }\n\n public int getId() {\n return super.getId();\n }\n\n public String getCharacterName() {\n return characterName;\n }\n\n public void setCharacterName(String characterName) {\n this.characterName = characterName;\n }\n\n public String getAlignment() {\n return alignment;\n }\n\n public void setAlignment(String alignment) {\n this.alignment = alignment;\n }\n\n public String getCharacterClass() {\n return characterClass;\n }\n\n public void setCharacterClass(String classInfo) {\n this.characterClass = classInfo;\n }\n\n public String getRace() {\n return race;\n }\n\n public void setRace(String race) {\n this.race = race;\n }\n\n public String getBackground() {\n return background;\n }\n\n public void setBackground(String background) {\n this.background = background;\n }\n\n public String getArmorChoice() {\n return armorChoice;\n }\n\n public void setArmorChoice(String armorChoice) {\n this.armorChoice = armorChoice;\n }\n\n public String getMagicArmor() {\n return magicArmor;\n }\n\n public void setMagicArmor(String magicArmor) {\n this.magicArmor = magicArmor;\n }\n\n public String getWeapon() {\n return weapon;\n }\n\n public void setWeapon(String weapon) {\n this.weapon = weapon;\n }\n\n public String getMagicWeapon() {\n return magicWeapon;\n }\n\n public void setMagicWeapon(String magicWeapon) {\n this.magicWeapon = magicWeapon;\n }\n\n public String getEquipment() {\n return equipment;\n }\n\n public void setEquipment(String equipment) {\n this.equipment = equipment;\n }\n\n public String getTreasure() {\n return treasure;\n }\n\n public void setTreasure(String treasure) {\n this.treasure = treasure;\n }\n\n public String getProficiencyOne() {\n return proficiencyOne;\n }\n\n public void setProficiencyOne(String proficiencyOne) {\n this.proficiencyOne = proficiencyOne;\n }\n\n public String getProficiencyTwo() {\n return proficiencyTwo;\n }\n\n public void setProficiencyTwo(String proficiencyTwo) {\n this.proficiencyTwo = proficiencyTwo;\n }\n\n public String getSpellOne() {\n return spellOne;\n }\n\n public void setSpellOne(String spellOne) {\n this.spellOne = spellOne;\n }\n\n public String getSpellTwo() {\n return spellTwo;\n }\n\n public void setSpellTwo(String spellTwo) {\n this.spellTwo = spellTwo;\n }\n\n public User getOwner() {\n return owner;\n }\n\n public void setOwner(User owner) {\n this.owner = owner;\n }\n}" }, { "identifier": "User", "path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/models/User.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class User extends AbstractIdentifiableModel{\n\n @Column\n private String username;\n @Column\n private String email;\n\n @Column\n private String password;\n\n public User() {}\n\n\n\n public User(String username, String email, String password) {\n super();\n this.username = username;\n this.email = email;\n setPassword(password);\n\n }\n\n public String getUserName() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n @JsonIgnore\n public String getPassword() {\n return password;\n }\n\n public static BCryptPasswordEncoder getEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n public boolean isPasswordEmpty() {\n return password == null || password.isEmpty();\n }\n\n public boolean isMatchingPassword(String password) {\n return getEncoder().matches(password, this.password);\n }\n}" } ]
import org.launchcode.fourohfourfound.finalproject.models.Character; import org.launchcode.fourohfourfound.finalproject.models.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List;
1,556
package org.launchcode.fourohfourfound.finalproject.repositories; @Repository public interface CharacterRepository extends JpaRepository<Character, Integer> {
package org.launchcode.fourohfourfound.finalproject.repositories; @Repository public interface CharacterRepository extends JpaRepository<Character, Integer> {
List<Character> findByOwner(User owner);
1
2023-11-28 01:32:31+00:00
2k
perfree/perfree-cms
perfree-system/perfree-system-biz/src/main/java/com/perfree/system/convert/plugins/PluginsConvert.java
[ { "identifier": "PageResult", "path": "perfree-core/src/main/java/com/perfree/commons/common/PageResult.java", "snippet": "@Schema(description = \"分页结果\")\n@Data\npublic final class PageResult<T> implements Serializable {\n\n @Schema(description = \"数据\", requiredMode = Schema.RequiredMode.REQUIRED)\n private List<T> list;\n\n @Schema(description = \"总量\", requiredMode = Schema.RequiredMode.REQUIRED)\n private Long total;\n\n public PageResult() {\n }\n\n public PageResult(List<T> list, Long total) {\n this.list = list;\n this.total = total;\n }\n\n public PageResult(Long total) {\n this.list = new ArrayList<>();\n this.total = total;\n }\n\n public static <T> PageResult<T> empty() {\n return new PageResult<>(0L);\n }\n\n public static <T> PageResult<T> empty(Long total) {\n return new PageResult<>(total);\n }\n\n}" }, { "identifier": "Plugins", "path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/model/Plugins.java", "snippet": "@Getter\n@Setter\n@TableName(\"p_plugins\")\npublic class Plugins implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * 插件名\n */\n private String name;\n\n /**\n * 路径\n */\n private String path;\n\n /**\n * 插件描述\n */\n @TableField(value = \"`desc`\")\n private String desc;\n\n /**\n * 版本\n */\n private String version;\n\n /**\n * 作者\n */\n private String author;\n\n /**\n * 插件状态:0禁用,1启用\n */\n private Integer status;\n\n /**\n * 创建时间\n */\n private Date createTime;\n\n /**\n * 更新时间\n */\n private Date updateTime;\n}" }, { "identifier": "PluginsRespVO", "path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/vo/plugins/PluginsRespVO.java", "snippet": "@Schema(description = \"管理后台 - 插件RespVO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class PluginsRespVO extends PluginsBaseVO{\n\n @Schema(description = \"id\")\n private Integer id;\n\n @Schema(description = \"创建时间\")\n private Date createTime;\n\n @Schema(description = \"更新时间\")\n private Date updateTime;\n}" } ]
import com.perfree.commons.common.PageResult; import com.perfree.system.model.Plugins; import com.perfree.system.vo.plugins.PluginsRespVO; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers;
753
package com.perfree.system.convert.plugins; @Mapper(componentModel = "spring") public interface PluginsConvert { PluginsConvert INSTANCE = Mappers.getMapper(PluginsConvert.class);
package com.perfree.system.convert.plugins; @Mapper(componentModel = "spring") public interface PluginsConvert { PluginsConvert INSTANCE = Mappers.getMapper(PluginsConvert.class);
PageResult<PluginsRespVO> convertPageResultVO(PageResult<Plugins> pluginsPageResult);
2
2023-12-01 23:37:25+00:00
2k
WolfpackRobotics3859/2024-D-Bot
src/main/java/frc/robot/commands/MoveToTarget.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n\n public static class MOTORS {\n public static final int MOTOR_LEFT_1_ID = 1;\n public static final int MOTOR_LEFT_2_ID = 3;\n public static final int MOTOR_RIGHT_1_ID = 2;\n public static final int MOTOR_RIGHT_2_ID = 4;\n }\n\n public static class CONTROLLERS {\n public static final int DRIVER_CONTROLLER = 0;\n }\n\n public static class CAMERA {\n public static double CAMERA_HEIGHT_METERS = Units.inchesToMeters(24);\n public static double TARGET_HEIGHT_METERS = Units.feetToMeters(5);\n public static double CAMERA_PITCH_RADIANS = Units.degreesToRadians(0);\n }\n}" }, { "identifier": "RobotContainer", "path": "src/main/java/frc/robot/RobotContainer.java", "snippet": "public class RobotContainer {\n\n //subsystems\n private final DriveTrain driveTrain = new DriveTrain();\n \n //controllers\n private final XboxController driverController = new XboxController(Constants.CONTROLLERS.DRIVER_CONTROLLER);\n\n //cameras\n public static PhotonCamera camera = new PhotonCamera(\"photonvision\");\n\n public RobotContainer() {\n\n driveTrain.setDefaultCommand(\n new ArcadeDrive(driveTrain, () -> driverController.getRawAxis(1), () -> driverController.getRawAxis(4))\n );\n\n configureBindings();\n }\n\n private void configureBindings() {\n // Move to Target\n new JoystickButton(driverController, 1).whileTrue(new MoveToTarget(driveTrain));\n\n // DriveFWD\n new JoystickButton(driverController, 2).whileTrue(new DriveFwd(driveTrain));\n \n }\n\n}" }, { "identifier": "DriveTrain", "path": "src/main/java/frc/robot/subsystems/DriveTrain.java", "snippet": "public class DriveTrain extends SubsystemBase {\n\n private WPI_VictorSPX motorLeft1 = new WPI_VictorSPX(Constants.MOTORS.MOTOR_LEFT_1_ID);\n private WPI_VictorSPX motorLeft2 = new WPI_VictorSPX(Constants.MOTORS.MOTOR_LEFT_2_ID);\n private WPI_VictorSPX motorRight1 = new WPI_VictorSPX(Constants.MOTORS.MOTOR_RIGHT_1_ID);\n private WPI_VictorSPX motorRight2 = new WPI_VictorSPX(Constants.MOTORS.MOTOR_RIGHT_2_ID);\n\n /** Creates a new DriveTrain. */\n public DriveTrain() {\n motorLeft1.configFactoryDefault();\n motorLeft2.configFactoryDefault();\n motorRight1.configFactoryDefault();\n motorRight2.configFactoryDefault();\n motorLeft2.setInverted(false);\n motorLeft1.setInverted(false);\n motorRight1.setInverted(true);\n }\n\n @Override\n public void periodic() {}\n\n public void setLeftMotors(double speed) {\n motorLeft1.set(ControlMode.PercentOutput, speed);\n motorLeft2.set(ControlMode.PercentOutput, speed);\n SmartDashboard.putNumber(\"Left Speed\", speed);\n }\n\n public void setRightMotors(double speed) {\n motorRight1.set(ControlMode.PercentOutput, speed);\n motorRight2.set(ControlMode.PercentOutput, speed);\n SmartDashboard.putNumber(\"Right Speed\", speed);\n }\n}" } ]
import org.photonvision.PhotonUtils; import org.photonvision.targeting.PhotonTrackedTarget; import edu.wpi.first.math.util.Units; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.Constants; import frc.robot.RobotContainer; import frc.robot.subsystems.DriveTrain;
1,083
// 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.commands; public class MoveToTarget extends CommandBase { private final DriveTrain driveTrain; public MoveToTarget(DriveTrain driveTrain) { this.driveTrain = driveTrain; addRequirements(driveTrain); } @Override public void initialize() { System.out.println("MoveToTarget cmd started"); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { var result = RobotContainer.camera.getLatestResult(); if(result.hasTargets()){ result.getBestTarget(); double range = PhotonUtils.calculateDistanceToTargetMeters(
// 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.commands; public class MoveToTarget extends CommandBase { private final DriveTrain driveTrain; public MoveToTarget(DriveTrain driveTrain) { this.driveTrain = driveTrain; addRequirements(driveTrain); } @Override public void initialize() { System.out.println("MoveToTarget cmd started"); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { var result = RobotContainer.camera.getLatestResult(); if(result.hasTargets()){ result.getBestTarget(); double range = PhotonUtils.calculateDistanceToTargetMeters(
Constants.CAMERA.CAMERA_HEIGHT_METERS,
0
2023-11-30 02:47:01+00:00
2k
JoeHeflin/hangman
src/util/Main.java
[ { "identifier": "HangmanGame", "path": "src/game/HangmanGame.java", "snippet": "public class HangmanGame {\n private static final String ALPHABET = \"abcdefghijklmnopqrstuvwxyz\";\n private static final String WORDS_FILE = \"lowerwords.txt\";\n\n // word that is being guessed\n private String mySecretWord;\n // how many guesses are remaining\n private int myNumGuessesLeft;\n // what is shown to the user\n private DisplayWord myDisplayWord;\n // tracks letters guessed\n private StringBuilder myLettersLeftToGuess;\n private Guesser myGuesser;\n private Executioner myRandomExecutioner;\n private Executioner myInteractiveExecutioner;\n\n\n /**\n * Create Hangman game with the given dictionary of words to play a game with words \n * of the given length and giving the user the given number of chances.\n */\n public HangmanGame (Guesser guesser, HangmanDictionary dictionary, int wordLength, int numGuesses) {\n// myRandomExecutioner = new RandomExecutioner(WORDS_FILE);\n myInteractiveExecutioner = new InteractiveExecutioner();\n mySecretWord = myRandomExecutioner.getSecretWord();\n myNumGuessesLeft = numGuesses;\n myLettersLeftToGuess = new StringBuilder(ALPHABET);\n myDisplayWord = new DisplayWord(mySecretWord);\n myGuesser = guesser;\n }\n\n /**\n * Play one complete game.\n */\n public void play () {\n boolean gameOver = false;\n while (!gameOver) {\n printStatus();\n\n String guess = myGuesser.getGuess();\n if (guess.length() == 1 && Character.isAlphabetic(guess.charAt(0))) {\n makeGuess(guess.toLowerCase().charAt(0));\n if (isGameLost()) {\n System.out.println(\"YOU ARE HUNG!!!\");\n gameOver = true;\n }\n else if (isGameWon()) {\n System.out.println(\"YOU WIN!!!\");\n gameOver = true;\n }\n }\n else {\n System.out.println(\"Please enter a single letter ...\");\n }\n }\n System.out.println(\"The secret word was \" + mySecretWord);\n }\n\n\n // Process a guess by updating the necessary internal state.\n private void makeGuess (char guess) {\n // do not count repeated guess as a miss\n int index = myLettersLeftToGuess.indexOf(\"\" + guess);\n if (index >= 0) {\n recordGuess(index);\n if (! checkGuessInSecret(guess)) {\n myNumGuessesLeft -= 1;\n }\n }\n }\n\n // Record that a specific letter was guessed\n private void recordGuess (int index) {\n myLettersLeftToGuess.deleteCharAt(index);\n }\n\n // Returns true only if given guess is in the secret word.\n private boolean checkGuessInSecret (char guess) {\n if (mySecretWord.indexOf(guess) >= 0) {\n myDisplayWord.update(guess, mySecretWord);\n return true;\n }\n return false;\n }\n\n // Returns a secret word.\n private String getSecretWord (HangmanDictionary dictionary, int wordLength) {\n return dictionary.getRandomWord(wordLength).toLowerCase();\n }\n\n // Returns true only if the guesser has guessed all letters in the secret word.\n private boolean isGameWon () {\n return myDisplayWord.equals(mySecretWord);\n }\n\n // Returns true only if the guesser has used up all their chances to guess.\n private boolean isGameLost () {\n return myNumGuessesLeft == 0;\n }\n\n // Print game stats\n private void printStatus () {\n System.out.println(myDisplayWord);\n System.out.println(\"# misses left = \" + myNumGuessesLeft);\n System.out.println(\"letters not yet guessed = \" + myLettersLeftToGuess);\n // NOT PUBLIC, but makes it easier to test\n System.out.println(\"*** \" + mySecretWord);\n System.out.println();\n }\n}" }, { "identifier": "InteractiveGuesser", "path": "src/game/InteractiveGuesser.java", "snippet": "public class InteractiveGuesser extends Guesser {\n /**\n * @see //Guesser#getGuess()\n */\n @Override\n public String getGuess () {\n return ConsoleReader.promptString(\"Make a guess: \");\n }\n}" } ]
import game.HangmanGame; import game.InteractiveGuesser;
1,148
package util; /** * This class launches the Hangman game and plays once. * * @author Michael Hewner * @author Mac Mason * @author Robert C. Duvall */ public class Main { public static final String DICTIONARY = "lowerwords.txt"; public static final int NUM_LETTERS = 6; public static final int NUM_MISSES = 8; public static void main (String[] args) { new HangmanGame(
package util; /** * This class launches the Hangman game and plays once. * * @author Michael Hewner * @author Mac Mason * @author Robert C. Duvall */ public class Main { public static final String DICTIONARY = "lowerwords.txt"; public static final int NUM_LETTERS = 6; public static final int NUM_MISSES = 8; public static void main (String[] args) { new HangmanGame(
new InteractiveGuesser(),
1
2023-11-28 18:10:53+00:00
2k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/admin/system/DashboardManager.java
[ { "identifier": "Session", "path": "api/src/main/java/top/hcode/hoj/pojo/entity/user/Session.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@ApiModel(value=\"session对象\", description=\"\")\npublic class Session {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n private String uid;\n\n private String userAgent;\n\n private String ip;\n\n @TableField(fill = FieldFill.INSERT)\n private Date gmtCreate;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date gmtModified;\n}" }, { "identifier": "UserRolesVo", "path": "DataBackup/src/main/java/top/hcode/hoj/pojo/vo/UserRolesVo.java", "snippet": "@ApiModel(value=\"用户信息以及其对应的角色\", description=\"\")\n@Data\npublic class UserRolesVo implements Serializable {\n\n private static final long serialVersionUID = 10000L;\n\n @ApiModelProperty(value = \"用户id\")\n private String uid;\n\n @ApiModelProperty(value = \"用户名\")\n private String username;\n\n @ApiModelProperty(value = \"密码\")\n private String password;\n\n @ApiModelProperty(value = \"昵称\")\n private String nickname;\n\n @ApiModelProperty(value = \"学校\")\n private String school;\n\n @ApiModelProperty(value = \"专业\")\n private String course;\n\n @ApiModelProperty(value = \"学号\")\n private String number;\n\n @ApiModelProperty(value = \"性别\")\n private String gender;\n\n @ApiModelProperty(value = \"真实姓名\")\n private String realname;\n\n @ApiModelProperty(value = \"cf的username\")\n private String cfUsername;\n\n @ApiModelProperty(value = \"github地址\")\n private String github;\n\n @ApiModelProperty(value = \"博客地址\")\n private String blog;\n\n @ApiModelProperty(value = \"邮箱\")\n private String email;\n\n @ApiModelProperty(value = \"头像地址\")\n private String avatar;\n\n @ApiModelProperty(value = \"头衔名称\")\n private String titleName;\n\n @ApiModelProperty(value = \"头衔背景颜色\")\n private String titleColor;\n\n @ApiModelProperty(value = \"RP值\")\n private Integer rp;\n\n @ApiModelProperty(value = \"个性签名\")\n private String signature;\n\n @ApiModelProperty(value = \"0可用,1不可用\")\n private int status;\n\n @ApiModelProperty(value = \"创建时间\")\n private Date gmtCreate;\n\n @ApiModelProperty(value = \"修改时间\")\n private Date gmtModified;\n\n @ApiModelProperty(value = \"角色列表\")\n private List<Role> roles;\n\n}" }, { "identifier": "ContestEntityService", "path": "DataBackup/src/main/java/top/hcode/hoj/dao/contest/ContestEntityService.java", "snippet": "public interface ContestEntityService extends IService<Contest> {\n\n List<ContestVo> getWithinNext14DaysContests();\n\n IPage<ContestVo> getContestList(Integer limit, Integer currentPage, Integer type, Integer status, String keyword);\n\n ContestVo getContestInfoById(long cid);\n}" }, { "identifier": "JudgeEntityService", "path": "DataBackup/src/main/java/top/hcode/hoj/dao/judge/JudgeEntityService.java", "snippet": "public interface JudgeEntityService extends IService<Judge> {\n\n IPage<JudgeVo> getCommonJudgeList(Integer limit,\n Integer currentPage,\n String searchPid,\n Integer status,\n String username,\n String uid,\n Boolean completeProblemID,\n Long gid);\n\n IPage<JudgeVo> getContestJudgeList(Integer limit,\n Integer currentPage,\n String displayId,\n Long cid,\n Integer status,\n String username,\n String uid,\n Boolean beforeContestSubmit,\n String rule,\n Date startTime,\n Date sealRankTime,\n String sealTimeUid,\n Boolean completeProblemID);\n public IPage<RpChangeVo> getRpChangeList(Integer limit,\n Integer currentPage,\n String searchUsername,\n String Id,\n String username,\n String uid,\n Integer rpChange,\n String description);\n\n void failToUseRedisPublishJudge(Long submitId, Long pid, Boolean isContest);\n\n ProblemCountVo getContestProblemCount(Long pid,\n Long cpid,\n Long cid,\n Date startTime,\n Date sealRankTime,\n List<String> adminList);\n\n ProblemCountVo getProblemCount(Long pid, Long gid);\n\n public int getTodayJudgeNum();\n\n public List<ProblemCountVo> getProblemListCount(List<Long> pidList);\n}" }, { "identifier": "SessionEntityService", "path": "DataBackup/src/main/java/top/hcode/hoj/dao/user/SessionEntityService.java", "snippet": "public interface SessionEntityService extends IService<Session> {\n\n public void checkRemoteLogin(String uid);\n\n}" }, { "identifier": "UserInfoEntityService", "path": "DataBackup/src/main/java/top/hcode/hoj/dao/user/UserInfoEntityService.java", "snippet": "public interface UserInfoEntityService extends IService<UserInfo> {\n\n public Boolean addUser(RegisterDto registerDto);\n\n public List<String> getSuperAdminUidList();\n\n public List<String> getProblemAdminUidList();\n}" } ]
import cn.hutool.core.map.MapUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import top.hcode.hoj.pojo.entity.user.Session; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.dao.contest.ContestEntityService; import top.hcode.hoj.dao.judge.JudgeEntityService; import top.hcode.hoj.dao.user.SessionEntityService; import top.hcode.hoj.dao.user.UserInfoEntityService; import java.util.List; import java.util.Map;
1,466
package top.hcode.hoj.manager.admin.system; /** * @Author: Himit_ZH * @Date: 2022/3/9 21:44 * @Description: */ @Component public class DashboardManager { @Autowired private ContestEntityService contestEntityService; @Autowired
package top.hcode.hoj.manager.admin.system; /** * @Author: Himit_ZH * @Date: 2022/3/9 21:44 * @Description: */ @Component public class DashboardManager { @Autowired private ContestEntityService contestEntityService; @Autowired
private JudgeEntityService judgeEntityService;
3
2023-12-03 14:15:51+00:00
2k
Seven0610/yaoyaolingxian_ordering_system
src/main/java/com/example/meal_ordering_system/service/impl/NoticeServiceImpl.java
[ { "identifier": "NoticeDao", "path": "src/main/java/com/example/meal_ordering_system/dao/NoticeDao.java", "snippet": "@Repository(\"noticeDao\")\npublic interface NoticeDao {\n\n /**\n * 通过ID查询单条数据\n *\n * @param id 主键\n * @return 实例对象\n */\n Notice queryById(Integer id);\n\n\n\n /**\n * 查询所有元素\n *\n * @return 对象列表\n */\n List<Notice> queryAll();\n\n /**\n * 新增数据\n *\n * @param notice 实例对象\n * @return 影响行数\n */\n int insert(Notice notice);\n\n /**\n * 批量新增数据(MyBatis原生foreach方法)\n *\n * @param entities List<Notice> 实例对象列表\n * @return 影响行数\n */\n int insertBatch(@Param(\"entities\") List<Notice> entities);\n\n /**\n * 批量新增或按主键更新数据(MyBatis原生foreach方法)\n *\n * @param entities List<Notice> 实例对象列表\n * @return 影响行数\n */\n int insertOrUpdateBatch(@Param(\"entities\") List<Notice> entities);\n\n /**\n * 修改数据\n *\n * @param notice 实例对象\n * @return 影响行数\n */\n int update(Notice notice);\n\n /**\n * 通过主键删除数据\n *\n * @param id 主键\n * @return 影响行数\n */\n int delete(Integer id);\n\n}" }, { "identifier": "Notice", "path": "src/main/java/com/example/meal_ordering_system/entity/Notice.java", "snippet": "public class Notice {\n\n\n\n private Integer id;\n\n private String name;\n\n private String content;\n\n private String times;\n\n public Notice() {\n }\n\n public Notice(Integer id, String name, String content, String times) {\n this.id = id;\n this.name = name;\n this.content = content;\n this.times = times;\n }\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 String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getTimes() {\n return times;\n }\n\n public void setTimes(String times) {\n this.times = times;\n }\n}" }, { "identifier": "NoticeService", "path": "src/main/java/com/example/meal_ordering_system/service/NoticeService.java", "snippet": "public interface NoticeService {\n\n /**\n * 通过ID查询单条数据\n *\n * @param id 主键\n * @return 实例对象\n */\n Notice queryById(Integer id);\n\n /**\n * 查询多条数据\n * @return 对象列表\n */\n List<Notice> queryAll();\n\n /**\n * 新增数据\n *\n * @param notice 实例对象\n * @return 实例对象\n */\n Notice insert(Notice notice);\n\n /**\n * 修改数据\n *\n * @param notice 实例对象\n * @return 实例对象\n */\n Notice update(Notice notice);\n\n /**\n * 通过主键删除数据\n *\n * @param id 主键\n * @return 是否成功\n */\n boolean delete(Integer id);\n\n}" } ]
import com.example.meal_ordering_system.dao.NoticeDao; import com.example.meal_ordering_system.entity.Notice; import com.example.meal_ordering_system.service.NoticeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List;
1,103
package com.example.meal_ordering_system.service.impl; /** * (Notice)表服务实现类 * * @author makejava * @since 2021-02-04 12:49:14 */ @Service("noticeService") public class NoticeServiceImpl implements NoticeService { @Autowired @Qualifier("noticeDao")
package com.example.meal_ordering_system.service.impl; /** * (Notice)表服务实现类 * * @author makejava * @since 2021-02-04 12:49:14 */ @Service("noticeService") public class NoticeServiceImpl implements NoticeService { @Autowired @Qualifier("noticeDao")
private NoticeDao noticeDao;
0
2023-11-29 07:32:54+00:00
2k
yichenhsiaonz/EscAIpe-room-final
src/test/java/nz/ac/auckland/se206/gpt/openai/ChatCompletionServiceTest.java
[ { "identifier": "ChatMessage", "path": "src/main/java/nz/ac/auckland/se206/gpt/ChatMessage.java", "snippet": "public class ChatMessage {\n\n private String role;\n private String content;\n\n /**\n * Constructs a new ChatMessage object with the specified role and content.\n *\n * @param role the role of the message (e.g., \"user\", \"assistant\")\n * @param content the content of the message\n */\n public ChatMessage(String role, String content) {\n this.role = role;\n this.content = content;\n }\n\n /**\n * Returns the role of the chat message.\n *\n * @return the role\n */\n public String getRole() {\n return role;\n }\n\n /**\n * Returns the content of the chat message.\n *\n * @return the content\n */\n public String getContent() {\n return content;\n }\n}" }, { "identifier": "Choice", "path": "src/main/java/nz/ac/auckland/se206/gpt/openai/ChatCompletionResult.java", "snippet": "public class Choice {\n\n private ChatMessage message;\n private int index;\n private String finishReason;\n\n /**\n * Constructs a new Choice object with the specified parameters.\n *\n * @param message the chat message\n * @param index the index of the choice\n * @param finishReason the reason for finishing the choice\n */\n protected Choice(ChatMessage message, int index, String finishReason) {\n this.message = message;\n this.index = index;\n this.finishReason = finishReason;\n }\n\n /**\n * Returns the chat message of the choice.\n *\n * @return the chat message\n */\n public ChatMessage getChatMessage() {\n return message;\n }\n\n /**\n * Returns the reason for finishing the choice.\n *\n * @return the finish reason\n */\n public String getFinishReason() {\n return finishReason;\n }\n\n /**\n * Returns the index of the choice.\n *\n * @return the index\n */\n public int getIndex() {\n return index;\n }\n}" } ]
import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashSet; import java.util.Set; import nz.ac.auckland.se206.gpt.ChatMessage; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult.Choice; import org.junit.jupiter.api.Test;
910
package nz.ac.auckland.se206.gpt.openai; public class ChatCompletionServiceTest { @Test public void testGptAuckland() { OpenAiService openAiService = new OpenAiService("apiproxy.config"); ChatCompletionRequest chatCompletionRequest = new ChatCompletionRequest(openAiService); chatCompletionRequest .addMessage("system", "You are a helpful assistant. Reply in less than 20 words.") .addMessage("user", "Where is New Zealand?") .addMessage("system", "New Zealand is a country located in the southwestern Pacific Ocean.") .addMessage("user", "What's one city there?"); chatCompletionRequest.setN(1); chatCompletionRequest.setTemperature(1.5); chatCompletionRequest.setTopP(0.05); chatCompletionRequest.setMaxTokens(100); Set<String> results = new HashSet<>(); try { ChatCompletionResult chatCompletionResult = chatCompletionRequest.execute(); System.out.println("model: " + chatCompletionResult.getModel()); System.out.println("created: " + chatCompletionResult.getCreated()); System.out.println("usagePromptTokens: " + chatCompletionResult.getUsagePromptTokens()); System.out.println( "usageCompletionTokens: " + chatCompletionResult.getUsageCompletionTokens()); System.out.println("usageTotalTokens: " + chatCompletionResult.getUsageTotalTokens()); System.out.println("Number of choices: " + chatCompletionResult.getNumChoices());
package nz.ac.auckland.se206.gpt.openai; public class ChatCompletionServiceTest { @Test public void testGptAuckland() { OpenAiService openAiService = new OpenAiService("apiproxy.config"); ChatCompletionRequest chatCompletionRequest = new ChatCompletionRequest(openAiService); chatCompletionRequest .addMessage("system", "You are a helpful assistant. Reply in less than 20 words.") .addMessage("user", "Where is New Zealand?") .addMessage("system", "New Zealand is a country located in the southwestern Pacific Ocean.") .addMessage("user", "What's one city there?"); chatCompletionRequest.setN(1); chatCompletionRequest.setTemperature(1.5); chatCompletionRequest.setTopP(0.05); chatCompletionRequest.setMaxTokens(100); Set<String> results = new HashSet<>(); try { ChatCompletionResult chatCompletionResult = chatCompletionRequest.execute(); System.out.println("model: " + chatCompletionResult.getModel()); System.out.println("created: " + chatCompletionResult.getCreated()); System.out.println("usagePromptTokens: " + chatCompletionResult.getUsagePromptTokens()); System.out.println( "usageCompletionTokens: " + chatCompletionResult.getUsageCompletionTokens()); System.out.println("usageTotalTokens: " + chatCompletionResult.getUsageTotalTokens()); System.out.println("Number of choices: " + chatCompletionResult.getNumChoices());
for (Choice choice : chatCompletionResult.getChoices()) {
1
2023-12-02 04:57:43+00:00
2k
SverreNystad/board-master
backend/src/main/java/board/master/model/agents/IterativeDeepeningAlphaBetaPruningMinimax.java
[ { "identifier": "Action", "path": "backend/src/main/java/board/master/model/Action.java", "snippet": "public abstract class Action {\n\n public abstract boolean equals(Object obj);\n}" }, { "identifier": "StateHandler", "path": "backend/src/main/java/board/master/model/StateHandler.java", "snippet": "public interface StateHandler {\n\n /**\n * Returns the identifier of the player whose turn it is to move in the current\n * state.\n * This method is used to determine which player should make the next move.\n *\n * @return the player identifier (int) whose turn it is to move in the current\n * state.\n */\n public int toMove();\n\n /**\n * Provides a list of all legal actions available in the current state of the\n * game.\n * This method is essential for understanding the possible moves a player can\n * make.\n *\n * @return a list of legal actions ({@link Action}) available in the current\n * state.\n */\n public List<Action> getActions();\n\n /**\n * Transitions the game to a new state based on the given action.\n * This method applies the specified action to the current state, resulting in a\n * new state.\n *\n * @param action the action ({@link Action}) to be taken in the current state.\n */\n public StateHandler result(Action action);\n\n /**\n * Determines if the current state is a terminal state, indicating the end of\n * the game.\n * Terminal states are those where the game has concluded, either in a win,\n * loss, or draw.\n *\n * @return {@code true} if the current state is terminal (game over);\n * {@code false} otherwise.\n */\n public boolean isTerminal();\n\n /**\n * Calculates and returns the utility of the current state for the player.\n * Utility is a numerical value representing the desirability or \"goodness\" of a\n * state for a player,\n * often used in game algorithms to determine optimal moves.\n *\n * @return the utility (int) of the current state for the player.\n */\n public int utility(int player);\n\n /**\n * Returns the board object associated with the current state.\n * \n * @return the board object associated with the current state.\n */\n public Board getBoard();\n}" } ]
import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.Comparator; import board.master.model.Action; import board.master.model.StateHandler;
858
package board.master.model.agents; /** * An implementation of the Iterative Deepening Alpha-Beta Pruning Minimax algorithm. * This class functions as an agent in turn-based board games. It employs the * Iterative Deepening technique to incrementally deepen the search depth, * combined with Alpha-Beta pruning to optimize the Minimax search process. * The agent selects the best move based on the current state of the game. */ public class IterativeDeepeningAlphaBetaPruningMinimax implements Agent { private int agentPlayerId; private final long maxTime; private long startTime; public IterativeDeepeningAlphaBetaPruningMinimax(long maxTime) { this.maxTime = maxTime; } /** * Determines the best action to take in the given game state. * This method iteratively deepens the search depth and uses alpha-beta pruning * to evaluate the minimax value of each possible action. It returns the action * with the highest evaluation. * * @param state The current state of the game. * @return The best action to take based on the evaluation. */ @Override
package board.master.model.agents; /** * An implementation of the Iterative Deepening Alpha-Beta Pruning Minimax algorithm. * This class functions as an agent in turn-based board games. It employs the * Iterative Deepening technique to incrementally deepen the search depth, * combined with Alpha-Beta pruning to optimize the Minimax search process. * The agent selects the best move based on the current state of the game. */ public class IterativeDeepeningAlphaBetaPruningMinimax implements Agent { private int agentPlayerId; private final long maxTime; private long startTime; public IterativeDeepeningAlphaBetaPruningMinimax(long maxTime) { this.maxTime = maxTime; } /** * Determines the best action to take in the given game state. * This method iteratively deepens the search depth and uses alpha-beta pruning * to evaluate the minimax value of each possible action. It returns the action * with the highest evaluation. * * @param state The current state of the game. * @return The best action to take based on the evaluation. */ @Override
public Action getAction(StateHandler state) {
1
2023-11-30 21:27:22+00:00
2k
vaniabesouro/demoproject
src/main/java/com/ips/tpsi/demo/controller/WebController.java
[ { "identifier": "WebBc", "path": "src/main/java/com/ips/tpsi/demo/bc/WebBc.java", "snippet": "@Service\r\npublic class WebBc {\r\n\r\n @Autowired\r\n UserRepository repository;\r\n\r\n public boolean isLoginValid(String name, String password) {\r\n if (name != null && password != null) {\r\n User user = repository.findUserByUsername(name);\r\n if (password.equals(user.getPassword())) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n public void getRepositoryUserInfo(String username, String pass) {\r\n List<User> userList = repository.findAll(); // select * from user;\r\n\r\n // método 1 - construir o objeto\r\n User user1 = new User();\r\n user1.setUsername(username);\r\n user1.setPassword(pass);\r\n repository.save(user1);\r\n\r\n // método 2 - construir o objeto c/ o que vem da bd + a alteração\r\n User user = repository.findUserByUsername(username);\r\n user.setPassword(pass);\r\n repository.save(user);\r\n }\r\n\r\n public User getRepositoryUserInfoByUsername(String username) {\r\n return repository.findUserByUsername(username);\r\n }\r\n\r\n}\r" }, { "identifier": "User", "path": "src/main/java/com/ips/tpsi/demo/entity/User.java", "snippet": "@Entity\r\n@Table(name = \"user\")\r\n@AllArgsConstructor\r\n@NoArgsConstructor\r\n@Getter\r\n@Setter\r\npublic class User {\r\n\r\n @Id\r\n @Column(name = \"id_user\")\r\n private Integer idUser;\r\n\r\n @Column(name = \"username\")\r\n private String username;\r\n\r\n @Column(name = \"password\")\r\n private String password;\r\n\r\n}\r" } ]
import com.ips.tpsi.demo.bc.WebBc; import com.ips.tpsi.demo.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView;
766
package com.ips.tpsi.demo.controller; @Controller public class WebController { @Autowired WebBc bc; public WebController(WebBc bc) { this.bc = bc; } @GetMapping("/home") // @GetMapping("/") public ModelAndView getHome() { ModelAndView mv = new ModelAndView("index"); // aceder à business component > acede ao repositorio > obtem dados return mv; } @GetMapping("/name") // @GetMapping("/") public ModelAndView getName() { ModelAndView mv = new ModelAndView("index"); // aceder à business component > acede ao repositorio > obtem dados mv.addObject("name", "Vania"); return mv; } @PostMapping("/login") public ModelAndView login(String uname, String psw) { // aceder à business component para validar o login boolean isLoginValid = bc.isLoginValid(uname, psw); // uma vez que o login é válido procedemos ao login ModelAndView mv = new ModelAndView("index"); if (isLoginValid) { // aceder à business component > acede ao repositorio > obtem dados mv.addObject("loginValid", "O Login é válido."); } else { mv.addObject("loginValid", "O Login é inválido."); } return mv; } @GetMapping("/username") public ModelAndView getUserByUsername(String username) {
package com.ips.tpsi.demo.controller; @Controller public class WebController { @Autowired WebBc bc; public WebController(WebBc bc) { this.bc = bc; } @GetMapping("/home") // @GetMapping("/") public ModelAndView getHome() { ModelAndView mv = new ModelAndView("index"); // aceder à business component > acede ao repositorio > obtem dados return mv; } @GetMapping("/name") // @GetMapping("/") public ModelAndView getName() { ModelAndView mv = new ModelAndView("index"); // aceder à business component > acede ao repositorio > obtem dados mv.addObject("name", "Vania"); return mv; } @PostMapping("/login") public ModelAndView login(String uname, String psw) { // aceder à business component para validar o login boolean isLoginValid = bc.isLoginValid(uname, psw); // uma vez que o login é válido procedemos ao login ModelAndView mv = new ModelAndView("index"); if (isLoginValid) { // aceder à business component > acede ao repositorio > obtem dados mv.addObject("loginValid", "O Login é válido."); } else { mv.addObject("loginValid", "O Login é inválido."); } return mv; } @GetMapping("/username") public ModelAndView getUserByUsername(String username) {
User user = bc.getRepositoryUserInfoByUsername(username);
1
2023-11-28 21:54:47+00:00
2k
advent-of-craft/advent-of-craft
solution/java/day07/src/test/java/ci/PipelineTest.java
[ { "identifier": "Config", "path": "exercise/java/day07/src/main/java/ci/dependencies/Config.java", "snippet": "public interface Config {\n boolean sendEmailSummary();\n}" }, { "identifier": "Emailer", "path": "exercise/java/day07/src/main/java/ci/dependencies/Emailer.java", "snippet": "public interface Emailer {\n void send(String message);\n}" }, { "identifier": "Project", "path": "exercise/java/day07/src/main/java/ci/dependencies/Project.java", "snippet": "public class Project {\n private final boolean buildsSuccessfully;\n private final TestStatus testStatus;\n\n private Project(boolean buildsSuccessfully, TestStatus testStatus) {\n this.buildsSuccessfully = buildsSuccessfully;\n this.testStatus = testStatus;\n }\n\n public static ProjectBuilder builder() {\n return new ProjectBuilder();\n }\n\n public boolean hasTests() {\n return testStatus != TestStatus.NO_TESTS;\n }\n\n public String runTests() {\n return testStatus == TestStatus.PASSING_TESTS ? \"success\" : \"failure\";\n }\n\n public String deploy() {\n return buildsSuccessfully ? \"success\" : \"failure\";\n }\n\n public static class ProjectBuilder {\n private boolean buildsSuccessfully;\n private TestStatus testStatus;\n\n public ProjectBuilder setTestStatus(TestStatus testStatus) {\n this.testStatus = testStatus;\n return this;\n }\n\n public ProjectBuilder setDeploysSuccessfully(boolean buildsSuccessfully) {\n this.buildsSuccessfully = buildsSuccessfully;\n return this;\n }\n\n public Project build() {\n return new Project(buildsSuccessfully, testStatus);\n }\n }\n}" }, { "identifier": "ProjectBuilder", "path": "exercise/java/day07/src/main/java/ci/dependencies/Project.java", "snippet": "public static class ProjectBuilder {\n private boolean buildsSuccessfully;\n private TestStatus testStatus;\n\n public ProjectBuilder setTestStatus(TestStatus testStatus) {\n this.testStatus = testStatus;\n return this;\n }\n\n public ProjectBuilder setDeploysSuccessfully(boolean buildsSuccessfully) {\n this.buildsSuccessfully = buildsSuccessfully;\n return this;\n }\n\n public Project build() {\n return new Project(buildsSuccessfully, testStatus);\n }\n}" }, { "identifier": "builder", "path": "exercise/java/day07/src/main/java/ci/dependencies/Project.java", "snippet": "public static ProjectBuilder builder() {\n return new ProjectBuilder();\n}" }, { "identifier": "TestStatus", "path": "exercise/java/day07/src/main/java/ci/dependencies/TestStatus.java", "snippet": "public enum TestStatus {\n NO_TESTS,\n PASSING_TESTS,\n FAILING_TESTS,\n}" } ]
import ci.dependencies.Config; import ci.dependencies.Emailer; import ci.dependencies.Project; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.function.Function; import static ci.dependencies.Project.ProjectBuilder; import static ci.dependencies.Project.builder; import static ci.dependencies.TestStatus.*; import static java.util.Arrays.stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*;
1,498
package ci; class PipelineTest { private final Config config = mock(Config.class); private final CapturingLogger log = new CapturingLogger(); private final Emailer emailer = mock(Emailer.class); private Pipeline pipeline; @BeforeEach void setUp() { pipeline = new Pipeline(config, emailer, log); } @Test void project_with_tests_that_deploys_successfully_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(true), true)); assertLog("INFO: Tests passed", "INFO: Deployment successful", "INFO: Sending email"); verify(emailer).send("Deployment completed successfully"); } @Test void project_with_tests_that_deploys_successfully_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(true), false)); assertLog("INFO: Tests passed", "INFO: Deployment successful", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_without_tests_that_deploys_successfully_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(true), true)); assertLog("INFO: No tests", "INFO: Deployment successful", "INFO: Sending email"); verify(emailer).send("Deployment completed successfully"); } @Test void project_without_tests_that_deploys_successfully_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(true), false)); assertLog("INFO: No tests", "INFO: Deployment successful", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_with_tests_that_fail_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(FAILING_TESTS), true)); assertLog("ERROR: Tests failed", "INFO: Sending email"); verify(emailer).send("Tests failed"); } @Test void project_with_tests_that_fail_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(FAILING_TESTS), false)); assertLog("ERROR: Tests failed", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_with_tests_and_failing_build_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(false), true)); assertLog("INFO: Tests passed", "ERROR: Deployment failed", "INFO: Sending email"); verify(emailer).send("Deployment failed"); } @Test void project_with_tests_and_failing_build_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(false), false)); assertLog("INFO: Tests passed", "ERROR: Deployment failed", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_without_tests_and_failing_build_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(false), true)); assertLog("INFO: No tests", "ERROR: Deployment failed", "INFO: Sending email"); verify(emailer).send("Deployment failed"); } @Test void project_without_tests_and_failing_build_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(false), false)); assertLog("INFO: No tests", "ERROR: Deployment failed", "INFO: Email disabled"); verify(emailer, never()).send(any()); } private Project project(
package ci; class PipelineTest { private final Config config = mock(Config.class); private final CapturingLogger log = new CapturingLogger(); private final Emailer emailer = mock(Emailer.class); private Pipeline pipeline; @BeforeEach void setUp() { pipeline = new Pipeline(config, emailer, log); } @Test void project_with_tests_that_deploys_successfully_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(true), true)); assertLog("INFO: Tests passed", "INFO: Deployment successful", "INFO: Sending email"); verify(emailer).send("Deployment completed successfully"); } @Test void project_with_tests_that_deploys_successfully_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(true), false)); assertLog("INFO: Tests passed", "INFO: Deployment successful", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_without_tests_that_deploys_successfully_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(true), true)); assertLog("INFO: No tests", "INFO: Deployment successful", "INFO: Sending email"); verify(emailer).send("Deployment completed successfully"); } @Test void project_without_tests_that_deploys_successfully_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(true), false)); assertLog("INFO: No tests", "INFO: Deployment successful", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_with_tests_that_fail_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(FAILING_TESTS), true)); assertLog("ERROR: Tests failed", "INFO: Sending email"); verify(emailer).send("Tests failed"); } @Test void project_with_tests_that_fail_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(FAILING_TESTS), false)); assertLog("ERROR: Tests failed", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_with_tests_and_failing_build_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(false), true)); assertLog("INFO: Tests passed", "ERROR: Deployment failed", "INFO: Sending email"); verify(emailer).send("Deployment failed"); } @Test void project_with_tests_and_failing_build_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(PASSING_TESTS) .setDeploysSuccessfully(false), false)); assertLog("INFO: Tests passed", "ERROR: Deployment failed", "INFO: Email disabled"); verify(emailer, never()).send(any()); } @Test void project_without_tests_and_failing_build_with_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(false), true)); assertLog("INFO: No tests", "ERROR: Deployment failed", "INFO: Sending email"); verify(emailer).send("Deployment failed"); } @Test void project_without_tests_and_failing_build_without_email_notification() { pipeline.run(project(p -> p.setTestStatus(NO_TESTS) .setDeploysSuccessfully(false), false)); assertLog("INFO: No tests", "ERROR: Deployment failed", "INFO: Email disabled"); verify(emailer, never()).send(any()); } private Project project(
Function<ProjectBuilder, ProjectBuilder> project,
3
2023-11-21 11:49:12+00:00
2k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/dao/mapper/LinkNetworkStatsMapper.java
[ { "identifier": "LinkNetworkStatsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkNetworkStatsDO.java", "snippet": "@Data\n@TableName(\"t_link_network_stats\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkNetworkStatsDO extends BaseDO {\n\n /**\n * id\n */\n private Long id;\n\n /**\n * 完整短链接\n */\n private String fullShortUrl;\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 日期\n */\n private Date date;\n\n /**\n * 访问量\n */\n private Integer cnt;\n\n /**\n * 访问网络\n */\n private String network;\n}" }, { "identifier": "ShortLinkGroupStatsReqDTO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dto/req/ShortLinkGroupStatsReqDTO.java", "snippet": "@Data\npublic class ShortLinkGroupStatsReqDTO {\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 开始日期\n */\n private String startDate;\n\n /**\n * 结束日期\n */\n private String endDate;\n}" }, { "identifier": "ShortLinkStatsReqDTO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dto/req/ShortLinkStatsReqDTO.java", "snippet": "@Data\npublic class ShortLinkStatsReqDTO {\n\n /**\n * 完整短链接\n */\n private String fullShortUrl;\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 开始日期\n */\n private String startDate;\n\n /**\n * 结束日期\n */\n private String endDate;\n}" } ]
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List;
1,073
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.dao.mapper; /** * 访问网络监控持久层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ public interface LinkNetworkStatsMapper extends BaseMapper<LinkNetworkStatsDO> { /** * 记录访问设备监控数据 */ @Insert("INSERT INTO t_link_network_stats (full_short_url, gid, date, cnt, network, create_time, update_time, del_flag) " + "VALUES( #{linkNetworkStats.fullShortUrl}, #{linkNetworkStats.gid}, #{linkNetworkStats.date}, #{linkNetworkStats.cnt}, #{linkNetworkStats.network}, NOW(), NOW(), 0) " + "ON DUPLICATE KEY UPDATE cnt = cnt + #{linkNetworkStats.cnt};") void shortLinkNetworkState(@Param("linkNetworkStats") LinkNetworkStatsDO linkNetworkStatsDO); /** * 根据短链接获取指定日期内访问网络监控数据 */ @Select("SELECT " + " network, " + " SUM(cnt) AS cnt " + "FROM " + " t_link_network_stats " + "WHERE " + " full_short_url = #{param.fullShortUrl} " + " AND gid = #{param.gid} " + " AND date BETWEEN #{param.startDate} and #{param.endDate} " + "GROUP BY " + " full_short_url, gid, network;")
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.dao.mapper; /** * 访问网络监控持久层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ public interface LinkNetworkStatsMapper extends BaseMapper<LinkNetworkStatsDO> { /** * 记录访问设备监控数据 */ @Insert("INSERT INTO t_link_network_stats (full_short_url, gid, date, cnt, network, create_time, update_time, del_flag) " + "VALUES( #{linkNetworkStats.fullShortUrl}, #{linkNetworkStats.gid}, #{linkNetworkStats.date}, #{linkNetworkStats.cnt}, #{linkNetworkStats.network}, NOW(), NOW(), 0) " + "ON DUPLICATE KEY UPDATE cnt = cnt + #{linkNetworkStats.cnt};") void shortLinkNetworkState(@Param("linkNetworkStats") LinkNetworkStatsDO linkNetworkStatsDO); /** * 根据短链接获取指定日期内访问网络监控数据 */ @Select("SELECT " + " network, " + " SUM(cnt) AS cnt " + "FROM " + " t_link_network_stats " + "WHERE " + " full_short_url = #{param.fullShortUrl} " + " AND gid = #{param.gid} " + " AND date BETWEEN #{param.startDate} and #{param.endDate} " + "GROUP BY " + " full_short_url, gid, network;")
List<LinkNetworkStatsDO> listNetworkStatsByShortLink(@Param("param") ShortLinkStatsReqDTO requestParam);
2
2023-11-19 16:04:32+00:00
2k
NEWCIH2023/galois
src/main/java/io/liuguangsheng/galois/conf/GlobalConfiguration.java
[ { "identifier": "Constant", "path": "src/main/java/io/liuguangsheng/galois/constants/Constant.java", "snippet": "public class Constant {\n\n public static final String APPLICATION = \"application\";\n public static final String PARAMETER_MAPS = \"parameterMaps\";\n public static final String KNOWN_MAPPERS = \"knownMappers\";\n public static final String LOADED_RESOURCES = \"loadedResources\";\n public static final String CACHE_REF_MAP = \"cacheRefMap\";\n public static final String MAPPED_STATEMENTS = \"mappedStatements\";\n public static final String USER_DIR = \"user.dir\";\n public static final String ID = \"id\";\n public static final String NAMESPACE = \"namespace\";\n public static final String GET_INSTANCE = \"getInstance\";\n public static final String SRC = \"src\";\n public static final String PACKAGE = \"package\";\n public static final String TRUE = \"true\";\n public static final String FALSE = \"false\";\n public static final String EMPTY = \"\";\n public static final String CLASS = \"class\";\n public static final String UNDER_LINE = \"_\";\n public static final String OPEN_BRACE = \"{\";\n public static final String CLOSE_BRACE = \"}\";\n public static final String DOT = \".\";\n public static final String OPEN_PAREN = \"(\";\n public static final String CLOSE_PAREN = \")\";\n public static final String OPEN_BRACKET = \"[\";\n public static final String CLOSE_BRACKET = \"]\";\n public static final String VERTICAL_BAR = \"|\";\n public static final String POUND = \"#\";\n public static final String SLASH = \"/\";\n public static final String DOUBLE_SLASH = \"//\";\n public static final String COLON = \":\";\n public static final String SEMICOLON = \";\";\n public static final String HYPHEN = \"-\";\n public static final String SPACE = \" \";\n public static final String COMMA = \",\";\n public static final String TILDE = \"~\";\n public static final String QUESTION_MARK = \"?\";\n public static final String DASH = \"--\";\n public static final String DOTS = \"...\";\n public static final String PARALLEL = \"||\";\n public static final String LF = \"\\n\";\n public static final String CR = \"\\r\";\n public static final String TAB = \"\\t\";\n public static final String RELEASE = \"RELEASE\";\n}" }, { "identifier": "StringUtil", "path": "src/main/java/io/liuguangsheng/galois/utils/StringUtil.java", "snippet": "public class StringUtil {\n\n /**\n * is blank\n *\n * @param str str\n * @return {@link boolean}\n */\n public static boolean isBlank(String str) {\n return isEmpty(str) || str.trim().isEmpty();\n }\n\n /**\n * is empty\n *\n * @param str str\n * @return {@link boolean}\n */\n public static boolean isEmpty(String str) {\n return str == null || str.isEmpty();\n }\n\n /**\n * is not blank\n *\n * @param str str\n * @return {@link boolean}\n */\n public static boolean isNotBlank(String str) {\n return !isBlank(str);\n }\n\n /**\n * is not empty\n *\n * @param str str\n * @return {@link boolean}\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n}" } ]
import io.liuguangsheng.galois.constants.Constant; import io.liuguangsheng.galois.utils.StringUtil; import java.io.IOException; import java.io.InputStream; import java.util.Properties;
1,378
/* * MIT License * * Copyright (c) [2023] [liuguangsheng] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.liuguangsheng.galois.conf; /** * global configuration service * * @author liuguangsheng * @since 1.0.0 */ public class GlobalConfiguration { private static final String GALOIS_PROPERTIES = "galois.properties"; private static final Properties configuration = new Properties(); private static class GlobalConfigurationHolder { private static final GlobalConfiguration globalConfiguration = new GlobalConfiguration(); } private GlobalConfiguration() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try (InputStream is = loader.getResourceAsStream(GALOIS_PROPERTIES)) { configuration.load(is); } catch (IOException e) { throw new RuntimeException(e); } } /** * get instance * * @return {@link GlobalConfiguration} * @see GlobalConfiguration */ public static GlobalConfiguration getInstance() { return GlobalConfigurationHolder.globalConfiguration; } /** * get string * * @param key key * @return {@link String} * @see String */ public String getStr(String key) { return getStr(key, Constant.EMPTY); } /** * get string * * @param key key * @param defaultValue defaultValue * @return {@link String} * @see String */ public String getStr(String key, String defaultValue) {
/* * MIT License * * Copyright (c) [2023] [liuguangsheng] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.liuguangsheng.galois.conf; /** * global configuration service * * @author liuguangsheng * @since 1.0.0 */ public class GlobalConfiguration { private static final String GALOIS_PROPERTIES = "galois.properties"; private static final Properties configuration = new Properties(); private static class GlobalConfigurationHolder { private static final GlobalConfiguration globalConfiguration = new GlobalConfiguration(); } private GlobalConfiguration() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try (InputStream is = loader.getResourceAsStream(GALOIS_PROPERTIES)) { configuration.load(is); } catch (IOException e) { throw new RuntimeException(e); } } /** * get instance * * @return {@link GlobalConfiguration} * @see GlobalConfiguration */ public static GlobalConfiguration getInstance() { return GlobalConfigurationHolder.globalConfiguration; } /** * get string * * @param key key * @return {@link String} * @see String */ public String getStr(String key) { return getStr(key, Constant.EMPTY); } /** * get string * * @param key key * @param defaultValue defaultValue * @return {@link String} * @see String */ public String getStr(String key, String defaultValue) {
if (StringUtil.isBlank(key)) {
1
2023-11-22 04:51:35+00:00
2k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/model/response/HitsOptimizedResult.java
[ { "identifier": "Range", "path": "src/main/java/com/ly/ckibana/model/compute/Range.java", "snippet": "@Data\npublic class Range {\n\n private String ckFieldName;\n\n private String ckFieldType;\n\n private boolean lessThanEq;\n\n private Object low;\n\n private boolean moreThanEq;\n\n private Object high;\n\n public Range() {\n }\n\n public Range(String ckFieldName, String ckFieldType) {\n this.ckFieldName = ckFieldName;\n this.ckFieldType = ckFieldType;\n }\n\n public Range(String ckFieldName, String ckFieldType, Object high, Object low) {\n this.ckFieldName = ckFieldName;\n this.ckFieldType = ckFieldType;\n this.high = high;\n this.low = low;\n }\n\n /**\n * range请求包装。将不支持range的原始字段转换为支持range的ck function包装后的值,并利用比较运算符组装为最终sql.\n * 1)时间字段:支持数值型timestamp 和DateTime64存储类型\n * 2)ip字段:支持字符串存储类型\n * 3)普通数值字段:支持数值型存储类型\n * 具体clickhouse函数参见方法getRangeWrappedBySqlFunction()\n *\n * @param isTimeField 是否为indexPattern的时间字段\n * @return sql\n */\n public String toSql(boolean isTimeField) {\n String result = \"\";\n Range rangeWrappedBySqlFunction = ProxyUtils.getRangeWrappedBySqlFunction(this, isTimeField);\n Object ckFieldSqlValue = rangeWrappedBySqlFunction.getCkFieldName();\n\n if (high != null && low != null) {\n result = String.format(\" %s AND %s \", getRangeHighSql(ckFieldSqlValue, rangeWrappedBySqlFunction.getHigh()),\n getRangeLowSql(ckFieldSqlValue, rangeWrappedBySqlFunction.getLow()));\n } else if (high == null && low != null) {\n result = getRangeLowSql(ckFieldSqlValue, rangeWrappedBySqlFunction.getLow());\n } else if (high != null && low == null) {\n result = getRangeHighSql(ckFieldSqlValue, rangeWrappedBySqlFunction.getHigh());\n }\n result = String.format(\"(%s)\", result);\n return result;\n }\n\n private String getRangeLowSql(Object ckFieldSqlValue, Object lowSqlValue) {\n return String.format(\" %s %s %s \", ckFieldSqlValue, moreThanEq ? Constants.Symbol.GTE : Constants.Symbol.GT, lowSqlValue);\n }\n\n private String getRangeHighSql(Object ckFieldSqlValue, Object highSqlValue) {\n return String.format(\" %s %s %s \", ckFieldSqlValue, lessThanEq ? Constants.Symbol.LTE : Constants.Symbol.LT, highSqlValue);\n }\n \n public Long getDiffMillSeconds() {\n return (Long) this.getHigh() - (Long) this.getLow();\n }\n}" }, { "identifier": "SortType", "path": "src/main/java/com/ly/ckibana/model/enums/SortType.java", "snippet": "public enum SortType {\n DESC,\n ASC\n}" } ]
import com.ly.ckibana.model.compute.Range; import com.ly.ckibana.model.enums.SortType; import lombok.AllArgsConstructor; import lombok.Data;
1,048
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ly.ckibana.model.response; /** * hits优化查询条件后的结果. * @author zl11357 * @since 2023/10/10 15:10 */ @Data @AllArgsConstructor public class HitsOptimizedResult { /** * 排序类型. */ private SortType sortType; /** * 优化后的时间区间. */
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ly.ckibana.model.response; /** * hits优化查询条件后的结果. * @author zl11357 * @since 2023/10/10 15:10 */ @Data @AllArgsConstructor public class HitsOptimizedResult { /** * 排序类型. */ private SortType sortType; /** * 优化后的时间区间. */
private Range optimizedTimeRange;
0
2023-11-21 09:12:07+00:00
2k
Team-B1ND/DAuth-SDK
src/main/java/com/b1nd/dauth/client/DAuthImpl.java
[ { "identifier": "DAuth", "path": "src/main/java/com/b1nd/dauth/DAuth.java", "snippet": "public interface DAuth {\n\n DAuthTokenInfo issueToken(String code);\n DAuthAccessTokenInfo reissueAccessToken(String refreshToken);\n DAuthUserInfo getUser(String accessToken);\n\n}" }, { "identifier": "DAuthTokenInfo", "path": "src/main/java/com/b1nd/dauth/client/response/DAuthTokenInfo.java", "snippet": "public final class DAuthTokenInfo {\n\n @JsonProperty(\"access_token\")\n private String accessToken;\n @JsonProperty(\"refresh_token\")\n private String refreshToken;\n @JsonProperty(\"token_type\")\n private String tokenType;\n @JsonProperty(\"expires_in\")\n private String expiresIn;\n\n public String getAccessToken() {\n return accessToken;\n }\n\n public String getRefreshToken() {\n return refreshToken;\n }\n\n public String getTokenType() {\n return tokenType;\n }\n\n public String getExpiresIn() {\n return expiresIn;\n }\n\n}" }, { "identifier": "DAuthAccessTokenInfo", "path": "src/main/java/com/b1nd/dauth/client/response/DAuthAccessTokenInfo.java", "snippet": "public final class DAuthAccessTokenInfo {\n\n @JsonProperty(\"access_token\")\n private String accessToken;\n @JsonProperty(\"token_type\")\n private String tokenType;\n @JsonProperty(\"expires_in\")\n private String expiresIn;\n\n public String getAccessToken() {\n return accessToken;\n }\n\n public String getTokenType() {\n return tokenType;\n }\n\n public String getExpiresIn() {\n return expiresIn;\n }\n\n}" }, { "identifier": "DAuthUserInfo", "path": "src/main/java/com/b1nd/dauth/client/response/DAuthUserInfo.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic final class DAuthUserInfo {\n\n @JsonProperty(\"data\")\n private DAuthUser user;\n\n public DAuthUser getUser() {\n return user;\n }\n\n}" }, { "identifier": "HttpProcessor", "path": "src/main/java/com/b1nd/dauth/helper/HttpProcessor.java", "snippet": "public abstract class HttpProcessor {\n\n public abstract String send(final ClassicHttpRequest request);\n\n public abstract <T> T convert(final String response, final Class<T> target);\n\n public <T> T execute(final ClassicHttpRequest request, final Class<T> target) {\n final String response = send(request);\n\n return convert(response, target);\n }\n\n}" }, { "identifier": "ObjectUtil", "path": "src/main/java/com/b1nd/dauth/util/ObjectUtil.java", "snippet": "public abstract class ObjectUtil {\n\n private static final ObjectMapper mapper = new ObjectMapper();\n\n public static <T> T convert(final String response, final Class<T> target) {\n try {\n return mapper.readValue(response, target);\n } catch (JsonProcessingException e) {\n throw new DAuthException(500);\n }\n }\n\n public static ObjectNode createNode(final String... keyValuePairs) {\n Assert.notOdd(keyValuePairs.length, \"Pairs\");\n\n final ObjectNode node = mapper.createObjectNode();\n\n return fillOut(node, keyValuePairs);\n }\n\n private static ObjectNode fillOut(final ObjectNode node, final String... keyValuePairs) {\n for (int i = 0; i<keyValuePairs.length; i+=2) {\n node.put(keyValuePairs[i], keyValuePairs[i+1]);\n }\n\n return node;\n }\n\n}" }, { "identifier": "HttpRequestUtil", "path": "src/main/java/com/b1nd/dauth/util/HttpRequestUtil.java", "snippet": "public abstract class HttpRequestUtil {\n\n public static ClassicHttpRequest create(final String uri, final ObjectNode node) {\n return ClassicRequestBuilder.post()\n .setUri(uri)\n .setEntity(toEntity(node))\n .build();\n }\n\n public static ClassicHttpRequest create(final String uri, final String accessToken) {\n return ClassicRequestBuilder.get()\n .setUri(uri)\n .setHeader(\"Authorization\", \"Bearer \" + accessToken)\n .build();\n }\n\n private static StringEntity toEntity(final ObjectNode node) {\n return new StringEntity(node.toString(), ContentType.APPLICATION_JSON);\n }\n\n}" }, { "identifier": "DodamUri", "path": "src/main/java/com/b1nd/dauth/client/DodamUri.java", "snippet": "enum DodamUri {\n\n USER_SERVER(\"http://open.dodam.b1nd.com/api/user\"),\n TOKEN_SERVER(\"http://dauth.b1nd.com/api/token\");\n\n private final String value;\n\n DodamUri(final String value) {\n this.value = value;\n }\n\n public String get() {\n return value;\n }\n\n}" } ]
import com.b1nd.dauth.DAuth; import com.b1nd.dauth.client.response.DAuthTokenInfo; import com.b1nd.dauth.client.response.DAuthAccessTokenInfo; import com.b1nd.dauth.client.response.DAuthUserInfo; import com.b1nd.dauth.helper.HttpProcessor; import com.b1nd.dauth.util.ObjectUtil; import com.b1nd.dauth.util.HttpRequestUtil; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.hc.core5.http.*; import static com.b1nd.dauth.client.DodamUri.*;
1,437
package com.b1nd.dauth.client; public class DAuthImpl implements DAuth { private final HttpProcessor httpProcessor; private final Client client; private static final String REFRESH = "/refresh"; DAuthImpl(final HttpProcessor httpProcessor, final Client client) { this.httpProcessor = httpProcessor; this.client = client; } @Override public DAuthTokenInfo issueToken(final String code) { final ObjectNode node = ObjectUtil.createNode("code", code, "client_id", client.id(), "client_secret", client.secret()); final ClassicHttpRequest request = HttpRequestUtil.create(TOKEN_SERVER.get(), node); return httpProcessor.execute(request, DAuthTokenInfo.class); } @Override public DAuthAccessTokenInfo reissueAccessToken(final String refreshToken) { final ObjectNode node = ObjectUtil.createNode("refreshToken", refreshToken, "clientId", client.id()); final String reissueAccessTokenUri = TOKEN_SERVER.get() + REFRESH; final ClassicHttpRequest request = HttpRequestUtil.create(reissueAccessTokenUri, node); return httpProcessor.execute(request, DAuthAccessTokenInfo.class); } @Override
package com.b1nd.dauth.client; public class DAuthImpl implements DAuth { private final HttpProcessor httpProcessor; private final Client client; private static final String REFRESH = "/refresh"; DAuthImpl(final HttpProcessor httpProcessor, final Client client) { this.httpProcessor = httpProcessor; this.client = client; } @Override public DAuthTokenInfo issueToken(final String code) { final ObjectNode node = ObjectUtil.createNode("code", code, "client_id", client.id(), "client_secret", client.secret()); final ClassicHttpRequest request = HttpRequestUtil.create(TOKEN_SERVER.get(), node); return httpProcessor.execute(request, DAuthTokenInfo.class); } @Override public DAuthAccessTokenInfo reissueAccessToken(final String refreshToken) { final ObjectNode node = ObjectUtil.createNode("refreshToken", refreshToken, "clientId", client.id()); final String reissueAccessTokenUri = TOKEN_SERVER.get() + REFRESH; final ClassicHttpRequest request = HttpRequestUtil.create(reissueAccessTokenUri, node); return httpProcessor.execute(request, DAuthAccessTokenInfo.class); } @Override
public DAuthUserInfo getUser(final String accessToken) {
3
2023-11-26 07:37:12+00:00
2k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/widgets/styles/PPspinnerStyle.java
[ { "identifier": "TextFieldStyle", "path": "core/src/main/java/com/badlogic/gdx/scenes/scene2d/ui/TextField.java", "snippet": "static public class TextFieldStyle {\n public BitmapFont font;\n public Color fontColor;\n public @Null Color focusedFontColor, disabledFontColor;\n public @Null Drawable background, focusedBackground, disabledBackground, cursor, selection;\n public @Null BitmapFont messageFont;\n public @Null Color messageFontColor;\n\n public TextFieldStyle () {\n }\n\n public TextFieldStyle (BitmapFont font, Color fontColor, @Null Drawable cursor, @Null Drawable selection,\n @Null Drawable background) {\n this.font = font;\n this.fontColor = fontColor;\n this.cursor = cursor;\n this.selection = selection;\n this.background = background;\n }\n\n public TextFieldStyle (TextFieldStyle style) {\n font = style.font;\n if (style.fontColor != null) fontColor = new Color(style.fontColor);\n if (style.focusedFontColor != null) focusedFontColor = new Color(style.focusedFontColor);\n if (style.disabledFontColor != null) disabledFontColor = new Color(style.disabledFontColor);\n\n background = style.background;\n focusedBackground = style.focusedBackground;\n disabledBackground = style.disabledBackground;\n cursor = style.cursor;\n selection = style.selection;\n\n messageFont = style.messageFont;\n if (style.messageFontColor != null) messageFontColor = new Color(style.messageFontColor);\n }\n}" }, { "identifier": "SpinnerStyle", "path": "core/src/main/java/com/ray3k/stripe/Spinner.java", "snippet": "static public class SpinnerStyle {\n public ButtonStyle buttonMinusStyle, buttonPlusStyle;\n public TextFieldStyle textFieldStyle;\n\n public SpinnerStyle() {\n\n }\n\n public SpinnerStyle(ButtonStyle buttonMinusStyle, ButtonStyle buttonPlusStyle, TextFieldStyle textFieldStyle) {\n this.buttonMinusStyle = buttonMinusStyle;\n this.buttonPlusStyle = buttonPlusStyle;\n this.textFieldStyle = textFieldStyle;\n }\n\n public SpinnerStyle(SpinnerStyle style) {\n buttonMinusStyle = style.buttonMinusStyle;\n buttonPlusStyle = style.buttonPlusStyle;\n textFieldStyle = style.textFieldStyle;\n }\n}" }, { "identifier": "skin", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/Core.java", "snippet": "public static Skin skin;" } ]
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.ray3k.stripe.Spinner.SpinnerStyle; import static com.ray3k.gdxparticleeditor.Core.skin;
647
package com.ray3k.gdxparticleeditor.widgets.styles; public class PPspinnerStyle extends SpinnerStyle { public PPspinnerStyle() {
package com.ray3k.gdxparticleeditor.widgets.styles; public class PPspinnerStyle extends SpinnerStyle { public PPspinnerStyle() {
buttonPlusStyle = skin.get("spinner-top", ButtonStyle.class);
2
2023-11-24 15:58:20+00:00
2k
373675032/love-charity
src/main/java/com/charity/component/LoginHandlerInterceptor.java
[ { "identifier": "RoleStatus", "path": "src/main/java/com/charity/constant/RoleStatus.java", "snippet": "public class RoleStatus {\n\n /**\n * 文章\n */\n public static final int USER = 0;\n\n /**\n * 活动\n */\n public static final int ADMIN = 1;\n}" }, { "identifier": "User", "path": "src/main/java/com/charity/entity/User.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class User implements Serializable {\n private static final long serialVersionUID = -15547846354844048L;\n /**\n * 主键ID\n */\n private Integer id;\n /**\n * 姓名\n */\n private String name;\n /**\n * 密码\n */\n private String password;\n /**\n * 邮箱地址\n */\n private String email;\n /**\n * 手机号码\n */\n private String phone;\n /**\n * 地址\n */\n private String address;\n /**\n * 性别:女(0)男(1)\n */\n private Integer sex;\n /**\n * 出生年月\n */\n private Date birthday;\n /**\n * 职业\n */\n private String career;\n /**\n * 认证ID\n */\n private Integer certificationId;\n /**\n * 头像地址\n */\n private String img;\n /**\n * 状态:正常(0),封禁(1)\n */\n private Integer status;\n /**\n * 注册时间\n */\n private Date gmtCreate;\n /**\n * 最近更新\n */\n private Date gmtModified;\n /**\n * 用户角色:普通用户(0),管理员(1)\n */\n private Integer role;\n\n}" } ]
import com.charity.constant.RoleStatus; import com.charity.entity.User; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
1,061
package com.charity.component; /** * 登录拦截器 * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ public class LoginHandlerInterceptor implements HandlerInterceptor { /** * 在目标方式执行之前执行 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getServletPath(); String[] array = new String[]{ "/publishActivity", "/updateActivity", "/deleteActivity", "/deleteBoard", "/checkCertification", "/deleteFeedBack", "/deleteLink", "/addLink", "/publishProject", "/updateProject", "/deleteProject", "/listUsers", "/editUser", "/admin-user", "/admin-certification", "/new-activity", "/edit-activity", "/admin-activity", "/new-project", "/admin-project", "/edit-project", "/admin-link", "/admin-feedback", "/admin-board", "/admin-project-comment", "/admin-activity-comment", "/admin-article", "/preview" }; List<String> adminPath = new ArrayList<>(Arrays.asList(array)); User user = (User) request.getSession().getAttribute("loginUser"); if (user == null) { //未登录,返回登录页面 response.sendRedirect("/love-charity/login-page"); return false; } else { // 如果是普通用户
package com.charity.component; /** * 登录拦截器 * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ public class LoginHandlerInterceptor implements HandlerInterceptor { /** * 在目标方式执行之前执行 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getServletPath(); String[] array = new String[]{ "/publishActivity", "/updateActivity", "/deleteActivity", "/deleteBoard", "/checkCertification", "/deleteFeedBack", "/deleteLink", "/addLink", "/publishProject", "/updateProject", "/deleteProject", "/listUsers", "/editUser", "/admin-user", "/admin-certification", "/new-activity", "/edit-activity", "/admin-activity", "/new-project", "/admin-project", "/edit-project", "/admin-link", "/admin-feedback", "/admin-board", "/admin-project-comment", "/admin-activity-comment", "/admin-article", "/preview" }; List<String> adminPath = new ArrayList<>(Arrays.asList(array)); User user = (User) request.getSession().getAttribute("loginUser"); if (user == null) { //未登录,返回登录页面 response.sendRedirect("/love-charity/login-page"); return false; } else { // 如果是普通用户
if (user.getRole() == RoleStatus.USER) {
0
2023-11-26 17:33:02+00:00
2k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_user/controller/admin/AdminMerchantWithdrawRecordController.java
[ { "identifier": "BasicResult", "path": "siam-common/src/main/java/com/siam/package_common/entity/BasicResult.java", "snippet": "@Data\npublic class BasicResult {\n\n public static final Integer CODE_DEFAULT_SUCCESS = 200;\n public static final Integer CODE_DEFAULT_ERROR = 500;\n\n public static final String MESSAGE_DEFAULT_SUCCESS = \"请求成功\";\n public static final String MESSAGE_DEFAULT_ERROR = \"网络异常\";\n\n private Boolean success;\n\n private Integer code;\n\n private String message;\n\n private Object data;\n\n public BasicResult() {\n }\n\n public BasicResult(Boolean success, Integer code, String message, Object data) {\n this.success = success;\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public static BasicResult success() {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, null);\n }\n\n public static BasicResult success(Object data) {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, data);\n }\n\n public static BasicResult error(String message) {\n return new BasicResult(false, CODE_DEFAULT_ERROR, message, null);\n }\n}" }, { "identifier": "ValidGroupOfAudit", "path": "siam-common/src/main/java/com/siam/package_common/model/valid_group/ValidGroupOfAudit.java", "snippet": "public interface ValidGroupOfAudit {\n}" }, { "identifier": "ValidGroupOfId", "path": "siam-common/src/main/java/com/siam/package_common/model/valid_group/ValidGroupOfId.java", "snippet": "public interface ValidGroupOfId {\n}" }, { "identifier": "MerchantWithdrawRecordParam", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_user/model/param/MerchantWithdrawRecordParam.java", "snippet": "@Data\npublic class MerchantWithdrawRecordParam extends MerchantWithdrawRecord {\n @NotNull(message = \"主键id不能为空\", groups = {ValidGroupOfId.class})\n private Integer id;\n\n private Integer merchantId;\n\n private BigDecimal withdrawAmount;\n\n private BigDecimal platformFee;\n\n private BigDecimal actualAmount;\n\n private Integer auditStatus;\n\n private String auditReason;\n\n private Date auditTime;\n\n private Date createTime;\n\n private Date updateTime;\n\n /**\n * 审核状态(1=通过 2=不通过)\n */\n @NotNull(message = \"审核状态不能为空\", groups = {ValidGroupOfAudit.class})\n @Range(min = 1, max = 2, message = \"审核状态必须介于1~2之间\", groups = {ValidGroupOfAudit.class})\n private Integer status;\n\n /**\n * 审核意见(当审核状态为不通过时必填)\n */\n private String opinion;\n\n //页码\n private Integer pageNo = 1;\n\n //页面大小\n private Integer pageSize = 20;\n}" }, { "identifier": "MerchantWithdrawRecordService", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_user/service/MerchantWithdrawRecordService.java", "snippet": "public interface MerchantWithdrawRecordService extends IService<MerchantWithdrawRecord> {\n\n int countByExample(MerchantWithdrawRecordExample example);\n\n void deleteByPrimaryKey(Integer id);\n\n void insert(MerchantWithdrawRecordParam param);\n\n MerchantWithdrawRecord selectByPrimaryKey(Integer id);\n\n void updateByPrimaryKeySelective(MerchantWithdrawRecord merchantWithdrawRecord);\n\n Page getListByPage(MerchantWithdrawRecordParam param);\n\n Page getListByPageJoinShop(MerchantWithdrawRecordParam param);\n\n Map<String, Object> statisticalAmount(MerchantWithdrawRecordParam param);\n\n /**\n * 审核申请体现商家信息\n *\n * @return\n * @author 暹罗\n */\n void auditApplyWithdraw(MerchantWithdrawRecordParam param);\n\n BasicResult countByAuditStatus(int auditStatus);\n}" } ]
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.annoation.AdminPermission; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.model.valid_group.ValidGroupOfAudit; import com.siam.package_common.model.valid_group.ValidGroupOfId; import com.siam.system.modular.package_user.model.param.MerchantWithdrawRecordParam; import com.siam.system.modular.package_user.service.MerchantWithdrawRecordService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map;
1,189
package com.siam.system.modular.package_user.controller.admin; @RestController @RequestMapping(value = "/rest/admin/merchantWithdrawRecord") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台商家提现记录模块相关接口", description = "AdminMerchantWithdrawRecordController") public class AdminMerchantWithdrawRecordController { @Autowired private MerchantWithdrawRecordService merchantWithdrawRecordService; @ApiOperation(value = "商家提现记录列表") @PostMapping(value = "/list")
package com.siam.system.modular.package_user.controller.admin; @RestController @RequestMapping(value = "/rest/admin/merchantWithdrawRecord") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台商家提现记录模块相关接口", description = "AdminMerchantWithdrawRecordController") public class AdminMerchantWithdrawRecordController { @Autowired private MerchantWithdrawRecordService merchantWithdrawRecordService; @ApiOperation(value = "商家提现记录列表") @PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) MerchantWithdrawRecordParam param){
0
2023-11-26 12:41:06+00:00
2k
junyharang-coding-study/GraphQL-Study
자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/team/repository/TeamQueryDslRepository.java
[ { "identifier": "team", "path": "자프링-GraphQL-실습/build/generated/querydsl/com/junyss/graphqltest/api/team/model/entity/QTeam.java", "snippet": "public static final QTeam team = new QTeam(\"team\");" }, { "identifier": "TeamSearchRequestDto", "path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/team/model/dto/request/TeamSearchRequestDto.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TeamSearchRequestDto {\n\tprivate String manager;\n\tprivate String office;\n\tprivate String extensionNumber;\n\tprivate String mascot;\n\tprivate String cleaningDuty;\n\tprivate String project;\n}" }, { "identifier": "TeamResponseDto", "path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/team/model/dto/response/TeamResponseDto.java", "snippet": "@Builder\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TeamResponseDto {\n\tprivate Long teamId;\n\tprivate String manager;\n\tprivate String office;\n\tprivate String extensionNumber;\n\tprivate String mascot;\n\tprivate String cleaningDuty;\n\tprivate String project;\n}" }, { "identifier": "PagingProcessUtil", "path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/util/PagingProcessUtil.java", "snippet": "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@Component\npublic class PagingProcessUtil {\n\n\tpublic static Pageable processPaging(int page, int size) {\n\t\tif (page <= 0 && size <= 0) {\n\t\t\tpage = 1;\n\t\t\tsize = 10;\n\t\t}\n\t\treturn PageRequest.of(page, size);\n\t}\n\n\tpublic static <T> List<T> queryDslPagingProcessing(JPAQuery<T> query, Pageable pageable) {\n\t\tList<T> result = new ArrayList<>();\n\n\t\tif (query.stream().count() >= 2) {\n\t\t\tresult = query.offset(pageable.getOffset())\n\t\t\t\t\t\t .limit(pageable.getPageSize())\n\t\t\t\t\t\t .fetch();\n\t\t} else {\n\t\t\tresult.add(query.fetchOne());\n\t\t}\n\n\t\treturn result;\n\t}\n}" } ]
import static com.junyss.graphqltest.api.team.model.entity.QTeam.team; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import com.junyss.graphqltest.api.team.model.dto.request.TeamSearchRequestDto; import com.junyss.graphqltest.api.team.model.dto.response.TeamResponseDto; import com.junyss.graphqltest.common.util.PagingProcessUtil; import com.querydsl.core.types.Projections; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import lombok.RequiredArgsConstructor;
706
package com.junyss.graphqltest.api.team.repository; @RequiredArgsConstructor @Repository public class TeamQueryDslRepository { private final JPAQueryFactory jpaQueryFactory;
package com.junyss.graphqltest.api.team.repository; @RequiredArgsConstructor @Repository public class TeamQueryDslRepository { private final JPAQueryFactory jpaQueryFactory;
public Page<TeamResponseDto> findBySearchAndPaging(TeamSearchRequestDto teamSearchRequestDto, Pageable pageable) {
2
2023-11-22 12:26:00+00:00
2k
windsbell/shardingkey-autofill
src/main/java/com/windsbell/shardingkey/autofill/handler/MapperShardingStrategyHandler.java
[ { "identifier": "CustomerLogger", "path": "src/main/java/com/windsbell/shardingkey/autofill/logger/CustomerLogger.java", "snippet": "public interface CustomerLogger {\n\n void info(String var1);\n\n void info(String var1, Object var2);\n\n void info(String var1, Object var2, Object var3);\n\n void info(String var1, Object... var2);\n\n void info(String var1, Throwable var2);\n\n void debug(String var1);\n\n void debug(String var1, Object var2);\n\n void debug(String var1, Object var2, Object var3);\n\n void debug(String var1, Object... var2);\n\n void debug(String var1, Throwable var2);\n\n void error(String var1);\n\n void error(String var1, Object var2);\n\n void error(String var1, Object var2, Object var3);\n\n void error(String var1, Object... var2);\n\n void error(String var1, Throwable var2);\n\n void warn(String var1);\n\n void warn(String var1, Object var2);\n\n void warn(String var1, Object var2, Object var3);\n\n void warn(String var1, Object... var2);\n\n void warn(String var1, Throwable var2);\n}" }, { "identifier": "CustomerLoggerFactory", "path": "src/main/java/com/windsbell/shardingkey/autofill/logger/CustomerLoggerFactory.java", "snippet": "public class CustomerLoggerFactory {\n\n // 打印开关\n private static boolean logEnabled = true;\n\n // 设置开关\n public static void init(Boolean logEnabled) {\n if (logEnabled != null) {\n CustomerLoggerFactory.logEnabled = logEnabled;\n }\n }\n\n public static CustomerLogger getLogger(Class<?> clazz) {\n return new CustomerLoggerImpl(LoggerFactory.getLogger(clazz), logEnabled);\n }\n\n}" }, { "identifier": "TableShardingKeyStrategy", "path": "src/main/java/com/windsbell/shardingkey/autofill/strategy/TableShardingKeyStrategy.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class TableShardingKeyStrategy extends ShardingKeyStrategy {\n\n private String table; // 表名\n\n private ShardingValueFinder shardingValueFinder; // 表对应的分片键查找器Class\n\n private List<String> necessaryBusinessKeys; // 必要业务键列表[条件中必须出现的业务键,通过其中出现的所有业务键可查出分库分表等键值对]\n\n private List<String> anyOneBusinessKeys; // 任意业务键列表[条件中出现以下任意一个业务键即可满足可查出分库分表等键值对]\n\n private String errorNotHasNecessaryBusinessKeys; // 检测提示未设置必要业务键列表\n\n private String errorNotHasAnyOneBusinessKeys; // 检测提示未设置任意业务键列表\n\n private String errorNotHaseDatabaseShardKey; // 检测提示未设置分库键\n\n private String errorNotHaseTableShardKey; // 检测提示未设置分表键\n\n\n}" } ]
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.windsbell.shardingkey.autofill.logger.CustomerLogger; import com.windsbell.shardingkey.autofill.logger.CustomerLoggerFactory; import com.windsbell.shardingkey.autofill.strategy.TableShardingKeyStrategy; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Parenthesis; import net.sf.jsqlparser.expression.operators.conditional.AndExpression; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.InExpression; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.update.Update; import org.springframework.util.Assert; import java.util.List;
1,081
package com.windsbell.shardingkey.autofill.handler; /** * mapper类型SQL自动填充分片键策略处理类 * 此处理器废弃:请移步新的Mapper2ShardingStrategyHandler * * @author windbell */ @Deprecated public class MapperShardingStrategyHandler extends AbstractShardingStrategyHandler implements ShardingStrategyHandler {
package com.windsbell.shardingkey.autofill.handler; /** * mapper类型SQL自动填充分片键策略处理类 * 此处理器废弃:请移步新的Mapper2ShardingStrategyHandler * * @author windbell */ @Deprecated public class MapperShardingStrategyHandler extends AbstractShardingStrategyHandler implements ShardingStrategyHandler {
private static final CustomerLogger log = CustomerLoggerFactory.getLogger(MapperShardingStrategyHandler.class);
0
2023-11-23 09:05:56+00:00
2k
Coderx-Gamer/cmd-utils
src/main/java/org/cmdutils/command/commands/SessionCommand.java
[ { "identifier": "MainClient", "path": "src/main/java/org/cmdutils/MainClient.java", "snippet": "public class MainClient implements ClientModInitializer {\n public static final Logger LOGGER = LoggerFactory.getLogger(\"cmd-utils\");\n\n\tpublic static KeyBinding terminalKey;\n\n\t@Override\n\tpublic void onInitializeClient() {\n\t\ttry {\n\t\t\tSystem.setProperty(\"java.awt.headless\", \"false\");\n\t\t\tSystem.setProperty(\"apple.awt.contentScaleFactor\", \"1\");\n\t\t\tSystem.setProperty(\"apple.awt.graphics.UseQuartz\", \"false\");\n\t\t} catch (Exception e) {\n\t\t\tLOGGER.warn(\"Failed to initialize Swing compatibility options on startup.\", e);\n\t\t}\n\n\t\tterminalKey = KeyBindingHelper.registerKeyBinding(new KeyBinding(\n\t\t\t\t\"key.terminal\",\n\t\t\t\tInputUtil.Type.KEYSYM,\n\t\t\t\tGLFW.GLFW_KEY_Y,\n\t\t\t\t\"key.categories.cmdutils\"\n\t\t));\n\n\t\tClientTickEvents.END_CLIENT_TICK.register((client) -> {\n\t\t\twhile (terminalKey.wasPressed()) {\n\t\t\t\tclient.setScreen(new InGameTerminalGui(null, null));\n\t\t\t}\n\t\t});\n\t}\n}" }, { "identifier": "Command", "path": "src/main/java/org/cmdutils/command/Command.java", "snippet": "public abstract class Command {\n public static final MinecraftClient client = MinecraftClient.getInstance();\n\n private final String name;\n private final String description;\n\n public Command(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public abstract int execute(String[] args, Logger logger, CommandEnvironment env);\n\n public String getName() {\n return this.name;\n }\n\n public String getDescription() {\n return this.description;\n }\n}" }, { "identifier": "CommandEnvironment", "path": "src/main/java/org/cmdutils/command/CommandEnvironment.java", "snippet": "public enum CommandEnvironment {\n IN_GAME, SWING\n}" }, { "identifier": "Commands", "path": "src/main/java/org/cmdutils/command/Commands.java", "snippet": "public class Commands {\n public static final int COMMAND_SUCCESS = 0;\n public static final int COMMAND_FAILURE = 1;\n\n public static final List<Command> COMMANDS = new ArrayList<>();\n\n public static void registerCommand(Command command) {\n COMMANDS.add(command);\n }\n\n public static Command find(String name) {\n for (Command command : COMMANDS) {\n if (command.getName().equals(name)) {\n return command;\n }\n }\n return null;\n }\n\n static {\n registerCommand(new ClearCommand());\n registerCommand(new HelpCommand());\n registerCommand(new CmdUtilsCommand());\n registerCommand(new SwingCommand());\n registerCommand(new CloseCommand());\n registerCommand(new DeSyncCommand());\n registerCommand(new MenuInfoCommand());\n registerCommand(new SaveGuiCommand());\n registerCommand(new RestoreGuiCommand());\n registerCommand(new LeaveCommand());\n registerCommand(new WakeCommand());\n registerCommand(new McfwCommand());\n registerCommand(new RPackCommand());\n registerCommand(new SessionCommand());\n registerCommand(new ChatCommand());\n registerCommand(new ClickCommand());\n registerCommand(new ButtonCommand());\n registerCommand(new TradeCommand());\n registerCommand(new LoopCommand());\n registerCommand(new DropCommand());\n }\n}" }, { "identifier": "SessionAccessor", "path": "src/main/java/org/cmdutils/mixin/accessor/SessionAccessor.java", "snippet": "@Mixin(Session.class)\npublic interface SessionAccessor {\n @Accessor\n String getUsername();\n\n @Accessor\n UUID getUuid();\n\n @Accessor\n String getAccessToken();\n\n @Accessor\n Session.AccountType getAccountType();\n\n @Accessor\n @Mutable\n void setUsername(String username);\n\n @Accessor\n @Mutable\n void setUuid(UUID uuid);\n\n @Accessor\n @Mutable\n void setAccessToken(String accessToken);\n\n @Accessor\n @Mutable\n void setAccountType(Session.AccountType accountType);\n}" }, { "identifier": "Logger", "path": "src/main/java/org/cmdutils/terminal/logger/Logger.java", "snippet": "public interface Logger {\n boolean canClear();\n void clear();\n void print(String text);\n void println(String text);\n void info(String log);\n void warn(String log);\n void error(String log);\n void error(Throwable throwable);\n void error(String log, Throwable throwable);\n}" } ]
import net.minecraft.client.session.Session; import org.cmdutils.MainClient; import org.cmdutils.command.Command; import org.cmdutils.command.CommandEnvironment; import org.cmdutils.command.Commands; import org.cmdutils.mixin.accessor.SessionAccessor; import org.cmdutils.terminal.logger.Logger; import java.util.UUID;
1,099
package org.cmdutils.command.commands; public class SessionCommand extends Command { public SessionCommand() { super("session", "Session ID getter/setter."); } @Override
package org.cmdutils.command.commands; public class SessionCommand extends Command { public SessionCommand() { super("session", "Session ID getter/setter."); } @Override
public int execute(String[] args, Logger logger, CommandEnvironment env) {
2
2023-11-20 15:23:34+00:00
2k
oxcened/opendialer
app/src/main/java/dev/alenajam/opendialer/App.java
[ { "identifier": "NotificationHelper", "path": "app/src/main/java/dev/alenajam/opendialer/helper/NotificationHelper.java", "snippet": "public abstract class NotificationHelper {\n private static final String CHANNEL_ID_INCOMING_CALLS = \"dev.alenajam.opendialer.notification_channel.incoming_calls\";\n private static final String CHANNEL_ID_ONGOING_CALLS = \"dev.alenajam.opendialer.notification_channel.ongoing_calls\";\n private static final String CHANNEL_ID_OUTGOING_CALLS = \"dev.alenajam.opendialer.notification_channel.outgoing_calls\";\n private static final int NOTIFICATION_ID_CALL = 1;\n private static final String INTENT_ACTION_CALL_BUTTON_CLICK_ACCEPT = \"dev.alenajam.opendialer.CALL_ACCEPT\";\n private static final String INTENT_ACTION_CALL_BUTTON_CLICK_DECLINE = \"dev.alenajam.opendialer.CALL_DECLINE\";\n\n\n public static void setupNotificationChannels(Context context) {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n createCallChannel(context, CHANNEL_ID_INCOMING_CALLS, context.getString(R.string.channel_incoming_calls), NotificationManager.IMPORTANCE_HIGH);\n createCallChannel(context, CHANNEL_ID_ONGOING_CALLS, context.getString(R.string.channel_ongoing_calls), NotificationManager.IMPORTANCE_DEFAULT);\n createCallChannel(context, CHANNEL_ID_OUTGOING_CALLS, context.getString(R.string.channel_outgoing_calls), NotificationManager.IMPORTANCE_DEFAULT);\n }\n }\n\n private static void createCallChannel(Context context, String channelId, String channelName, int channelImportance) {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);\n\n notificationChannel.setSound(null, null);\n\n NotificationManager notificationManager = context.getSystemService(NotificationManager.class);\n if (notificationManager != null) {\n notificationManager.createNotificationChannel(notificationChannel);\n }\n }\n }\n}" }, { "identifier": "SharedPreferenceHelper", "path": "app/src/main/java/dev/alenajam/opendialer/helper/SharedPreferenceHelper.java", "snippet": "public abstract class SharedPreferenceHelper {\n public static final String SP_QUICK_RESPONSES = \"SP_QUICK_RESPONSES\";\n public static final String KEY_SETTING_THEME = \"theme\";\n\n public static SharedPreferences getSharedPreferences(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n public static void init(Context context) {\n SharedPreferences sharedPreferences = getSharedPreferences(context);\n\n String theme = sharedPreferences.getString(SharedPreferenceHelper.KEY_SETTING_THEME, null);\n try {\n CommonUtils.setTheme(theme == null ? AppCompatDelegate.MODE_NIGHT_NO : Integer.parseInt(theme));\n } catch (NumberFormatException e) {\n if (e.getLocalizedMessage() != null)\n Log.d(App.class.getSimpleName(), e.getLocalizedMessage());\n }\n\n if (!sharedPreferences.contains(SharedPreferenceHelper.SP_QUICK_RESPONSES)) {\n String[] quickResponses = context.getResources().getStringArray(R.array.array_quick_responses);\n ArrayList<String> quickResponseList = new ArrayList<>(Arrays.asList(quickResponses));\n sharedPreferences.edit().putString(SharedPreferenceHelper.SP_QUICK_RESPONSES, new Gson().toJson(quickResponseList)).apply();\n }\n }\n}" } ]
import android.app.Application; import dagger.hilt.android.HiltAndroidApp; import dev.alenajam.opendialer.helper.NotificationHelper; import dev.alenajam.opendialer.helper.SharedPreferenceHelper;
823
package dev.alenajam.opendialer; @HiltAndroidApp public class App extends Application { @Override public void onCreate() { super.onCreate();
package dev.alenajam.opendialer; @HiltAndroidApp public class App extends Application { @Override public void onCreate() { super.onCreate();
NotificationHelper.setupNotificationChannels(this);
0
2023-11-21 21:24:39+00:00
2k
pewaru-333/HomeMedkit-App
app/src/main/java/ru/application/homemedkit/helpers/SettingsHelper.java
[ { "identifier": "CHECK_EXP_DATE", "path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java", "snippet": "public static final String CHECK_EXP_DATE = \"check_exp_date\";" }, { "identifier": "MainActivity", "path": "app/src/main/java/ru/application/homemedkit/activities/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n private ActivityMainBinding binding;\n private SettingsHelper settings;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n\n settings = new SettingsHelper(this);\n settings.getAppTheme();\n\n binding.bottomNavigationBarView.setOnItemSelectedListener(pickMenuItem());\n\n getFragmentPage();\n setExpirationChecker();\n }\n\n @Override\n public void onConfigurationChanged(@NonNull Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n\n recreate();\n getIntent().putExtra(SETTINGS_CHANGED, true);\n }\n\n private void getFragmentPage() {\n\n if (getIntent().getBooleanExtra(NEW_MEDICINE, false))\n binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_medicines);\n else if (getIntent().getBooleanExtra(NEW_INTAKE, false))\n binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_intakes);\n else if (getIntent().getBooleanExtra(SETTINGS_CHANGED, false))\n binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_settings);\n else toHomePage();\n }\n\n private NavigationBarView.OnItemSelectedListener pickMenuItem() {\n return item -> {\n int itemId = item.getItemId();\n\n if (itemId == R.id.bottom_menu_main) replace(new FragmentHome());\n else if (itemId == R.id.bottom_menu_medicines) replace(new FragmentMedicines());\n else if (itemId == R.id.bottom_menu_intakes) replace(new FragmentIntakes());\n else if (itemId == R.id.bottom_menu_settings) replace(new FragmentSettings());\n\n return true;\n };\n }\n\n private void toHomePage() {\n String[] pages = getResources().getStringArray(R.array.fragment_pages);\n String homePage = settings.getHomePage();\n\n if (homePage.equals(pages[1]))\n binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_medicines);\n else if (homePage.equals(pages[2]))\n binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_intakes);\n else if (homePage.equals(pages[3]))\n binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_settings);\n else binding.bottomNavigationBarView.setSelectedItemId(R.id.bottom_menu_main);\n }\n\n private void replace(Fragment fragment) {\n getSupportFragmentManager().beginTransaction().replace(R.id.constraintLayout, fragment).commit();\n }\n\n public void setExpirationChecker() {\n new AlarmSetter(this).checkExpiration();\n }\n}" } ]
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM; import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO; import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES; import static androidx.appcompat.app.AppCompatDelegate.setApplicationLocales; import static androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode; import static androidx.core.os.LocaleListCompat.forLanguageTags; import static ru.application.homemedkit.helpers.ConstantsHelper.CHECK_EXP_DATE; import android.content.Context; import android.content.SharedPreferences; import androidx.fragment.app.FragmentActivity; import androidx.preference.PreferenceManager; import ru.application.homemedkit.R; import ru.application.homemedkit.activities.MainActivity;
1,159
package ru.application.homemedkit.helpers; public class SettingsHelper { public static final String LANGUAGE = "language"; public static final String KEY_FRAGMENT = "default_start_fragment"; public static final String APP_THEME = "app_theme"; public static final String LIGHT_PERIOD = "light_period_picker"; private static final String KEY_ORDER = "sorting_order"; public static String DEFAULT_FRAGMENT, DEFAULT_SORTING, DEFAULT_THEME; private final SharedPreferences preferences; private String[] themes; public SettingsHelper(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); loadValues(context); } public String getHomePage() { return preferences.getString(KEY_FRAGMENT, DEFAULT_FRAGMENT); } public String getSortingOrder() { return preferences.getString(KEY_ORDER, DEFAULT_SORTING); } public void setSortingOrder(String order) { preferences.edit().putString(KEY_ORDER, order).apply(); } public void changeLanguage(String language) { setApplicationLocales(forLanguageTags(language)); preferences.edit().putString(LANGUAGE, language).apply(); } public void getAppTheme() { String theme = preferences.getString(APP_THEME, DEFAULT_THEME); changeTheme(theme); } private void changeTheme(String theme) { if (theme.equals(themes[0])) setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM); else if (theme.equals(themes[1])) setDefaultNightMode(MODE_NIGHT_NO); else setDefaultNightMode(MODE_NIGHT_YES); } public void setAppTheme(String theme) { preferences.edit().putString(APP_THEME, theme).apply(); changeTheme(theme); } public void setExpDateChecker(FragmentActivity activity, boolean value) {
package ru.application.homemedkit.helpers; public class SettingsHelper { public static final String LANGUAGE = "language"; public static final String KEY_FRAGMENT = "default_start_fragment"; public static final String APP_THEME = "app_theme"; public static final String LIGHT_PERIOD = "light_period_picker"; private static final String KEY_ORDER = "sorting_order"; public static String DEFAULT_FRAGMENT, DEFAULT_SORTING, DEFAULT_THEME; private final SharedPreferences preferences; private String[] themes; public SettingsHelper(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); loadValues(context); } public String getHomePage() { return preferences.getString(KEY_FRAGMENT, DEFAULT_FRAGMENT); } public String getSortingOrder() { return preferences.getString(KEY_ORDER, DEFAULT_SORTING); } public void setSortingOrder(String order) { preferences.edit().putString(KEY_ORDER, order).apply(); } public void changeLanguage(String language) { setApplicationLocales(forLanguageTags(language)); preferences.edit().putString(LANGUAGE, language).apply(); } public void getAppTheme() { String theme = preferences.getString(APP_THEME, DEFAULT_THEME); changeTheme(theme); } private void changeTheme(String theme) { if (theme.equals(themes[0])) setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM); else if (theme.equals(themes[1])) setDefaultNightMode(MODE_NIGHT_NO); else setDefaultNightMode(MODE_NIGHT_YES); } public void setAppTheme(String theme) { preferences.edit().putString(APP_THEME, theme).apply(); changeTheme(theme); } public void setExpDateChecker(FragmentActivity activity, boolean value) {
preferences.edit().putBoolean(CHECK_EXP_DATE, value).apply();
0
2023-11-19 10:26:15+00:00
2k
ThomasVitale/multitenant-spring-boot-demo
instrument-service/src/main/java/com/thomasvitale/instrumentservice/demo/DataConfig.java
[ { "identifier": "Instrument", "path": "instrument-service/src/main/java/com/thomasvitale/instrumentservice/instrument/domain/Instrument.java", "snippet": "@Entity\npublic class Instrument {\n \n\t@Id\n\t@GeneratedValue(strategy=GenerationType.UUID)\n\tprivate UUID id;\n\n\t@NotEmpty\n\tprivate String name;\n\n\tprivate String type;\n\n\tpublic Instrument() {}\n\n\tpublic Instrument(String name, String type) {\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t}\n\n\tpublic Instrument(UUID id, String name, String type) {\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t}\n\n\tpublic UUID getId() {\n\t\treturn id;\n\t}\n\n \tpublic void setId(UUID id) {\n\t\tthis.id = id;\n\t}\n\n \tpublic String getName() {\n \treturn name;\n \t}\n\n \tpublic void setName(String name) {\n \tthis.name = name;\n \t}\n\n \tpublic String getType() {\n \treturn type;\n \t}\n\n \tpublic void setType(String type) {\n \tthis.type = type;\n \t}\n\n}" }, { "identifier": "InstrumentRepository", "path": "instrument-service/src/main/java/com/thomasvitale/instrumentservice/instrument/domain/InstrumentRepository.java", "snippet": "public interface InstrumentRepository extends JpaRepository<Instrument,UUID> {\n\tList<Instrument> findByType(String type);\n}" }, { "identifier": "TenantContext", "path": "instrument-service/src/main/java/com/thomasvitale/instrumentservice/multitenancy/context/TenantContext.java", "snippet": "public final class TenantContext {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(TenantContext.class);\n\tprivate static final ThreadLocal<String> tenantId = new InheritableThreadLocal<>();\n \n\tpublic static void setTenantId(String tenant) {\n \tlog.debug(\"Setting current tenant to {}\", tenant);\n \ttenantId.set(tenant);\n\t}\n\n\tpublic static String getTenantId() {\n \treturn tenantId.get();\n \t}\n\n\tpublic static void clear() {\n \ttenantId.remove();\n \t}\n\n}" } ]
import java.util.List; import com.thomasvitale.instrumentservice.instrument.domain.Instrument; import com.thomasvitale.instrumentservice.instrument.domain.InstrumentRepository; import com.thomasvitale.instrumentservice.multitenancy.context.TenantContext; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener;
664
package com.thomasvitale.instrumentservice.demo; @Configuration(proxyBeanMethods = false) public class DataConfig { private final InstrumentRepository instrumentRepository; public DataConfig(InstrumentRepository instrumentRepository) { this.instrumentRepository = instrumentRepository; } @EventListener(ApplicationReadyEvent.class) public void loadTestData() { TenantContext.setTenantId("dukes"); if (instrumentRepository.count() == 0) {
package com.thomasvitale.instrumentservice.demo; @Configuration(proxyBeanMethods = false) public class DataConfig { private final InstrumentRepository instrumentRepository; public DataConfig(InstrumentRepository instrumentRepository) { this.instrumentRepository = instrumentRepository; } @EventListener(ApplicationReadyEvent.class) public void loadTestData() { TenantContext.setTenantId("dukes"); if (instrumentRepository.count() == 0) {
var piano = new Instrument("Steinway", "piano");
0
2023-11-20 15:41:58+00:00
2k
3dcitydb/citydb-tool
citydb-plugin/src/main/java/org/citydb/plugin/PluginManager.java
[ { "identifier": "LazyInitializer", "path": "citydb-core/src/main/java/org/citydb/core/concurrent/LazyInitializer.java", "snippet": "public class LazyInitializer<T, E extends Throwable> {\n private final Object lock = new Object();\n private final CheckedSupplier<T, E> supplier;\n private volatile boolean initialized = false;\n private T object = null;\n\n private LazyInitializer(CheckedSupplier<T, E> supplier) {\n this.supplier = supplier;\n }\n\n public static <T, E extends Exception> LazyInitializer<T, E> of(CheckedSupplier<T, E> supplier) {\n return new LazyInitializer<>(supplier);\n }\n\n public T get() throws E {\n if (!initialized) {\n synchronized (lock) {\n if (!initialized) {\n T result = supplier.get();\n object = result;\n initialized = true;\n return result;\n }\n }\n }\n\n return object;\n }\n}" }, { "identifier": "PluginMetadata", "path": "citydb-plugin/src/main/java/org/citydb/plugin/metadata/PluginMetadata.java", "snippet": "public class PluginMetadata {\n private String name;\n private String version;\n private String url;\n @JSONField(name = \"description\")\n private final Map<String, String> descriptions = new HashMap<>();\n private PluginVendor vendor;\n private boolean startEnabled = true;\n\n public String getName() {\n return name;\n }\n\n public PluginMetadata setName(String name) {\n this.name = name;\n return this;\n }\n\n public String getVersion() {\n return version;\n }\n\n public PluginMetadata setVersion(String version) {\n this.version = version;\n return this;\n }\n\n public String getUrl() {\n return url;\n }\n\n public PluginMetadata setUrl(String url) {\n this.url = url;\n return this;\n }\n\n public Map<String, String> getDescriptions() {\n return descriptions;\n }\n\n public PluginMetadata addDescription(String language, String description) {\n descriptions.put(language, description);\n return this;\n }\n\n public PluginVendor getVendor() {\n return vendor;\n }\n\n public PluginMetadata setVendor(PluginVendor vendor) {\n this.vendor = vendor;\n return this;\n }\n\n public boolean isStartEnabled() {\n return startEnabled;\n }\n\n public PluginMetadata setStartEnabled(boolean startEnabled) {\n this.startEnabled = startEnabled;\n return this;\n }\n}" } ]
import java.nio.file.Path; import java.util.*; import java.util.stream.Stream; import com.alibaba.fastjson2.JSON; import org.citydb.core.concurrent.LazyInitializer; import org.citydb.plugin.metadata.PluginMetadata; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileVisitOption; import java.nio.file.Files;
936
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.plugin; public class PluginManager { private static final PluginManager instance = new PluginManager(); private final Map<String, Plugin> plugins = new HashMap<>(); private final Map<Class<? extends Extension>, ExtensionInfo> extensions = new HashMap<>(); private Map<String, List<PluginException>> exceptions; private ClassLoader loader;
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.plugin; public class PluginManager { private static final PluginManager instance = new PluginManager(); private final Map<String, Plugin> plugins = new HashMap<>(); private final Map<Class<? extends Extension>, ExtensionInfo> extensions = new HashMap<>(); private Map<String, List<PluginException>> exceptions; private ClassLoader loader;
private record ExtensionInfo(LazyInitializer<Extension, PluginException> extension, Plugin plugin) {
0
2023-11-19 12:29:54+00:00
2k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/craftbukkit/v1_12_R1/scheduler/CraftAsyncTask.java
[ { "identifier": "Plugin", "path": "src/main/java/org/bukkit/plugin/Plugin.java", "snippet": "public interface Plugin extends TabExecutor {\n /**\n * Returns the folder that the plugin data's files are located in. The\n * folder may not yet exist.\n *\n * @return The folder\n */\n public File getDataFolder();\n\n /**\n * Returns the plugin.yaml file containing the details for this plugin\n *\n * @return Contents of the plugin.yaml file\n */\n public PluginDescriptionFile getDescription();\n\n /**\n * Gets a {@link FileConfiguration} for this plugin, read through\n * \"config.yml\"\n * <p>\n * If there is a default config.yml embedded in this plugin, it will be\n * provided as a default for this Configuration.\n *\n * @return Plugin configuration\n */\n public FileConfiguration getConfig();\n\n /**\n * Gets an embedded resource in this plugin\n *\n * @param filename Filename of the resource\n * @return File if found, otherwise null\n */\n public InputStream getResource(String filename);\n\n /**\n * Saves the {@link FileConfiguration} retrievable by {@link #getConfig()}.\n */\n public void saveConfig();\n\n /**\n * Saves the raw contents of the default config.yml file to the location\n * retrievable by {@link #getConfig()}.\n * <p>\n * This should fail silently if the config.yml already exists.\n */\n public void saveDefaultConfig();\n\n /**\n * Saves the raw contents of any resource embedded with a plugin's .jar\n * file assuming it can be found using {@link #getResource(String)}.\n * <p>\n * The resource is saved into the plugin's data folder using the same\n * hierarchy as the .jar file (subdirectories are preserved).\n *\n * @param resourcePath the embedded resource path to look for within the\n * plugin's .jar file. (No preceding slash).\n * @param replace if true, the embedded resource will overwrite the\n * contents of an existing file.\n * @throws IllegalArgumentException if the resource path is null, empty,\n * or points to a nonexistent resource.\n */\n public void saveResource(String resourcePath, boolean replace);\n\n /**\n * Discards any data in {@link #getConfig()} and reloads from disk.\n */\n public void reloadConfig();\n\n /**\n * Gets the associated PluginLoader responsible for this plugin\n *\n * @return PluginLoader that controls this plugin\n */\n public PluginLoader getPluginLoader();\n\n /**\n * Returns the Server instance currently running this plugin\n *\n * @return Server running this plugin\n */\n public Server getServer();\n\n /**\n * Returns a value indicating whether or not this plugin is currently\n * enabled\n *\n * @return true if this plugin is enabled, otherwise false\n */\n public boolean isEnabled();\n\n /**\n * Called when this plugin is disabled\n */\n public void onDisable();\n\n /**\n * Called after a plugin is loaded but before it has been enabled.\n * <p>\n * When multiple plugins are loaded, the onLoad() for all plugins is\n * called before any onEnable() is called.\n */\n public void onLoad();\n\n /**\n * Called when this plugin is enabled\n */\n public void onEnable();\n\n /**\n * Simple boolean if we can still nag to the logs about things\n *\n * @return boolean whether we can nag\n */\n public boolean isNaggable();\n\n /**\n * Set naggable state\n *\n * @param canNag is this plugin still naggable?\n */\n public void setNaggable(boolean canNag);\n\n /**\n * Gets a {@link ChunkGenerator} for use in a default world, as specified\n * in the server configuration\n *\n * @param worldName Name of the world that this will be applied to\n * @param id Unique ID, if any, that was specified to indicate which\n * generator was requested\n * @return ChunkGenerator for use in the default world generation\n */\n public ChunkGenerator getDefaultWorldGenerator(String worldName, String id);\n\n /**\n * Returns the plugin logger associated with this server's logger. The\n * returned logger automatically tags all log messages with the plugin's\n * name.\n *\n * @return Logger associated with this plugin\n */\n public Logger getLogger();\n\n /**\n * Returns the name of the plugin.\n * <p>\n * This should return the bare name of the plugin and should be used for\n * comparison.\n *\n * @return name of the plugin\n */\n public String getName();\n}" }, { "identifier": "BukkitWorker", "path": "src/main/java/org/bukkit/scheduler/BukkitWorker.java", "snippet": "public interface BukkitWorker {\n\n /**\n * Returns the taskId for the task being executed by this worker.\n *\n * @return Task id number\n */\n public int getTaskId();\n\n /**\n * Returns the Plugin that owns this task.\n *\n * @return The Plugin that owns the task\n */\n public Plugin getOwner();\n\n /**\n * Returns the thread for the worker.\n *\n * @return The Thread object for the worker\n */\n public Thread getThread();\n\n}" } ]
import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.logging.Level; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitWorker;
1,424
package org.bukkit.craftbukkit.v1_12_R1.scheduler; class CraftAsyncTask extends CraftTask { private final LinkedList<BukkitWorker> workers = new LinkedList<BukkitWorker>(); private final Map<Integer, CraftTask> runners;
package org.bukkit.craftbukkit.v1_12_R1.scheduler; class CraftAsyncTask extends CraftTask { private final LinkedList<BukkitWorker> workers = new LinkedList<BukkitWorker>(); private final Map<Integer, CraftTask> runners;
CraftAsyncTask(final Map<Integer, CraftTask> runners, final Plugin plugin, final Runnable task, final int id, final long delay) {
0
2023-11-22 11:25:51+00:00
2k
Barsanti5BI/flight-simulator
src/Aereo/Aereo.java
[ { "identifier": "Parcheggio", "path": "src/TorreDiControllo/Parcheggio.java", "snippet": "public class Parcheggio {\n public int id;\n private Aereo aereo;\n private Gate gate;\n public Boolean distanza;\n\n public Manutentore manu;\n\n public Parcheggio(int n, Gate g)\n {\n this.id = n;\n this.gate = g;\n //this.manu = new Manutentore();ancora da mettere\n Random r = new Random();\n distanza = r.nextBoolean();\n\n }\n\n //controlla se il parcheggio è libero\n public Boolean isFree()\n {\n return aereo == null;\n }\n\n //passa l'aereo al manutentore e fa la manutenzione\n public void aereoArrivato(Aereo A)\n {\n aereo = A;\n manu.a = A;\n manu.Manutenzione();\n }\n\n //libera il parcheggio\n public void AereoInPartenza()\n {\n aereo = null;\n manu.a = null;\n }\n\n public int GetId()\n {\n return id;\n }\n\n //restituisce la distanza\n public boolean GetDistanza()\n {\n return distanza;\n }\n\n public Gate GetGate()\n {\n return gate;\n }\n\n public Aereo GetAereo()\n {\n return aereo;\n }\n public boolean GateFree()\n {\n return gate.getTerminatiIControlli();\n }\n}" }, { "identifier": "Pista", "path": "src/TorreDiControllo/Pista.java", "snippet": "public class Pista {\n\n private boolean occupata; //Variabile boolean per indicare se la pista sia libera o occupata\n private int id; //Variabile int per rappresentare la pista\n public Aereo aereo; //Aereo\n private LocalDateTime istanteOccupazione;\n\n public Pista(int id){ //Costruttore\n aereo = null;\n this.id = id;\n this.occupata = false;\n }\n\n //controlla se la pista sia occupata o meno\n public boolean isOccupata() {\n return occupata;\n }\n\n //identifica la pista\n public int getId() {\n return id;\n }\n\n //Feauture Matteo\n // Verifica se il meteo consente di occupare la pista\n //Se la funzione GetMeteo mi restituisce \"true\" la pista potra' essere occupata\n public void occupaPista(Meteo meteo) {\n if (meteo.DammiMeteoAttuale()) {\n if (!occupata) {\n System.out.println(\"La pista \" + id + \" è ora occupata.\");\n occupata = true;\n istanteOccupazione = LocalDateTime.now();\n } else {\n System.out.println(\"La pista \" + id + \" è già occupata.\");\n }\n } else {\n System.out.println(\"Impossibile occupare la pista \" + id + \" a causa delle condizioni meteorologiche.\");\n }\n }\n\n //Feauture Matteo\n public void liberaPista() {\n if (occupata) {\n System.out.println(\"La pista \" + id + \" è ora libera.\");\n occupata = false;\n istanteOccupazione = null;\n } else {\n System.out.println(\"La pista \" + id + \" è già libera.\");\n }\n }\n\n\n //Stato della pista\n //Questa funzione (semplice ToString) mostra lo stato generale della pista\n public String toString() {\n return \"Pista{\" +\n \"id=\" + id +\n \", occupata=\" + occupata +\n \", istanteOccupazione=\" + istanteOccupazione +\n '}';\n }\n\n public void SetAereo(Aereo a)\n {\n aereo = a;\n }\n}" } ]
import TorreDiControllo.Parcheggio; import TorreDiControllo.Pista; import java.util.ArrayList; import java.util.Random;
1,173
package Aereo; public abstract class Aereo extends Thread{ public int id; public String destinazione; public int posizione; public Gate gate; private ArrayList<Bagno> bagni; private ScatolaNera scatolaNera; private ArrayList<Turbina> turbine; private Stiva stiva; private Serbatoio serbatoio; private boolean pilotaAutomatico; public Alieni alieni; public boolean einvolo; private boolean maltempo; private Random r; private Pista p;
package Aereo; public abstract class Aereo extends Thread{ public int id; public String destinazione; public int posizione; public Gate gate; private ArrayList<Bagno> bagni; private ScatolaNera scatolaNera; private ArrayList<Turbina> turbine; private Stiva stiva; private Serbatoio serbatoio; private boolean pilotaAutomatico; public Alieni alieni; public boolean einvolo; private boolean maltempo; private Random r; private Pista p;
private Parcheggio parcheggio;
0
2023-11-18 07:13:43+00:00
2k
KirillKurdyukov/ydb-r2dbc
src/main/java/tech/ydb/io/r2dbc/YDBStatement.java
[ { "identifier": "YDBConnectionState", "path": "src/main/java/tech/ydb/io/r2dbc/state/YDBConnectionState.java", "snippet": "public sealed interface YDBConnectionState permits Close, InTransaction, OutTransaction {\n\n CompletableFuture<Result<DataQueryResult>> executeDataQuery(String yql, Params params);\n}" }, { "identifier": "YDBParameterResolver", "path": "src/main/java/tech/ydb/io/r2dbc/parameter/YDBParameterResolver.java", "snippet": "public class YDBParameterResolver {\n\n private static final HashMap<Class<?>, YDBType> CLASS_YDB_TYPE = new HashMap<>();\n\n static {\n for (YDBType value : YDBType.values()) {\n CLASS_YDB_TYPE.put(value.getJavaType(), value);\n }\n }\n\n private YDBParameterResolver() {\n }\n\n public static Value<?> resolve(Object param) {\n if (param instanceof Value<?> value) {\n return value;\n } else if (param instanceof Parameter parameter) {\n return resolveParameter(parameter, param);\n }\n\n if (CLASS_YDB_TYPE.containsKey(param.getClass())) {\n return CLASS_YDB_TYPE.get(param.getClass())\n .createValue(param);\n } else {\n throw new RuntimeException(); // TODO correct exception\n }\n }\n\n private static Value<?> resolveParameter(Parameter parameter, Object param) {\n if (parameter.getType() instanceof R2dbcType r2dbcType) {\n return YDBType.valueOf(r2dbcType).createValue(param);\n } else if (parameter.getType() instanceof YDBType ydbType) {\n return ydbType.createValue(param);\n }\n\n throw new RuntimeException(); // TODO correct exception\n }\n}" } ]
import io.r2dbc.spi.Result; import io.r2dbc.spi.Statement; import reactor.core.publisher.Mono; import tech.ydb.io.r2dbc.state.YDBConnectionState; import tech.ydb.io.r2dbc.parameter.YDBParameterResolver; import tech.ydb.table.query.Params;
743
/* * Copyright 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 tech.ydb.io.r2dbc; /** * @author Kirill Kurdyukov */ public class YDBStatement implements Statement { private final String sql; // YQL Dialect private final YDBConnectionState state; private final Params params; public YDBStatement(YDBConnectionState state, String sql) { this.sql = sql; this.state = state; this.params = Params.create(); } @Override public Statement add() { throw new UnsupportedOperationException("Unsupported batch params"); } @Override public Statement bind(int index, Object value) { throw new UnsupportedOperationException("Use parameter binding by name"); } @Override public Statement bind(String name, Object value) {
/* * Copyright 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 tech.ydb.io.r2dbc; /** * @author Kirill Kurdyukov */ public class YDBStatement implements Statement { private final String sql; // YQL Dialect private final YDBConnectionState state; private final Params params; public YDBStatement(YDBConnectionState state, String sql) { this.sql = sql; this.state = state; this.params = Params.create(); } @Override public Statement add() { throw new UnsupportedOperationException("Unsupported batch params"); } @Override public Statement bind(int index, Object value) { throw new UnsupportedOperationException("Use parameter binding by name"); } @Override public Statement bind(String name, Object value) {
params.put(String.format("$%s", name), YDBParameterResolver.resolve(value));
1
2023-11-26 10:39:40+00:00
2k
Youkehai/openai_assistants_java
assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/run/RunBaseResp.java
[ { "identifier": "RunStatusEnum", "path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/constant/RunStatusEnum.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum RunStatusEnum {\n\n EXPIRED(\"expired\", \"过期\"),\n COMPLETED(\"completed\", \"已完成\"),\n FAILED(\"failed\", \"执行失败\"),\n CANCELLED(\"cancelled\", \"已取消\"),\n CANCELLING(\"cancelling\", \"正在取消\"),\n REQUIRES_ACTION(\"requires_action\", \"在等待必要动作\"),\n IN_PROGRESS(\"in_progress\", \"正在处理\"),\n QUEUED(\"queued\", \"队列中\");\n\n /**\n * 对应状态\n */\n private final String status;\n\n /**\n * 中文描述\n */\n private final String descZh;\n\n /**\n * 判断当前状态是否属于结束状态\n * 目前: 过期,已完成,执行失败,已取消 四个状态都算结束状态\n *\n * @param status 被判断的状态\n * @return true 表示该 run 已结束\n */\n public static boolean isEnd(String status) {\n return EXPIRED.status.equals(status) || COMPLETED.status.equals(status)\n || FAILED.status.equals(status) || CANCELLED.status.equals(status);\n }\n}" }, { "identifier": "BaseResp", "path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/BaseResp.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class BaseResp {\n\n private String createAt;\n\n @JsonIgnore\n private Long created_at;\n\n public String getCreateAt() {\n return DateUtil.formatDateByTimeStamp(created_at);\n }\n\n /**\n * ID\n */\n private String id;\n\n /**\n * 类型,例如:thread , message,assistant\n */\n private String object;\n\n /**\n * metadata 字段:可以附加到对象的 16 对键值对。\n * 这对于以结构化格式存储有关对象的额外信息很有用。\n * 键的最大长度为 64 个字符,值的最大长度为 512 个字符\n */\n private Map<String, String> metadata;\n\n}" }, { "identifier": "DateUtil", "path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/util/DateUtil.java", "snippet": "public class DateUtil {\n\n /**\n * 通过时间戳格式化\n *\n * @param timeStamp 时间戳\n * @return yyyy-mm-dd hh:mm:ss\n */\n public static String formatDateByTimeStamp(Long timeStamp) {\n if (ObjectUtil.isEmpty(timeStamp)) {\n return \"\";\n }\n DateTime date = cn.hutool.core.date.DateUtil.date(timeStamp * 1000);\n return date.toString();\n }\n}" } ]
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.youkehai.assistant.core.constant.RunStatusEnum; import io.github.youkehai.assistant.core.resp.BaseResp; import io.github.youkehai.assistant.core.util.DateUtil; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors;
864
package io.github.youkehai.assistant.core.resp.run; /** * run 的返回值基类 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true)
package io.github.youkehai.assistant.core.resp.run; /** * run 的返回值基类 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true)
public class RunBaseResp extends BaseResp {
1
2023-11-25 13:19:47+00:00
2k
confluentinc/flink-cookbook
latest-transaction/src/main/java/io/confluent/developer/cookbook/flink/StreamingDataStreamJob.java
[ { "identifier": "Transaction", "path": "compiled-plan/src/test/java/io/confluent/developer/cookbook/flink/records/Transaction.java", "snippet": "public class Transaction {\n\n /**\n * Without this annotation, the timestamps are serialized like this:\n * {\"t_time\":1658419083.146222000, ...} <br>\n * and the Kafka connector used with the Table API won't be able to deserialize this.\n */\n @JsonFormat(\n shape = JsonFormat.Shape.STRING,\n pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\",\n timezone = \"UTC\")\n public Instant t_time;\n\n public long t_id;\n public long t_customer_id;\n public BigDecimal t_amount;\n\n public Transaction() {}\n\n public Transaction(Instant t_time, long t_id, long t_customer_id, BigDecimal t_amount) {\n this.t_time = t_time;\n this.t_id = t_id;\n this.t_customer_id = t_customer_id;\n this.t_amount = t_amount;\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 Transaction that = (Transaction) o;\n return t_id == that.t_id\n && t_customer_id == that.t_customer_id\n && t_time.equals(that.t_time)\n && t_amount.equals(that.t_amount);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(t_time, t_id, t_customer_id, t_amount);\n }\n\n @Override\n public String toString() {\n return \"Transaction(\"\n + \"t_time=\"\n + t_time\n + \", t_id=\"\n + t_id\n + \", t_customer_id=\"\n + t_customer_id\n + \", t_amount=\"\n + t_amount\n + ')';\n }\n}" }, { "identifier": "TransactionDeserializer", "path": "latest-transaction/src/main/java/io/confluent/developer/cookbook/flink/records/TransactionDeserializer.java", "snippet": "public class TransactionDeserializer extends AbstractDeserializationSchema<Transaction> {\n\n private static final long serialVersionUID = 1L;\n\n private transient ObjectMapper objectMapper;\n\n @Override\n public void open(InitializationContext context) {\n // JavaTimeModule is needed for Java 8 data time (Instant) support\n objectMapper = JsonMapper.builder().build().registerModule(new JavaTimeModule());\n }\n\n @Override\n public Transaction deserialize(byte[] message) throws IOException {\n return objectMapper.readValue(message, Transaction.class);\n }\n}" }, { "identifier": "DataStreamWorkflow", "path": "latest-transaction/src/main/java/io/confluent/developer/cookbook/flink/workflows/DataStreamWorkflow.java", "snippet": "public class DataStreamWorkflow {\n public static void defineWorkflow(\n StreamExecutionEnvironment env,\n Source<Transaction, ?, ?> transactionSource,\n Consumer<DataStream<Transaction>> sinkApplier) {\n\n DataStream<Transaction> transactionStream =\n env.fromSource(transactionSource, WatermarkStrategy.noWatermarks(), \"Transactions\");\n\n DataStream<Transaction> results =\n transactionStream\n .keyBy(t -> t.t_customer_id)\n .process(new LatestTransactionFunction());\n\n // attach the sink\n sinkApplier.accept(results);\n }\n}" } ]
import io.confluent.developer.cookbook.flink.records.Transaction; import io.confluent.developer.cookbook.flink.records.TransactionDeserializer; import io.confluent.developer.cookbook.flink.workflows.DataStreamWorkflow; import java.util.function.Consumer; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.sink.PrintSink;
1,050
package io.confluent.developer.cookbook.flink; public class StreamingDataStreamJob { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); setupJob(env, "transactions", workflow -> workflow.sinkTo(new PrintSink<>())); env.execute(); } static void setupJob( StreamExecutionEnvironment env, String kafkaTopic, Consumer<DataStream<Transaction>> sinkApplier) { KafkaSource<Transaction> unboundedSource = KafkaSource.<Transaction>builder() .setBootstrapServers("localhost:9092") .setTopics(kafkaTopic) .setStartingOffsets(OffsetsInitializer.earliest())
package io.confluent.developer.cookbook.flink; public class StreamingDataStreamJob { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); setupJob(env, "transactions", workflow -> workflow.sinkTo(new PrintSink<>())); env.execute(); } static void setupJob( StreamExecutionEnvironment env, String kafkaTopic, Consumer<DataStream<Transaction>> sinkApplier) { KafkaSource<Transaction> unboundedSource = KafkaSource.<Transaction>builder() .setBootstrapServers("localhost:9092") .setTopics(kafkaTopic) .setStartingOffsets(OffsetsInitializer.earliest())
.setValueOnlyDeserializer(new TransactionDeserializer())
1
2023-11-20 16:31:54+00:00
2k
booksongs/RedisDelay
rd-core/src/main/java/io/github/booksongs/rd/listener/RedisEndpointListener.java
[ { "identifier": "DelayRedisson", "path": "rd-core/src/main/java/io/github/booksongs/rd/config/DelayRedisson.java", "snippet": "public class DelayRedisson extends Redisson {\n public DelayRedisson(Config config) {\n super(config);\n }\n}" }, { "identifier": "RedissonProperties", "path": "rd-core/src/main/java/io/github/booksongs/rd/config/RedissonProperties.java", "snippet": "@Getter\n@Setter\n@Configuration\n@ConfigurationProperties(prefix = \"spring.redis.delay\")\npublic class RedissonProperties {\n\n /**\n * 定时任务线程的刷新周期毫秒\n */\n private long refreshCycle = 100;\n /**\n * 常驻线程数\n */\n public int corePollSize = 10;\n\n /**\n * Database index used by the connection factory.\n */\n private int database = 0;\n\n /**\n * Connection URL. Overrides host, port, username, and password. Example:\n * redis://user:[email protected]:6379\n */\n private String url;\n\n private String host = \"localhost\";\n\n private String username;\n\n private String password;\n\n private int port = 6379;\n /**\n * 全局重试开关,优先级低于 RedisDelayQueue 注解的设置\n */\n private Boolean retry = false;\n\n /**\n * 尝试次数\n */\n private int retryAttempts = 0;\n\n /**\n * 重试保存策略\n */\n private String confirmPersistenceStrategy = \"defaultConfirmPersistenceStrategy\";\n\n}" }, { "identifier": "ConfirmPersistenceStrategy", "path": "rd-core/src/main/java/io/github/booksongs/rd/confirm/ConfirmPersistenceStrategy.java", "snippet": "public interface ConfirmPersistenceStrategy {\n void doRetryRecord(int retryAttempts, Object message, MethodRedisListenerEndpoint listenerEndpoint);\n}" }, { "identifier": "ConfirmUtil", "path": "rd-core/src/main/java/io/github/booksongs/rd/confirm/ConfirmUtil.java", "snippet": "public class ConfirmUtil {\n\n public final static String RETRY = \"RETRY_\";\n\n public static RAtomicLong getAtomicLong(String key, DelayRedisson delayRedisson) {\n return delayRedisson.getAtomicLong(key);\n }\n\n public static void incrementAndGet(String key, DelayRedisson delayRedisson) {\n getAtomicLong(key, delayRedisson).incrementAndGet();\n }\n\n public static void del(String key, DelayRedisson delayRedisson) {\n getAtomicLong(key, delayRedisson).delete();\n }\n\n public static void addDeadLetterQueue(String key, DelayRedisson delayRedisson, DeadLetterProvider message) {\n RList<DeadLetterProvider> list = delayRedisson.getList(key);\n list.add(message);\n }\n}" } ]
import io.github.booksongs.rd.annotation.RedisListener; import io.github.booksongs.rd.config.DelayRedisson; import io.github.booksongs.rd.config.RedissonProperties; import io.github.booksongs.rd.confirm.ConfirmPersistenceStrategy; import io.github.booksongs.rd.confirm.ConfirmUtil; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RBlockingDeque; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ApplicationContextEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
862
package io.github.booksongs.rd.listener; @Slf4j @Component public class RedisEndpointListener implements ApplicationListener<ContextRefreshedEvent> { boolean isInitialized = false; private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); private ApplicationContext applicationContext;
package io.github.booksongs.rd.listener; @Slf4j @Component public class RedisEndpointListener implements ApplicationListener<ContextRefreshedEvent> { boolean isInitialized = false; private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); private ApplicationContext applicationContext;
private RedissonProperties redissonProperties;
1
2023-11-24 07:11:36+00:00
2k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/generator/MegaTurbineWorkableHandler.java
[ { "identifier": "IMegaTurbine", "path": "src/main/java/cn/gtcommunity/epimorphism/api/metatileentity/multiblock/IMegaTurbine.java", "snippet": "public interface IMegaTurbine {\n // 这个接口是为了给转子仓和涡轮解耦用的,不太有用,可能会删除\n List<IReinforcedRotorHolder> getRotorHolders();\n int getMode();\n}" }, { "identifier": "IReinforcedRotorHolder", "path": "src/main/java/cn/gtcommunity/epimorphism/api/capability/IReinforcedRotorHolder.java", "snippet": "public interface IReinforcedRotorHolder extends IRotorHolder {\n void setRotor(ItemStack itemStack);\n void setCurrentSpeed(int speed);\n Material getRotorMaterial();\n}" } ]
import cn.gtcommunity.epimorphism.api.metatileentity.multiblock.IMegaTurbine; import cn.gtcommunity.epimorphism.api.capability.IReinforcedRotorHolder; import gregtech.api.GTValues; import gregtech.api.capability.impl.MultiblockFuelRecipeLogic; import gregtech.api.metatileentity.multiblock.FuelMultiblockController; import gregtech.api.metatileentity.multiblock.MultiblockAbility; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeBuilder; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fluids.capability.IFluidHandler; import java.util.List;
716
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock.generator; public class MegaTurbineWorkableHandler extends MultiblockFuelRecipeLogic { private final int BASE_EU_OUTPUT; private int excessVoltage; public MegaTurbineWorkableHandler(RecipeMapMultiblockController metaTileEntity, int tier) { super(metaTileEntity); this.BASE_EU_OUTPUT = (int) (GTValues.V[tier] * 2 * 16); } @Override protected void updateRecipeProgress() { if (canRecipeProgress) { // turbines can void energy drawEnergy(recipeEUt, false); //as recipe starts with progress on 1 this has to be > only not => to compensate for it if (++progressTime > maxProgressTime) { completeRecipe(); } } } public FluidStack getInputFluidStack() { // Previous Recipe is always null on first world load, so try to acquire a new recipe if (previousRecipe == null) { Recipe recipe = findRecipe(Integer.MAX_VALUE, getInputInventory(), getInputTank()); return recipe == null ? null : getInputTank().drain(new FluidStack(recipe.getFluidInputs().get(0).getInputFluidStack().getFluid(), Integer.MAX_VALUE), false); } FluidStack fuelStack = previousRecipe.getFluidInputs().get(0).getInputFluidStack(); return getInputTank().drain(new FluidStack(fuelStack.getFluid(), Integer.MAX_VALUE), false); } @Override public long getMaxVoltage() {
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock.generator; public class MegaTurbineWorkableHandler extends MultiblockFuelRecipeLogic { private final int BASE_EU_OUTPUT; private int excessVoltage; public MegaTurbineWorkableHandler(RecipeMapMultiblockController metaTileEntity, int tier) { super(metaTileEntity); this.BASE_EU_OUTPUT = (int) (GTValues.V[tier] * 2 * 16); } @Override protected void updateRecipeProgress() { if (canRecipeProgress) { // turbines can void energy drawEnergy(recipeEUt, false); //as recipe starts with progress on 1 this has to be > only not => to compensate for it if (++progressTime > maxProgressTime) { completeRecipe(); } } } public FluidStack getInputFluidStack() { // Previous Recipe is always null on first world load, so try to acquire a new recipe if (previousRecipe == null) { Recipe recipe = findRecipe(Integer.MAX_VALUE, getInputInventory(), getInputTank()); return recipe == null ? null : getInputTank().drain(new FluidStack(recipe.getFluidInputs().get(0).getInputFluidStack().getFluid(), Integer.MAX_VALUE), false); } FluidStack fuelStack = previousRecipe.getFluidInputs().get(0).getInputFluidStack(); return getInputTank().drain(new FluidStack(fuelStack.getFluid(), Integer.MAX_VALUE), false); } @Override public long getMaxVoltage() {
List<IReinforcedRotorHolder> rotorHolders = ((IMegaTurbine) metaTileEntity).getRotorHolders();
1
2023-11-26 01:56:35+00:00
2k
LaughingMuffin/laughing-logger
app/src/main/java/org/laughing/logger/widget/dialogs/SweetContentDialog.java
[ { "identifier": "ControlsItem", "path": "app/src/main/java/org/laughing/logger/widget/dialogs/adapters/ControlsItem.java", "snippet": "public class ControlsItem {\n private @DrawableRes int icon;\n private CharSequence title;\n private View.OnClickListener action;\n\n\n public ControlsItem(@DrawableRes int icon, CharSequence title, View.OnClickListener listener) {\n this.icon = icon;\n this.title = title;\n this.action = listener;\n }\n\n public CharSequence getTitle() {\n return title;\n }\n\n public @DrawableRes int getIcon() {\n return icon;\n }\n\n public View.OnClickListener getAction() {\n return action;\n }\n}" }, { "identifier": "DialogControlsAdapter", "path": "app/src/main/java/org/laughing/logger/widget/dialogs/adapters/DialogControlsAdapter.java", "snippet": "public class DialogControlsAdapter extends RecyclerView.Adapter<DialogControlsAdapter.ViewHolder> {\n List<ControlsItem> items;\n private OnItemClickListener itemClickListener;\n\n public DialogControlsAdapter(List<ControlsItem> items) {\n this.items = items;\n }\n\n public void setItemClickListener(OnItemClickListener itemClickListener) {\n this.itemClickListener = itemClickListener;\n }\n\n public ControlsItem getItem(int position) {\n return items.get(position);\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dialog_controls, parent, false);\n return new ViewHolder(v);\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n @Override\n public void onBindViewHolder(ViewHolder holder, int position) {\n ControlsItem item = getItem(position);\n assert item != null;\n\n holder.text.setText(item.getTitle());\n holder.icon.setImageResource(item.getIcon());\n }\n\n public interface OnItemClickListener {\n void onItemClick(ControlsItem menuItem, int position);\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n public TextView text;\n public ImageView icon;\n\n public ViewHolder(View v) {\n super(v);\n text = v.findViewById(R.id.list_item_content);\n icon = v.findViewById(R.id.list_item_icon);\n\n v.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n if (itemClickListener != null) {\n itemClickListener.onItemClick(getItem(getLayoutPosition()), getLayoutPosition());\n }\n }\n }\n}" } ]
import android.content.Context; import android.graphics.drawable.Drawable; import android.text.Spanned; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.DrawableRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.appcompat.content.res.AppCompatResources; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.bottomsheet.BottomSheetDialog; import org.laughing.logger.R; import org.laughing.logger.widget.dialogs.adapters.ControlsItem; import org.laughing.logger.widget.dialogs.adapters.DialogControlsAdapter; import java.util.ArrayList;
1,286
package org.laughing.logger.widget.dialogs; /** * Created by Snow Volf on 26.08.2017, 21:38 */ public class SweetContentDialog extends BottomSheetDialog { private Context mContext; private FrameLayout mContentFrame; private TextView mCaption, mContentView; private RecyclerView mControllerView; private ArrayList<ControlsItem> mControls = new ArrayList<>(); private boolean mDismissOnTouch = false; public SweetContentDialog(@NonNull Context context) { super(context); mContext = context; initContentView(); } private void initContentView() { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.dialog_simple_content, null); mCaption = view.findViewById(R.id.content_caption); mContentFrame = view.findViewById(R.id.content_frame); mContentView = view.findViewById(R.id.content); mControllerView = view.findViewById(R.id.list); setContentView(view); } @Override public void setTitle(CharSequence title) { mCaption.setText(title); } public void setMessage(int resId) { mContentView.setText(resId); } public void setMessage(StringBuilder sb) { mContentView.setText(sb); } public void setMessage(CharSequence text) { mContentView.setText(text); } public void setMessage(Spanned text){ mContentView.setText(text); } public void setView(@LayoutRes int resId){ setView(LayoutInflater.from(getContext()).inflate(resId, null)); } public void setIcon(@DrawableRes int resId){ setIcon(AppCompatResources.getDrawable(mContext, resId)); } public void setIcon(Drawable icon){ mCaption.setCompoundDrawablesRelative(icon, null, null, null); } public void setView(View view) { mContentFrame.removeAllViews(); mContentFrame.addView(view); } public void setPositive(@DrawableRes int resId, CharSequence text, View.OnClickListener listener) { mControls.add(new ControlsItem(resId, text, listener)); } public void setNegative(@DrawableRes int resId, CharSequence text, View.OnClickListener listener) { mControls.add(new ControlsItem(resId, text, listener)); } public void setNeutral(@DrawableRes int resId, CharSequence text, View.OnClickListener listener) { mControls.add(new ControlsItem(resId, text, listener)); } public void setDismissOnTouch(boolean dismissOnTouch) { this.mDismissOnTouch = dismissOnTouch; } @Override public void show() { super.show(); if (mControls.size() > 0) {
package org.laughing.logger.widget.dialogs; /** * Created by Snow Volf on 26.08.2017, 21:38 */ public class SweetContentDialog extends BottomSheetDialog { private Context mContext; private FrameLayout mContentFrame; private TextView mCaption, mContentView; private RecyclerView mControllerView; private ArrayList<ControlsItem> mControls = new ArrayList<>(); private boolean mDismissOnTouch = false; public SweetContentDialog(@NonNull Context context) { super(context); mContext = context; initContentView(); } private void initContentView() { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.dialog_simple_content, null); mCaption = view.findViewById(R.id.content_caption); mContentFrame = view.findViewById(R.id.content_frame); mContentView = view.findViewById(R.id.content); mControllerView = view.findViewById(R.id.list); setContentView(view); } @Override public void setTitle(CharSequence title) { mCaption.setText(title); } public void setMessage(int resId) { mContentView.setText(resId); } public void setMessage(StringBuilder sb) { mContentView.setText(sb); } public void setMessage(CharSequence text) { mContentView.setText(text); } public void setMessage(Spanned text){ mContentView.setText(text); } public void setView(@LayoutRes int resId){ setView(LayoutInflater.from(getContext()).inflate(resId, null)); } public void setIcon(@DrawableRes int resId){ setIcon(AppCompatResources.getDrawable(mContext, resId)); } public void setIcon(Drawable icon){ mCaption.setCompoundDrawablesRelative(icon, null, null, null); } public void setView(View view) { mContentFrame.removeAllViews(); mContentFrame.addView(view); } public void setPositive(@DrawableRes int resId, CharSequence text, View.OnClickListener listener) { mControls.add(new ControlsItem(resId, text, listener)); } public void setNegative(@DrawableRes int resId, CharSequence text, View.OnClickListener listener) { mControls.add(new ControlsItem(resId, text, listener)); } public void setNeutral(@DrawableRes int resId, CharSequence text, View.OnClickListener listener) { mControls.add(new ControlsItem(resId, text, listener)); } public void setDismissOnTouch(boolean dismissOnTouch) { this.mDismissOnTouch = dismissOnTouch; } @Override public void show() { super.show(); if (mControls.size() > 0) {
final DialogControlsAdapter adapter = new DialogControlsAdapter(mControls);
1
2023-11-19 15:31:51+00:00
2k
GT-ARC/opaca-core
opaca-model/src/main/java/de/gtarc/opaca/api/CommonApi.java
[ { "identifier": "AgentDescription", "path": "opaca-model/src/main/java/de/gtarc/opaca/model/AgentDescription.java", "snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class AgentDescription {\n\n // TODO also list messages this agent understands and would react to\n\n /** ID of the agent, should be globally unique, e.g. a UUID */\n @NonNull\n String agentId;\n\n /** name/type of the agent, e.g. \"VehicleAgent\" or similar */\n String agentType;\n\n /** list of actions provided by this agent, if any */\n @NonNull\n List<Action> actions = List.of();\n\n /** list of endpoints for sending or receiving streaming data */\n @NonNull\n List<Stream> streams = List.of();\n\n}" }, { "identifier": "Message", "path": "opaca-model/src/main/java/de/gtarc/opaca/model/Message.java", "snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class Message {\n\n // TODO recipient here, or in API method, or both?\n // TODO specify format/API for reply-to callback\n // TODO expected result type?\n\n /** the actual payload of the message */\n JsonNode payload;\n\n /** URL of REST service where to post replies; optional; for inter/intra platform\n * communication this could also be a \"path\" like \"platformId/containerId/agentId\" */\n String replyTo;\n\n}" } ]
import com.fasterxml.jackson.databind.JsonNode; import de.gtarc.opaca.model.AgentDescription; import de.gtarc.opaca.model.Message; import java.io.IOException; import java.util.List; import java.util.Map; import org.springframework.http.ResponseEntity; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
665
package de.gtarc.opaca.api; /** * API for both, Agent Containers and Runtime Platform. In fact, those are primarily the * Agent Container functions, but separated here, since the Agent Container will also have * a specific "info" route. */ public interface CommonApi { /** * Get list of Agents running in this Agent Container. * * REST: GET /agents * * @return List of Agents running in the container */ List<AgentDescription> getAgents() throws IOException; /** * Get description of one specific Agent * * REST: GET /agents/{id} * * @param agentId ID of the agent * @return Description of that agent */ AgentDescription getAgent(String agentId) throws IOException; /** * Send message to a single agent in the container. * * REST: POST /send/{id}?containerId={containerId}&forward={true|false}` * * @param agentId ID of the agent * @param message The message envelope * @param containerId ID of the Container to use (optional) * @param forward flag whether to forward the message to connected platforms (optional) */
package de.gtarc.opaca.api; /** * API for both, Agent Containers and Runtime Platform. In fact, those are primarily the * Agent Container functions, but separated here, since the Agent Container will also have * a specific "info" route. */ public interface CommonApi { /** * Get list of Agents running in this Agent Container. * * REST: GET /agents * * @return List of Agents running in the container */ List<AgentDescription> getAgents() throws IOException; /** * Get description of one specific Agent * * REST: GET /agents/{id} * * @param agentId ID of the agent * @return Description of that agent */ AgentDescription getAgent(String agentId) throws IOException; /** * Send message to a single agent in the container. * * REST: POST /send/{id}?containerId={containerId}&forward={true|false}` * * @param agentId ID of the agent * @param message The message envelope * @param containerId ID of the Container to use (optional) * @param forward flag whether to forward the message to connected platforms (optional) */
void send(String agentId, Message message, String containerId, boolean forward) throws IOException;
1
2023-11-23 11:06:10+00:00
2k
lushangkan/AutoStreamingAssistant
src/main/java/cn/cutemc/autostreamingassistant/network/packets/ClientRequestStatusHandler.java
[ { "identifier": "AutoStreamingAssistant", "path": "src/main/java/cn/cutemc/autostreamingassistant/AutoStreamingAssistant.java", "snippet": "@Log4j2\npublic class AutoStreamingAssistant implements ClientModInitializer {\n\n public static String VERSION;\n public static ModConfig CONFIG;\n public static ModKeyBinding KEYBINDING;\n public static Camera CAMERA;\n\n public static boolean isLinuxMint = false;\n public static WorldStatus worldStatus = new WorldStatus();\n\n @Override\n public void onInitializeClient() {\n\n log.info(\"Loading AutoStreamingAssistant...\");\n\n VERSION = FabricLoader.getInstance().getModContainer(\"autostreamingassistant\").get().getMetadata().getVersion().getFriendlyString();\n\n isLinuxMint = SystemUtils.isLinuxMint();\n\n log.info(\"Registering KeyBindings...\");\n KEYBINDING = new ModKeyBinding();\n\n log.info(\"Registering Listeners...\");\n new ConfigListener();\n new KeyListener();\n\n log.info(\"Loading Config...\");\n CONFIG = new ModConfig();\n\n log.info(\"Registering Commands...\");\n new ModCommands();\n\n log.info(\"Creating Camera...\");\n CAMERA = new Camera();\n\n log.info(\"Initializing Network Listener...\");\n new ClientBindCameraHandler();\n new ClientUnbindCameraHandler();\n new ClientRequestStatusHandler();\n new ClientRequestBindStatusHandle();\n\n log.info(\"AutoStreamingAssistant Loaded!\");\n\n }\n\n}" }, { "identifier": "ClientStatus", "path": "src/main/java/cn/cutemc/autostreamingassistant/ClientStatus.java", "snippet": "public enum ClientStatus {\n\n READY,\n BOUND;\n\n @Override\n public String toString() {\n return name().toLowerCase();\n }\n\n public static ClientStatus fromString(String str) {\n return valueOf(str.toUpperCase());\n }\n}" }, { "identifier": "PacketID", "path": "src/main/java/cn/cutemc/autostreamingassistant/network/PacketID.java", "snippet": "public class PacketID {\n\n public static final Identifier REQUEST_STATUS = new Identifier(\"autostreamingassistant\", \"request_status\");\n public static final Identifier REQUEST_BIND_STATUS = new Identifier(\"autostreamingassistant\", \"request_bind_status\");\n public static final Identifier CLIENT_STATUS = new Identifier(\"autostreamingassistant\", \"client_status\");\n public static final Identifier BIND_STATUS = new Identifier(\"autostreamingassistant\", \"bind_status\");\n\n public static final Identifier BIND_CAMERA = new Identifier(\"autostreamingassistant\", \"bind_camera\");\n public static final Identifier UNBIND_CAMERA = new Identifier(\"autostreamingassistant\", \"unbind_camera\");\n\n public static final Identifier BIND_CAMERA_RESULT = new Identifier(\"autostreamingassistant\", \"bind_camera_result\");\n public static final Identifier UNBIND_CAMERA_RESULT = new Identifier(\"autostreamingassistant\", \"unbind_camera_result\");\n\n public static final Identifier MANUAL_BIND_CAMERA = new Identifier(\"autostreamingassistant\", \"manual_bind_camera\");\n}" }, { "identifier": "BufferUtils", "path": "src/main/java/cn/cutemc/autostreamingassistant/utils/BufferUtils.java", "snippet": "public class BufferUtils {\n\n /**\n * 将ByteBuffer转换为byte数组,使用fori解决Buffer实际大小大于capacity大小的问题\n * @param buffer ByteBuffer\n * @return byte数组\n */\n public static byte[] toBytes(ByteBuffer buffer) {\n byte[] bytes = new byte[buffer.capacity()];\n for (int i = 0; i < buffer.capacity(); i++) {\n bytes[i] = buffer.get(i);\n }\n return bytes;\n }\n\n /**\n * 将PacketByteBuf转换为byte数组,使用fori解决Buffer实际大小大于capacity大小的问题\n * @param buffer PacketByteBuf\n * @return byte数组\n */\n public static byte[] toBytes(PacketByteBuf buffer) {\n return toBytes(buffer.nioBuffer());\n }\n}" } ]
import cn.cutemc.autostreamingassistant.AutoStreamingAssistant; import cn.cutemc.autostreamingassistant.ClientStatus; import cn.cutemc.autostreamingassistant.network.PacketID; import cn.cutemc.autostreamingassistant.utils.BufferUtils; import com.google.gson.Gson; import lombok.Getter; import lombok.Setter; import lombok.extern.log4j.Log4j2; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.network.PacketByteBuf; import java.nio.charset.StandardCharsets;
1,130
package cn.cutemc.autostreamingassistant.network.packets; @Log4j2 public class ClientRequestStatusHandler implements ClientPlayNetworking.PlayChannelHandler { public ClientRequestStatusHandler() {
package cn.cutemc.autostreamingassistant.network.packets; @Log4j2 public class ClientRequestStatusHandler implements ClientPlayNetworking.PlayChannelHandler { public ClientRequestStatusHandler() {
ClientPlayNetworking.registerGlobalReceiver(PacketID.REQUEST_STATUS, this);
2
2023-11-20 14:02:38+00:00
2k
hardcodedjoy/android-app-speaker-test
app/src/main/java/com/hardcodedjoy/example/speakertest/SettingsActivity.java
[ { "identifier": "GuiUtil", "path": "app/src/main/java/com/hardcodedjoy/util/GuiUtil.java", "snippet": "public class GuiUtil {\n\n static public void setOnClickListenerToAllButtons(ViewGroup vg, View.OnClickListener ocl) {\n int n = vg.getChildCount();\n View v;\n for(int i=0; i<n; i++) {\n v = vg.getChildAt(i);\n if(v instanceof ViewGroup) { setOnClickListenerToAllButtons((ViewGroup)v, ocl); }\n else if(v instanceof Button) { v.setOnClickListener(ocl); }\n else if(v instanceof ImageButton) { v.setOnClickListener(ocl); }\n }\n }\n\n static public void link(@NonNull EditText et, @NonNull final SetGetter setGetter) {\n\n // first time (init)\n // get value from settings and set on et\n String value = setGetter.get();\n if(value != null) {\n et.setText(value);\n }\n setGetter.set(value);\n\n et.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}\n @Override\n public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}\n @Override\n public void afterTextChanged(Editable e) { setGetter.set(e.toString()); }\n });\n\n }\n\n static public void link(@NonNull CheckBox cb, @NonNull final SetGetter setGetter) {\n try {\n boolean b = Boolean.parseBoolean(setGetter.get());\n cb.setChecked(b);\n setGetter.set(\"\" + b);\n cb.setOnCheckedChangeListener((compoundButton, b1) -> setGetter.set(\"\" + b1));\n } catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n static public void link(@NonNull SeekBar sb, @NonNull final SetGetter setGetter) {\n try {\n int val = Integer.parseInt(setGetter.get());\n sb.setProgress(val);\n setGetter.set(\"\" + val);\n sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {\n @Override\n public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {\n setGetter.set(\"\" + progress);\n }\n @Override\n public void onStartTrackingTouch(SeekBar seekBar) {}\n @Override\n public void onStopTrackingTouch(SeekBar seekBar) {}\n });\n } catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n public static void link(@NonNull RadioButton rb, @NonNull final SetGetter setGetter) {\n try {\n boolean b = Boolean.parseBoolean(setGetter.get());\n rb.setChecked(b);\n setGetter.set(\"\" + b);\n rb.setOnCheckedChangeListener((compoundButton, b1) -> setGetter.set(\"\" + b1));\n } catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n public static void link(@NonNull RadioGroup rg, @NonNull final SetGetter setGetter) {\n\n String current = setGetter.get();\n\n int n = rg.getChildCount();\n RadioButton rb;\n for(int i=0; i<n ;i++) {\n rb = (RadioButton) rg.getChildAt(i);\n if(rb.getText().toString().equals(current)) {\n rb.setChecked(true);\n break;\n }\n }\n\n rg.setOnCheckedChangeListener((group, checkedId) -> {\n RadioButton rb1 = group.findViewById(checkedId);\n setGetter.set(rb1.getText().toString());\n });\n }\n}" }, { "identifier": "SetGetter", "path": "app/src/main/java/com/hardcodedjoy/util/SetGetter.java", "snippet": "public interface SetGetter {\n void set(String value);\n String get();\n}" }, { "identifier": "ThemeUtil", "path": "app/src/main/java/com/hardcodedjoy/util/ThemeUtil.java", "snippet": "public class ThemeUtil {\n\n static public final String LIGHT = \"light\";\n static public final String DARK = \"dark\";\n static public final String SYSTEM = \"system\";\n\n static private int resIdThemeDark;\n static private int resIdThemeLight;\n\n static public void setResIdThemeDark(int resId) { ThemeUtil.resIdThemeDark = resId; }\n static public void setResIdThemeLight(int resId) { ThemeUtil.resIdThemeLight = resId; }\n\n static public void set(Activity activity, String theme) {\n switch (theme) {\n case LIGHT:\n activity.setTheme(resIdThemeLight);\n break;\n case DARK:\n activity.setTheme(resIdThemeDark);\n break;\n case SYSTEM:\n int systemUiMode = activity.getResources().getConfiguration().uiMode;\n int nightMode = systemUiMode & Configuration.UI_MODE_NIGHT_MASK;\n if(nightMode == Configuration.UI_MODE_NIGHT_YES) {\n activity.setTheme(resIdThemeDark);\n } else {\n activity.setTheme(resIdThemeLight);\n }\n break;\n default:\n break;\n }\n }\n}" } ]
import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import com.hardcodedjoy.util.GuiUtil; import com.hardcodedjoy.util.SetGetter; import com.hardcodedjoy.util.ThemeUtil; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Window;
1,563
/* MIT License Copyright © 2023 HARDCODED JOY S.R.L. (https://hardcodedjoy.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.hardcodedjoy.example.speakertest; public class SettingsActivity extends Activity { private Settings settings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); settings = new Settings(getSharedPreferences(getPackageName(), Context.MODE_PRIVATE)); initGUI(); } private void initGUI() { // we use our own title bar requestWindowFeature(Window.FEATURE_NO_TITLE);
/* MIT License Copyright © 2023 HARDCODED JOY S.R.L. (https://hardcodedjoy.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.hardcodedjoy.example.speakertest; public class SettingsActivity extends Activity { private Settings settings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); settings = new Settings(getSharedPreferences(getPackageName(), Context.MODE_PRIVATE)); initGUI(); } private void initGUI() { // we use our own title bar requestWindowFeature(Window.FEATURE_NO_TITLE);
ThemeUtil.set(this, settings.getTheme());
2
2023-11-22 08:33:08+00:00
2k
sanjarzayniev/iks-nolik
src/Server.java
[ { "identifier": "Logger", "path": "src/helpers/Logger.java", "snippet": "public class Logger {\n private static void log(String type, String message) {\n System.out.println(\"[\" + type.toUpperCase() + \"] \" + message);\n }\n\n public static void info(String message) {\n log(\"info\", message);\n }\n\n public static void error(String message) {\n log(\"error\", message);\n }\n\n public static void warning(String message) {\n log(\"warning\", message);\n }\n\n public static void success(String message) {\n log(\"success\", message);\n }\n}" }, { "identifier": "ServerSettings", "path": "src/settings/ServerSettings.java", "snippet": "public class ServerSettings {\n public final static int SERVER_PORT = 41583,\n FAIL_STATUS_CODE = -1,\n PLAYERS_COUNT = 2,\n TOTAL_BUTTONS = 9,\n FRAME_SIZE = 250;\n\n public final static String DATABASE_KEY_FILE = \"database.key\",\n SERVER_HOST = \"abduazizziyodov.jprq.app\",\n FRAME_TITLE = \"Server Logs\";\n}" } ]
import java.awt.*; import java.net.*; import java.util.*; import javax.swing.*; import java.io.IOException; import java.util.concurrent.*; import java.util.concurrent.locks.*; import helpers.Logger; import settings.ServerSettings;
770
public class Server extends JFrame { // Player constants private final static int PLAYER_X = 0; private final static int PLAYER_O = 1; private final static String[] MARKS = { "X", "O" }; // Server socket private ServerSocket server; private int currentPlayer; // Store two opponnest private final Player[] players; // Store server logs private JTextArea outputArea; // Players threadpool private final ExecutorService runGame; // Abstract board ;D private final String[] board = new String[ServerSettings.TOTAL_BUTTONS]; private final Lock gameLock; private final Condition otherPlayerTurn; private final Condition otherPlayerConnected; public static void main(String[] args) { new Server().start(); } public Server() { super(ServerSettings.FRAME_TITLE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); runGame = Executors.newFixedThreadPool(ServerSettings.PLAYERS_COUNT); gameLock = new ReentrantLock(); // create lock for game // condition variable for the other player's turn otherPlayerTurn = gameLock.newCondition(); // condition variable for both players being connected otherPlayerConnected = gameLock.newCondition(); players = new Player[ServerSettings.PLAYERS_COUNT]; currentPlayer = PLAYER_X; // set current player to first player initServerSocket(); initAbstractBoard(); setSize(ServerSettings.FRAME_SIZE, ServerSettings.FRAME_SIZE); setUpOutputArea(); } private void setUpOutputArea() { // Create and add styles to text area (for logs) outputArea = new JTextArea(); outputArea.setBackground(Color.BLACK); outputArea.setForeground(Color.WHITE); outputArea.setFont(new Font("Ink Free", Font.PLAIN, 12)); String serverAddress = String.format( "Server: %s:%s\n", ServerSettings.SERVER_HOST, ServerSettings.SERVER_PORT); outputArea.setText(serverAddress); setVisible(true); add(outputArea, BorderLayout.CENTER); } private void initServerSocket() { try { server = new ServerSocket(ServerSettings.SERVER_PORT, ServerSettings.PLAYERS_COUNT); } catch (IOException exc) {
public class Server extends JFrame { // Player constants private final static int PLAYER_X = 0; private final static int PLAYER_O = 1; private final static String[] MARKS = { "X", "O" }; // Server socket private ServerSocket server; private int currentPlayer; // Store two opponnest private final Player[] players; // Store server logs private JTextArea outputArea; // Players threadpool private final ExecutorService runGame; // Abstract board ;D private final String[] board = new String[ServerSettings.TOTAL_BUTTONS]; private final Lock gameLock; private final Condition otherPlayerTurn; private final Condition otherPlayerConnected; public static void main(String[] args) { new Server().start(); } public Server() { super(ServerSettings.FRAME_TITLE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); runGame = Executors.newFixedThreadPool(ServerSettings.PLAYERS_COUNT); gameLock = new ReentrantLock(); // create lock for game // condition variable for the other player's turn otherPlayerTurn = gameLock.newCondition(); // condition variable for both players being connected otherPlayerConnected = gameLock.newCondition(); players = new Player[ServerSettings.PLAYERS_COUNT]; currentPlayer = PLAYER_X; // set current player to first player initServerSocket(); initAbstractBoard(); setSize(ServerSettings.FRAME_SIZE, ServerSettings.FRAME_SIZE); setUpOutputArea(); } private void setUpOutputArea() { // Create and add styles to text area (for logs) outputArea = new JTextArea(); outputArea.setBackground(Color.BLACK); outputArea.setForeground(Color.WHITE); outputArea.setFont(new Font("Ink Free", Font.PLAIN, 12)); String serverAddress = String.format( "Server: %s:%s\n", ServerSettings.SERVER_HOST, ServerSettings.SERVER_PORT); outputArea.setText(serverAddress); setVisible(true); add(outputArea, BorderLayout.CENTER); } private void initServerSocket() { try { server = new ServerSocket(ServerSettings.SERVER_PORT, ServerSettings.PLAYERS_COUNT); } catch (IOException exc) {
Logger.error(exc.toString());
0
2023-11-21 13:42:25+00:00
2k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/util/CachedImage.java
[ { "identifier": "Identifier", "path": "src/main/java/xyz/zcraft/zpixiv/api/artwork/Identifier.java", "snippet": "@Data\npublic class Identifier {\n private final String id;\n private final Type type;\n private final int index;\n private final String quality;\n\n private Identifier(String id, Type type, int index, String quality) {\n this.id = id;\n this.type = type;\n this.index = index;\n this.quality = quality;\n }\n\n @SuppressWarnings(\"unused\")\n public enum Type {\n Artwork, Gif, Profile\n }\n\n public static Identifier of(String id, Type type, int index, Quality quality) {\n return new Identifier(id, type, index, quality.name());\n }\n}" }, { "identifier": "Main", "path": "src/main/java/xyz/zcraft/zpixiv/ui/Main.java", "snippet": "public class Main extends Application {\n @Getter\n public static final LinkedList<CachedImage> loginBackground = new LinkedList<>();\n private static final Logger LOG = LogManager.getLogger(Main.class);\n @Getter\n private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool();\n @Getter\n private static final Timer timer = new Timer();\n @Getter\n private static final Path dataPath = Path.of(\"data\");\n @Getter\n private static final Path configPath = dataPath.resolve(\"config.json\");\n @Getter\n private static final Path userPath = dataPath.resolve(\"user\");\n @Getter\n private static Config config;\n @Getter\n private static Stage stage = null;\n @Getter\n private static MainController mainController = null;\n @Getter\n @Setter\n private static PixivClient client = null;\n\n public static void saveCookie(String cookie) throws IOException {\n Files.writeString(userPath, Base64.getEncoder().encodeToString(cookie.getBytes()));\n }\n\n public static String loadCookie() throws IOException {\n if (!Files.exists(userPath)) return null;\n else return new String(Base64.getDecoder().decode(Files.readString(userPath)));\n }\n\n public static void deleteCookie() throws IOException {\n Files.delete(userPath);\n }\n\n public static void main(String[] args) {\n try {\n config = loadConfig();\n } catch (Exception e) {\n config = new Config();\n LOG.error(\"Error loading config.\", e);\n }\n launch(args);\n }\n\n public static void showAlert(String title, String content) {\n mainController.showAlert(title, content);\n }\n\n public static void saveConfig() throws Exception {\n String string = JSONObject.from(config).toString(JSONWriter.Feature.PrettyFormat);\n Files.writeString(configPath, string);\n }\n\n public static Config loadConfig() throws Exception {\n if (Files.exists(configPath)) {\n return JSONObject.parseObject(Files.readString(configPath)).to(Config.class);\n } else {\n return new Config();\n }\n }\n\n public static void openInspectStage(CachedImage[] images) {\n try {\n final FXMLLoader fxmlLoader = new FXMLLoader(ResourceLoader.load(\"fxml/Inspect.fxml\"));\n\n Stage inspectStage = new Stage();\n inspectStage.setScene(new Scene(fxmlLoader.load()));\n InspectController controller = fxmlLoader.getController();\n controller.init(inspectStage, images);\n\n inspectStage.show();\n } catch (IOException e) {\n LOG.error(\"Failed to open inspection stage.\", e);\n showAlert(\"错误\", \"打开失败\");\n }\n }\n\n @Override\n public void start(Stage stage) {\n Main.stage = stage;\n try {\n SSLUtil.ignoreSsl();\n LOG.info(\"Loading frame\");\n FXMLLoader loader = new FXMLLoader(Main.class.getResource(\"fxml/Main.fxml\"));\n final Pane main = loader.load();\n main.maxWidthProperty().bind(stage.widthProperty());\n main.maxHeightProperty().bind(stage.heightProperty());\n mainController = loader.getController();\n Scene s = new Scene(main);\n stage.setScene(s);\n\n stage.initStyle(StageStyle.UNDECORATED);\n\n stage.show();\n } catch (IOException e) {\n LOG.error(\"Exception in window initialize\", e);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n}" } ]
import javafx.scene.image.Image; import lombok.EqualsAndHashCode; import lombok.Getter; import xyz.zcraft.zpixiv.api.artwork.Identifier; import xyz.zcraft.zpixiv.ui.Main; import java.nio.file.Files; import java.nio.file.Path; import java.util.LinkedList; import java.util.Optional; import java.util.function.Function;
1,120
package xyz.zcraft.zpixiv.util; @Getter @EqualsAndHashCode(of = {"identifier"}) public class CachedImage { private final Path path;
package xyz.zcraft.zpixiv.util; @Getter @EqualsAndHashCode(of = {"identifier"}) public class CachedImage { private final Path path;
private final Identifier identifier;
0
2023-11-23 15:08:16+00:00
2k
heyliceeee/generic-data-structure
generic-data-structure/src/main/java/org/example/structures/LinkedBinaryTree.java
[ { "identifier": "EmptyCollectionException", "path": "generic-data-structure/src/main/java/org/example/exceptions/EmptyCollectionException.java", "snippet": "public class EmptyCollectionException extends RuntimeException {\n public EmptyCollectionException(String collectionType){\n super(collectionType + \" is empty.\");\n }\n}" }, { "identifier": "BinaryTreeADT", "path": "generic-data-structure/src/main/java/org/example/interfaces/BinaryTreeADT.java", "snippet": "public interface BinaryTreeADT<T>\n{\n /**\n * retorna uma referencia do elemento root\n * @return uma referencia do elemento root\n */\n public T getRoot();\n\n /**\n * retorna true se a árvore binaria estiver vazia, caso contrário retorna falso\n * @return true se a árvore binaria estiver vazia\n */\n public boolean isEmpty();\n\n /**\n * retorna o número de elementos da árvore binária\n * @return o número de elementos da árvore\n */\n public int size();\n\n /**\n * retorna true se a árvore binária conter o elemento procurado, caso contrário retorna false\n * @param targetElement o elemento a ser procurado\n * @return true se a árvore conter o elemento procurado\n */\n public boolean contains(T targetElement);\n\n /**\n * retorna uma referencia de um especifico elemento se este for encontrado na árvore binaria, caso o elemento não for encontrado, retorna uma exceção\n * @param targetElement o elemento a ser procurado na árvore\n * @return uma referencia de um especifico elemento se este for encontrado na árvore\n */\n public T find(T targetElement);\n\n /**\n * retorna a árvore binária\n * @return a árvore\n */\n public String toString();\n\n /**\n * executa uma travessia inorder na árvore binária chamando um método inorder recursivo sobrecarregando que começa com a root\n * @return um iterador sobre os elementos da árvore\n */\n public Iterator<T> iteratorInOrder();\n\n /**\n * executa uma travessia preorder na árvore binária chamando um método preorder recursivo sobrecarregando que começa com a root\n * @return um iterador sobre os elementos da árvore\n */\n public Iterator<T> iteratorPreOrder();\n\n /**\n * executa uma travessia postorder na árvore binária chamando um método postorder recursivo sobrecarregado que começa com a root\n * @return um iterador sobre os elementos da árvore\n */\n public Iterator<T> iteratorPostOrder();\n\n\n /**\n * executa uma travessia levelorder na árvore binária utilizando uma queue\n * @return um iterador sobre os elementos da árvore\n */\n public Iterator<T> iteratorLevelOrder();\n}" }, { "identifier": "QueueADT", "path": "generic-data-structure/src/main/java/org/example/interfaces/QueueADT.java", "snippet": "public interface QueueADT<T>\n{\n /**\n * adiciona um elemento ao rear da queue\n * @param element o elemento que vai ser adicionado na rear da queue\n */\n public void enqueue(T element);\n\n /**\n * remove e retorna o elemento da front da queue\n * @return o elemento da front da queue\n */\n public T dequeue();\n\n /**\n * retorna, sem remover, o elemento da front da queue\n * @return o primeiro elemento da queue\n */\n public T first();\n\n /**\n * retorna true se a queue não contém elementos\n * @return true se a queue não contém elementos\n */\n public boolean isEmpty();\n\n /**\n * retorna o número de elementos da queue\n * @return o tamanho da queue\n */\n public int size();\n\n /**\n * retorna uma string da queue\n * @return uma string da queue\n */\n public String toString();\n}" } ]
import org.example.exceptions.EmptyCollectionException; import org.example.interfaces.BinaryTreeADT; import org.example.interfaces.QueueADT; import java.util.Iterator;
1,245
package org.example.structures; public class LinkedBinaryTree<T> implements BinaryTreeADT<T> { protected int count; //tamanho da árvore protected BinaryTreeNode<T> root; //node que é o root da árvore /** * cria uma árvore binária vazia */ public LinkedBinaryTree() { count = 0; root = null; } /** * cria uma árvore binária com o elemento específico como root * @param element o elemento que irá ser como root na nova árvore binária */ public LinkedBinaryTree(T element) { count = 1; root = new BinaryTreeNode<T>(element); } @Override public T getRoot() { return this.root.element; } @Override public boolean isEmpty() { return (this.count == 0); } @Override public int size() { return this.count; } @Override public boolean contains(T targetElement) { try { find(targetElement); }
package org.example.structures; public class LinkedBinaryTree<T> implements BinaryTreeADT<T> { protected int count; //tamanho da árvore protected BinaryTreeNode<T> root; //node que é o root da árvore /** * cria uma árvore binária vazia */ public LinkedBinaryTree() { count = 0; root = null; } /** * cria uma árvore binária com o elemento específico como root * @param element o elemento que irá ser como root na nova árvore binária */ public LinkedBinaryTree(T element) { count = 1; root = new BinaryTreeNode<T>(element); } @Override public T getRoot() { return this.root.element; } @Override public boolean isEmpty() { return (this.count == 0); } @Override public int size() { return this.count; } @Override public boolean contains(T targetElement) { try { find(targetElement); }
catch (EmptyCollectionException e)
0
2023-11-23 06:45:53+00:00
2k