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
LuckPerms/rest-api-java-client
src/test/java/me/lucko/luckperms/rest/UserServiceTest.java
[ { "identifier": "LuckPermsRestClient", "path": "src/main/java/net/luckperms/rest/LuckPermsRestClient.java", "snippet": "public interface LuckPermsRestClient extends AutoCloseable {\n\n /**\n * Creates a new client builder.\n *\n * @return the new builder\n */\n static Builder builder() {\n return new LuckPermsRestClientImpl.BuilderImpl();\n }\n\n /**\n * Gets the user service.\n *\n * @return the user service\n */\n UserService users();\n\n /**\n * Gets the group service.\n *\n * @return the group service\n */\n GroupService groups();\n\n /**\n * Gets the track service.\n *\n * @return the track service\n */\n TrackService tracks();\n\n /**\n * Gets the action service.\n *\n * @return the action service\n */\n ActionService actions();\n\n /**\n * Gets the misc service.\n *\n * @return the misc service.\n */\n MiscService misc();\n\n /**\n * Close the underlying resources used by the client.\n */\n @Override\n void close();\n\n /**\n * A builder for {@link LuckPermsRestClient}\n */\n interface Builder {\n\n /**\n * Sets the API base URL.\n *\n * @param baseUrl the base url\n * @return this builder\n */\n Builder baseUrl(String baseUrl);\n\n /**\n * Sets the API key for authentication.\n *\n * @param apiKey the api key\n * @return this builder\n */\n Builder apiKey(String apiKey);\n\n /**\n * Builds a client.\n *\n * @return a client\n */\n LuckPermsRestClient build();\n }\n}" }, { "identifier": "Context", "path": "src/main/java/net/luckperms/rest/model/Context.java", "snippet": "public class Context extends AbstractModel {\n private final String key;\n private final String value;\n\n public Context(String key, String value) {\n this.key = key;\n this.value = value;\n }\n\n public String key() {\n return this.key;\n }\n\n public String value() {\n return this.value;\n }\n}" }, { "identifier": "CreateGroupRequest", "path": "src/main/java/net/luckperms/rest/model/CreateGroupRequest.java", "snippet": "public class CreateGroupRequest extends AbstractModel {\n private final String name;\n\n public CreateGroupRequest(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n}" }, { "identifier": "CreateTrackRequest", "path": "src/main/java/net/luckperms/rest/model/CreateTrackRequest.java", "snippet": "public class CreateTrackRequest extends AbstractModel {\n private final String name;\n\n public CreateTrackRequest(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n}" }, { "identifier": "CreateUserRequest", "path": "src/main/java/net/luckperms/rest/model/CreateUserRequest.java", "snippet": "public class CreateUserRequest extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n\n public CreateUserRequest(UUID uniqueId, String username) {\n this.uniqueId = uniqueId;\n this.username = username;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n}" }, { "identifier": "DemotionResult", "path": "src/main/java/net/luckperms/rest/model/DemotionResult.java", "snippet": "public class DemotionResult extends AbstractModel {\n private final boolean success;\n private final Status status;\n private final String groupFrom; // nullable\n private final String groupTo; // nullable\n\n public DemotionResult(boolean success, Status status, String groupFrom, String groupTo) {\n this.success = success;\n this.status = status;\n this.groupFrom = groupFrom;\n this.groupTo = groupTo;\n }\n\n public boolean success() {\n return this.success;\n }\n\n public Status status() {\n return this.status;\n }\n\n public String groupFrom() {\n return this.groupFrom;\n }\n\n public String groupTo() {\n return this.groupTo;\n }\n\n public enum Status {\n\n @SerializedName(\"success\")\n SUCCESS,\n\n @SerializedName(\"removed_from_first_group\")\n REMOVED_FROM_FIRST_GROUP,\n\n @SerializedName(\"malformed_track\")\n MALFORMED_TRACK,\n\n @SerializedName(\"not_on_track\")\n NOT_ON_TRACK,\n\n @SerializedName(\"ambiguous_call\")\n AMBIGUOUS_CALL,\n\n @SerializedName(\"undefined_failure\")\n UNDEFINED_FAILURE\n }\n}" }, { "identifier": "Group", "path": "src/main/java/net/luckperms/rest/model/Group.java", "snippet": "public class Group extends AbstractModel {\n private final String name;\n private final String displayName;\n private final int weight;\n private final Collection<Node> nodes;\n private final Metadata metadata;\n\n public Group(String name, String displayName, int weight, Collection<Node> nodes, Metadata metadata) {\n this.name = name;\n this.displayName = displayName;\n this.weight = weight;\n this.nodes = nodes;\n this.metadata = metadata;\n }\n\n public String name() {\n return this.name;\n }\n\n public int weight() {\n return this.weight;\n }\n\n public Collection<Node> nodes() {\n return this.nodes;\n }\n\n public String displayName() {\n return this.displayName;\n }\n\n public Metadata metadata() {\n return this.metadata;\n }\n}" }, { "identifier": "Metadata", "path": "src/main/java/net/luckperms/rest/model/Metadata.java", "snippet": "public class Metadata extends AbstractModel {\n private final Map<String, String> meta;\n private final String prefix; // nullable\n private final String suffix; // nullable\n private final String primaryGroup; // nullable\n\n public Metadata(Map<String, String> meta, String prefix, String suffix, String primaryGroup) {\n this.meta = meta;\n this.prefix = prefix;\n this.suffix = suffix;\n this.primaryGroup = primaryGroup;\n }\n\n public Map<String, String> meta() {\n return this.meta;\n }\n\n public String prefix() {\n return this.prefix;\n }\n\n public String suffix() {\n return this.suffix;\n }\n\n public String primaryGroup() {\n return this.primaryGroup;\n }\n}" }, { "identifier": "Node", "path": "src/main/java/net/luckperms/rest/model/Node.java", "snippet": "public class Node extends AbstractModel {\n private final String key;\n private final Boolean value;\n private final Set<Context> context;\n private final Long expiry;\n\n public Node(String key, Boolean value, Set<Context> context, Long expiry) {\n this.key = key;\n this.value = value;\n this.context = context;\n this.expiry = expiry;\n }\n\n public String key() {\n return this.key;\n }\n\n public Boolean value() {\n return this.value;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n\n public Long expiry() {\n return this.expiry;\n }\n}" }, { "identifier": "NodeType", "path": "src/main/java/net/luckperms/rest/model/NodeType.java", "snippet": "public enum NodeType {\n\n @SerializedName(\"regex_permission\")\n REGEX_PERMISSION,\n\n @SerializedName(\"inheritance\")\n INHERITANCE,\n\n @SerializedName(\"prefix\")\n PREFIX,\n\n @SerializedName(\"suffix\")\n SUFFIX,\n\n @SerializedName(\"meta\")\n META,\n\n @SerializedName(\"weight\")\n WEIGHT,\n\n @SerializedName(\"display_name\")\n DISPLAY_NAME;\n\n @Override\n public String toString() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n}" }, { "identifier": "PermissionCheckRequest", "path": "src/main/java/net/luckperms/rest/model/PermissionCheckRequest.java", "snippet": "public class PermissionCheckRequest extends AbstractModel {\n private final String permission;\n private final QueryOptions queryOptions; // nullable\n\n public PermissionCheckRequest(String permission, QueryOptions queryOptions) {\n this.permission = permission;\n this.queryOptions = queryOptions;\n }\n\n public String permission() {\n return this.permission;\n }\n\n public QueryOptions queryOptions() {\n return this.queryOptions;\n }\n}" }, { "identifier": "PermissionCheckResult", "path": "src/main/java/net/luckperms/rest/model/PermissionCheckResult.java", "snippet": "public class PermissionCheckResult extends AbstractModel {\n private final Tristate result;\n private final Node node;\n\n public PermissionCheckResult(Tristate result, Node node) {\n this.result = result;\n this.node = node;\n }\n\n public Tristate result() {\n return this.result;\n }\n\n public Node node() {\n return this.node;\n }\n\n public enum Tristate {\n\n @SerializedName(\"true\")\n TRUE,\n\n @SerializedName(\"false\")\n FALSE,\n\n @SerializedName(\"undefined\")\n UNDEFINED\n }\n}" }, { "identifier": "PlayerSaveResult", "path": "src/main/java/net/luckperms/rest/model/PlayerSaveResult.java", "snippet": "public class PlayerSaveResult extends AbstractModel {\n private final Set<Outcome> outcomes;\n private final String previousUsername; // nullable\n private final Set<UUID> otherUniqueIds; // nullable\n\n public PlayerSaveResult(Set<Outcome> outcomes, String previousUsername, Set<UUID> otherUniqueIds) {\n this.outcomes = outcomes;\n this.previousUsername = previousUsername;\n this.otherUniqueIds = otherUniqueIds;\n }\n\n public Set<Outcome> outcomes() {\n return this.outcomes;\n }\n\n public String previousUsername() {\n return this.previousUsername;\n }\n\n public Set<UUID> otherUniqueIds() {\n return this.otherUniqueIds;\n }\n\n public enum Outcome {\n\n @SerializedName(\"clean_insert\")\n CLEAN_INSERT,\n\n @SerializedName(\"no_change\")\n NO_CHANGE,\n\n @SerializedName(\"username_updated\")\n USERNAME_UPDATED,\n\n @SerializedName(\"other_unique_ids_present_for_username\")\n OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME,\n }\n\n}" }, { "identifier": "PromotionResult", "path": "src/main/java/net/luckperms/rest/model/PromotionResult.java", "snippet": "public class PromotionResult extends AbstractModel {\n private final boolean success;\n private final Status status;\n private final String groupFrom; // nullable\n private final String groupTo; // nullable\n\n public PromotionResult(boolean success, Status status, String groupFrom, String groupTo) {\n this.success = success;\n this.status = status;\n this.groupFrom = groupFrom;\n this.groupTo = groupTo;\n }\n\n public boolean success() {\n return this.success;\n }\n\n public Status status() {\n return this.status;\n }\n\n public String groupFrom() {\n return this.groupFrom;\n }\n\n public String groupTo() {\n return this.groupTo;\n }\n\n public enum Status {\n\n @SerializedName(\"success\")\n SUCCESS,\n\n @SerializedName(\"added_to_first_group\")\n ADDED_TO_FIRST_GROUP,\n\n @SerializedName(\"malformed_track\")\n MALFORMED_TRACK,\n\n @SerializedName(\"end_of_track\")\n END_OF_TRACK,\n\n @SerializedName(\"ambiguous_call\")\n AMBIGUOUS_CALL,\n\n @SerializedName(\"undefined_failure\")\n UNDEFINED_FAILURE\n }\n}" }, { "identifier": "QueryOptions", "path": "src/main/java/net/luckperms/rest/model/QueryOptions.java", "snippet": "public class QueryOptions extends AbstractModel {\n private final Mode queryMode; // nullable\n private final Set<Flag> flags; // nullable\n private final Set<Context> contexts; // nullable\n\n public QueryOptions(Mode queryMode, Set<Flag> flags, Set<Context> contexts) {\n this.queryMode = queryMode;\n this.flags = flags;\n this.contexts = contexts;\n }\n\n public Mode queryMode() {\n return this.queryMode;\n }\n\n public Set<Flag> flags() {\n return this.flags;\n }\n\n public Set<Context> contexts() {\n return this.contexts;\n }\n\n public enum Mode {\n\n @SerializedName(\"contextual\")\n CONTEXTUAL,\n\n @SerializedName(\"non_contextual\")\n NON_CONTEXTUAL\n }\n\n public enum Flag {\n\n @SerializedName(\"resolve_inheritance\")\n RESOLVE_INHERITANCE,\n\n @SerializedName(\"include_nodes_without_server_context\")\n INCLUDE_NODES_WITHOUT_SERVER_CONTEXT,\n\n @SerializedName(\"include_nodes_without_world_context\")\n INCLUDE_NODES_WITHOUT_WORLD_CONTEXT,\n\n @SerializedName(\"apply_inheritance_nodes_without_server_context\")\n APPLY_INHERITANCE_NODES_WITHOUT_SERVER_CONTEXT,\n\n @SerializedName(\"apply_inheritance_nodes_without_world_context\")\n APPLY_INHERITANCE_NODES_WITHOUT_WORLD_CONTEXT\n }\n}" }, { "identifier": "TemporaryNodeMergeStrategy", "path": "src/main/java/net/luckperms/rest/model/TemporaryNodeMergeStrategy.java", "snippet": "public enum TemporaryNodeMergeStrategy {\n\n @SerializedName(\"add_new_duration_to_existing\")\n ADD_NEW_DURATION_TO_EXISTING,\n\n @SerializedName(\"replace_existing_if_duration_longer\")\n REPLACE_EXISTING_IF_DURATION_LONGER,\n\n @SerializedName(\"none\")\n NONE\n\n}" }, { "identifier": "TrackRequest", "path": "src/main/java/net/luckperms/rest/model/TrackRequest.java", "snippet": "public class TrackRequest extends AbstractModel {\n private final String track;\n private final Set<Context> context;\n\n public TrackRequest(String track, Set<Context> context) {\n this.track = track;\n this.context = context;\n }\n\n public String track() {\n return this.track;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n}" }, { "identifier": "UpdateTrackRequest", "path": "src/main/java/net/luckperms/rest/model/UpdateTrackRequest.java", "snippet": "public class UpdateTrackRequest extends AbstractModel {\n private final List<String> groups;\n\n public UpdateTrackRequest(List<String> groups) {\n this.groups = groups;\n }\n\n public List<String> username() {\n return this.groups;\n }\n}" }, { "identifier": "UpdateUserRequest", "path": "src/main/java/net/luckperms/rest/model/UpdateUserRequest.java", "snippet": "public class UpdateUserRequest extends AbstractModel {\n private final String username;\n\n public UpdateUserRequest(String username) {\n this.username = username;\n }\n\n public String username() {\n return this.username;\n }\n}" }, { "identifier": "User", "path": "src/main/java/net/luckperms/rest/model/User.java", "snippet": "public class User extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n private final List<String> parentGroups;\n private final List<Node> nodes;\n private final Metadata metadata;\n\n public User(UUID uniqueId, String username, List<String> parentGroups, List<Node> nodes, Metadata metadata) {\n this.uniqueId = uniqueId;\n this.username = username;\n this.parentGroups = parentGroups;\n this.nodes = nodes;\n this.metadata = metadata;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n\n public List<String> parentGroups() {\n return this.parentGroups;\n }\n\n public List<Node> nodes() {\n return this.nodes;\n }\n\n public Metadata metadata() {\n return this.metadata;\n }\n}" }, { "identifier": "UserLookupResult", "path": "src/main/java/net/luckperms/rest/model/UserLookupResult.java", "snippet": "public class UserLookupResult extends AbstractModel {\n private final String username;\n private final UUID uniqueId;\n\n public UserLookupResult(String username, UUID uniqueId) {\n this.username = username;\n this.uniqueId = uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n}" }, { "identifier": "UserSearchResult", "path": "src/main/java/net/luckperms/rest/model/UserSearchResult.java", "snippet": "public class UserSearchResult extends AbstractModel {\n private final UUID uniqueId;\n private final Collection<Node> results;\n\n public UserSearchResult(UUID uniqueId, Collection<Node> results) {\n this.uniqueId = uniqueId;\n this.results = results;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public Collection<Node> results() {\n return this.results;\n }\n}" } ]
import net.luckperms.rest.LuckPermsRestClient; import net.luckperms.rest.model.Context; import net.luckperms.rest.model.CreateGroupRequest; import net.luckperms.rest.model.CreateTrackRequest; import net.luckperms.rest.model.CreateUserRequest; import net.luckperms.rest.model.DemotionResult; import net.luckperms.rest.model.Group; import net.luckperms.rest.model.Metadata; import net.luckperms.rest.model.Node; import net.luckperms.rest.model.NodeType; import net.luckperms.rest.model.PermissionCheckRequest; import net.luckperms.rest.model.PermissionCheckResult; import net.luckperms.rest.model.PlayerSaveResult; import net.luckperms.rest.model.PromotionResult; import net.luckperms.rest.model.QueryOptions; import net.luckperms.rest.model.TemporaryNodeMergeStrategy; import net.luckperms.rest.model.TrackRequest; import net.luckperms.rest.model.UpdateTrackRequest; import net.luckperms.rest.model.UpdateUserRequest; import net.luckperms.rest.model.User; import net.luckperms.rest.model.UserLookupResult; import net.luckperms.rest.model.UserSearchResult; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; import retrofit2.Response; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue;
7,327
long expiryTime = (System.currentTimeMillis() / 1000L) + 60; assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime), new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null), new Node("suffix.100. test", true, Collections.emptySet(), null), new Node("meta.hello.world", true, Collections.emptySet(), null) )).execute().isSuccessful()); // searchNodesByKey Response<List<UserSearchResult>> resp1 = client.users().searchNodesByKey("test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("test.node.one", true, Collections.emptySet(), null))) ), resp1.body()); // searchNodesByKeyStartsWith Response<List<UserSearchResult>> resp2 = client.users().searchNodesByKeyStartsWith("test.node").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) )) ), resp2.body()); // searchNodesByMetaKey Response<List<UserSearchResult>> resp3 = client.users().searchNodesByMetaKey("hello").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("meta.hello.world", true, Collections.emptySet(), null))) ), resp3.body()); // searchNodesByType Response<List<UserSearchResult>> resp4 = client.users().searchNodesByType(NodeType.PREFIX).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null))) ), resp4.body()); } @Test public void testUserPermissionCheck() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null) )).execute().isSuccessful()); Response<PermissionCheckResult> resp0 = client.users().permissionCheck(uuid, "test.node.zero").execute(); assertTrue(resp0.isSuccessful()); assertNotNull(resp0.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp0.body().result()); assertNull(resp0.body().node()); Response<PermissionCheckResult> resp1 = client.users().permissionCheck(uuid, "test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp1.body().result()); assertEquals(new Node("test.node.one", true, Collections.emptySet(), null), resp1.body().node()); Response<PermissionCheckResult> resp2 = client.users().permissionCheck(uuid, "test.node.two").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(PermissionCheckResult.Tristate.FALSE, resp2.body().result()); assertEquals(new Node("test.node.two", false, Collections.emptySet(), null), resp2.body().node()); Response<PermissionCheckResult> resp3 = client.users().permissionCheck(uuid, "test.node.three").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp3.body().result()); assertNull(resp3.body().node()); Response<PermissionCheckResult> resp4 = client.users().permissionCheck(uuid, new PermissionCheckRequest( "test.node.three", new QueryOptions(null, null, ImmutableSet.of(new Context("server", "test"), new Context("world", "aaa"))) )).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp4.body().result()); assertEquals(new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), resp4.body().node()); } @Test public void testUserPromoteDemote() throws IOException { LuckPermsRestClient client = createClient(); // create a user UUID uuid = UUID.randomUUID(); String username = randomName(); assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // create a track String trackName = randomName(); assertTrue(client.tracks().create(new CreateTrackRequest(trackName)).execute().isSuccessful()); // create some groups Group group1 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group2 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group3 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); ImmutableList<String> groupNames = ImmutableList.of(group1.name(), group2.name(), group3.name()); // update the track
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * 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 me.lucko.luckperms.rest; public class UserServiceTest extends AbstractIntegrationTest { @Test public void testUserCrud() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp.isSuccessful()); assertEquals(201, createResp.code()); PlayerSaveResult result = createResp.body(); assertNotNull(result); // read Response<User> readResp = client.users().get(uuid).execute(); assertTrue(readResp.isSuccessful()); User user = readResp.body(); assertNotNull(user); assertEquals(uuid, user.uniqueId()); assertEquals(username, user.username()); // update Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute(); assertTrue(updateResp.isSuccessful()); // delete Response<Void> deleteResp = client.users().delete(uuid).execute(); assertTrue(deleteResp.isSuccessful()); } @Test public void testUserCreate() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create - clean insert Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp1.isSuccessful()); assertEquals(201, createResp1.code()); PlayerSaveResult result1 = createResp1.body(); assertNotNull(result1); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes()); assertNull(result1.previousUsername()); assertNull(result1.otherUniqueIds()); // create - no change Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp2.isSuccessful()); assertEquals(200, createResp2.code()); PlayerSaveResult result2 = createResp2.body(); assertNotNull(result2); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes()); assertNull(result2.previousUsername()); assertNull(result2.otherUniqueIds()); // create - changed username String otherUsername = randomName(); Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute(); assertTrue(createResp3.isSuccessful()); assertEquals(200, createResp3.code()); PlayerSaveResult result3 = createResp3.body(); assertNotNull(result3); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes()); assertEquals(username, result3.previousUsername()); assertNull(result3.otherUniqueIds()); // create - changed uuid UUID otherUuid = UUID.randomUUID(); Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute(); assertTrue(createResp4.isSuccessful()); assertEquals(201, createResp4.code()); PlayerSaveResult result4 = createResp4.body(); assertNotNull(result4); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes()); assertNull(result4.previousUsername()); assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds()); } @Test public void testUserList() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user & give it a permission assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful()); Response<Set<UUID>> resp = client.users().list().execute(); assertTrue(resp.isSuccessful()); assertNotNull(resp.body()); assertTrue(resp.body().contains(uuid)); } @Test public void testUserLookup() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // uuid to username Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute(); assertTrue(uuidToUsername.isSuccessful()); assertNotNull(uuidToUsername.body()); assertEquals(username, uuidToUsername.body().username()); // username to uuid Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute(); assertTrue(usernameToUuid.isSuccessful()); assertNotNull(usernameToUuid.body()); assertEquals(uuid, uuidToUsername.body().uniqueId()); // not found assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code()); assertEquals(404, client.users().lookup(randomName()).execute().code()); } @Test public void testUserNodes() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // get user nodes and validate they are as expected List<Node> nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableList.of( new Node("group.default", true, Collections.emptySet(), null) ), nodes); long expiryTime = (System.currentTimeMillis() / 1000L) + 60; // add a node assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful()); // add multiple nodes assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) )).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) ), ImmutableSet.copyOf(nodes)); // delete nodes assertTrue(client.users().nodesDelete(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null) )).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) ), ImmutableSet.copyOf(nodes)); // add a duplicate node with a later expiry time long laterExpiryTime = expiryTime + 60; assertTrue(client.users().nodesAdd(uuid, new Node("test.node.four", false, Collections.emptySet(), laterExpiryTime), TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), laterExpiryTime) ), ImmutableSet.copyOf(nodes)); long evenLaterExpiryTime = expiryTime + 60; // add multiple nodes assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), evenLaterExpiryTime) ), TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), evenLaterExpiryTime) ), ImmutableSet.copyOf(nodes)); // set nodes assertTrue(client.users().nodesSet(uuid, ImmutableList.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.five", false, Collections.emptySet(), null), new Node("test.node.six", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.seven", false, Collections.emptySet(), evenLaterExpiryTime) )).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.five", false, Collections.emptySet(), null), new Node("test.node.six", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.seven", false, Collections.emptySet(), evenLaterExpiryTime) ), ImmutableSet.copyOf(nodes)); // delete all nodes assertTrue(client.users().nodesDelete(uuid).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null) ), ImmutableSet.copyOf(nodes)); } @Test public void testUserMetadata() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null), new Node("suffix.100. test", true, Collections.emptySet(), null), new Node("meta.hello.world", true, Collections.emptySet(), null) )).execute().isSuccessful()); // assert metadata Response<Metadata> resp = client.users().metadata(uuid).execute(); assertTrue(resp.isSuccessful()); Metadata metadata = resp.body(); assertNotNull(metadata); assertEquals("&c[Admin] ", metadata.prefix()); assertEquals(" test", metadata.suffix()); assertEquals("default", metadata.primaryGroup()); Map<String, String> metaMap = metadata.meta(); assertEquals("world", metaMap.get("hello")); } @Test public void testUserSearch() throws IOException { LuckPermsRestClient client = createClient(); // clear existing users Set<UUID> existingUsers = client.users().list().execute().body(); if (existingUsers != null) { for (UUID u : existingUsers) { client.users().delete(u).execute(); } } UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions long expiryTime = (System.currentTimeMillis() / 1000L) + 60; assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime), new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null), new Node("suffix.100. test", true, Collections.emptySet(), null), new Node("meta.hello.world", true, Collections.emptySet(), null) )).execute().isSuccessful()); // searchNodesByKey Response<List<UserSearchResult>> resp1 = client.users().searchNodesByKey("test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("test.node.one", true, Collections.emptySet(), null))) ), resp1.body()); // searchNodesByKeyStartsWith Response<List<UserSearchResult>> resp2 = client.users().searchNodesByKeyStartsWith("test.node").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) )) ), resp2.body()); // searchNodesByMetaKey Response<List<UserSearchResult>> resp3 = client.users().searchNodesByMetaKey("hello").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("meta.hello.world", true, Collections.emptySet(), null))) ), resp3.body()); // searchNodesByType Response<List<UserSearchResult>> resp4 = client.users().searchNodesByType(NodeType.PREFIX).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null))) ), resp4.body()); } @Test public void testUserPermissionCheck() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null) )).execute().isSuccessful()); Response<PermissionCheckResult> resp0 = client.users().permissionCheck(uuid, "test.node.zero").execute(); assertTrue(resp0.isSuccessful()); assertNotNull(resp0.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp0.body().result()); assertNull(resp0.body().node()); Response<PermissionCheckResult> resp1 = client.users().permissionCheck(uuid, "test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp1.body().result()); assertEquals(new Node("test.node.one", true, Collections.emptySet(), null), resp1.body().node()); Response<PermissionCheckResult> resp2 = client.users().permissionCheck(uuid, "test.node.two").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(PermissionCheckResult.Tristate.FALSE, resp2.body().result()); assertEquals(new Node("test.node.two", false, Collections.emptySet(), null), resp2.body().node()); Response<PermissionCheckResult> resp3 = client.users().permissionCheck(uuid, "test.node.three").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp3.body().result()); assertNull(resp3.body().node()); Response<PermissionCheckResult> resp4 = client.users().permissionCheck(uuid, new PermissionCheckRequest( "test.node.three", new QueryOptions(null, null, ImmutableSet.of(new Context("server", "test"), new Context("world", "aaa"))) )).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp4.body().result()); assertEquals(new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), resp4.body().node()); } @Test public void testUserPromoteDemote() throws IOException { LuckPermsRestClient client = createClient(); // create a user UUID uuid = UUID.randomUUID(); String username = randomName(); assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // create a track String trackName = randomName(); assertTrue(client.tracks().create(new CreateTrackRequest(trackName)).execute().isSuccessful()); // create some groups Group group1 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group2 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group3 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); ImmutableList<String> groupNames = ImmutableList.of(group1.name(), group2.name(), group3.name()); // update the track
assertTrue(client.tracks().update(trackName, new UpdateTrackRequest(groupNames)).execute().isSuccessful());
17
2023-10-22 16:07:30+00:00
12k
RoessinghResearch/senseeact
SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/compat/UserV4.java
[ { "identifier": "MaritalStatus", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/MaritalStatus.java", "snippet": "public enum MaritalStatus {\n\tSINGLE,\n\tPARTNER,\n\tMARRIED,\n\tDIVORCED,\n\tWIDOW\n}" }, { "identifier": "Role", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/Role.java", "snippet": "public enum Role {\n\tADMIN,\n\tPROFESSIONAL,\n\tPATIENT\n}" }, { "identifier": "User", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/User.java", "snippet": "public class User extends AbstractDatabaseObject {\n\t@JsonIgnore\n\tprivate String id;\n\n\t@DatabaseField(value=DatabaseType.STRING, index=true)\n\t@ValidateNotNull\n\tprivate String userid;\n\n\t@DatabaseField(value=DatabaseType.STRING, index=true)\n\t@ValidateEmail\n\t@ValidateNotNull\n\tprivate String email;\n\n\t@DatabaseField(value=DatabaseType.BYTE)\n\tprivate boolean emailVerified = false;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\t@ValidateEmail\n\tprivate String emailPendingVerification;\n\n\t@DatabaseField(value=DatabaseType.BYTE)\n\tprivate boolean hasTemporaryEmail = false;\n\n\t@DatabaseField(value=DatabaseType.BYTE)\n\tprivate boolean hasTemporaryPassword = false;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate Role role;\n\n\t@DatabaseField(value=DatabaseType.BYTE)\n\tprivate boolean active = true;\n\n\t@DatabaseField(value=DatabaseType.ISOTIME)\n\t@JsonSerialize(using= IsoDateTimeSerializer.class)\n\t@JsonDeserialize(using= DateTimeFromIsoDateTimeDeserializer.class)\n\tprivate ZonedDateTime created;\n\n\t@DatabaseField(value=DatabaseType.ISOTIME)\n\t@JsonSerialize(using=IsoDateTimeSerializer.class)\n\t@JsonDeserialize(using=DateTimeFromIsoDateTimeDeserializer.class)\n\tprivate ZonedDateTime lastActive = null;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate Gender gender;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate MaritalStatus maritalStatus;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String title;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String initials;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String firstName;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String officialFirstNames;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String prefixes;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String lastName;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String officialLastNames;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String fullName;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String nickName;\n\t\n\t@DatabaseField(value=DatabaseType.STRING)\n\t@ValidateEmail\n\tprivate String altEmail;\n\t\n\t@DatabaseField(value=DatabaseType.DATE)\n\t@JsonSerialize(using=SqlDateSerializer.class)\n\t@JsonDeserialize(using=SqlDateDeserializer.class)\n\tprivate LocalDate birthDate;\n\t\n\t@DatabaseField(value=DatabaseType.DATE)\n\t@JsonSerialize(using=SqlDateSerializer.class)\n\t@JsonDeserialize(using=SqlDateDeserializer.class)\n\tprivate LocalDate deceasedDate;\n\t\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String idNumber;\n\t\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String landlinePhone;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String mobilePhone;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String street;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String streetNumber;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String addressExtra;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String postalCode;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String town;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String departmentCode;\n\n\t@DatabaseField(value=DatabaseType.TEXT)\n\tprivate String extraInfo;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String localeCode;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String languageFormality;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\t@ValidateTimeZone\n\tprivate String timeZone;\n\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String status;\n\n\t@Override\n\tpublic void copyFrom(DatabaseObject other) {\n\t\tif (!(other instanceof User)) {\n\t\t\tsuper.copyFrom(other);\n\t\t\treturn;\n\t\t}\n\t\tUser otherUser = (User)other;\n\t\tid = otherUser.id;\n\t\tuserid = otherUser.userid;\n\t\temail = otherUser.email;\n\t\temailVerified = otherUser.emailVerified;\n\t\temailPendingVerification = otherUser.emailPendingVerification;\n\t\thasTemporaryEmail = otherUser.hasTemporaryEmail;\n\t\thasTemporaryPassword = otherUser.hasTemporaryPassword;\n\t\trole = otherUser.role;\n\t\tactive = otherUser.active;\n\t\tcreated = otherUser.created;\n\t\tlastActive = otherUser.lastActive;\n\t\tgender = otherUser.gender;\n\t\tmaritalStatus = otherUser.maritalStatus;\n\t\ttitle = otherUser.title;\n\t\tinitials = otherUser.initials;\n\t\tfirstName = otherUser.firstName;\n\t\tofficialFirstNames = otherUser.officialFirstNames;\n\t\tprefixes = otherUser.prefixes;\n\t\tlastName = otherUser.lastName;\n\t\tofficialLastNames = otherUser.officialLastNames;\n\t\tfullName = otherUser.fullName;\n\t\tnickName = otherUser.nickName;\n\t\taltEmail = otherUser.altEmail;\n\t\tbirthDate = otherUser.birthDate;\n\t\tdeceasedDate = otherUser.deceasedDate;\n\t\tidNumber = otherUser.idNumber;\n\t\tlandlinePhone = otherUser.landlinePhone;\n\t\tmobilePhone = otherUser.mobilePhone;\n\t\tstreet = otherUser.street;\n\t\tstreetNumber = otherUser.streetNumber;\n\t\taddressExtra = otherUser.addressExtra;\n\t\tpostalCode = otherUser.postalCode;\n\t\ttown = otherUser.town;\n\t\tdepartmentCode = otherUser.departmentCode;\n\t\textraInfo = otherUser.extraInfo;\n\t\tlocaleCode = otherUser.localeCode;\n\t\tlanguageFormality = otherUser.languageFormality;\n\t\ttimeZone = otherUser.timeZone;\n\t\tstatus = otherUser.status;\n\t}\n\t\n\t/**\n\t * Returns the ID. This is not defined on the client side. Users are\n\t * identified by their email address.\n\t * \n\t * @return the ID\n\t */\n\t@Override\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Sets the ID. This is not defined on the client side. Users are\n\t * identified by their email address.\n\t * \n\t * @param id the ID\n\t */\n\t@Override\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Returns the user ID. This is a required field. The user ID can be a UUID\n\t * or an email address (for legacy users). This field identifies the user\n\t * throughout the database.\n\t *\n\t * @return the user ID\n\t */\n\tpublic String getUserid() {\n\t\treturn userid;\n\t}\n\n\t/**\n\t * Sets the user ID. This is a required field. The user ID can be a UUID or\n\t * an email address (for legacy users). This field identifies the user\n\t * throughout the database.\n\t *\n\t * @param userid the user ID\n\t */\n\tpublic void setUserid(String userid) {\n\t\tthis.userid = userid;\n\t}\n\n\t/**\n\t * Returns the email address. This is a required field.\n\t * \n\t * @return the email address\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Sets the email address. This is a required field.\n\t * \n\t * @param email the email address\n\t */\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Returns whether the email address has been verified.\n\t *\n\t * @return true if the email address has been verified, false otherwise\n\t */\n\tpublic boolean isEmailVerified() {\n\t\treturn emailVerified;\n\t}\n\n\t/**\n\t * Sets whether the email address has been verified.\n\t *\n\t * @param emailVerified true if the email address has been verified, false\n\t * otherwise\n\t */\n\tpublic void setEmailVerified(boolean emailVerified) {\n\t\tthis.emailVerified = emailVerified;\n\t}\n\n\t/**\n\t * This field is set if a user with a verified email address tries to change\n\t * their address. In that case it will be set in this field and an email is\n\t * sent to verify this new email address. Only when that is confirmed, this\n\t * address will be moved to field \"email\".\n\t *\n\t * @return an email address pending verification or null\n\t */\n\tpublic String getEmailPendingVerification() {\n\t\treturn emailPendingVerification;\n\t}\n\n\t/**\n\t * This field is set if a user with a verified email address tries to change\n\t * their address. In that case it will be set in this field and an email is\n\t * sent to verify this new email address. Only when that is confirmed, this\n\t * address will be moved to field \"email\".\n\t *\n\t * @param emailPendingVerification an email address pending verification or\n\t * null\n\t */\n\tpublic void setEmailPendingVerification(String emailPendingVerification) {\n\t\tthis.emailPendingVerification = emailPendingVerification;\n\t}\n\n\t/**\n\t * Returns whether the user has a temporary email address. This is true if\n\t * the user signed up as a temporary user and did not change the email\n\t * address yet.\n\t *\n\t * @return true if the user has a temporary email address, false otherwise\n\t */\n\tpublic boolean isHasTemporaryEmail() {\n\t\treturn hasTemporaryEmail;\n\t}\n\n\t/**\n\t * Sets whether the user has a temporary email address. This is true if the\n\t * user signed up as a temporary user and did not change the email address\n\t * yet.\n\t *\n\t * @param hasTemporaryEmail true if the user has a temporary email address,\n\t * false otherwise\n\t */\n\tpublic void setHasTemporaryEmail(boolean hasTemporaryEmail) {\n\t\tthis.hasTemporaryEmail = hasTemporaryEmail;\n\t}\n\n\t/**\n\t * Returns whether the user has a temporary password. This is true if the\n\t * user signed up as a temporary user and did not change the password yet.\n\t *\n\t * @return true if the user has a temporary password, false otherwise\n\t */\n\tpublic boolean isHasTemporaryPassword() {\n\t\treturn hasTemporaryPassword;\n\t}\n\n\t/**\n\t * Sets whether the user has a temporary password. This is true if the user\n\t * signed up as a temporary user and did not change the password yet.\n\t *\n\t * @param hasTemporaryPassword true if the user has a temporary password,\n\t * false otherwise\n\t */\n\tpublic void setHasTemporaryPassword(boolean hasTemporaryPassword) {\n\t\tthis.hasTemporaryPassword = hasTemporaryPassword;\n\t}\n\n\t/**\n\t * Returns the role. This is a required field.\n\t * \n\t * @return the role\n\t */\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\t/**\n\t * Sets the role. This is a required field.\n\t * \n\t * @param role the role\n\t */\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n\n\t/**\n\t * Returns whether the user is active. An inactive user cannot log in and\n\t * is excluded from system services. The default is true.\n\t * \n\t * @return true if the user is active, false if the user is inactive\n\t */\n\tpublic boolean isActive() {\n\t\treturn active;\n\t}\n\n\t/**\n\t * Sets whether the user is active. An inactive user cannot log in and is\n\t * excluded from system services. The default is true.\n\t * \n\t * @param active true if the user is active, false if the user is inactive\n\t */\n\tpublic void setActive(boolean active) {\n\t\tthis.active = active;\n\t}\n\n\t/**\n\t * Returns the time when the user was created.\n\t *\n\t * @return the time when the user was created\n\t */\n\tpublic ZonedDateTime getCreated() {\n\t\treturn created;\n\t}\n\n\t/**\n\t * Sets the time when the user was created.\n\t *\n\t * @param created the time when the user was created\n\t */\n\tpublic void setCreated(ZonedDateTime created) {\n\t\tthis.created = created;\n\t}\n\n\t/**\n\t * Returns the time when the user was last active. This is updated each time\n\t * the user calls an endpoint where the authentication token is validated.\n\t *\n\t * @return the time when the user was last active\n\t */\n\tpublic ZonedDateTime getLastActive() {\n\t\treturn lastActive;\n\t}\n\n\t/**\n\t * Sets the time when the user was last active. This is updated each time\n\t * the user calls an endpoint where the authentication token is validated.\n\t *\n\t * @param lastActive the time when the user was last active\n\t */\n\tpublic void setLastActive(ZonedDateTime lastActive) {\n\t\tthis.lastActive = lastActive;\n\t}\n\n\t/**\n\t * Returns the gender.\n\t * \n\t * @return the gender or null\n\t */\n\tpublic Gender getGender() {\n\t\treturn gender;\n\t}\n\n\t/**\n\t * Sets the gender.\n\t * \n\t * @param gender the gender or null\n\t */\n\tpublic void setGender(Gender gender) {\n\t\tthis.gender = gender;\n\t}\n\n\t/**\n\t * Returns the marital status.\n\t * \n\t * @return the marital status or null\n\t */\n\tpublic MaritalStatus getMaritalStatus() {\n\t\treturn maritalStatus;\n\t}\n\n\t/**\n\t * Sets the marital status.\n\t * \n\t * @param maritalStatus the marital status or null\n\t */\n\tpublic void setMaritalStatus(MaritalStatus maritalStatus) {\n\t\tthis.maritalStatus = maritalStatus;\n\t}\n\n\t/**\n\t * Returns the title.\n\t * \n\t * @return the title or null\n\t */\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\t/**\n\t * Sets the title.\n\t * \n\t * @param title the title or null\n\t */\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\t/**\n\t * Returns the initials of the first names formatted as A.B.C.\n\t * \n\t * @return the initials or null\n\t */\n\tpublic String getInitials() {\n\t\treturn initials;\n\t}\n\n\t/**\n\t * Sets the initials of the first names formatted as A.B.C.\n\t * \n\t * @param initials the initials or null\n\t */\n\tpublic void setInitials(String initials) {\n\t\tthis.initials = initials;\n\t}\n\n\t/**\n\t * Returns the first name. This should be the familiar first name used to\n\t * address the person in friendly language.\n\t * \n\t * @return the first name or null\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\t/**\n\t * Sets the first name. This should be the familiar first name used to\n\t * address the person in friendly language.\n\t * \n\t * @param firstName the first name or null\n\t */\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\t/**\n\t * Returns the official first names.\n\t * \n\t * @return the official first names or null\n\t */\n\tpublic String getOfficialFirstNames() {\n\t\treturn officialFirstNames;\n\t}\n\n\t/**\n\t * Sets the official first names.\n\t * \n\t * @param officialFirstNames the official first names or null\n\t */\n\tpublic void setOfficialFirstNames(String officialFirstNames) {\n\t\tthis.officialFirstNames = officialFirstNames;\n\t}\n\n\t/**\n\t * Returns the prefixes for the last name. Languages such as Dutch have\n\t * prefixes for last names that should be ignored when sorting.\n\t * \n\t * @return the prefixes or null\n\t */\n\tpublic String getPrefixes() {\n\t\treturn prefixes;\n\t}\n\n\t/**\n\t * Sets the prefixes for the last name. Languages such as Dutch have\n\t * prefixes for last names that should be ignored when sorting.\n\t * \n\t * @param prefixes the prefixes or null\n\t */\n\tpublic void setPrefixes(String prefixes) {\n\t\tthis.prefixes = prefixes;\n\t}\n\n\t/**\n\t * Returns the last name. This should be the familiar last name used to\n\t * address the person in friendly language.\n\t * \n\t * @return the last name or null\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\t/**\n\t * Sets the last name. This should be the familiar last name used to\n\t * address the person in friendly language.\n\t * \n\t * @param lastName the last name or null\n\t */\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\t/**\n\t * Returns the official last names.\n\t * \n\t * @return the official last names or null\n\t */\n\tpublic String getOfficialLastNames() {\n\t\treturn officialLastNames;\n\t}\n\n\t/**\n\t * Sets the official last names.\n\t * \n\t * @param officialLastNames the official last names or null\n\t */\n\tpublic void setOfficialLastNames(String officialLastNames) {\n\t\tthis.officialLastNames = officialLastNames;\n\t}\n\n\t/**\n\t * Returns the full name. This field can be used for applications that do\n\t * not separate first name and last name.\n\t *\n\t * @return the full name or null\n\t */\n\tpublic String getFullName() {\n\t\treturn fullName;\n\t}\n\n\t/**\n\t * Sets the full name. This field can be used for applications that do not\n\t * separate first name and last name.\n\t *\n\t * @param fullName the full name or null\n\t */\n\tpublic void setFullName(String fullName) {\n\t\tthis.fullName = fullName;\n\t}\n\n\t/**\n\t * Returns the nickname.\n\t *\n\t * @return the nickname or null\n\t */\n\tpublic String getNickName() {\n\t\treturn nickName;\n\t}\n\n\t/**\n\t * Sets the nickname.\n\t *\n\t * @param nickName the nickname or null\n\t */\n\tpublic void setNickName(String nickName) {\n\t\tthis.nickName = nickName;\n\t}\n\n\t/**\n\t * Returns the alternative email address.\n\t * \n\t * @return the alternative email address or null\n\t */\n\tpublic String getAltEmail() {\n\t\treturn altEmail;\n\t}\n\n\t/**\n\t * Sets the alternative email address.\n\t * \n\t * @param altEmail the alternative email address or null\n\t */\n\tpublic void setAltEmail(String altEmail) {\n\t\tthis.altEmail = altEmail;\n\t}\n\n\t/**\n\t * Returns the birth date.\n\t * \n\t * @return the birth date or null\n\t */\n\tpublic LocalDate getBirthDate() {\n\t\treturn birthDate;\n\t}\n\n\t/**\n\t * Sets the birth date.\n\t * \n\t * @param birthDate the birth date or null\n\t */\n\tpublic void setBirthDate(LocalDate birthDate) {\n\t\tthis.birthDate = birthDate;\n\t}\n\n\t/**\n\t * If the user has deceased, this method returns the date of decease.\n\t * \n\t * @return the date of decease or null\n\t */\n\tpublic LocalDate getDeceasedDate() {\n\t\treturn deceasedDate;\n\t}\n\n\t/**\n\t * If the user has deceased, this method sets the date of decease.\n\t * \n\t * @param deceasedDate the date of decease or null\n\t */\n\tpublic void setDeceasedDate(LocalDate deceasedDate) {\n\t\tthis.deceasedDate = deceasedDate;\n\t}\n\n\t/**\n\t * Returns the identification number. This could be the personal\n\t * identification number for government services or in a hospital\n\t * administration system.\n\t * \n\t * @return the identification number or null\n\t */\n\tpublic String getIdNumber() {\n\t\treturn idNumber;\n\t}\n\n\t/**\n\t * Sets the identification number. This could be the personal\n\t * identification number for government services or in a hospital\n\t * administration system.\n\t * \n\t * @param idNumber the identification number or null\n\t */\n\tpublic void setIdNumber(String idNumber) {\n\t\tthis.idNumber = idNumber;\n\t}\n\n\t/**\n\t * Returns the landline phone number. It could include characters such as\n\t * hyphens, parentheses and spaces. The format is not validated.\n\t * \n\t * @return the landline phone number or null\n\t */\n\tpublic String getLandlinePhone() {\n\t\treturn landlinePhone;\n\t}\n\n\t/**\n\t * Sets the landline phone number. It could include characters such as\n\t * hyphens, parentheses and spaces. The format is not validated.\n\t * \n\t * @param landlinePhone the landline phone number or null\n\t */\n\tpublic void setLandlinePhone(String landlinePhone) {\n\t\tthis.landlinePhone = landlinePhone;\n\t}\n\n\t/**\n\t * Returns the mobile phone number. It could include characters such as\n\t * hyphens, parentheses and spaces. The format is not validated.\n\t * \n\t * @return the mobile phone number or null\n\t */\n\tpublic String getMobilePhone() {\n\t\treturn mobilePhone;\n\t}\n\n\t/**\n\t * Sets the mobile phone number. It could include characters such as\n\t * hyphens, parentheses and spaces. The format is not validated.\n\t * \n\t * @param mobilePhone the mobile phone number or null\n\t */\n\tpublic void setMobilePhone(String mobilePhone) {\n\t\tthis.mobilePhone = mobilePhone;\n\t}\n\n\t/**\n\t * Returns the street name.\n\t * \n\t * @return the street name or null\n\t */\n\tpublic String getStreet() {\n\t\treturn street;\n\t}\n\n\t/**\n\t * Sets the street name.\n\t * \n\t * @param street the street name or null\n\t */\n\tpublic void setStreet(String street) {\n\t\tthis.street = street;\n\t}\n\n\t/**\n\t * Returns the house number in the street.\n\t * \n\t * @return the house number or null\n\t */\n\tpublic String getStreetNumber() {\n\t\treturn streetNumber;\n\t}\n\n\t/**\n\t * Sets the house number in the street.\n\t * \n\t * @param streetNumber the house number or null\n\t */\n\tpublic void setStreetNumber(String streetNumber) {\n\t\tthis.streetNumber = streetNumber;\n\t}\n\n\t/**\n\t * Returns extra address lines.\n\t * \n\t * @return extra address lines or null\n\t */\n\tpublic String getAddressExtra() {\n\t\treturn addressExtra;\n\t}\n\n\t/**\n\t * Sets extra address lines.\n\t * \n\t * @param addressExtra extra address lines or null\n\t */\n\tpublic void setAddressExtra(String addressExtra) {\n\t\tthis.addressExtra = addressExtra;\n\t}\n\n\t/**\n\t * Returns the postal code. The format is not validated.\n\t * \n\t * @return the postal code or null\n\t */\n\tpublic String getPostalCode() {\n\t\treturn postalCode;\n\t}\n\n\t/**\n\t * Sets the postal code. The format is not validated.\n\t * \n\t * @param postalCode the postal code or null\n\t */\n\tpublic void setPostalCode(String postalCode) {\n\t\tthis.postalCode = postalCode;\n\t}\n\n\t/**\n\t * Returns the town name.\n\t * \n\t * @return the town name or null\n\t */\n\tpublic String getTown() {\n\t\treturn town;\n\t}\n\n\t/**\n\t * Sets the town name.\n\t * \n\t * @param town the town name or null\n\t */\n\tpublic void setTown(String town) {\n\t\tthis.town = town;\n\t}\n\n\t/**\n\t * Returns a string code for the department.\n\t * \n\t * @return the department code or null\n\t */\n\tpublic String getDepartmentCode() {\n\t\treturn departmentCode;\n\t}\n\n\t/**\n\t * Sets a string code for the department.\n\t * \n\t * @param departmentCode the department code or null\n\t */\n\tpublic void setDepartmentCode(String departmentCode) {\n\t\tthis.departmentCode = departmentCode;\n\t}\n\n\t/**\n\t * Returns any extra information.\n\t * \n\t * @return any extra information or null\n\t */\n\tpublic String getExtraInfo() {\n\t\treturn extraInfo;\n\t}\n\n\t/**\n\t * Sets any extra information.\n\t * \n\t * @param extraInfo any extra information or null\n\t */\n\tpublic void setExtraInfo(String extraInfo) {\n\t\tthis.extraInfo = extraInfo;\n\t}\n\n\t/**\n\t * Returns the locale code. For example en_GB. It should consists of an\n\t * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country\n\t * code.\n\t *\n\t * @return the locale code or null\n\t */\n\tpublic String getLocaleCode() {\n\t\treturn localeCode;\n\t}\n\n\t/**\n\t * Sets the locale code. For example en_GB. It should consists of an\n\t * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country\n\t * code.\n\t *\n\t * @param localeCode the locale code or null\n\t */\n\tpublic void setLocaleCode(String localeCode) {\n\t\tthis.localeCode = localeCode;\n\t}\n\n\t/**\n\t * Returns the language formality that the user prefers to be addressed\n\t * with. This can be \"FORMAL\", \"INFORMAL\" or null.\n\t *\n\t * @return the language formality or null\n\t */\n\tpublic String getLanguageFormality() {\n\t\treturn languageFormality;\n\t}\n\n\t/**\n\t * Sets the language formality that the user prefers to be addressed with.\n\t * This can be \"FORMAL\", \"INFORMAL\" or null.\n\t *\n\t * @param languageFormality the language formality or null\n\t */\n\tpublic void setLanguageFormality(String languageFormality) {\n\t\tthis.languageFormality = languageFormality;\n\t}\n\n\t/**\n\t * Returns the time zone. This should be a location-based time zone ID from\n\t * the tz database. For example Europe/Amsterdam.\n\t *\n\t * @return the time zone or null\n\t */\n\tpublic String getTimeZone() {\n\t\treturn timeZone;\n\t}\n\n\t/**\n\t * Sets the time zone. This should be a location-based time zone ID from\n\t * the tz database. For example Europe/Amsterdam.\n\t *\n\t * @param timeZone the time zone or null\n\t */\n\tpublic void setTimeZone(String timeZone) {\n\t\tthis.timeZone = timeZone;\n\t}\n\n\t/**\n\t * Returns the status of this user. This field can be used if your\n\t * application needs more status information than {@link #isActive()\n\t * isActive()}.\n\t * \n\t * @return the status or null\n\t */\n\tpublic String getStatus() {\n\t\treturn status;\n\t}\n\n\t/**\n\t * Sets the status of this user. This field can be used if your application\n\t * needs more status information than {@link #isActive() isActive()}.\n\t * \n\t * @param status the status or null\n\t */\n\tpublic void setStatus(String status) {\n\t\tthis.status = status;\n\t}\n\n\t/**\n\t * Returns the time zone object for this user. If no time zone ID is defined\n\t * in the timeZone field, this method returns the default time zone.\n\t * \n\t * @return the time zone\n\t */\n\tpublic ZoneId toTimeZone() {\n\t\tif (getTimeZone() != null)\n\t\t\treturn ZoneId.of(getTimeZone());\n\t\telse\n\t\t\treturn ZoneId.systemDefault();\n\t}\n\t\n\t/**\n\t * Returns the Locale object for the locale code for this user. If no locale\n\t * code is defined in the localeCode field, or if the locale code is\n\t * invalid, this method returns the default locale.\n\t * \n\t * @return the locale\n\t */\n\tpublic Locale toLocale() {\n\t\tif (localeCode == null)\n\t\t\treturn Locale.getDefault();\n\t\tString code = localeCode.toLowerCase();\n\t\tPattern regex = Pattern.compile(\"([a-z]{2})(_([a-z]{2}))?\");\n\t\tMatcher m = regex.matcher(code);\n\t\tif (!m.matches())\n\t\t\treturn Locale.getDefault();\n\t\tString language = m.group(1);\n\t\tString country = m.group(3);\n\t\tif (country == null)\n\t\t\treturn new Locale(language);\n\t\telse\n\t\t\treturn new Locale(language, country.toUpperCase());\n\t}\n\n\t/**\n\t * Returns the real name of this user. It uses the fields \"fullName\",\n\t * \"lastName\", \"officialLastNames\", \"prefixes\", \"firstName\",\n\t * \"officialFirstNames\" and \"initials\". If none of the full name and the 4\n\t * first and last name fields are assigned, then this method returns null.\n\t * \n\t * @return the real name\n\t */\n\tpublic String toRealName() {\n\t\tif (fullName != null && fullName.trim().length() > 0)\n\t\t\treturn fullName.trim();\n\t\tString lastName = null;\n\t\tif (this.lastName != null && this.lastName.trim().length() > 0) {\n\t\t\tlastName = this.lastName.trim();\n\t\t} else if (officialLastNames != null &&\n\t\t\t\tofficialLastNames.trim().length() > 0) {\n\t\t\tlastName = officialLastNames.trim();\n\t\t}\n\t\tif (lastName != null && prefixes != null &&\n\t\t\t\tprefixes.trim().length() > 0) {\n\t\t\tlastName = prefixes.trim() + \" \" + lastName;\n\t\t}\n\t\tString initials = null;\n\t\tif (this.initials != null && this.initials.trim().length() > 0)\n\t\t\tinitials = this.initials.trim();\n\t\tString firstName = null;\n\t\tif (this.firstName != null && this.firstName.trim().length() > 0) {\n\t\t\tfirstName = this.firstName.trim();\n\t\t} else if (officialFirstNames != null &&\n\t\t\t\tofficialFirstNames.trim().length() > 0) {\n\t\t\tfirstName = officialFirstNames.trim();\n\t\t}\n\t\tif (firstName != null && lastName != null)\n\t\t\treturn firstName + \" \" + lastName;\n\t\telse if (initials != null && lastName != null)\n\t\t\treturn initials + \" \" + lastName;\n\t\telse if (lastName != null)\n\t\t\treturn lastName;\n\t\telse\n\t\t\treturn firstName;\n\t}\n}" }, { "identifier": "AbstractDatabaseObject", "path": "DataAccessObjects/src/main/java/nl/rrd/senseeact/dao/AbstractDatabaseObject.java", "snippet": "public abstract class AbstractDatabaseObject implements DatabaseObject,\n\t\tCloneable {\n\tprivate String id;\n\t\n\t@Override\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(false);\n\t}\n\n\t/**\n\t * Copies the values from another database object into this object.\n\t *\n\t * @param other the other database object\n\t */\n\tpublic void copyFrom(DatabaseObject other) {\n\t\tDatabaseObjectMapper mapper = new DatabaseObjectMapper();\n\t\tMap<String,Object> map = mapper.objectToMap(other, false);\n\t\tother = mapper.mapToObject(map, other.getClass(), false);\n\t\tfor (String prop : map.keySet()) {\n\t\t\tObject value = PropertyReader.readProperty(other, prop);\n\t\t\tPropertyWriter.writeProperty(this, prop, value);\n\t\t}\n\t}\n\t\n\t/**\n\t * Returns a string representation of this object. If \"human\" is true, the\n\t * returned string will have a friendly formatting, possibly spanning\n\t * multiple lines.\n\t * \n\t * @param human true for friendly formatting, false for single-line\n\t * formatting\n\t * @return the string\n\t */\n\tpublic String toString(boolean human) {\n\t\tDatabaseObjectMapper mapper = new DatabaseObjectMapper();\n\t\tMap<String,Object> map = mapper.objectToMap(this, true);\n\t\tDataFormatter formatter = new DataFormatter();\n\t\treturn getClass().getSimpleName() + \" \" + formatter.format(map, human);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tDatabaseObjectMapper mapper = new DatabaseObjectMapper();\n\t\tMap<String,Object> map = mapper.objectToMap(this, false);\n\t\tresult = prime * result + map.hashCode();\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tAbstractDatabaseObject other = (AbstractDatabaseObject)obj;\n\t\tDatabaseObjectMapper mapper = new DatabaseObjectMapper();\n\t\tMap<String,Object> map = mapper.objectToMap(this, false);\n\t\tMap<String,Object> otherMap = mapper.objectToMap(other, false);\n\t\treturn map.equals(otherMap);\n\t}\n\t\n\t/**\n\t * Compares the value fields of this database object with another database\n\t * object. The \"id\" field is ignored.\n\t * \n\t * @param obj the other object\n\t * @return true if both objects have the same values, false otherwise\n\t */\n\tpublic boolean equalValues(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tAbstractDatabaseObject other = (AbstractDatabaseObject)obj;\n\t\tDatabaseObjectMapper mapper = new DatabaseObjectMapper();\n\t\tMap<String,Object> map = mapper.objectToMap(this, false);\n\t\tmap.remove(\"id\");\n\t\tMap<String,Object> otherMap = mapper.objectToMap(other, false);\n\t\totherMap.remove(\"id\");\n\t\treturn map.equals(otherMap);\n\t}\n\n\t@Override\n\tprotected Object clone() throws CloneNotSupportedException {\n\t\tDatabaseObjectMapper mapper = new DatabaseObjectMapper();\n\t\treturn mapper.mapToObject(mapper.objectToMap(this, false), getClass(),\n\t\t\t\tfalse);\n\t}\n}" }, { "identifier": "DatabaseObject", "path": "DataAccessObjects/src/main/java/nl/rrd/senseeact/dao/DatabaseObject.java", "snippet": "public interface DatabaseObject {\n\t\n\t/**\n\t * Returns the ID.\n\t * \n\t * @return the ID\n\t */\n\tString getId();\n\t\n\t/**\n\t * Sets the ID.\n\t * \n\t * @param id the ID\n\t */\n\tvoid setId(String id);\n}" }, { "identifier": "DatabaseType", "path": "DataAccessObjects/src/main/java/nl/rrd/senseeact/dao/DatabaseType.java", "snippet": "public enum DatabaseType {\n\tBYTE,\n\tSHORT,\n\tINT,\n\tLONG,\n\tFLOAT,\n\tDOUBLE,\n\tSTRING,\n\tTEXT,\n\tDATE,\n\tTIME,\n\tDATETIME,\n\tISOTIME\n}" } ]
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import nl.rrd.utils.json.SqlDateDeserializer; import nl.rrd.utils.json.SqlDateSerializer; import nl.rrd.utils.validation.ValidateEmail; import nl.rrd.utils.validation.ValidateNotNull; import nl.rrd.utils.validation.ValidateTimeZone; import nl.rrd.senseeact.client.model.MaritalStatus; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.User; import nl.rrd.senseeact.dao.AbstractDatabaseObject; import nl.rrd.senseeact.dao.DatabaseField; import nl.rrd.senseeact.dao.DatabaseObject; import nl.rrd.senseeact.dao.DatabaseType; import java.time.LocalDate; import java.util.LinkedHashSet; import java.util.Set;
10,707
* * @return the town name or null */ public String getTown() { return town; } /** * Sets the town name. * * @param town the town name or null */ public void setTown(String town) { this.town = town; } /** * Returns a string code for the department. * * @return the department code or null */ public String getDepartmentCode() { return departmentCode; } /** * Sets a string code for the department. * * @param departmentCode the department code or null */ public void setDepartmentCode(String departmentCode) { this.departmentCode = departmentCode; } /** * Returns any extra information. * * @return any extra information or null */ public String getExtraInfo() { return extraInfo; } /** * Sets any extra information. * * @param extraInfo any extra information or null */ public void setExtraInfo(String extraInfo) { this.extraInfo = extraInfo; } /** * Returns the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @return the locale code or null */ public String getLocaleCode() { return localeCode; } /** * Sets the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @param localeCode the locale code or null */ public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } /** * Returns the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @return the time zone or null */ public String getTimeZone() { return timeZone; } /** * Sets the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @param timeZone the time zone or null */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } /** * Returns the status of this user. For example this could indicate whether * a user is active or inactive. * * @return the status or null */ public String getStatus() { return status; } /** * Sets the status of this user. For example this could indicate whether a * user is active or inactive. * * @param status the status or null */ public void setStatus(String status) { this.status = status; } /** * Converts a User object to a UserV4 object. * * @param user the User object * @return the UserV4 object */
package nl.rrd.senseeact.client.model.compat; /** * Model of a user in SenSeeAct. This class is used on the client side. The * server side has an extension of this class with sensitive information about * the authentication of a user. On the server it's stored in a database. * Therefore this class is a {@link DatabaseObject DatabaseObject} and it has an * ID field, but the ID field is not used on the client side. The email address * is used to identify a user. * * <p>Only two fields are always defined on the client side: email and role. * All other fields may be null.</p> * * @author Dennis Hofs (RRD) */ public class UserV4 extends AbstractDatabaseObject { @JsonIgnore private String id; @DatabaseField(value=DatabaseType.STRING, index=true) @ValidateEmail @ValidateNotNull private String email; @DatabaseField(value=DatabaseType.STRING) private Role role; @DatabaseField(value=DatabaseType.BYTE) private boolean active = true; @DatabaseField(value=DatabaseType.STRING) private GenderV0 gender; @DatabaseField(value=DatabaseType.STRING) private MaritalStatus maritalStatus; @DatabaseField(value=DatabaseType.STRING) private String title; @DatabaseField(value=DatabaseType.STRING) private String initials; @DatabaseField(value=DatabaseType.STRING) private String firstName; @DatabaseField(value=DatabaseType.STRING) private String officialFirstNames; @DatabaseField(value=DatabaseType.STRING) private String prefixes; @DatabaseField(value=DatabaseType.STRING) private String lastName; @DatabaseField(value=DatabaseType.STRING) private String officialLastNames; @DatabaseField(value=DatabaseType.STRING) private String fullName; @DatabaseField(value=DatabaseType.STRING) private String nickName; @DatabaseField(value=DatabaseType.STRING) @ValidateEmail private String altEmail; @DatabaseField(value=DatabaseType.DATE) @JsonSerialize(using=SqlDateSerializer.class) @JsonDeserialize(using=SqlDateDeserializer.class) private LocalDate birthDate; @DatabaseField(value=DatabaseType.DATE) @JsonSerialize(using=SqlDateSerializer.class) @JsonDeserialize(using=SqlDateDeserializer.class) private LocalDate deathDate; @DatabaseField(value=DatabaseType.STRING) private String idNumber; @DatabaseField(value=DatabaseType.STRING) private String landlinePhone; @DatabaseField(value=DatabaseType.STRING) private String mobilePhone; @DatabaseField(value=DatabaseType.STRING) private String street; @DatabaseField(value=DatabaseType.STRING) private String streetNumber; @DatabaseField(value=DatabaseType.STRING) private String addressExtra; @DatabaseField(value=DatabaseType.STRING) private String postalCode; @DatabaseField(value=DatabaseType.STRING) private String town; @DatabaseField(value=DatabaseType.STRING) private String departmentCode; @DatabaseField(value=DatabaseType.TEXT) private String extraInfo; @DatabaseField(value=DatabaseType.STRING) private String localeCode; @DatabaseField(value=DatabaseType.STRING) @ValidateTimeZone private String timeZone; @DatabaseField(value=DatabaseType.STRING) private String status; /** * Returns the ID. This is not defined on the client side. Users are * identified by their email address. * * @return the ID */ @Override public String getId() { return id; } /** * Sets the ID. This is not defined on the client side. Users are * identified by their email address. * * @param id the ID */ @Override public void setId(String id) { this.id = id; } /** * Returns the email address. This is a required field. The email address * identifies the user. * * @return the email address */ public String getEmail() { return email; } /** * Sets the email address. This is a required field. The email address * identifies the user. * * @param email the email address */ public void setEmail(String email) { this.email = email; } /** * Returns the role. This is a required field. * * @return the role */ public Role getRole() { return role; } /** * Sets the role. This is a required field. * * @param role the role */ public void setRole(Role role) { this.role = role; } /** * Returns whether the user is active. An inactive user cannot log in and * is excluded from system services. The default is true. * * @return true if the user is active, false if the user is inactive */ public boolean isActive() { return active; } /** * Sets whether the user is active. An inactive user cannot log in and is * excluded from system services. The default is true. * * @param active true if the user is active, false if the user is inactive */ public void setActive(boolean active) { this.active = active; } /** * Returns the gender. * * @return the gender or null */ public GenderV0 getGender() { return gender; } /** * Sets the gender. * * @param gender the gender or null */ public void setGender(GenderV0 gender) { this.gender = gender; } /** * Returns the marital status. * * @return the marital status or null */ public MaritalStatus getMaritalStatus() { return maritalStatus; } /** * Sets the marital status. * * @param maritalStatus the marital status or null */ public void setMaritalStatus(MaritalStatus maritalStatus) { this.maritalStatus = maritalStatus; } /** * Returns the title. * * @return the title or null */ public String getTitle() { return title; } /** * Sets the title. * * @param title the title or null */ public void setTitle(String title) { this.title = title; } /** * Returns the initials of the first names formatted as A.B.C. * * @return the initials or null */ public String getInitials() { return initials; } /** * Sets the initials of the first names formatted as A.B.C. * * @param initials the initials or null */ public void setInitials(String initials) { this.initials = initials; } /** * Returns the first name. This should be the familiar first name used to * address the person in friendly language. * * @return the first name or null */ public String getFirstName() { return firstName; } /** * Sets the first name. This should be the familiar first name used to * address the person in friendly language. * * @param firstName the first name or null */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Returns the official first names. * * @return the official first names or null */ public String getOfficialFirstNames() { return officialFirstNames; } /** * Sets the official first names. * * @param officialFirstNames the official first names or null */ public void setOfficialFirstNames(String officialFirstNames) { this.officialFirstNames = officialFirstNames; } /** * Returns the prefixes for the last name. Languages such as Dutch have * prefixes for last names that should be ignored when sorting. * * @return the prefixes or null */ public String getPrefixes() { return prefixes; } /** * Sets the prefixes for the last name. Languages such as Dutch have * prefixes for last names that should be ignored when sorting. * * @param prefixes the prefixes or null */ public void setPrefixes(String prefixes) { this.prefixes = prefixes; } /** * Returns the last name. This should be the familiar last name used to * address the person in friendly language. * * @return the last name or null */ public String getLastName() { return lastName; } /** * Sets the last name. This should be the familiar last name used to * address the person in friendly language. * * @param lastName the last name or null */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Returns the official last names. * * @return the official last names or null */ public String getOfficialLastNames() { return officialLastNames; } /** * Sets the official last names. * * @param officialLastNames the official last names or null */ public void setOfficialLastNames(String officialLastNames) { this.officialLastNames = officialLastNames; } /** * Returns the full name. This field can be used for applications that do * not separate first name and last name. * * @return the full name or null */ public String getFullName() { return fullName; } /** * Sets the full name. This field can be used for applications that do not * separate first name and last name. * * @param fullName the full name or null */ public void setFullName(String fullName) { this.fullName = fullName; } /** * Returns the nickname. * * @return the nickname or null */ public String getNickName() { return nickName; } /** * Sets the nickname. * * @param nickName the nickname or null */ public void setNickName(String nickName) { this.nickName = nickName; } /** * Returns the alternative email address. * * @return the alternative email address or null */ public String getAltEmail() { return altEmail; } /** * Sets the alternative email address. * * @param altEmail the alternative email address or null */ public void setAltEmail(String altEmail) { this.altEmail = altEmail; } /** * Returns the birth date. * * @return the birth date or null */ public LocalDate getBirthDate() { return birthDate; } /** * Sets the birth date. * * @param birthDate the birth date or null */ public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; } /** * Returns the date of death. * * @return the date of death or null */ public LocalDate getDeathDate() { return deathDate; } /** * Sets the date of death. * * @param deathDate the date of death or null */ public void setDeathDate(LocalDate deathDate) { this.deathDate = deathDate; } /** * Returns the identification number. This could be the personal * identification number for government services or in a hospital * administration system. * * @return the identification number or null */ public String getIdNumber() { return idNumber; } /** * Sets the identification number. This could be the personal * identification number for government services or in a hospital * administration system. * * @param idNumber the identification number or null */ public void setIdNumber(String idNumber) { this.idNumber = idNumber; } /** * Returns the landline phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @return the landline phone number or null */ public String getLandlinePhone() { return landlinePhone; } /** * Sets the landline phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @param landlinePhone the landline phone number or null */ public void setLandlinePhone(String landlinePhone) { this.landlinePhone = landlinePhone; } /** * Returns the mobile phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @return the mobile phone number or null */ public String getMobilePhone() { return mobilePhone; } /** * Sets the mobile phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @param mobilePhone the mobile phone number or null */ public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } /** * Returns the street name. * * @return the street name or null */ public String getStreet() { return street; } /** * Sets the street name. * * @param street the street name or null */ public void setStreet(String street) { this.street = street; } /** * Returns the house number in the street. * * @return the house number or null */ public String getStreetNumber() { return streetNumber; } /** * Sets the house number in the street. * * @param streetNumber the house number or null */ public void setStreetNumber(String streetNumber) { this.streetNumber = streetNumber; } /** * Returns extra address lines. * * @return extra address lines or null */ public String getAddressExtra() { return addressExtra; } /** * Sets extra address lines. * * @param addressExtra extra address lines or null */ public void setAddressExtra(String addressExtra) { this.addressExtra = addressExtra; } /** * Returns the postal code. The format is not validated. * * @return the postal code or null */ public String getPostalCode() { return postalCode; } /** * Sets the postal code. The format is not validated. * * @param postalCode the postal code or null */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * Returns the town name. * * @return the town name or null */ public String getTown() { return town; } /** * Sets the town name. * * @param town the town name or null */ public void setTown(String town) { this.town = town; } /** * Returns a string code for the department. * * @return the department code or null */ public String getDepartmentCode() { return departmentCode; } /** * Sets a string code for the department. * * @param departmentCode the department code or null */ public void setDepartmentCode(String departmentCode) { this.departmentCode = departmentCode; } /** * Returns any extra information. * * @return any extra information or null */ public String getExtraInfo() { return extraInfo; } /** * Sets any extra information. * * @param extraInfo any extra information or null */ public void setExtraInfo(String extraInfo) { this.extraInfo = extraInfo; } /** * Returns the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @return the locale code or null */ public String getLocaleCode() { return localeCode; } /** * Sets the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @param localeCode the locale code or null */ public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } /** * Returns the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @return the time zone or null */ public String getTimeZone() { return timeZone; } /** * Sets the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @param timeZone the time zone or null */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } /** * Returns the status of this user. For example this could indicate whether * a user is active or inactive. * * @return the status or null */ public String getStatus() { return status; } /** * Sets the status of this user. For example this could indicate whether a * user is active or inactive. * * @param status the status or null */ public void setStatus(String status) { this.status = status; } /** * Converts a User object to a UserV4 object. * * @param user the User object * @return the UserV4 object */
public static UserV4 fromUser(User user) {
2
2023-10-24 09:36:50+00:00
12k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/Robot.java
[ { "identifier": "Intake", "path": "src/main/java/frc/robot/intake/Intake.java", "snippet": "public class Intake extends Mechanism {\n public class IntakeConfig extends Config {\n\n public double fullSpeed = 1.0;\n public double ejectSpeed = -1.0;\n\n public IntakeConfig() {\n super(\"Intake\", 60, \"3847\");\n configPIDGains(0, 0.55, 0, 0.2);\n configFeedForwardGains(0, 0, 0, 0);\n configGearRatio(2);\n configSupplyCurrentLimit(20, true);\n configClockwise_Positive();\n }\n }\n\n public IntakeConfig config;\n\n public Intake(boolean attached) {\n super(attached);\n if (attached) {\n motor = TalonFXFactory.createConfigTalon(config.id, config.talonConfig);\n }\n }\n\n @Override\n public void periodic() {}\n\n public Command runVelocity(double velocity) {\n return run(() -> setMMVelocityFOC(velocity)).withName(\"Intake.runVelocity\");\n }\n\n @Override\n protected Config setConfig() {\n config = new IntakeConfig();\n return config;\n }\n}" }, { "identifier": "IntakeCommands", "path": "src/main/java/frc/robot/intake/IntakeCommands.java", "snippet": "public class IntakeCommands {\n private static Intake intake = Robot.intake;\n\n public static void setupDefaultCommand() {\n intake.setDefaultCommand(intake.runVelocity(0).withName(\"Intake.default\"));\n }\n\n public static Command runFull() {\n return intake.runVelocity(intake.config.fullSpeed);\n }\n\n public static Command eject() {\n return intake.runVelocity(intake.config.ejectSpeed);\n }\n}" }, { "identifier": "LEDs", "path": "src/main/java/frc/robot/leds/LEDs.java", "snippet": "public class LEDs extends SpectrumLEDs {\n public LEDsConfig config;\n\n public LEDs() {\n super(LEDsConfig.port, LEDsConfig.length);\n config = new LEDsConfig();\n\n RobotTelemetry.print(\"LEDs Subsystem Initialized: \");\n }\n\n // LED Patterns\n // Many of these were borrowed from 6328-2023 code\n public void solid(Section section, Color color, int priority) {\n if (getUpdate()) {\n if (color != null) {\n for (int i = section.start(); i < section.end(); i++) {\n setLED(i, color, priority);\n }\n }\n }\n }\n\n /**\n * Sets a percentage of the LEDs to a color\n *\n * @param percent The percentage of LEDs to set\n * @param color The color to set the LEDs to\n */\n public void solid(double percent, Color color, int priority) {\n if (getUpdate()) {\n for (int i = 0;\n i < MathUtil.clamp(LEDsConfig.length * percent, 0, LEDsConfig.length);\n i++) {\n setLED(i, color, priority);\n }\n }\n }\n\n /**\n * Set a section of the LEDs to strobe\n *\n * @param section The section of the LEDs to strobe\n * @param color The color to strobe\n * @param duration The duration of the strobe\n */\n public void strobe(Section section, Color color, double duration, int priority) {\n if (getUpdate()) {\n boolean on = ((getLEDTime() % duration) / duration) > 0.5;\n solid(section, on ? color : Color.kBlack, priority);\n }\n }\n\n public void breath(Section section, Color c1, Color c2, double duration, int priority) {\n breath(section, c1, c2, duration, getLEDTime(), priority);\n }\n\n public void breath(\n Section section, Color c1, Color c2, double duration, double timestamp, int priority) {\n if (getUpdate()) {\n double x =\n ((timestamp % LEDsConfig.breathDuration) / LEDsConfig.breathDuration)\n * 2.0\n * Math.PI;\n double ratio = (Math.sin(x) + 1.0) / 2.0;\n double red = (c1.red * (1 - ratio)) + (c2.red * ratio);\n double green = (c1.green * (1 - ratio)) + (c2.green * ratio);\n double blue = (c1.blue * (1 - ratio)) + (c2.blue * ratio);\n solid(section, new Color(red, green, blue), priority);\n }\n }\n\n /**\n * Sets the LEDs to a rainbow pattern\n *\n * @param section The section of the LEDs to set\n * @param cycleLength The length of the rainbow cycle in LEDs\n * @param duration The duration of the rainbow\n */\n public void rainbow(Section section, double cycleLength, double duration, int priority) {\n if (getUpdate()) {\n double x = (1 - ((getLEDTime() / duration) % 1.0)) * 180.0;\n double xDiffPerLed = 180.0 / cycleLength;\n for (int i = section.start(); i < section.end(); i++) {\n x += xDiffPerLed;\n x %= 180.0;\n setHSV(i, (int) x, 255, 255, priority);\n }\n }\n }\n\n /**\n * Sets the LEDs to a wave pattern\n *\n * @param section The section of the LEDs to set\n * @param c1 The first color of the wave\n * @param c2 The second color of the wave\n * @param cycleLength The length of the wave cycle in LEDs\n * @param duration The duration of the wave\n */\n public void wave(\n Section section,\n Color c1,\n Color c2,\n double cycleLength,\n double duration,\n int priority) {\n if (getUpdate()) {\n double x = (1 - ((getLEDTime() % duration) / duration)) * 2.0 * Math.PI;\n double xDiffPerLed = (2.0 * Math.PI) / cycleLength;\n for (int i = section.start(); i < section.end(); i++) {\n x += xDiffPerLed;\n\n double ratio = (Math.pow(Math.sin(x), LEDsConfig.waveExponent) + 1.0) / 2.0;\n if (Double.isNaN(ratio)) {\n ratio = (-Math.pow(Math.sin(x + Math.PI), LEDsConfig.waveExponent) + 1.0) / 2.0;\n }\n if (Double.isNaN(ratio)) {\n ratio = 0.5;\n }\n double red = (c1.red * (1 - ratio)) + (c2.red * ratio);\n double green = (c1.green * (1 - ratio)) + (c2.green * ratio);\n double blue = (c1.blue * (1 - ratio)) + (c2.blue * ratio);\n setLED(i, new Color(red, green, blue), priority);\n }\n }\n }\n\n public void stripes(\n Section section, List<Color> colors, int length, double duration, int priority) {\n if (getUpdate()) {\n int offset = (int) (getLEDTime() % duration / duration * length * colors.size());\n for (int i = section.start(); i < section.end(); i++) {\n int colorIndex =\n (int) (Math.floor((double) (i - offset) / length) + colors.size())\n % colors.size();\n colorIndex = colors.size() - 1 - colorIndex;\n setLED(i, colors.get(colorIndex), priority);\n }\n }\n }\n}" }, { "identifier": "LEDsCommands", "path": "src/main/java/frc/robot/leds/LEDsCommands.java", "snippet": "public class LEDsCommands {\n private static LEDs leds = Robot.leds;\n\n public static void setupDefaultCommand() {\n leds.setDefaultCommand(defaultCommand());\n }\n\n /** Specific Commands */\n public static Command defaultCommand() {\n return leds.run(\n () -> {\n rainbow(Section.FULL, LEDsConfig.length / 2, 2, 0).execute();\n })\n .ignoringDisable(true)\n .withName(\"LEDs.default\");\n }\n\n public static Command solidPurpleLED() {\n return LEDsCommands.solid(Section.HALF_HIGH, Color.kPurple, 2)\n .withName(\"LEDs.solidPurpleLED\");\n }\n\n public static Command strobeOrangeLED() {\n return LEDsCommands.strobe(Section.QUARTER_HIGH, Color.kOrange, 0.5, 2)\n .withName(\"LEDs.strobeOrangeLED\");\n }\n\n public static Command breathBlueLED() {\n return LEDsCommands.breath(Section.FULL, Color.kBlue, Color.kBlack, 1, 4)\n .withName(\"LEDs.breathBlueLED\");\n }\n\n /** Common Commands */\n public static Command runLEDPattern(Runnable r) {\n // Needs to be Commands.run and not leds.run so it doesn't require led subsystem\n return Commands.run(r) // The the method passed to this method\n .ignoringDisable(true) // Run while disabled\n .finallyDo((b) -> leds.resetPriority()) // Reset the Priority when an LED command\n // ends\n .withName(\"LEDs.runLEDCommand\"); // Set a default name if one isn't set later\n }\n\n public static Command solid(Color color, int priority) {\n return solid(Section.FULL, color, priority);\n }\n\n public static Command solid(Section section, Color color, int priority) {\n return runLEDPattern(() -> leds.solid(section, color, priority)).withName(\"LEDs.solid\");\n }\n\n public static Command solid(double percent, Color color, int priority) {\n return runLEDPattern(() -> leds.solid(percent, color, priority)).withName(\"LEDs.solid\");\n }\n\n public static Command strobe(Color color, int priority) {\n return strobe(Section.FULL, color, 0.5, priority);\n }\n\n public static Command strobe(Section section, Color color, double duration, int priority) {\n return runLEDPattern(() -> leds.strobe(section, color, duration, priority))\n .withName(\"LEDs.strobe\");\n }\n\n public static Command breath(Color c1, Color c2, int priority) {\n return breath(Section.FULL, c1, c2, 1, priority);\n }\n\n public static Command breath(\n Section section, Color c1, Color c2, double duration, int priority) {\n return runLEDPattern(() -> leds.breath(section, c1, c2, duration, priority))\n .withName(\"LEDs.breath\");\n }\n\n public static Command rainbow(int priority) {\n return rainbow(Section.FULL, LEDsConfig.length, 1, priority);\n }\n\n public static Command rainbow(\n Section section, double cycleLength, double duration, int priority) {\n return runLEDPattern(() -> leds.rainbow(section, cycleLength, duration, priority))\n .withName(\"LEDs.rainbow\");\n }\n\n public static Command wave(Color c1, Color c2, int priority) {\n return wave(Section.FULL, c1, c2, LEDsConfig.length, 1, priority);\n }\n\n public static Command wave(\n Section section,\n Color c1,\n Color c2,\n double cycleLength,\n double duration,\n int priority) {\n return runLEDPattern(() -> leds.wave(section, c1, c2, cycleLength, duration, priority))\n .withName(\"LEDs.wave\");\n }\n}" }, { "identifier": "Pilot", "path": "src/main/java/frc/robot/pilot/Pilot.java", "snippet": "public class Pilot extends Gamepad {\n public class PilotConfig {\n public static final String name = \"Pilot\";\n public static final int port = 0;\n\n public static final double slowModeScalor = 0.5;\n\n public final double leftStickDeadzone = 0.1;\n public final double leftStickExp = 2.0;\n public final double leftStickScalor = Robot.swerve.config.maxVelocity;\n\n public final double triggersDeadzone = 0.1;\n public final double triggersExp = 2.0;\n public final double triggersScalor = Robot.swerve.config.maxAngularVelocity;\n }\n\n public PilotConfig config;\n private boolean isSlowMode = false;\n private boolean isFieldOriented = false;\n private ExpCurve LeftStickCurve;\n private ExpCurve TriggersCurve;\n\n /** Create a new Pilot with the default name and port. */\n public Pilot() {\n super(PilotConfig.name, PilotConfig.port);\n config = new PilotConfig();\n\n // Curve objects that we use to configure the controller axis ojbects\n LeftStickCurve =\n new ExpCurve(\n config.leftStickExp, 0, config.leftStickScalor, config.leftStickDeadzone);\n TriggersCurve =\n new ExpCurve(config.triggersExp, 0, config.triggersScalor, config.triggersDeadzone);\n\n RobotTelemetry.print(\"Pilot Subsystem Initialized: \");\n }\n\n /** Setup the Buttons for telop mode. */\n /* A, B, X, Y, Left Bumper, Right Bumper = Buttons 1 to 6 in simualation */\n public void setupTeleopButtons() {\n // Prints Once\n controller.a().whileTrue(TrainingCommands.printOnceCommand());\n controller.a().whileTrue(LEDsCommands.solidPurpleLED());\n\n // Prints every periodic loop that the button is pressed\n // Change this to .onTrue() to continue printing even when the button is released\n controller.b().whileTrue(TrainingCommands.periodicCommand());\n controller.b().whileTrue(LEDsCommands.strobeOrangeLED());\n\n // Runs the FullComman Training Command, doesn't run while disabled\n controller.x().whileTrue(TrainingCommands.fullCommand());\n\n // Prints every periodic loop for 1 second\n controller.y().and(noBumpers()).whileTrue(TrainingCommands.periodicTimeoutCommand());\n\n // Prints one line once and then prints one line every periodic loop\n controller.y().and(leftBumperOnly()).whileTrue(TrainingCommands.sequentialGroupCommand());\n\n // Prints two lines every periodic loop\n controller.y().and(rightBumperOnly()).whileTrue(TrainingCommands.parellelGroupCommand());\n\n leftXTrigger(ThresholdType.GREATER_THAN, 0).whileTrue(RobotCommands.PrintAndBreathLED());\n\n // Use the pilot drive if we are manually steering the robot\n controller\n .rightTrigger(config.triggersDeadzone)\n .or(controller.leftTrigger(config.triggersDeadzone))\n .whileTrue(PilotCommands.pilotDrive());\n\n // Use the right stick to set a cardinal direction to aim at\n rightXTrigger(ThresholdType.ABS_GREATER_THAN, 0.5)\n .and(rightYTrigger(ThresholdType.ABS_GREATER_THAN, 0.5))\n .whileTrue(PilotCommands.stickSteerDrive());\n };\n\n /** Setup the Buttons for Disabled mode. */\n public void setupDisabledButtons() {\n // This is just for training, most robots will have different buttons during disabled\n setupTeleopButtons();\n };\n\n /** Setup the Buttons for Test mode. */\n public void setupTestButtons() {\n // This is just for training, robots may have different buttons during test\n setupTeleopButtons();\n };\n\n public void setMaxVelocity(double maxVelocity) {\n LeftStickCurve.setScalar(maxVelocity);\n }\n\n public void setMaxRotationalVelocity(double maxRotationalVelocity) {\n TriggersCurve.setScalar(maxRotationalVelocity);\n }\n\n public void setSlowMode(boolean isSlowMode) {\n this.isSlowMode = isSlowMode;\n }\n\n public void setFieldOriented(boolean isFieldOriented) {\n this.isFieldOriented = isFieldOriented;\n }\n\n public boolean getFieldOriented() {\n return isFieldOriented;\n }\n\n // Positive is forward, up on the left stick is positive\n // Applies Expontial Curve, Deadzone, and Slow Mode toggle\n public double getDriveFwdPositive() {\n double fwdPositive = LeftStickCurve.calculate(-1 * controller.getLeftY());\n if (isSlowMode) {\n fwdPositive *= Math.abs(PilotConfig.slowModeScalor);\n }\n return fwdPositive;\n }\n\n // Positive is left, left on the left stick is positive\n // Applies Expontial Curve, Deadzone, and Slow Mode toggle\n public double getDriveLeftPositive() {\n double leftPositive = -1 * LeftStickCurve.calculate(controller.getLeftX());\n if (isSlowMode) {\n leftPositive *= Math.abs(PilotConfig.slowModeScalor);\n }\n return leftPositive;\n }\n\n // Positive is counter-clockwise, left Trigger is positive\n // Applies Expontial Curve, Deadzone, and Slow Mode toggle\n public double getDriveCCWPositive() {\n double ccwPositive = TriggersCurve.calculate(getTwist());\n if (isSlowMode) {\n ccwPositive *= Math.abs(PilotConfig.slowModeScalor);\n }\n return ccwPositive;\n }\n}" }, { "identifier": "PilotCommands", "path": "src/main/java/frc/robot/pilot/PilotCommands.java", "snippet": "public class PilotCommands {\n private static Pilot pilot = Robot.pilot;\n\n /** Set default command to turn off the rumble */\n public static void setupDefaultCommand() {\n pilot.setDefaultCommand(rumble(0, 99999).repeatedly().withName(\"Pilot.default\"));\n }\n\n /** Command that can be used to rumble the pilot controller */\n public static Command rumble(double intensity, double durationSeconds) {\n return pilot.rumbleCommand(intensity, durationSeconds);\n }\n\n /** Full control of the swerve by the Pilot command */\n public static Command pilotDrive() {\n return SwerveCommands.Drive(\n () -> pilot.getDriveFwdPositive(),\n () -> pilot.getDriveLeftPositive(),\n () -> pilot.getDriveCCWPositive(),\n () -> pilot.getFieldOriented(), // true is field oriented\n () -> true)\n .withName(\"Swerve.PilotDrive\");\n }\n\n public static Command fullTurnDrive() {\n return SwerveCommands.Drive(\n () -> pilot.getDriveFwdPositive(),\n () -> pilot.getDriveLeftPositive(),\n () -> 1.0,\n () -> pilot.getFieldOriented(), // true is field oriented\n () -> true)\n .withName(\"Swerve.PilotFullTurnDrive\")\n .withTimeout(2);\n }\n\n public static Command headingLockDrive() {\n return SwerveCommands.headingLock(\n () -> pilot.getDriveFwdPositive(),\n () -> pilot.getDriveLeftPositive(),\n () -> pilot.getFieldOriented(), // true is field oriented\n () -> true)\n .withName(\"Swerve.PilotHeadingLockDrive\");\n }\n\n /**\n * Drive the robot using left stick and control orientation using the right stick Only Cardinal\n * directions are allowed\n *\n * @return\n */\n public static Command stickSteerDrive() {\n return SwerveCommands.aimDrive(\n () -> pilot.getDriveFwdPositive(),\n () -> pilot.getDriveLeftPositive(),\n () -> pilot.getRightStickCardinals(),\n () -> pilot.getFieldOriented(), // true is field oriented\n () -> true)\n .withName(\"Swerve.PilotStickSteer\");\n }\n\n /**\n * Command that can be used to turn on the slow mode. Slow mode modifies the fwd, left, and CCW\n * methods, we don't want these to require the pilot subsystem\n */\n public static Command slowMode() {\n return Commands.startEnd(() -> pilot.setSlowMode(true), () -> pilot.setSlowMode(false));\n }\n\n /**\n * Command that can be used to turn on the FPV mode. FPV sets field oriented or not. We don't\n * want this command to require the pilot subsystem so we use Commands.startend()\n */\n public static Command fpvMode() {\n return Commands.startEnd(\n () -> pilot.setFieldOriented(false), () -> pilot.setFieldOriented(true));\n }\n}" }, { "identifier": "Slide", "path": "src/main/java/frc/robot/slide/Slide.java", "snippet": "public class Slide extends Mechanism {\n public class SlideConfig extends Config {\n\n public double top = 10;\n\n public SlideConfig() {\n super(\"Slide\", 50, \"3847\");\n configSupplyCurrentLimit(20, true);\n configPIDGains(0, 0.55, 0, 0.2);\n configFeedForwardGains(0, 0, 0, 0);\n configReverseSoftLimit(0, true);\n configForwardSoftLimit(top, true);\n configCounterClockwise_Positive();\n }\n }\n\n public SlideConfig config;\n\n public Slide(boolean attached) {\n super(attached);\n if (attached) {\n motor = TalonFXFactory.createConfigTalon(config.id, config.talonConfig);\n }\n }\n\n @Override\n public void periodic() {}\n\n public Command runPosition(double position) {\n return run(() -> setMMPositionFOC(position)).withName(\"Slide.runPosition\");\n }\n\n public Command runStop() {\n return run(() -> stop()).withName(\"Slide.runStop\");\n }\n\n @Override\n protected Config setConfig() {\n config = new SlideConfig();\n return config;\n }\n}" }, { "identifier": "SlideCommands", "path": "src/main/java/frc/robot/slide/SlideCommands.java", "snippet": "public class SlideCommands {\n private static Slide slide = Robot.slide;\n\n public static void setupDefaultCommand() {\n slide.setDefaultCommand(slide.runStop().withName(\"Slide.default\"));\n }\n}" }, { "identifier": "Swerve", "path": "src/main/java/frc/robot/swerve/Swerve.java", "snippet": "public class Swerve implements Subsystem {\n public final SwerveConfig config;\n private final Drivetrain drivetrain;\n private final RotationController rotationController;\n private double OdometryUpdateFrequency = 250;\n private double targetHeading = 0;\n private ReadWriteLock m_stateLock = new ReentrantReadWriteLock();\n private SwerveModuleState[] Setpoints = new SwerveModuleState[] {};\n\n public Swerve() {\n RobotTelemetry.print(\"Swerve Subsystem Starting: \");\n\n // Choose the correct swerve configuration\n switch (Robot.config.getRobotType()) {\n case NOTEBLOCK:\n config = NOTEBLOCK2023.config;\n break;\n case MUSICDISC:\n config = MUSICDISC2023.config;\n break;\n case SIM: // runs in simulation\n OdometryUpdateFrequency = 50;\n config = NOTEBLOCK2023.config;\n break;\n default:\n config = NOTEBLOCK2023.config;\n break;\n }\n drivetrain = new Drivetrain(config, OdometryUpdateFrequency);\n\n rotationController = new RotationController(this);\n RobotTelemetry.print(\"Swerve Subsystem Initialized: \");\n }\n\n @Override\n public void periodic() {\n // Log measured states\n Logger.recordOutput(\"SwerveStates/Measured\", drivetrain.getState().ModuleStates);\n\n // Log empty setpoint states when disabled\n if (DriverStation.isDisabled()) {\n Logger.recordOutput(\"SwerveStates/Setpoints\", new SwerveModuleState[] {});\n } else {\n // Log setpoint states\n Logger.recordOutput(\"SwerveStates/Setpoints\", readSetpoints());\n ;\n }\n\n // Log Odometry Pose\n Logger.recordOutput(\"Odometry/Robot\", getPose());\n }\n\n @Override\n public void simulationPeriodic() {\n drivetrain.updateSimState(0.02, 12);\n }\n\n // Returns a commmand that applies the given request to the drivetrain\n public Command applyRequest(Supplier<Request> requestSupplier) {\n return run(() -> setControlMode(requestSupplier.get()));\n }\n\n // Use this to control the swerve drive, set motors, etc.\n public void setControlMode(Request mode) {\n drivetrain.setControl(mode);\n }\n\n public DriveState getState() {\n return drivetrain.getState();\n }\n\n public Pose2d getPose() {\n return getState().Pose;\n }\n\n public void resetPose(Pose2d pose) {\n drivetrain.seedFieldRelative(pose);\n }\n\n public ChassisSpeeds getRobotRelativeSpeeds() {\n return drivetrain.getChassisSpeeds();\n }\n\n public Rotation2d getRotation() {\n return getPose().getRotation();\n }\n\n public void resetRotationController() {\n rotationController.reset();\n }\n\n public double calculateRotationController(DoubleSupplier targetRadians) {\n return rotationController.calculate(targetRadians.getAsDouble());\n }\n\n public void setTargetHeading(double targetHeading) {\n this.targetHeading = targetHeading;\n }\n\n public double getTargetHeading() {\n return targetHeading;\n }\n\n /**\n * Takes the current orientation of the robot plus an angle offset and makes it X forward for\n * field-relative maneuvers.\n */\n public void seedFieldRelative(double offsetDegrees) {\n drivetrain.seedFieldRelative(offsetDegrees);\n }\n\n /** This will zero the entire odometry, and place the robot at 0,0 */\n public void zeroOdoemtry() {\n drivetrain.tareEverything();\n }\n\n public void addVisionMeasurement(\n Pose2d visionRobotPoseMeters,\n double timestampSeconds,\n Matrix<N3, N1> visionMeasurementStdDevs) {\n drivetrain.addVisionMeasurement(\n visionRobotPoseMeters, timestampSeconds, visionMeasurementStdDevs);\n }\n\n public void addVisionMeasurement(Pose2d visionRobotPoseMeters, double timestampSeconds) {\n drivetrain.addVisionMeasurement(visionRobotPoseMeters, timestampSeconds);\n }\n\n public void setVisionMeasurementStdDevs(Matrix<N3, N1> visionMeasurementStdDevs) {\n drivetrain.setVisionMeasurementStdDevs(visionMeasurementStdDevs);\n }\n\n /**\n * Register the specified lambda to be executed whenever our SwerveDriveState function is\n * updated in our odometry thread.\n *\n * <p>It is imperative that this function is cheap, as it will be executed along with the\n * odometry call, and if this takes a long time, it may negatively impact the odometry of this\n * stack.\n *\n * <p>This can also be used for logging data if the function performs logging instead of\n * telemetry\n *\n * @param telemetryFunction Function to call for telemetry or logging\n */\n public void registerTelemetry(Consumer<DriveState> telemetryFunction) {\n drivetrain.registerTelemetry(telemetryFunction);\n }\n\n /**\n * Applies the specified control request to this swerve drivetrain.\n *\n * @param request Request to apply\n */\n public void writeSetpoints(SwerveModuleState[] setpoints) {\n try {\n m_stateLock.writeLock().lock();\n\n this.Setpoints = setpoints;\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n public SwerveModuleState[] readSetpoints() {\n try {\n m_stateLock.readLock().lock();\n return Setpoints;\n } finally {\n m_stateLock.readLock().unlock();\n }\n }\n}" }, { "identifier": "SwerveCommands", "path": "src/main/java/frc/robot/swerve/commands/SwerveCommands.java", "snippet": "public class SwerveCommands {\n private static Swerve swerve = Robot.swerve;\n\n public static void setupDefaultCommand() {\n swerve.setDefaultCommand(PilotCommands.pilotDrive());\n }\n\n /** Turn the swerve wheels to an X to prevent the robot from moving */\n public static Command Xbrake() {\n return Xbrake.run().withName(\"Swerve.Xbrake\");\n }\n\n /** Drive the swerve */\n public static Command Drive(\n DoubleSupplier velocityX,\n DoubleSupplier velocityY,\n DoubleSupplier rotationalRate,\n BooleanSupplier isFieldOriented,\n BooleanSupplier isOpenLoop) {\n return Drive.run(velocityX, velocityY, rotationalRate, isFieldOriented, isOpenLoop)\n .withName(\"Swerve.Drive\")\n .ignoringDisable(true);\n }\n\n /**\n * Reset the turn controller and then run the drive command with a angle supplier. This can be\n * used for aiming at a goal or heading locking, etc\n */\n public static Command aimDrive(\n DoubleSupplier velocityX,\n DoubleSupplier velocityY,\n DoubleSupplier targetRadians,\n BooleanSupplier isFieldOriented,\n BooleanSupplier isOpenLoop) {\n return resetTurnController()\n .andThen(\n Drive(\n velocityX,\n velocityY,\n () -> swerve.calculateRotationController(targetRadians),\n isFieldOriented,\n isOpenLoop))\n .withName(\"Swerve.AimDrive\");\n }\n\n /**\n * Reset the turn controller, set the target heading to the current heading(end that command\n * immediately), and then run the drive command with the Rotation controller. The rotation\n * controller will only engague if you are driving x or y.\n */\n public static Command headingLock(\n DoubleSupplier velocityX,\n DoubleSupplier velocityY,\n BooleanSupplier isFieldOriented,\n BooleanSupplier isOpenLoop) {\n return resetTurnController()\n .andThen(\n setTargetHeading(() -> swerve.getRotation().getRadians()).until(() -> true),\n Drive(\n velocityX,\n velocityY,\n () -> {\n if (velocityX.getAsDouble() == 0\n && velocityY.getAsDouble() == 0) {\n return 0.0;\n } else {\n return swerve.calculateRotationController(\n () -> swerve.getTargetHeading());\n }\n },\n isFieldOriented,\n isOpenLoop))\n .withName(\"Swerve.HeadingLock\");\n }\n\n /** Apply a chassis speed to the swerve */\n public static Command ApplyChassisSpeeds(\n Supplier<ChassisSpeeds> speeds, BooleanSupplier isOpenLoop) {\n return ApplyChassisSpeeds.run(speeds, isOpenLoop).withName(\"Swerve.ApplyChassisSpeeds\");\n }\n\n /** Reset the turn controller */\n public static Command resetTurnController() {\n return swerve.runOnce(() -> swerve.resetRotationController())\n .withName(\"ResetTurnController\");\n }\n\n public static Command setTargetHeading(DoubleSupplier targetHeading) {\n return Commands.run(() -> swerve.setTargetHeading(targetHeading.getAsDouble()))\n .withName(\"SetTargetHeading\");\n }\n\n // Swerve Command Options\n // - Drive needs to work with slow mode (this might be done in PilotCommands)\n}" }, { "identifier": "Training", "path": "src/main/java/frc/robot/training/Training.java", "snippet": "public class Training extends SubsystemBase {\n\n public TrainingConfig config;\n\n /**\n * This is the constructor for the Training subsystem. This subsystem is used to test and train\n * new students. It is not used in competition.\n */\n // Subsystem Documentation:\n // https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems.html\n public Training() {\n config = new TrainingConfig();\n\n RobotTelemetry.print(\"Training Subsystem Initialized: \");\n }\n}" }, { "identifier": "TrainingCommands", "path": "src/main/java/frc/robot/training/commands/TrainingCommands.java", "snippet": "public class TrainingCommands {\n\n private static Training training = Robot.training;\n /**\n * This method will setup the default command for the subsystem This should be called from\n * RobotInit in Robot.java\n */\n public static void setupDefaultCommand() {\n training.setDefaultCommand(\n printOnceCommand(\"Training Default Command is running\")\n .withName(\"Training.default\"));\n }\n\n public static Command fullCommand() {\n return new FullCommand();\n }\n\n /** Specific Commands */\n public static Command printOnceCommand() {\n return printOnceCommand(\"Print Once\").withName(\"Training.Print Once\");\n }\n\n public static Command periodicCommand() {\n return printPeriodicCommand(\"Print Periodic\").withName(\"Training.periodicCommand\");\n }\n\n public static Command periodicTimeoutCommand() {\n return printPeriodicCommand(\"Print Periodic with Timeout\")\n .withTimeout(1)\n .withName(\"Training.periodicTimeoutCommand\");\n }\n\n public static Command sequentialGroupCommand() {\n return sequentialPrintCommand(\"Print Instant\", \"Print Periodic\")\n .withName(\"Training.Sequential Group\");\n }\n\n public static Command parellelGroupCommand() {\n return parallelPrintCommand(\"Print Periodic 1\", \"Print Periodic 2\")\n .withName(\"Training.Parellel Group\");\n }\n\n /** Common Commands */\n /**\n * This command will print the text to the console once and then end immediately. If this is\n * called by a whileTrue trigger it will start over again.\n *\n * @param txt\n * @return\n */\n public static Command printInstantCommand(String txt) {\n return training.runOnce(() -> RobotTelemetry.print(txt))\n .ignoringDisable(true)\n .withName(\"Training.PrintInstantCommand\");\n }\n\n /**\n * This command will print the text to the console once and continue running but not printing ()\n * -> {} is an empty lambda function to do nothing\n *\n * @param txt\n * @return\n */\n public static Command printOnceCommand(String txt) {\n return training.startEnd(() -> RobotTelemetry.print(txt), () -> {})\n .ignoringDisable(true)\n .withName(\"Training.PrintOunceCommand\");\n }\n\n /**\n * This command will print the text to the console every execute loop of the robot\n *\n * @param txt\n * @return\n */\n public static Command printPeriodicCommand(String txt) {\n return training.run(() -> RobotTelemetry.print(txt))\n .ignoringDisable(true)\n .withName(\"Training.PrintPerioicCommand\");\n }\n\n /**\n * This command will print one string once and then start printing a second string every\n * execute. This command creates a Sequential Command Group using the andThen method. Only the\n * name of the Sequential Command Group is used as the indvidual commands aren't actually run by\n * the scheduler. Command Groups require all of the subsystems of every command in the group.\n *\n * @param commandName\n * @param oneTimeText\n * @param periodicText\n * @return\n */\n public static Command sequentialPrintCommand(String oneTimeText, String periodicText) {\n return printInstantCommand(oneTimeText)\n .andThen(printPeriodicCommand(periodicText))\n .ignoringDisable(true)\n .withName(\"Training.Sequential Group\");\n }\n\n /**\n * This command will print two strings every execute loop of the robot. They will run together\n * at the same time because they are in a Parrell Command Group. This is created using hte\n * alongWith method.\n */\n public static Command parallelPrintCommand(String periodicText1, String periodicText2) {\n return printPeriodicCommand(periodicText1)\n .alongWith(Commands.print(periodicText2).repeatedly())\n // Have to use PrintCommand and repeatedly becuase it doesn't require the Training\n // Subystem\n .ignoringDisable(true)\n .withName(\"Training.Parallel Group\")\n .finallyDo(\n () -> {\n RobotTelemetry.print(\"Finally Do\");\n });\n }\n}" }, { "identifier": "CrashTracker", "path": "src/main/java/frc/spectrumLib/util/CrashTracker.java", "snippet": "public class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n /**\n * Logs details of a Throwable exception to a designated file. This method captures the unique\n * run instance UUID, the type of marker (in this case, \"Exception\"), the current date and time,\n * and the stack trace of the Throwable, if present. The log entry is appended to the file\n * '/home/lvuser/crash_tracking.txt', ensuring that each incident is recorded sequentially\n * without overwriting previous entries. This method is typically used to record unexpected\n * exceptions or crashes that occur during the runtime of the application, aiding in post-event\n * analysis and debugging.\n *\n * @param throwable The Throwable exception to log. Can be any subclass of Throwable, capturing\n * errors and exceptions that occur during the application's execution.\n */\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n // used to just log a message to the file\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n try (PrintWriter writer =\n new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n\n writer.println();\n } catch (IOException e) {\n if (e instanceof FileNotFoundException) {\n if (Robot.isSimulation()) {\n System.out.println(\n \"CrashTracker failed to save crash file to robot: running in simulation mode\");\n } else {\n System.out.println(\n \"CrashTracker failed to save crash file to robot: path `/home/lvuser/crash_tracking.txt` not found\");\n }\n } else {\n e.printStackTrace();\n }\n }\n }\n}" } ]
import edu.wpi.first.wpilibj2.command.CommandScheduler; import frc.robot.intake.Intake; import frc.robot.intake.IntakeCommands; import frc.robot.leds.LEDs; import frc.robot.leds.LEDsCommands; import frc.robot.pilot.Pilot; import frc.robot.pilot.PilotCommands; import frc.robot.slide.Slide; import frc.robot.slide.SlideCommands; import frc.robot.swerve.Swerve; import frc.robot.swerve.commands.SwerveCommands; import frc.robot.training.Training; import frc.robot.training.commands.TrainingCommands; import frc.spectrumLib.util.CrashTracker; import org.littletonrobotics.junction.LoggedRobot; import org.littletonrobotics.junction.Logger; import org.littletonrobotics.junction.networktables.NT4Publisher; import org.littletonrobotics.junction.wpilog.WPILOGWriter;
9,916
package frc.robot; public class Robot extends LoggedRobot { public static RobotConfig config; public static RobotTelemetry telemetry; /** Create a single static instance of all of your subsystems */ public static Training training; public static Swerve swerve; public static Intake intake; public static Slide slide; public static LEDs leds; public static Pilot pilot; // public static Auton auton; /** * This method cancels all commands and returns subsystems to their default commands and the * gamepad configs are reset so that new bindings can be assigned based on mode This method * should be called when each mode is intialized */ public static void resetCommandsAndButtons() { CommandScheduler.getInstance().cancelAll(); // Disable any currently running commands CommandScheduler.getInstance().getActiveButtonLoop().clear(); // Reset Config for all gamepads and other button bindings pilot.resetConfig(); } /* ROBOT INIT (Initialization) */ /** This method is called once when the robot is first powered on. */ public void robotInit() { try { RobotTelemetry.print("--- Robot Init Starting ---"); /** Set up the config */ config = new RobotConfig(); /** * Intialize the Subsystems of the robot. Subsystems are how we divide up the robot * code. Anything with an output that needs to be independently controlled is a * subsystem Something that don't have an output are alos subsystems. */ training = new Training(); swerve = new Swerve(); intake = new Intake(config.intakeAttached); slide = new Slide(true); pilot = new Pilot(); leds = new LEDs(); /** Intialize Telemetry and Auton */ telemetry = new RobotTelemetry(); // auton = new Auton(); advantageKitInit(); /** * Set Default Commands this method should exist for each subsystem that has default * command these must be done after all the subsystems are intialized */ TrainingCommands.setupDefaultCommand(); SwerveCommands.setupDefaultCommand(); IntakeCommands.setupDefaultCommand();
package frc.robot; public class Robot extends LoggedRobot { public static RobotConfig config; public static RobotTelemetry telemetry; /** Create a single static instance of all of your subsystems */ public static Training training; public static Swerve swerve; public static Intake intake; public static Slide slide; public static LEDs leds; public static Pilot pilot; // public static Auton auton; /** * This method cancels all commands and returns subsystems to their default commands and the * gamepad configs are reset so that new bindings can be assigned based on mode This method * should be called when each mode is intialized */ public static void resetCommandsAndButtons() { CommandScheduler.getInstance().cancelAll(); // Disable any currently running commands CommandScheduler.getInstance().getActiveButtonLoop().clear(); // Reset Config for all gamepads and other button bindings pilot.resetConfig(); } /* ROBOT INIT (Initialization) */ /** This method is called once when the robot is first powered on. */ public void robotInit() { try { RobotTelemetry.print("--- Robot Init Starting ---"); /** Set up the config */ config = new RobotConfig(); /** * Intialize the Subsystems of the robot. Subsystems are how we divide up the robot * code. Anything with an output that needs to be independently controlled is a * subsystem Something that don't have an output are alos subsystems. */ training = new Training(); swerve = new Swerve(); intake = new Intake(config.intakeAttached); slide = new Slide(true); pilot = new Pilot(); leds = new LEDs(); /** Intialize Telemetry and Auton */ telemetry = new RobotTelemetry(); // auton = new Auton(); advantageKitInit(); /** * Set Default Commands this method should exist for each subsystem that has default * command these must be done after all the subsystems are intialized */ TrainingCommands.setupDefaultCommand(); SwerveCommands.setupDefaultCommand(); IntakeCommands.setupDefaultCommand();
SlideCommands.setupDefaultCommand();
7
2023-10-23 17:01:53+00:00
12k
MYSTD/BigDataApiTest
data-governance-assessment/src/main/java/com/std/dga/governance/service/impl/GovernanceAssessDetailServiceImpl.java
[ { "identifier": "Assessor", "path": "data-governance-assessment/src/main/java/com/std/dga/assessor/Assessor.java", "snippet": "public abstract class Assessor {\n\n public final GovernanceAssessDetail doAssessor(AssessParam assessParam){\n\n// System.out.println(\"Assessor 管理流程\");\n GovernanceAssessDetail governanceAssessDetail = new GovernanceAssessDetail();\n governanceAssessDetail.setAssessDate(assessParam.getAssessDate());\n governanceAssessDetail.setMetricId(assessParam.getTableMetaInfo().getId()+\"\");\n governanceAssessDetail.setTableName(assessParam.getTableMetaInfo().getTableName());\n governanceAssessDetail.setSchemaName(assessParam.getTableMetaInfo().getSchemaName());\n governanceAssessDetail.setMetricName(assessParam.getGovernanceMetric().getMetricName());\n governanceAssessDetail.setGovernanceType(assessParam.getGovernanceMetric().getGovernanceType());\n governanceAssessDetail.setTecOwner(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTecOwnerUserName());\n governanceAssessDetail.setCreateTime(new Date());\n //默认先给满分, 在考评器查找问题的过程中,如果有问题,再按照指标的要求重新给分。\n governanceAssessDetail.setAssessScore(BigDecimal.TEN);\n\n try {\n checkProblem(governanceAssessDetail, assessParam);\n }catch (Exception e) {\n governanceAssessDetail.setAssessScore(BigDecimal.ZERO);\n governanceAssessDetail.setIsAssessException(\"1\");\n //记录异常信息\n //简单记录\n //governanceAssessDetail.setAssessExceptionMsg( e.getMessage());\n\n //详细记录\n StringWriter stringWriter = new StringWriter() ;\n PrintWriter msgPrintWriter = new PrintWriter(stringWriter) ;\n e.printStackTrace( msgPrintWriter);\n governanceAssessDetail.setAssessExceptionMsg( stringWriter.toString().substring( 0, Math.min( 2000 , stringWriter.toString().length())) );\n }\n\n return governanceAssessDetail;\n }\n\n public abstract void checkProblem(GovernanceAssessDetail governanceAssessDetail , AssessParam assessParam) throws Exception;\n}" }, { "identifier": "TDsTaskDefinition", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskDefinition.java", "snippet": "@Data\n@TableName(\"t_ds_task_definition\")\npublic class TDsTaskDefinition implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * self-increasing id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * encoding\n */\n private Long code;\n\n /**\n * task definition name\n */\n private String name;\n\n /**\n * task definition version\n */\n private Integer version;\n\n /**\n * description\n */\n private String description;\n\n /**\n * project code\n */\n private Long projectCode;\n\n /**\n * task definition creator id\n */\n private Integer userId;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * job priority\n */\n private Byte taskPriority;\n\n /**\n * worker grouping\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * number of failed retries\n */\n private Integer failRetryTimes;\n\n /**\n * failed retry interval\n */\n private Integer failRetryInterval;\n\n /**\n * timeout flag:0 close, 1 open\n */\n private Byte timeoutFlag;\n\n /**\n * timeout notification policy: 0 warning, 1 fail\n */\n private Byte timeoutNotifyStrategy;\n\n /**\n * timeout length,unit: minute\n */\n private Integer timeout;\n\n /**\n * delay execution time,unit: minute\n */\n private Integer delayTime;\n\n /**\n * resource id, separated by comma\n */\n private String resourceIds;\n\n /**\n * create time\n */\n private Date createTime;\n\n /**\n * update time\n */\n private Date updateTime;\n\n @TableField(exist = false)\n private String taskSql; // 任务SQL\n}" }, { "identifier": "TDsTaskInstance", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskInstance.java", "snippet": "@Data\n@TableName(\"t_ds_task_instance\")\npublic class TDsTaskInstance implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * key\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * task name\n */\n private String name;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * task definition code\n */\n private Long taskCode;\n\n /**\n * task definition version\n */\n private Integer taskDefinitionVersion;\n\n /**\n * process instance id\n */\n private Integer processInstanceId;\n\n /**\n * Status: 0 commit succeeded, 1 running, 2 prepare to pause, 3 pause, 4 prepare to stop, 5 stop, 6 fail, 7 succeed, 8 need fault tolerance, 9 kill, 10 wait for thread, 11 wait for dependency to complete\n */\n private Byte state;\n\n /**\n * task submit time\n */\n private Date submitTime;\n\n /**\n * task start time\n */\n private Date startTime;\n\n /**\n * task end time\n */\n private Date endTime;\n\n /**\n * host of task running on\n */\n private String host;\n\n /**\n * task execute path in the host\n */\n private String executePath;\n\n /**\n * task log path\n */\n private String logPath;\n\n /**\n * whether alert\n */\n private Byte alertFlag;\n\n /**\n * task retry times\n */\n private Integer retryTimes;\n\n /**\n * pid of task\n */\n private Integer pid;\n\n /**\n * yarn app id\n */\n private String appLink;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * retry interval when task failed \n */\n private Integer retryInterval;\n\n /**\n * max retry times\n */\n private Integer maxRetryTimes;\n\n /**\n * task instance priority:0 Highest,1 High,2 Medium,3 Low,4 Lowest\n */\n private Integer taskInstancePriority;\n\n /**\n * worker group id\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * this config contains many environment variables config\n */\n private String environmentConfig;\n\n private Integer executorId;\n\n /**\n * task first submit time\n */\n private Date firstSubmitTime;\n\n /**\n * task delay execution time\n */\n private Integer delayTime;\n\n /**\n * var_pool\n */\n private String varPool;\n\n /**\n * dry run flag: 0 normal, 1 dry run\n */\n private Byte dryRun;\n}" }, { "identifier": "TDsTaskDefinitionService", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/service/TDsTaskDefinitionService.java", "snippet": "@DS(\"dolphinscheduler\")\npublic interface TDsTaskDefinitionService extends IService<TDsTaskDefinition> {\n\n List<TDsTaskDefinition> selectList();\n\n}" }, { "identifier": "TDsTaskInstanceService", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/service/TDsTaskInstanceService.java", "snippet": "@DS(\"dolphinscheduler\")\npublic interface TDsTaskInstanceService extends IService<TDsTaskInstance> {\n\n List<TDsTaskInstance> selectList(String assessDate);\n\n List<TDsTaskInstance> selectFailedTask(String taskName, String assessDate);\n\n List<TDsTaskInstance> selectBeforeNDaysInstance(String taskName, String startDate, String assessDate);\n}" }, { "identifier": "AssessParam", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/AssessParam.java", "snippet": "@Data\npublic class AssessParam {\n\n private String assessDate ;\n private TableMetaInfo tableMetaInfo ;\n private GovernanceMetric governanceMetric ;\n\n private Map<String ,TableMetaInfo> tableMetaInfoMap ; // 所有表\n\n private TDsTaskDefinition tDsTaskDefinition ; // 该指标需要的任务定义\n\n private TDsTaskInstance tDsTaskInstance ; // 该指标需要的任务状态信息(当日)\n\n}" }, { "identifier": "GovernanceAssessDetail", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetail.java", "snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetail implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 指标项id\n */\n private String metricId;\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n /**\n * 考评得分\n */\n private BigDecimal assessScore;\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n /**\n * 考评备注\n */\n private String assessComment;\n\n /**\n * 考评是否异常\n */\n private String isAssessException;\n\n /**\n * 异常信息\n */\n private String assessExceptionMsg;\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n\n /**\n * 创建日期\n */\n private Date createTime;\n}" }, { "identifier": "GovernanceAssessDetailVO", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetailVO.java", "snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetailVO {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n}" }, { "identifier": "GovernanceMetric", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceMetric.java", "snippet": "@Data\n@TableName(\"governance_metric\")\npublic class GovernanceMetric implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 指标名称\n */\n private String metricName;\n\n /**\n * 指标编码\n */\n private String metricCode;\n\n /**\n * 指标描述\n */\n private String metricDesc;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 指标参数\n */\n private String metricParamsJson;\n\n /**\n * 治理连接\n */\n private String governanceUrl;\n\n /**\n * 跳过考评的表名(多表逗号分割)\n */\n private String skipAssessTables;\n\n /**\n * 是否启用\n */\n private String isDisabled;\n}" }, { "identifier": "GovernanceAssessDetailMapper", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/mapper/GovernanceAssessDetailMapper.java", "snippet": "@Mapper\n@DS(\"dga\")\npublic interface GovernanceAssessDetailMapper extends BaseMapper<GovernanceAssessDetail> {\n\n}" }, { "identifier": "GovernanceAssessDetailService", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/service/GovernanceAssessDetailService.java", "snippet": "public interface GovernanceAssessDetailService extends IService<GovernanceAssessDetail> {\n\n void mainAssess( String assessDate);\n\n List<GovernanceAssessDetailVO> getProblemList(String governanceType, Integer pageNo, Integer pageSize);\n\n Map<String, Long> getProblemNum();\n}" }, { "identifier": "GovernanceMetricService", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/service/GovernanceMetricService.java", "snippet": "public interface GovernanceMetricService extends IService<GovernanceMetric> {\n\n}" }, { "identifier": "TableMetaInfo", "path": "data-governance-assessment/src/main/java/com/std/dga/meta/bean/TableMetaInfo.java", "snippet": "@Data\n@TableName(\"table_meta_info\")\npublic class TableMetaInfo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 表id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 字段名json ( 来源:hive)\n */\n private String colNameJson;\n\n /**\n * 分区字段名json( 来源:hive)\n */\n private String partitionColNameJson;\n\n /**\n * hdfs所属人 ( 来源:hive)\n */\n private String tableFsOwner;\n\n /**\n * 参数信息 ( 来源:hive)\n */\n private String tableParametersJson;\n\n /**\n * 表备注 ( 来源:hive)\n */\n private String tableComment;\n\n /**\n * hdfs路径 ( 来源:hive)\n */\n private String tableFsPath;\n\n /**\n * 输入格式( 来源:hive)\n */\n private String tableInputFormat;\n\n /**\n * 输出格式 ( 来源:hive)\n */\n private String tableOutputFormat;\n\n /**\n * 行格式 ( 来源:hive)\n */\n private String tableRowFormatSerde;\n\n /**\n * 表创建时间 ( 来源:hive)\n */\n private Date tableCreateTime;\n\n /**\n * 表类型 ( 来源:hive)\n */\n private String tableType;\n\n /**\n * 分桶列 ( 来源:hive)\n */\n private String tableBucketColsJson;\n\n /**\n * 分桶个数 ( 来源:hive)\n */\n private Long tableBucketNum;\n\n /**\n * 排序列 ( 来源:hive)\n */\n private String tableSortColsJson;\n\n /**\n * 数据量大小 ( 来源:hdfs)\n */\n private Long tableSize=0L;\n\n /**\n * 所有副本数据总量大小 ( 来源:hdfs)\n */\n private Long tableTotalSize=0L;\n\n /**\n * 最后修改时间 ( 来源:hdfs)\n */\n private Date tableLastModifyTime;\n\n /**\n * 最后访问时间 ( 来源:hdfs)\n */\n private Date tableLastAccessTime;\n\n /**\n * 当前文件系统容量 ( 来源:hdfs)\n */\n private Long fsCapcitySize;\n\n /**\n * 当前文件系统使用量 ( 来源:hdfs)\n */\n private Long fsUsedSize;\n\n /**\n * 当前文件系统剩余量 ( 来源:hdfs)\n */\n private Long fsRemainSize;\n\n /**\n * 考评日期 \n */\n private String assessDate;\n\n /**\n * 创建时间 (自动生成)\n */\n private Date createTime;\n\n /**\n * 更新时间 (自动生成)\n */\n private Date updateTime;\n\n\n /**\n * 额外辅助信息\n */\n @TableField(exist = false)\n private TableMetaInfoExtra tableMetaInfoExtra;\n\n}" }, { "identifier": "TableMetaInfoMapper", "path": "data-governance-assessment/src/main/java/com/std/dga/meta/mapper/TableMetaInfoMapper.java", "snippet": "@Mapper\n@DS(\"dga\")\npublic interface TableMetaInfoMapper extends BaseMapper<TableMetaInfo> {\n\n @Select(\n \"SELECT ti.*, te.* , ti.id ti_id , te.id te_id\\n\" +\n \"FROM table_meta_info ti JOIN table_meta_info_extra te\\n\" +\n \"ON ti.schema_name = te.schema_name AND ti.table_name = te.table_name \\n\" +\n \"WHERE ti.assess_date = #{assessDate} \"\n )\n @ResultMap(\"meta_result_map\")\n List<TableMetaInfo> selectTableMetaInfoList(String assessDate);\n\n @Select(\"${sql}\")\n List<TableMetaInfoVO> selectTableMetaInfoVoList(String sql);\n @Select(\"${sql}\")\n Integer selectTableMetaInfoCount(String sql);\n}" }, { "identifier": "SpringBeanProvider", "path": "data-governance-assessment/src/main/java/com/std/dga/util/SpringBeanProvider.java", "snippet": "@Component\npublic class SpringBeanProvider implements ApplicationContextAware {\n\n ApplicationContext applicationContext ;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext ;\n }\n\n /**\n * 通过组件的名字,从容器中获取到对应的组件对象\n */\n public <T> T getBeanByName(String beanName , Class<T> tClass){\n T bean = applicationContext.getBean(beanName, tClass);\n return bean ;\n }\n}" } ]
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.std.dga.assessor.Assessor; import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition; import com.std.dga.dolphinscheduler.bean.TDsTaskInstance; import com.std.dga.dolphinscheduler.service.TDsTaskDefinitionService; import com.std.dga.dolphinscheduler.service.TDsTaskInstanceService; import com.std.dga.governance.bean.AssessParam; import com.std.dga.governance.bean.GovernanceAssessDetail; import com.std.dga.governance.bean.GovernanceAssessDetailVO; import com.std.dga.governance.bean.GovernanceMetric; import com.std.dga.governance.mapper.GovernanceAssessDetailMapper; import com.std.dga.governance.service.GovernanceAssessDetailService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.std.dga.governance.service.GovernanceMetricService; import com.std.dga.meta.bean.TableMetaInfo; import com.std.dga.meta.mapper.TableMetaInfoMapper; import com.std.dga.util.SpringBeanProvider; import com.sun.codemodel.internal.JForEach; import org.apache.tomcat.util.threads.ThreadPoolExecutor; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
7,233
package com.std.dga.governance.service.impl; /** * <p> * 治理考评结果明细 服务实现类 * </p> * * @author std * @since 2023-10-10 */ @Service @DS("dga") public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService { @Autowired TableMetaInfoMapper tableMetaInfoMapper; @Autowired GovernanceMetricService governanceMetricService; @Autowired SpringBeanProvider springBeanProvider; // 用于动态获取对象 @Autowired TDsTaskDefinitionService tDsTaskDefinitionService; @Autowired TDsTaskInstanceService tDsTaskInstanceService; /* TODO : JUC 线程池优化: * 先按照corePoolSize数量运行, * 不够的在BlockingDeque队列等待,队列不够 * 再开辟新的线程,最多maximumPoolSize个 */ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(20, 30, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2000)); /** * * 主考评方法 * * 对每张表, 每个指标, 逐个考评 * 如何考评? * 将每个指标设计成一个具体的类, 考评器 * 例如: 是否有技术OWNER , TEC_OWNER TecOwnerAssessor * 模板设计模式 * 整个考评的过程是一致的 , 通过父类的方法来进行总控。 控制整个考评过程。 * 每个指标考评的细节(查找问题)是不同的 , 通过每个指标对应的考评器(子类) , 实现考评的细节。 * * 待解决: 如何将指标对应到考评器???(动态获取) * 方案一: 反射的方式: * 约定 : 考评器类的名字与 指标编码 遵循下划线与驼峰的映射规则。 * TEC_OWNER => tec_owner => TecOwner => TecOwnerAssessor * String code = governanceMetric.getMetricCode().toLowerCase(); * String className = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, code); * className = className+"Assessor"; * String superPackageName = "com.atguigu.dga.assessor" ; * String subPackageName = governanceMetric.getGovernanceType().toLowerCase() ; * String fullClassName = superPackageName +"." + subPackageName + "." + className ; * Assessor assessor = null; * try { * assessor = (Assessor)Class.forName(fullClassName).newInstance(); * } catch (Exception e) { * e.printStackTrace(); * } * * assessor.doAssess(); * 方案二: 通过spring容器管理考评器 * 每个组件被管理到Spring的容器中后,都有一个默认的名字, 就是类名(首字母小写 ) * 也可以显示的指定组件的名字。 * * 将指标的编码作为考评器的名字来使用。 未来, 获取到一个指标, 就可以通过指标编码从 * 容器中获取到对应的考评器对象。 */ @Override public void mainAssess(String assessDate) { // 幂等处理 remove( new QueryWrapper<GovernanceAssessDetail>() .eq("assess_date", assessDate) ); // remove( // new QueryWrapper<GovernanceAssessDetail>() // .eq("schema_name" , "gmall") // ) ; // 1. 读取所有待考评的表 List<TableMetaInfo> tableMetaInfoList = tableMetaInfoMapper.selectTableMetaInfoList(assessDate); System.out.println(tableMetaInfoList); HashMap<String, TableMetaInfo> tableMetaInfoMap = new HashMap<>(); for (TableMetaInfo tableMetaInfo : tableMetaInfoList) { tableMetaInfoMap.put(tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName(), tableMetaInfo); } // 2. 读取所有启用的指标 List<GovernanceMetric> governanceMetricList = governanceMetricService.list( new QueryWrapper<GovernanceMetric>() .eq("is_disabled", "0") ); // 从DS中查询所有的任务定义 List<TDsTaskDefinition> tDsTaskDefinitions = tDsTaskDefinitionService.selectList(); // 封装到Map中 HashMap<String, TDsTaskDefinition> tDsTaskDefinitionHashMap = new HashMap<>(); for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitions) { tDsTaskDefinitionHashMap.put(tDsTaskDefinition.getName(), tDsTaskDefinition); } // 从DS中查询所有的任务实例 List<TDsTaskInstance> tDsTaskInstances = tDsTaskInstanceService.selectList(assessDate); // 封装到Map中 HashMap<String, TDsTaskInstance> tDsTaskInstanceHashMap = new HashMap<>(); for (TDsTaskInstance tDsTaskInstance : tDsTaskInstances) { tDsTaskInstanceHashMap.put(tDsTaskInstance.getName(), tDsTaskInstance); } List<GovernanceAssessDetail> governanceAssessDetailList = new ArrayList<>(); // 未来要执行的任务集合 List<CompletableFuture<GovernanceAssessDetail>> futureList = new ArrayList<>(); for (TableMetaInfo tableMetaInfo : tableMetaInfoList) { for (GovernanceMetric governanceMetric : governanceMetricList) { // 处理白名单 String skipAssessTables = governanceMetric.getSkipAssessTables(); boolean isAssess = true; if (skipAssessTables != null && !skipAssessTables.trim().isEmpty()) { String[] skipTables = skipAssessTables.split(","); for (String skipTable : skipTables) { if (skipTable.equals(tableMetaInfo.getTableName())) { isAssess = false; break; } } } if (!isAssess) continue; // 动态获取各考评器组件对象(重点) // 也可以通过反射方式获取 Assessor assessor = springBeanProvider.getBeanByName(governanceMetric.getMetricCode(), Assessor.class); // 封装考评参数 AssessParam assessParam = new AssessParam(); assessParam.setAssessDate(assessDate); assessParam.setTableMetaInfo(tableMetaInfo); assessParam.setGovernanceMetric(governanceMetric); assessParam.setTableMetaInfoMap(tableMetaInfoMap); // 封装DS中的task定义与实例 assessParam.setTDsTaskDefinition(tDsTaskDefinitionHashMap.get(tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName())); assessParam.setTDsTaskInstance(tDsTaskInstanceHashMap.get(tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName())); // 开始考评 // GovernanceAssessDetail governanceAssessDetail = assessor.doAssessor(assessParam); // // governanceAssessDetailList.add(governanceAssessDetail); // JUC 异步改造优化,做任务编排 CompletableFuture<GovernanceAssessDetail> future = CompletableFuture.supplyAsync( () -> { // 考评 return assessor.doAssessor(assessParam); }, threadPoolExecutor ); futureList.add(future); } } // 异步计算, 最后集结, 统一计算 governanceAssessDetailList = futureList .stream().map(CompletableFuture::join).collect(Collectors.toList()); // 批写 saveBatch(governanceAssessDetailList); } /** * 获取问题列表 * <p> * 页面的请求: http://dga.gmall.com/governance/problemList/SPEC/1/5 * <p> * 返回的结果: * [ * {"assessComment":"","assessDate":"2023-05-01","assessProblem":"缺少技术OWNER","assessScore":0.00,"commentLog":"", * "createTime":1682954933000,"governanceType":"SPEC", * "governanceUrl":"/table_meta/table_meta/detail?tableId=1803","id":21947, * "isAssessException":"0","metricId":1,"metricName":"是否有技术Owner", * "schemaName":"gmall","tableName":"ads_page_path"} * , * {...},.... * ] */ @Override
package com.std.dga.governance.service.impl; /** * <p> * 治理考评结果明细 服务实现类 * </p> * * @author std * @since 2023-10-10 */ @Service @DS("dga") public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService { @Autowired TableMetaInfoMapper tableMetaInfoMapper; @Autowired GovernanceMetricService governanceMetricService; @Autowired SpringBeanProvider springBeanProvider; // 用于动态获取对象 @Autowired TDsTaskDefinitionService tDsTaskDefinitionService; @Autowired TDsTaskInstanceService tDsTaskInstanceService; /* TODO : JUC 线程池优化: * 先按照corePoolSize数量运行, * 不够的在BlockingDeque队列等待,队列不够 * 再开辟新的线程,最多maximumPoolSize个 */ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(20, 30, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2000)); /** * * 主考评方法 * * 对每张表, 每个指标, 逐个考评 * 如何考评? * 将每个指标设计成一个具体的类, 考评器 * 例如: 是否有技术OWNER , TEC_OWNER TecOwnerAssessor * 模板设计模式 * 整个考评的过程是一致的 , 通过父类的方法来进行总控。 控制整个考评过程。 * 每个指标考评的细节(查找问题)是不同的 , 通过每个指标对应的考评器(子类) , 实现考评的细节。 * * 待解决: 如何将指标对应到考评器???(动态获取) * 方案一: 反射的方式: * 约定 : 考评器类的名字与 指标编码 遵循下划线与驼峰的映射规则。 * TEC_OWNER => tec_owner => TecOwner => TecOwnerAssessor * String code = governanceMetric.getMetricCode().toLowerCase(); * String className = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, code); * className = className+"Assessor"; * String superPackageName = "com.atguigu.dga.assessor" ; * String subPackageName = governanceMetric.getGovernanceType().toLowerCase() ; * String fullClassName = superPackageName +"." + subPackageName + "." + className ; * Assessor assessor = null; * try { * assessor = (Assessor)Class.forName(fullClassName).newInstance(); * } catch (Exception e) { * e.printStackTrace(); * } * * assessor.doAssess(); * 方案二: 通过spring容器管理考评器 * 每个组件被管理到Spring的容器中后,都有一个默认的名字, 就是类名(首字母小写 ) * 也可以显示的指定组件的名字。 * * 将指标的编码作为考评器的名字来使用。 未来, 获取到一个指标, 就可以通过指标编码从 * 容器中获取到对应的考评器对象。 */ @Override public void mainAssess(String assessDate) { // 幂等处理 remove( new QueryWrapper<GovernanceAssessDetail>() .eq("assess_date", assessDate) ); // remove( // new QueryWrapper<GovernanceAssessDetail>() // .eq("schema_name" , "gmall") // ) ; // 1. 读取所有待考评的表 List<TableMetaInfo> tableMetaInfoList = tableMetaInfoMapper.selectTableMetaInfoList(assessDate); System.out.println(tableMetaInfoList); HashMap<String, TableMetaInfo> tableMetaInfoMap = new HashMap<>(); for (TableMetaInfo tableMetaInfo : tableMetaInfoList) { tableMetaInfoMap.put(tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName(), tableMetaInfo); } // 2. 读取所有启用的指标 List<GovernanceMetric> governanceMetricList = governanceMetricService.list( new QueryWrapper<GovernanceMetric>() .eq("is_disabled", "0") ); // 从DS中查询所有的任务定义 List<TDsTaskDefinition> tDsTaskDefinitions = tDsTaskDefinitionService.selectList(); // 封装到Map中 HashMap<String, TDsTaskDefinition> tDsTaskDefinitionHashMap = new HashMap<>(); for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitions) { tDsTaskDefinitionHashMap.put(tDsTaskDefinition.getName(), tDsTaskDefinition); } // 从DS中查询所有的任务实例 List<TDsTaskInstance> tDsTaskInstances = tDsTaskInstanceService.selectList(assessDate); // 封装到Map中 HashMap<String, TDsTaskInstance> tDsTaskInstanceHashMap = new HashMap<>(); for (TDsTaskInstance tDsTaskInstance : tDsTaskInstances) { tDsTaskInstanceHashMap.put(tDsTaskInstance.getName(), tDsTaskInstance); } List<GovernanceAssessDetail> governanceAssessDetailList = new ArrayList<>(); // 未来要执行的任务集合 List<CompletableFuture<GovernanceAssessDetail>> futureList = new ArrayList<>(); for (TableMetaInfo tableMetaInfo : tableMetaInfoList) { for (GovernanceMetric governanceMetric : governanceMetricList) { // 处理白名单 String skipAssessTables = governanceMetric.getSkipAssessTables(); boolean isAssess = true; if (skipAssessTables != null && !skipAssessTables.trim().isEmpty()) { String[] skipTables = skipAssessTables.split(","); for (String skipTable : skipTables) { if (skipTable.equals(tableMetaInfo.getTableName())) { isAssess = false; break; } } } if (!isAssess) continue; // 动态获取各考评器组件对象(重点) // 也可以通过反射方式获取 Assessor assessor = springBeanProvider.getBeanByName(governanceMetric.getMetricCode(), Assessor.class); // 封装考评参数 AssessParam assessParam = new AssessParam(); assessParam.setAssessDate(assessDate); assessParam.setTableMetaInfo(tableMetaInfo); assessParam.setGovernanceMetric(governanceMetric); assessParam.setTableMetaInfoMap(tableMetaInfoMap); // 封装DS中的task定义与实例 assessParam.setTDsTaskDefinition(tDsTaskDefinitionHashMap.get(tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName())); assessParam.setTDsTaskInstance(tDsTaskInstanceHashMap.get(tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName())); // 开始考评 // GovernanceAssessDetail governanceAssessDetail = assessor.doAssessor(assessParam); // // governanceAssessDetailList.add(governanceAssessDetail); // JUC 异步改造优化,做任务编排 CompletableFuture<GovernanceAssessDetail> future = CompletableFuture.supplyAsync( () -> { // 考评 return assessor.doAssessor(assessParam); }, threadPoolExecutor ); futureList.add(future); } } // 异步计算, 最后集结, 统一计算 governanceAssessDetailList = futureList .stream().map(CompletableFuture::join).collect(Collectors.toList()); // 批写 saveBatch(governanceAssessDetailList); } /** * 获取问题列表 * <p> * 页面的请求: http://dga.gmall.com/governance/problemList/SPEC/1/5 * <p> * 返回的结果: * [ * {"assessComment":"","assessDate":"2023-05-01","assessProblem":"缺少技术OWNER","assessScore":0.00,"commentLog":"", * "createTime":1682954933000,"governanceType":"SPEC", * "governanceUrl":"/table_meta/table_meta/detail?tableId=1803","id":21947, * "isAssessException":"0","metricId":1,"metricName":"是否有技术Owner", * "schemaName":"gmall","tableName":"ads_page_path"} * , * {...},.... * ] */ @Override
public List<GovernanceAssessDetailVO> getProblemList(String governanceType, Integer pageNo, Integer pageSize) {
7
2023-10-20 10:13:43+00:00
12k
RaulGB88/MOD-034-Microservicios-con-Java
REM20231023/catalogo/src/main/java/com/example/application/resources/FilmResource.java
[ { "identifier": "DomainEventService", "path": "REM20231023/catalogo/src/main/java/com/example/DomainEventService.java", "snippet": "@Service\npublic class DomainEventService {\n\n\t@Data @AllArgsConstructor\n\tpublic class MessageDTO implements Serializable {\n\t\tprivate static final long serialVersionUID = 1L;\n\t\tprivate String evento;\n\t\tprivate String origen;\n\t\tprivate int id;\n\t}\n\n\tprivate static final Logger LOG = LoggerFactory.getLogger(DomainEventService.class);\n\t@Value(\"${spring.kafka.bootstrap-servers}\")\n\tprivate String kafkaBootstraServers;\n\t@Value(\"${topic.name}\")\n\tprivate String topic;\n\t@Value(\"${sensor.id}\")\n\tprivate String key;\n\n\t@Autowired\n\tprivate KafkaTemplate<String, String> kafkaTemplate;\n\n\tprivate ObjectMapper objectMapper = new ObjectMapper();\n\t\n\tpublic void sendAdd(String entity, int id) {\n\t\ttry {\n\t\t\tString json = objectMapper.writeValueAsString(new MessageDTO(\"add\", entity, id));\n\t\t\tsendMessage(json);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tLOG.error(\"Error send add\", e);\n\t\t}\n\t}\n\n\tpublic void sendModify(String entity, int id) {\n\t\ttry {\n\t\t\tString json = objectMapper.writeValueAsString(new MessageDTO(\"modify\", entity, id));\n\t\t\tsendMessage(json);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tLOG.error(\"Error send modify\", e);\n\t\t}\n\t}\n\n\tpublic void sendDelete(String entity, int id) {\n\t\ttry {\n\t\t\tString json = objectMapper.writeValueAsString(new MessageDTO(\"delete\", entity, id));\n\t\t\tsendMessage(json);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tLOG.error(\"Error send delete\", e);\n\t\t}\n\t}\n\n\tprivate void sendMessage(String message) {\n\t\tkafkaTemplate.send(topic, key, message)\n\t\t\t.thenAccept(result -> LOG.info(String.format(\"TOPIC: %s, KEY: %s, MESSAGE: %s, OFFSET: %s\", topic, key, message,\n\t\t\t\t\tresult.getRecordMetadata().offset())))\n\t\t\t.exceptionally(ex -> {\n\t\t\t\tLOG.error(String.format(\"TOPIC: %s, KEY: %s, MESSAGE: %s, ERROR: %s\", topic, key, message,\n\t\t\t\t\t\tex.getMessage())); \n\t\t\t\treturn null;\n\t\t\t});\n\t}\n}" }, { "identifier": "MeGustaProxy", "path": "REM20231023/catalogo/src/main/java/com/example/application/proxies/MeGustaProxy.java", "snippet": "@FeignClient(name=\"MEGUSTA-SERVICE\")\npublic interface MeGustaProxy {\n\t@PostMapping(path = \"/me-gusta/hash/{id}\")\n\tString sendLike(@PathVariable int id);\n\t@PostMapping(path = \"/me-gusta/hash/{id}\")\n\tString sendLike(@PathVariable int id, @RequestHeader(value = \"Authorization\", required = true) String authorization);\n}" }, { "identifier": "FilmService", "path": "REM20231023/catalogo/src/main/java/com/example/domains/contracts/services/FilmService.java", "snippet": "public interface FilmService extends ProjectionDomainService<Film, Integer> {\n\tList<Film> novedades(Timestamp fecha);\n}" }, { "identifier": "Category", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/Category.java", "snippet": "@Entity\n@Table(name=\"category\")\n@NamedQuery(name=\"Category.findAll\", query=\"SELECT c FROM Category c\")\npublic class Category extends EntityBase<Category> implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\t@Column(name=\"category_id\")\n\t@JsonProperty(\"id\")\n\tprivate int categoryId;\n\n\t@Column(name=\"last_update\", insertable = false, updatable = false)\n\t@PastOrPresent\n\t@JsonIgnore\n\tprivate Timestamp lastUpdate;\n\n\t@NotBlank\n\t@Size(max=25)\n\t@JsonProperty(\"categoria\")\n\tprivate String name;\n\n\t//bi-directional many-to-one association to FilmCategory\n\t@OneToMany(mappedBy=\"category\")\n\t@JsonIgnore\n\tprivate List<FilmCategory> filmCategories;\n\n\tpublic Category() {\n\t}\n\n\tpublic Category(int categoryId) {\n\t\tsuper();\n\t\tthis.categoryId = categoryId;\n\t}\n\n\tpublic int getCategoryId() {\n\t\treturn this.categoryId;\n\t}\n\n\tpublic void setCategoryId(int categoryId) {\n\t\tthis.categoryId = categoryId;\n\t}\n\n\tpublic Timestamp getLastUpdate() {\n\t\treturn this.lastUpdate;\n\t}\n\n\tpublic void setLastUpdate(Timestamp lastUpdate) {\n\t\tthis.lastUpdate = lastUpdate;\n\t}\n\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic List<FilmCategory> getFilmCategories() {\n\t\treturn this.filmCategories;\n\t}\n\n\tpublic void setFilmCategories(List<FilmCategory> filmCategories) {\n\t\tthis.filmCategories = filmCategories;\n\t}\n\n\tpublic FilmCategory addFilmCategory(FilmCategory filmCategory) {\n\t\tgetFilmCategories().add(filmCategory);\n\t\tfilmCategory.setCategory(this);\n\n\t\treturn filmCategory;\n\t}\n\n\tpublic FilmCategory removeFilmCategory(FilmCategory filmCategory) {\n\t\tgetFilmCategories().remove(filmCategory);\n\t\tfilmCategory.setCategory(null);\n\n\t\treturn filmCategory;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(categoryId);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tCategory other = (Category) obj;\n\t\treturn categoryId == other.categoryId;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Category [categoryId=\" + categoryId + \", name=\" + name + \", lastUpdate=\" + lastUpdate + \"]\";\n\t}\n\n}" }, { "identifier": "Film", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/Film.java", "snippet": "@Entity\n@Table(name=\"film\")\n@NamedQuery(name=\"Film.findAll\", query=\"SELECT f FROM Film f\")\npublic class Film extends EntityBase<Film> implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\tpublic static enum Rating {\n\t GENERAL_AUDIENCES(\"G\"),\n\t PARENTAL_GUIDANCE_SUGGESTED(\"PG\"),\n\t PARENTS_STRONGLY_CAUTIONED(\"PG-13\"),\n\t RESTRICTED(\"R\"),\n\t ADULTS_ONLY(\"NC-17\");\n\n\t String value;\n\t \n\t Rating(String value) {\n\t this.value = value;\n\t }\n\n\t public String getValue() {\n\t return value;\n\t }\n\t\tpublic static Rating getEnum(String value) {\n\t\t\tswitch (value) {\n\t\t\tcase \"G\": return Rating.GENERAL_AUDIENCES;\n\t\t\tcase \"PG\": return Rating.PARENTAL_GUIDANCE_SUGGESTED;\n\t\t\tcase \"PG-13\": return Rating.PARENTS_STRONGLY_CAUTIONED;\n\t\t\tcase \"R\": return Rating.RESTRICTED;\n\t\t\tcase \"NC-17\": return Rating.ADULTS_ONLY;\n\t\t\tcase \"\": return null;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unexpected value: \" + value);\n\t\t\t}\n\t\t}\n\t\tpublic static final String[] VALUES = {\"G\", \"PG\", \"PG-13\", \"R\", \"NC-17\"};\n\t}\n\t@Converter\n\tprivate static class RatingConverter implements AttributeConverter<Rating, String> {\n\t @Override\n\t public String convertToDatabaseColumn(Rating rating) {\n\t if (rating == null) {\n\t return null;\n\t }\n\t return rating.getValue();\n\t }\n\t @Override\n\t public Rating convertToEntityAttribute(String value) {\n\t if (value == null) {\n\t return null;\n\t }\n\n\t return Rating.getEnum(value);\n\t }\n\t}\n\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\t@Column(name=\"film_id\", unique=true, nullable=false)\n\tprivate int filmId;\n\n\t@Lob\n\tprivate String description;\n\n\t@Column(name=\"last_update\", insertable = false, updatable = false, nullable=false)\n\tprivate Timestamp lastUpdate;\n\n\t@Positive\n\tprivate Integer length;\n\n\t@Convert(converter = RatingConverter.class)\n\tprivate Rating rating;\n\n\t//@Temporal(TemporalType.DATE)\n\t//@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy\")\n\t@Min(1901) @Max(2155)\n\t@Column(name=\"release_year\")\n\tprivate Short releaseYear;\n\n\t@NotNull\n\t@Positive\n\t@Column(name=\"rental_duration\", nullable=false)\n\tprivate Byte rentalDuration;\n\n\t@NotNull\n @Digits(integer=2, fraction=2)\n\t@DecimalMin(value = \"0.0\", inclusive = false)\n\t@Column(name=\"rental_rate\", nullable=false, precision=10, scale=2)\n\tprivate BigDecimal rentalRate;\n\n\t@NotNull\n @Digits(integer=3, fraction=2)\n\t@DecimalMin(value = \"0.0\", inclusive = false)\n\t@Column(name=\"replacement_cost\", nullable=false, precision=10, scale=2)\n\tprivate BigDecimal replacementCost;\n\n\t@NotBlank\n\t@Size(max = 128)\n\t@Column(nullable=false, length=128)\n\tprivate String title;\n\n\t//bi-directional many-to-one association to Language\n\t@ManyToOne\n\t@JoinColumn(name=\"language_id\")\n\t@NotNull\n\tprivate Language language;\n\n\t//bi-directional many-to-one association to Language\n\t@ManyToOne\n\t@JoinColumn(name=\"original_language_id\")\n\tprivate Language languageVO;\n\n\t//bi-directional many-to-one association to FilmActor\n\t@OneToMany(mappedBy=\"film\", cascade = CascadeType.ALL, orphanRemoval = true)\n\t@JsonIgnore\n\tprivate List<FilmActor> filmActors = new ArrayList<FilmActor>();\n\n\t//bi-directional many-to-one association to FilmCategory\n\t@OneToMany(mappedBy=\"film\", cascade = CascadeType.ALL, orphanRemoval = true)\n\t@JsonIgnore\n\tprivate List<FilmCategory> filmCategories = new ArrayList<FilmCategory>();\n\n\tpublic Film() {\n\t}\n\n\tpublic Film(int filmId) {\n\t\tthis.filmId = filmId;\n\t}\n\n\tpublic Film(int filmId, @NotBlank @Size(max = 128) String title, String description, @Min(1895) Short releaseYear,\n\t\t\t@NotNull Language language, Language languageVO, @Positive Byte rentalDuration,\n\t\t\t@Positive @DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 2, fraction = 2) BigDecimal rentalRate,\n\t\t\t@Positive Integer length,\n\t\t\t@DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 3, fraction = 2) BigDecimal replacementCost,\n\t\t\tRating rating) {\n\t\tsuper();\n\t\tthis.filmId = filmId;\n\t\tthis.title = title;\n\t\tthis.description = description;\n\t\tthis.releaseYear = releaseYear;\n\t\tthis.language = language;\n\t\tthis.languageVO = languageVO;\n\t\tthis.rentalDuration = rentalDuration;\n\t\tthis.rentalRate = rentalRate;\n\t\tthis.length = length;\n\t\tthis.replacementCost = replacementCost;\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Film(@NotBlank @Size(max = 128) String title,\n\t\t\t@NotNull Language language, \n\t\t\t@Positive Byte rentalDuration,\n\t\t\t@Positive @DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 2, fraction = 2) BigDecimal rentalRate,\n\t\t\t@Positive int length,\n\t\t\t@DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 3, fraction = 2) BigDecimal replacementCost) {\n\t\tsuper();\n\t\tthis.title = title;\n\t\tthis.language = language;\n\t\tthis.rentalDuration = rentalDuration;\n\t\tthis.rentalRate = rentalRate;\n\t\tthis.length = length;\n\t\tthis.replacementCost = replacementCost;\n\t}\n\n\tpublic int getFilmId() {\n\t\treturn this.filmId;\n\t}\n\n\tpublic void setFilmId(int filmId) {\n\t\tthis.filmId = filmId;\n\t\tif(filmActors != null && filmActors.size() > 0)\n\t\t\tfilmActors.forEach(item -> { if(item.getId().getFilmId() != filmId) item.getId().setFilmId(filmId); });\n\t\tif(filmCategories != null && filmCategories.size() > 0)\n\t\t\tfilmCategories.forEach(item -> { if(item.getId().getFilmId() != filmId) item.getId().setFilmId(filmId); });\n\t}\n\n\tpublic String getDescription() {\n\t\treturn this.description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic Timestamp getLastUpdate() {\n\t\treturn this.lastUpdate;\n\t}\n\n\tpublic void setLastUpdate(Timestamp lastUpdate) {\n\t\tthis.lastUpdate = lastUpdate;\n\t}\n\n\tpublic Integer getLength() {\n\t\treturn this.length;\n\t}\n\n\tpublic void setLength(Integer length) {\n\t\tthis.length = length;\n\t}\n\n\tpublic Rating getRating() {\n\t\treturn this.rating;\n\t}\n\n\tpublic void setRating(Rating rating) {\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Short getReleaseYear() {\n\t\treturn this.releaseYear;\n\t}\n\n\tpublic void setReleaseYear(Short releaseYear) {\n\t\tthis.releaseYear = releaseYear;\n\t}\n\n\tpublic Byte getRentalDuration() {\n\t\treturn this.rentalDuration;\n\t}\n\n\tpublic void setRentalDuration(Byte rentalDuration) {\n\t\tthis.rentalDuration = rentalDuration;\n\t}\n\n\tpublic BigDecimal getRentalRate() {\n\t\treturn this.rentalRate;\n\t}\n\n\tpublic void setRentalRate(BigDecimal rentalRate) {\n\t\tthis.rentalRate = rentalRate;\n\t}\n\n\tpublic BigDecimal getReplacementCost() {\n\t\treturn this.replacementCost;\n\t}\n\n\tpublic void setReplacementCost(BigDecimal replacementCost) {\n\t\tthis.replacementCost = replacementCost;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn this.title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic Language getLanguage() {\n\t\treturn this.language;\n\t}\n\n\tpublic void setLanguage(Language language) {\n\t\tthis.language = language;\n\t}\n\n\tpublic Language getLanguageVO() {\n\t\treturn this.languageVO;\n\t}\n\n\tpublic void setLanguageVO(Language languageVO) {\n\t\tthis.languageVO = languageVO;\n\t}\n\n\t// Gestión de actores\n\n\tpublic List<Actor> getActors() {\n\t\treturn this.filmActors.stream().map(item -> item.getActor()).toList();\n\t}\n\tpublic void setActors(List<Actor> source) {\n\t\tif(filmActors == null || !filmActors.isEmpty()) clearActors();\n\t\tsource.forEach(item -> addActor(item));\n\t}\n\tpublic void clearActors() {\n\t\tfilmActors = new ArrayList<FilmActor>() ;\n\t}\n\tpublic void addActor(Actor actor) {\n\t\tFilmActor filmActor = new FilmActor(this, actor);\n\t\tfilmActors.add(filmActor);\n\t}\n\tpublic void addActor(int actorId) {\n\t\taddActor(new Actor(actorId));\n\t}\n\tpublic void removeActor(Actor actor) {\n\t\tvar filmActor = filmActors.stream().filter(item -> item.getActor().equals(actor)).findFirst();\n\t\tif(filmActor.isEmpty())\n\t\t\treturn;\n\t\tfilmActors.remove(filmActor.get());\n\t}\n\n\t// Gestión de categorias\n\n\tpublic List<Category> getCategories() {\n\t\treturn this.filmCategories.stream().map(item -> item.getCategory()).toList();\n\t}\n\tpublic void setCategories(List<Category> source) {\n\t\tif(filmCategories == null || !filmCategories.isEmpty()) clearCategories();\n\t\tsource.forEach(item -> addCategory(item));\n\t}\n\tpublic void clearCategories() {\n\t\tfilmCategories = new ArrayList<FilmCategory>() ;\n\t}\n\tpublic void addCategory(Category item) {\n\t\tFilmCategory filmCategory = new FilmCategory(this, item);\n\t\tfilmCategories.add(filmCategory);\n\t}\n\tpublic void addCategory(int id) {\n\t\taddCategory(new Category(id));\n\t}\n\tpublic void removeCategory(Category ele) {\n\t\tvar filmCategory = filmCategories.stream().filter(item -> item.getCategory().equals(ele)).findFirst();\n\t\tif(filmCategory.isEmpty())\n\t\t\treturn;\n\t\tfilmCategories.remove(filmCategory.get());\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(filmId);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tFilm other = (Film) obj;\n\t\treturn filmId == other.filmId;\n\t}\n\n\tpublic Film merge(Film target) {\n\t\ttarget.title = title;\n\t\ttarget.description = description;\n\t\ttarget.releaseYear = releaseYear;\n\t\ttarget.language = language;\n\t\ttarget.languageVO = languageVO;\n\t\ttarget.rentalDuration = rentalDuration;\n\t\ttarget.rentalRate = rentalRate;\n\t\ttarget.length = length;\n\t\ttarget.replacementCost = replacementCost;\n\t\ttarget.rating = rating;\n\t\t// Borra los actores que sobran\n\t\ttarget.getActors().stream()\n\t\t\t.filter(item -> !getActors().contains(item))\n\t\t\t.forEach(item -> target.removeActor(item));\n\t\t// Añade los actores que faltan\n\t\tgetActors().stream()\n\t\t\t.filter(item -> !target.getActors().contains(item))\n\t\t\t.forEach(item -> target.addActor(item));\n\t\t// Añade las categorias que faltan\n\t\ttarget.getCategories().stream()\n\t\t\t.filter(item -> !getCategories().contains(item))\n\t\t\t.forEach(item -> target.removeCategory(item));\n\t\t// Borra las categorias que sobran\n\t\tgetCategories().stream()\n\t\t\t.filter(item -> !target.getCategories().contains(item))\n\t\t\t.forEach(item -> target.addCategory(item));\n\t\treturn target;\n\t}\n}" }, { "identifier": "ActorDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/ActorDTO.java", "snippet": "@Value\npublic class ActorDTO {\n\t@JsonProperty(\"id\")\n\tprivate int actorId;\n\t@JsonProperty(\"nombre\")\n\tprivate String firstName;\n\t@JsonProperty(\"apellidos\")\n\tprivate String lastName;\n\t\n\tpublic static ActorDTO from(Actor target) {\n\t\treturn new ActorDTO(target.getActorId(), target.getFirstName(), target.getLastName());\n\t}\n\n\tpublic static Actor from(ActorDTO target) {\n\t\treturn new Actor(target.getActorId(), target.getFirstName(), target.getLastName());\n\t}\n\n}" }, { "identifier": "FilmDetailsDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/FilmDetailsDTO.java", "snippet": "@Schema(name = \"Pelicula (Detalles)\", description = \"Version completa de las peliculas\")\n@Value\npublic class FilmDetailsDTO {\n\t@Schema(description = \"Identificador de la pelicula\", accessMode = AccessMode.READ_ONLY)\n\tprivate int filmId;\n\t@Schema(description = \"Una breve descripción o resumen de la trama de la película\")\n\tprivate String description;\n\t@Schema(description = \"La duración de la película, en minutos\")\n\tprivate Integer length;\n\t@Schema(description = \"La clasificación por edades asignada a la película\", allowableValues = {\"G\", \"PG\", \"PG-13\", \"R\", \"NC-17\"})\n\tprivate String rating;\n\t@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy\")\n\t@Schema(description = \"El año en que se estrenó la película\")\n\tprivate Short releaseYear;\n\t@Schema(description = \"La duración del período de alquiler, en días\")\n\tprivate Byte rentalDuration;\n\t@Schema(description = \"El coste de alquilar la película por el período establecido\")\n\tprivate BigDecimal rentalRate;\n\t@Schema(description = \"El importe cobrado al cliente si la película no se devuelve o se devuelve en un estado dañado\")\n\tprivate BigDecimal replacementCost;\n\t@Schema(description = \"El título de la película\", required = true)\n\tprivate String title;\n\t@Schema(description = \"El idioma de la película\")\n\tprivate String language;\n\t@Schema(description = \"El idioma original de la película\")\n\tprivate String languageVO;\n\t@Schema(description = \"La lista de actores que participan en la película\")\n\tprivate List<String> actors;\n\t@Schema(description = \"La lista de categorías asignadas a la película\")\n\tprivate List<String> categories;\n\t\n\tpublic static FilmDetailsDTO from(Film source) {\n\t\treturn new FilmDetailsDTO(\n\t\t\t\tsource.getFilmId(), \n\t\t\t\tsource.getDescription(),\n\t\t\t\tsource.getLength(),\n\t\t\t\tsource.getRating() == null ? null : source.getRating().getValue(),\n\t\t\t\tsource.getReleaseYear(),\n\t\t\t\tsource.getRentalDuration(),\n\t\t\t\tsource.getRentalRate(),\n\t\t\t\tsource.getReplacementCost(),\n\t\t\t\tsource.getTitle(),\n\t\t\t\tsource.getLanguage() == null ? null : source.getLanguage().getName(),\n\t\t\t\tsource.getLanguageVO() == null ? null : source.getLanguageVO().getName(),\n\t\t\t\tsource.getActors().stream().map(item -> item.getFirstName() + \" \" + item.getLastName())\n\t\t\t\t\t.sorted().toList(),\n\t\t\t\tsource.getCategories().stream().map(item -> item.getName()).sorted().toList()\n\t\t\t\t);\n\t}\n}" }, { "identifier": "FilmEditDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/FilmEditDTO.java", "snippet": "@Schema(name = \"Pelicula (Editar)\", description = \"Version editable de las películas\")\n@Data @AllArgsConstructor @NoArgsConstructor\npublic class FilmEditDTO {\n\t@Schema(description = \"Identificador de la película\", accessMode = AccessMode.READ_ONLY)\n\tprivate int filmId;\n\t@Schema(description = \"Una breve descripción o resumen de la trama de la película\", minLength = 2)\n\tprivate String description;\n\t@Schema(description = \"La duración de la película, en minutos\", minimum = \"0\", exclusiveMinimum = true)\n\tprivate Integer length;\n\t@Schema(description = \"La clasificación por edades asignada a la película\", allowableValues = {\"G\", \"PG\", \"PG-13\", \"R\", \"NC-17\"})\n//\t@Pattern(regexp = \"^(G|PG|PG-13|R|NC-17)$\")\n\tprivate String rating;\n\t@Schema(description = \"El año en que se estrenó la película\", minimum = \"1901\", maximum = \"2155\")\n\tprivate Short releaseYear;\n\t@Schema(description = \"La duración del período de alquiler, en días\", minimum = \"0\", exclusiveMinimum = true)\n\t@NotNull\n\tprivate Byte rentalDuration;\n\t@Schema(description = \"El coste de alquilar la película por el período establecido\", minimum = \"0\", exclusiveMinimum = true)\n\t@NotNull\n\tprivate BigDecimal rentalRate;\n\t@Schema(description = \"El importe cobrado al cliente si la película no se devuelve o se devuelve en un estado dañado\", minimum = \"0\", exclusiveMinimum = true)\n\t@NotNull\n\tprivate BigDecimal replacementCost;\n\t@Schema(description = \"El título de la película\")\n\t@NotBlank\n\t@Size(min=2, max = 128)\n\tprivate String title;\n\t@Schema(description = \"El identificador del idioma de la película\")\n\t@NotNull\n\tprivate Integer languageId;\n\t@Schema(description = \"El identificador del idioma original de la película\")\n\tprivate Integer languageVOId;\n\t@Schema(description = \"La lista de identificadores de actores que participan en la película\")\n\tprivate List<Integer> actors = new ArrayList<Integer>();\n\t@Schema(description = \"La lista de identificadores de categorías asignadas a la película\")\n\t@ArraySchema(uniqueItems = true, minItems = 1, maxItems = 3)\n\tprivate List<Integer> categories = new ArrayList<Integer>();\n\n \tpublic static FilmEditDTO from(Film source) {\n\t\treturn new FilmEditDTO(\n\t\t\t\tsource.getFilmId(), \n\t\t\t\tsource.getDescription(),\n\t\t\t\tsource.getLength(),\n\t\t\t\tsource.getRating() == null ? null : source.getRating().getValue(),\n\t\t\t\tsource.getReleaseYear(),\n\t\t\t\tsource.getRentalDuration(),\n\t\t\t\tsource.getRentalRate(),\n\t\t\t\tsource.getReplacementCost(),\n\t\t\t\tsource.getTitle(),\n\t\t\t\tsource.getLanguage() == null ? null : source.getLanguage().getLanguageId(),\n\t\t\t\tsource.getLanguageVO() == null ? null : source.getLanguageVO().getLanguageId(),\n\t\t\t\tsource.getActors().stream().map(item -> item.getActorId())\n\t\t\t\t\t.collect(Collectors.toList()),\n\t\t\t\tsource.getCategories().stream().map(item -> item.getCategoryId())\n\t\t\t\t\t.collect(Collectors.toList())\n\t\t\t\t);\n\t}\n\tpublic static Film from(FilmEditDTO source) {\n\t\tFilm rslt = new Film(\n\t\t\t\tsource.getFilmId(), \n\t\t\t\tsource.getTitle(),\n\t\t\t\tsource.getDescription(),\n\t\t\t\tsource.getReleaseYear(),\n\t\t\t\tsource.getLanguageId() == null ? null : new Language(source.getLanguageId()),\n\t\t\t\tsource.getLanguageVOId() == null ? null : new Language(source.getLanguageVOId()),\n\t\t\t\tsource.getRentalDuration(),\n\t\t\t\tsource.getRentalRate(),\n\t\t\t\tsource.getLength(),\n\t\t\t\tsource.getReplacementCost(),\n\t\t\t\tsource.getRating() == null ? null : Film.Rating.getEnum(source.getRating())\n\t\t\t\t);\n\t\tsource.getActors().stream().forEach(item -> rslt.addActor(item));\n\t\tsource.getCategories().stream().forEach(item -> rslt.addCategory(item));\n\t\treturn rslt;\n\t}\n\n}" }, { "identifier": "FilmShortDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/FilmShortDTO.java", "snippet": "@Schema(name = \"Pelicula (Corto)\", description = \"Version corta de las peliculas\")\n@Value\npublic class FilmShortDTO {\n\t@Schema(description = \"Identificador de la pelicula\", accessMode = AccessMode.READ_ONLY)\n\tprivate int filmId;\n\t@Schema(description = \"Titulo de la pelicula\")\n\tprivate String title;\n\t\n\tpublic static FilmShortDTO from(Film source) {\n\t\treturn new FilmShortDTO(source.getFilmId(), source.getTitle());\n\t}\n}" }, { "identifier": "BadRequestException", "path": "REM20231023/catalogo/src/main/java/com/example/exceptions/BadRequestException.java", "snippet": "public class BadRequestException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic BadRequestException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic BadRequestException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic BadRequestException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n}" }, { "identifier": "NotFoundException", "path": "REM20231023/catalogo/src/main/java/com/example/exceptions/NotFoundException.java", "snippet": "public class NotFoundException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Not found\";\n\t\n\tpublic NotFoundException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic NotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic NotFoundException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n}" } ]
import java.net.URI; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.transaction.Transactional; import jakarta.validation.Valid; import org.springdoc.core.converters.models.PageableAsQueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.example.DomainEventService; import com.example.application.proxies.MeGustaProxy; import com.example.domains.contracts.services.FilmService; import com.example.domains.entities.Category; import com.example.domains.entities.Film; import com.example.domains.entities.dtos.ActorDTO; import com.example.domains.entities.dtos.FilmDetailsDTO; import com.example.domains.entities.dtos.FilmEditDTO; import com.example.domains.entities.dtos.FilmShortDTO; import com.example.exceptions.BadRequestException; import com.example.exceptions.NotFoundException; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag;
7,239
package com.example.application.resources; //import org.springdoc.api.annotations.ParameterObject; @RestController @Tag(name = "peliculas-service", description = "Mantenimiento de peliculas") @RequestMapping(path = "/peliculas/v1") public class FilmResource { @Autowired private FilmService srv; @Autowired DomainEventService deSrv; @Hidden @GetMapping(params = "page")
package com.example.application.resources; //import org.springdoc.api.annotations.ParameterObject; @RestController @Tag(name = "peliculas-service", description = "Mantenimiento de peliculas") @RequestMapping(path = "/peliculas/v1") public class FilmResource { @Autowired private FilmService srv; @Autowired DomainEventService deSrv; @Hidden @GetMapping(params = "page")
public Page<FilmShortDTO> getAll(Pageable pageable,
8
2023-10-24 14:35:15+00:00
12k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/commons/forms/impl/JavaScriptFormGenerator.java
[ { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static final String REQUIRED = \"NotNull\";\n public static final String NOT_NULL = \"NotNull\";\n public static final String NOT_VALID = \"NotValid\";\n public static final String NOT_VALID_EMAIL = \"NotValidEmail\";\n public static final String NOT_VALID_WORKSPACE = \"NotValidWorkspace\";\n public static final String NOT_UNIQUE_USER = \"NotUniqueUser\";\n public static final String NOT_VALID_OPTION = \"NotValidOption\";\n\n public static final String MAX_SIZE = \"javax.validation.constraints.Max.message\";\n public static final String MIN_SIZE = \"javax.validation.constraints.Min.message\";\n\n public static final String PERIOD_INIDATE_BEFORE = \"period.msgdt1\";\n\n public static final String UNDEFINED = \"global.notdef\";\n\n /**\n * keys in the message bundle to get information about date format in the selected locale\n */\n // convert from string to date\n public static final String LOCALE_DATE_FORMAT = \"locale.dateFormat\";\n // mask in editing control\n public static final String LOCALE_DATE_MASK = \"locale.dateMask\";\n // hint to be displayed as a place holder in date controls\n public static final String LOCALE_DATE_HINT = \"locale.dateHint\";\n // convert a date to a displayable string\n public static final String LOCALE_DISPLAY_DATE_FORMAT = \"locale.displayDateFormat\";\n\n\n /**\n * The pattern to get the keys to be replaced inside the string\n */\n public static final Pattern EXP_PATTERN = Pattern.compile(\"\\\\$\\\\{(.*?)\\\\}\");\n\n\n @Resource\n MessageSource messageSource;\n\n /**\n * Get the message by its key\n *\n * @param key the message key\n * @return the message to be displayed to the user\n */\n public String get(String key) {\n Locale locale = LocaleContextHolder.getLocale();\n try {\n return messageSource.getMessage(key, null, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"No message found for \" + key + \" in the locale \" + locale.getDisplayName());\n return key;\n }\n }\n\n\n /**\n * Get the message using a message source resolvable object\n *\n * @param res instance of the MessageSourceResolvable interface containing the message\n * @return the string message\n */\n public String get(MessageSourceResolvable res) {\n Locale locale = LocaleContextHolder.getLocale();\n try {\n return messageSource.getMessage(res, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"No message found for \" + res.getDefaultMessage() + \" in the locale \" + locale.getDisplayName());\n }\n return res.getDefaultMessage();\n }\n\n\n /**\n * Evaluate a string and replace message keys between ${key} by the message in the resource bundle file\n * @param text the string to be evaluated\n * @return the new evaluated string\n */\n public String eval(String text) {\n Matcher matcher = EXP_PATTERN.matcher(text);\n while (matcher.find()) {\n String s = matcher.group();\n String key = s.substring(2, s.length() - 1);\n\n text = text.replace(s, get(key));\n }\n\n return text;\n }\n\n\n /**\n * Get the message from the given key and process the arguments inside the message\n * @param msg\n * @param args\n * @return\n */\n public String format(String msg, Object... args) {\n Object[] dest = new Object[args.length];\n int index = 0;\n for (Object obj: args) {\n Object obj2 = obj instanceof Date ? dateToDisplay((Date)obj) : obj;\n dest[index++] = obj2;\n }\n\n return MessageFormat.format(msg, dest);\n }\n\n\n /**\n * Convert a date object to a displayable string\n * @param dt the date to be displayed\n * @return\n */\n public String dateToDisplay(Date dt) {\n Locale locale = LocaleContextHolder.getLocale();\n String pattern;\n try {\n pattern = messageSource.getMessage(LOCALE_DISPLAY_DATE_FORMAT, null, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"Date format key in message bunldle not found for key \" + LOCALE_DISPLAY_DATE_FORMAT +\n \" in locale \" + locale.getDisplayName());\n pattern = \"dd-MMM-yyyy\";\n }\n\n SimpleDateFormat format = new SimpleDateFormat(pattern);\n return format.format(dt);\n }\n}" }, { "identifier": "FormException", "path": "src/main/java/org/msh/etbm/commons/forms/FormException.java", "snippet": "public class FormException extends RuntimeException {\n\n public FormException(String message) {\n super(message);\n }\n\n public FormException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "Control", "path": "src/main/java/org/msh/etbm/commons/forms/controls/Control.java", "snippet": "public class Control {\n /**\n * The control ID, unique in the whole form\n */\n private String id;\n\n /**\n * The control type. Each control will have specific features\n */\n private String type;\n\n private JSFuncValue<Boolean> visible;\n\n private JSFuncValue<Boolean> readOnly;\n\n private JSFuncValue<Boolean> disabled;\n\n private Size size;\n\n /**\n * If true, the control will start in a new row\n */\n private boolean newRow;\n\n /**\n * If true, the next control will start in a new row\n */\n private boolean spanRow;\n\n /**\n * If the control contains other controls, probably this method must be overriden\n * @return\n */\n public List<Control> getControls() {\n return null;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public JSFuncValue<Boolean> getVisible() {\n return visible;\n }\n\n public void setVisible(JSFuncValue<Boolean> visible) {\n this.visible = visible;\n }\n\n public JSFuncValue<Boolean> getReadOnly() {\n return readOnly;\n }\n\n public void setReadOnly(JSFuncValue<Boolean> readOnly) {\n this.readOnly = readOnly;\n }\n\n public JSFuncValue<Boolean> getDisabled() {\n return disabled;\n }\n\n public void setDisabled(JSFuncValue<Boolean> disabled) {\n this.disabled = disabled;\n }\n\n public Size getSize() {\n return size;\n }\n\n public void setSize(Size size) {\n this.size = size;\n }\n\n public boolean isNewRow() {\n return newRow;\n }\n\n public void setNewRow(boolean newRow) {\n this.newRow = newRow;\n }\n\n public boolean isSpanRow() {\n return spanRow;\n }\n\n public void setSpanRow(boolean spanRow) {\n this.spanRow = spanRow;\n }\n}" }, { "identifier": "ValuedControl", "path": "src/main/java/org/msh/etbm/commons/forms/controls/ValuedControl.java", "snippet": "public abstract class ValuedControl extends Control {\n\n private String property;\n\n @JsonIgnore\n private Field field;\n\n public Field getField() {\n if (field == null) {\n field = createField();\n }\n return field;\n }\n\n protected abstract Field createField();\n\n public String getProperty() {\n return property;\n }\n\n public void setProperty(String property) {\n this.property = property;\n }\n\n /**\n * Generate a form request to return resources to be used by the control\n * @param doc the document of the form\n * @return\n */\n public FormRequest generateFormRequest(Map<String, Object> doc) {\n return null;\n }\n\n public Object gerValue(Map<String, Object> doc) {\n if (property == null) {\n return null;\n }\n\n if (property.contains(\".\")) {\n throw new FormException(\"nested property not implemented yet: \" + property);\n }\n\n return doc.get(property);\n }\n}" }, { "identifier": "DataModel", "path": "src/main/java/org/msh/etbm/commons/forms/data/DataModel.java", "snippet": "public interface DataModel {\n\n /**\n * Return an instance of the {@link Field} represented by the given field reference.\n * The {@link Field} instance comes from the corresponding {@link org.msh.etbm.commons.models.data.Model}\n * referenced in the data model\n *\n * @param modelManager\n * @param fieldRef\n * @return\n */\n Field getFieldModel(ModelManager modelManager, String fieldRef);\n}" }, { "identifier": "Form", "path": "src/main/java/org/msh/etbm/commons/forms/data/Form.java", "snippet": "public class Form {\n\n private DataModel dataModel;\n\n private List<Control> controls;\n\n private Map<String, JSFuncValue> defaultProperties;\n\n private JSFuncValue<String> title;\n\n private List<Validator> validators;\n\n /**\n * Search for a control by the value being referenced\n * @param value the value reference\n * @return the instance of {@link ValuedControl}, or null if it is not found\n */\n public ValuedControl searchControlByValue(String value) {\n List<Control> controls = getControls();\n\n if (controls == null) {\n return null;\n }\n\n for (Control ctrl: controls) {\n if (ctrl instanceof ValuedControl) {\n if (value.equals(((ValuedControl) ctrl).getProperty())) {\n return (ValuedControl)ctrl;\n }\n }\n }\n\n return null;\n }\n\n /**\n * Return a list of all instances of {@link ValuedControl} found in the form, inclusive\n * child controls inside containers\n *\n * @return\n */\n public List<ValuedControl> collectAllValuedControls() {\n List<ValuedControl> lst = new ArrayList<>();\n\n recursiveControlSearch(getControls(), lst);\n\n return lst;\n }\n\n\n /**\n * Browse the control tree and retrieve all controls of type {@link ValuedControl} inside\n * the given list\n * @param controls\n * @param list\n */\n private void recursiveControlSearch(List<Control> controls, List<ValuedControl> list) {\n for (Control control: controls) {\n if (control instanceof ValuedControl) {\n ValuedControl vc = (ValuedControl)control;\n list.add(vc);\n }\n\n if (control.getControls() != null) {\n recursiveControlSearch(control.getControls(), list);\n }\n }\n }\n\n public List<Control> getControls() {\n return controls;\n }\n\n public void setControls(List<Control> controls) {\n this.controls = controls;\n }\n\n public DataModel getDataModel() {\n return dataModel;\n }\n\n public void setDataModel(DataModel dataModel) {\n this.dataModel = dataModel;\n }\n\n public Map<String, JSFuncValue> getDefaultProperties() {\n return defaultProperties;\n }\n\n public void setDefaultProperties(Map<String, JSFuncValue> defaultProperties) {\n this.defaultProperties = defaultProperties;\n }\n\n public JSFuncValue<String> getTitle() {\n return title;\n }\n\n public void setTitle(JSFuncValue<String> title) {\n this.title = title;\n }\n\n public List<Validator> getValidators() {\n return validators;\n }\n\n public void setValidators(List<Validator> validators) {\n this.validators = validators;\n }\n}" }, { "identifier": "ModelManager", "path": "src/main/java/org/msh/etbm/commons/models/ModelManager.java", "snippet": "@Service\npublic class ModelManager {\n\n @Autowired\n ModelStoreService modelStoreService;\n\n @Autowired\n SchemaUpdateService schemaUpdateService;\n\n\n // A simple local cache of compiled models\n // this local cache will avoid compilation of the model to JS on any call\n private Map<String, CompiledModel> models = new HashMap<>();\n\n public ModelManager(ObjectMapper objectMapper) {\n objectMapper.registerModule(new ModelJacksonModule());\n }\n\n /**\n * Get an instance of the {@link CompiledModel} from the given model ID. The {@link CompiledModel}\n * can be used for validation of a document against the model\n * @param modelId the ID of the model\n * @return\n */\n public CompiledModel getCompiled(String modelId) {\n Model model = modelStoreService.get(modelId);\n\n // check if compiled model is available\n CompiledModel compModel = models.get(modelId);\n\n // check if there is no compiled model or if the compiled model is\n // with a different version of the model from the data store\n if (compModel == null || compModel.getModel().getVersion() != model.getVersion()) {\n compModel = new CompiledModel(model);\n models.put(modelId, compModel);\n }\n\n return compModel;\n }\n\n\n /**\n * Return the list of available models. The list contains the model ID and its name\n * @return List of {@link Item}\n */\n public List<Item<String>> getModels() {\n return modelStoreService.getModels();\n }\n\n /**\n * Return a copy of the model\n * @param modelId the model ID\n * @return the instance of {@link Model}\n */\n public Model get(String modelId) {\n return modelStoreService.get(modelId);\n }\n\n /**\n * Update a model. This operation also updates the table structure, if necessary\n * @param model The model to be updated\n */\n public void update(Model model) {\n Model currentModel = modelStoreService.get(model.getName());\n schemaUpdateService.update(currentModel, model);\n\n modelStoreService.update(model);\n }\n}" }, { "identifier": "Field", "path": "src/main/java/org/msh/etbm/commons/models/data/Field.java", "snippet": "@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = \"type\")\n@JsonTypeIdResolver(FieldTypeResolver.class)\npublic abstract class Field {\n\n /**\n * Field name\n */\n @NotNull\n private String name;\n\n /**\n * The field ID. All fields must have an ID. Is by the ID that the Model engine\n * checks if the field name has changed, on a model update\n */\n @NotNull\n private int id;\n\n /**\n * List of validators of the field\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @Valid\n private List<Validator> validators;\n\n /**\n * Indicate if the field is required or not\n */\n private JSFuncValue<Boolean> required;\n\n /**\n * The description label of the field\n */\n @NotNull\n private String label;\n\n /**\n * The default value, if none is informed to the record\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private JSFuncValue defaultValue;\n\n /**\n * Is a custom field, i.é, not part of the model but created by the user\n */\n private boolean custom;\n\n /**\n * If true, this value must be unique in the column\n */\n @JsonIgnore\n private boolean unique;\n\n /**\n * List of possible values to the field\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private FieldOptions options;\n\n /**\n * A simple java script expression to validate the field. The return of the expression is the\n * message to be displayed, or return null or unassigned to indicate it was validated\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private JSFunction validate;\n\n\n public Field() {\n super();\n }\n\n public Field(String name) {\n super();\n this.name = name;\n }\n\n /**\n * Return the type name uded in the class\n * @return\n */\n @JsonIgnore\n public String getTypeName() {\n FieldType ftype = getClass().getAnnotation(FieldType.class);\n if (ftype == null) {\n throw new ModelException(\"Annotation \" + FieldType.class.getName() + \" not found in class \" + getClass().getName());\n }\n\n return ftype.value();\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 List<Validator> getValidators() {\n return validators;\n }\n\n public void setValidators(List<Validator> validators) {\n this.validators = validators;\n }\n\n public JSFuncValue<Boolean> getRequired() {\n return required;\n }\n\n public void setRequired(JSFuncValue<Boolean> required) {\n this.required = required;\n }\n\n public String getLabel() {\n return label;\n }\n\n public void setLabel(String label) {\n this.label = label;\n }\n\n public JSFuncValue getDefaultValue() {\n return defaultValue;\n }\n\n public void setDefaultValue(JSFuncValue defaultValue) {\n this.defaultValue = defaultValue;\n }\n\n public boolean isCustom() {\n return custom;\n }\n\n public void setCustom(boolean custom) {\n this.custom = custom;\n }\n\n public FieldOptions getOptions() {\n return options;\n }\n\n public void setOptions(FieldOptions options) {\n this.options = options;\n }\n\n public boolean isUnique() {\n return unique;\n }\n\n public void setUnique(boolean unique) {\n this.unique = unique;\n }\n\n public JSFunction getValidate() {\n return validate;\n }\n\n public void setValidate(JSFunction validate) {\n this.validate = validate;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n}" }, { "identifier": "JSFuncValue", "path": "src/main/java/org/msh/etbm/commons/models/data/JSFuncValue.java", "snippet": "public class JSFuncValue<K> {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private K value;\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private String function;\n\n public JSFuncValue(K value) {\n this.value = value;\n }\n\n /**\n * Default constructor\n */\n public JSFuncValue() {\n super();\n }\n\n /**\n * Check if value is available\n * @return true if value is available, or null, if value is null\n */\n @JsonIgnore\n public boolean isValuePresent() {\n return value != null;\n }\n\n @JsonIgnore\n public boolean isExpressionPresent() {\n return function != null;\n }\n\n public K getValue() {\n return value;\n }\n\n public void setValue(K value) {\n this.value = value;\n if (value != null) {\n function = null;\n }\n }\n\n public String getFunction() {\n return function;\n }\n\n public void setFunction(String function) {\n this.function = function;\n if (function != null) {\n value = null;\n }\n }\n\n public static <K> JSFuncValue<K> function(String expr) {\n JSFuncValue<K> p = new JSFuncValue<>();\n p.setFunction(expr);\n return p;\n }\n\n public static <K> JSFuncValue<K> of(K value) {\n return new JSFuncValue<>(value);\n }\n}" }, { "identifier": "Validator", "path": "src/main/java/org/msh/etbm/commons/models/data/Validator.java", "snippet": "public class Validator {\n /**\n * The java script function expression used in validation process\n */\n @NotNull\n private JSFunction rule;\n\n /**\n * The message to be displayed. This one is used if messageKey is not defined\n */\n private String message;\n\n public JSFunction getRule() {\n return rule;\n }\n\n public void setRule(JSFunction rule) {\n this.rule = rule;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "identifier": "ObjectUtils", "path": "src/main/java/org/msh/etbm/commons/objutils/ObjectUtils.java", "snippet": "public class ObjectUtils {\n\n /**\n * Since there are just static methods, avoid others of creating this class\n */\n private ObjectUtils() {\n super();\n }\n\n /**\n * Read the property value of an object\n *\n * @param obj the object to have its property read\n * @param property the property name to read\n * @return the property value, or {@link ObjectAccessException} if any error occurs\n */\n public static Object getProperty(Object obj, String property) {\n try {\n return PropertyUtils.getProperty(obj, property);\n } catch (Exception e) {\n throw new ObjectAccessException(obj, property, \"Error reading property \" + property, e);\n }\n }\n\n /**\n * Set a property value of an object\n *\n * @param obj the object to have its property value set\n * @param property the property name to set its value\n * @param value the value to set\n */\n public static void setProperty(Object obj, String property, Object value) {\n try {\n PropertyUtils.setProperty(obj, property, value);\n } catch (Exception e) {\n throw new ObjectAccessException(obj, property,\n \"Error writing property \" + obj + '.' + property + \" with value \" + value, e);\n }\n }\n\n /**\n * Return property type of the given property in the given object\n *\n * @param obj the object to have its property type returned\n * @param property the name of the property in the object\n * @return the property type\n */\n public static Class getPropertyType(Object obj, String property) {\n try {\n return PropertyUtils.getPropertyType(obj, property);\n } catch (Exception e) {\n throw new ObjectAccessException(obj, property,\n \"Error getting type of property \" + property, e);\n }\n }\n\n /**\n * Create a new instance of a given class. The class must implement a constructor with\n * no arguments, otherwise a {@link ObjectAccessException} will be thrown\n *\n * @param clazz The class to create an instance from\n * @return the object instance of the given class\n */\n public static <E> E newInstance(Class<E> clazz) {\n try {\n return clazz.newInstance();\n } catch (Exception e) {\n throw new ObjectAccessException(\"Error when trying to create an instance of \" + clazz, e);\n }\n }\n\n\n /**\n * Return the generic type assigned to the given class\n *\n * @param clazz the class to get the generic type assigned to\n * @param typeindex the index of the generic type, when there are more than one, but must be 0\n * if there is just one single generic type or you want the first generic type\n * @return the generic class type assigned to the class\n */\n public static Class getGenericType(Class clazz, int typeindex) {\n Type type = clazz.getGenericSuperclass();\n if (type instanceof ParameterizedType) {\n ParameterizedType paramType = (ParameterizedType) type;\n if (paramType.getActualTypeArguments().length > 0) {\n return (Class) paramType.getActualTypeArguments()[typeindex];\n }\n }\n return null;\n }\n\n\n /**\n * Get a class by its name\n *\n * @param className the full qualified class name\n * @return The class\n */\n public static Class forClass(String className) {\n try {\n return Class.forName(className);\n } catch (ClassNotFoundException e) {\n throw new ObjectAccessException(\"Class not found: \" + className, e);\n }\n }\n\n\n /**\n * Generate a hash of the object, hashing every property value using the JDK Objects.hash function\n *\n * @param obj\n * @return\n */\n public static int hash(Object obj) {\n if (obj == null || obj instanceof String || obj instanceof Number || obj instanceof Date ||\n obj instanceof Collection || obj.getClass().isArray()) {\n return Objects.hash(obj);\n }\n\n Map<String, Object> values = describeProperties(obj);\n Object[] vals = new Object[values.size()];\n int index = 0;\n for (Map.Entry<String, Object> prop : values.entrySet()) {\n vals[index] = prop.getValue();\n index++;\n }\n return Objects.hash(vals);\n }\n\n /**\n * Hash an object using the SHA1 hash algorithm\n * @param obj the object to hash\n * @return A string representation of the object hash\n */\n public static String hashSHA1(Object obj) {\n ByteArrayOutputStream baos = null;\n ObjectOutputStream oos = null;\n try {\n try {\n baos = new ByteArrayOutputStream();\n oos = new ObjectOutputStream(baos);\n oos.writeObject(obj);\n MessageDigest md = MessageDigest.getInstance(\"SHA1\");\n byte[] thedigest = md.digest(baos.toByteArray());\n return DatatypeConverter.printHexBinary(thedigest);\n } finally {\n oos.close();\n baos.close();\n }\n } catch (Exception e) {\n throw new ObjectHashException(e);\n }\n }\n\n /**\n * Return a map containing the object property name and its values\n *\n * @param obj\n * @return\n */\n public static Map<String, Object> describeProperties(Object obj) {\n Map<String, Object> values;\n try {\n values = PropertyUtils.describe(obj);\n\n PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(obj);\n\n // remove properties that don't have a get or a set\n for (PropertyDescriptor prop : props) {\n if (prop.getReadMethod() == null || prop.getWriteMethod() == null) {\n values.remove(prop.getName());\n }\n }\n\n } catch (Exception e) {\n throw new ObjectAccessException(\"Error getting object properties\", e);\n }\n\n return values;\n }\n\n /**\n * Convert an array of bytes to an UUID object\n *\n * @param val an array of bytes\n * @return instance of UUID\n */\n public static UUID bytesToUUID(byte[] val) {\n ByteBuffer bb = ByteBuffer.wrap(val);\n long high = bb.getLong();\n long low = bb.getLong();\n return new UUID(high, low);\n }\n\n /**\n * Convert an UUID instance to an array of bytes\n * @param uuid\n * @return\n */\n public static byte[] uuidAsBytes(UUID uuid) {\n ByteBuffer bb = ByteBuffer.wrap(new byte[16]);\n bb.putLong(uuid.getMostSignificantBits());\n bb.putLong(uuid.getLeastSignificantBits());\n return bb.array();\n }\n\n\n /**\n * Return the generic type declared in the field property of the class\n * @param beanClass\n * @param fieldName\n * @param typeIndex\n * @return\n */\n public static Class getPropertyGenericType(Class beanClass, String fieldName, int typeIndex) {\n Field field = findField(beanClass, fieldName);\n\n if (field == null) {\n throw new ObjectAccessException(\"Class field not found: [\" + fieldName + \"] in class \" + beanClass);\n }\n\n return getPropertyGenericType(field, typeIndex);\n }\n\n /**\n * Return the generic type declared in the field instance\n * @param field the field containing the generic type declaration\n * @param typeIndex the declaration order of the generic type (zero is the first)\n * @return the generic type declaration, or null if no generic type is declared\n */\n public static Class getPropertyGenericType(Field field, int typeIndex) {\n Type type = field.getGenericType();\n\n if (!(type instanceof ParameterizedType)) {\n return null;\n }\n\n ParameterizedType ptype = (ParameterizedType)type;\n Type[] typeArgs = ptype.getActualTypeArguments();\n\n return (Class)typeArgs[typeIndex];\n }\n\n /**\n * Search for the instance of the field that declared the property in the given\n * class or its super classes\n * @param beanClass the bean class name\n * @param fieldName the field name to search for\n * @return the instance of Field or null if field is not found\n */\n public static Field findField(Class beanClass, String fieldName) {\n Class clazz = beanClass;\n\n while (clazz != null && clazz != Object.class) {\n Field[] fields = clazz.getDeclaredFields();\n\n for (Field field: fields) {\n if (field.getName().equals(fieldName)) {\n return field;\n }\n }\n\n clazz = clazz.getSuperclass();\n }\n\n return null;\n }\n\n /**\n * Search for a method by its name in the bean class or, if not found, in the super classes\n * @param beanClass the class to search the method\n * @param methodName the method name\n * @return instance of the method from java reflection, or null if not found\n */\n public static Method findMethod(Class beanClass, String methodName) {\n Class clazz = beanClass;\n\n while (clazz != null && clazz != Object.class) {\n Method[] methods = clazz.getDeclaredMethods();\n\n for (Method method: methods) {\n if (method.getName().equals(methodName)) {\n return method;\n }\n }\n\n clazz = clazz.getSuperclass();\n }\n\n return null;\n }\n\n /**\n * Convert a string to an enum value of the given enum class\n * @param value the string representation of the enum value\n * @param enumClass the enum class\n * @param <E>\n * @return the enum value\n */\n public static <E extends Enum> E stringToEnum(String value, Class<E> enumClass) {\n Object[] vals = enumClass.getEnumConstants();\n\n for (Object val: vals) {\n if (val.toString().equals(value)) {\n return (E)val;\n }\n }\n return null;\n }\n\n\n /**\n * Make a shallow copy of the properties of one object to another\n * Source and target objects doesn't have to be of same type, and just shared\n * properties available in target are copied. Properties with the same name must\n * have the same type, otherwise an exception will be thrown\n *\n * @param source the source object\n * @param target the target object that will receive the property values from source\n */\n public static void copyObject(Object source, Object target) {\n Map<String, Object> props = describeProperties(source);\n Map<String, Object> targProps = describeProperties(target);\n\n for (Map.Entry<String, Object> entry: props.entrySet()) {\n String prop = entry.getKey();\n if (targProps.containsKey(prop)) {\n setProperty(target, prop, entry.getValue());\n }\n }\n }\n}" } ]
import com.fasterxml.jackson.annotation.JsonIgnore; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.forms.FormException; import org.msh.etbm.commons.forms.controls.Control; import org.msh.etbm.commons.forms.controls.ValuedControl; import org.msh.etbm.commons.forms.data.DataModel; import org.msh.etbm.commons.forms.data.Form; import org.msh.etbm.commons.models.ModelManager; import org.msh.etbm.commons.models.data.Field; import org.msh.etbm.commons.models.data.JSFuncValue; import org.msh.etbm.commons.models.data.Validator; import org.msh.etbm.commons.objutils.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map;
8,135
package org.msh.etbm.commons.forms.impl; /** * Generate java script code to be sent to the client (browser) with a form schema. * The code generated is wrapped by a function and can be executed with an eval function * in the javascript environment. * * Created by rmemoria on 26/7/16. */ @Service public class JavaScriptFormGenerator { @Autowired Messages messages; @Autowired ModelManager modelManager; /** * Generate the java script code with a form schema to be executed by the browser * @param form the form data, instance of {@link Form} * @param funcName the name of the function to be declared as the entry point function in the script * @return the java script code */
package org.msh.etbm.commons.forms.impl; /** * Generate java script code to be sent to the client (browser) with a form schema. * The code generated is wrapped by a function and can be executed with an eval function * in the javascript environment. * * Created by rmemoria on 26/7/16. */ @Service public class JavaScriptFormGenerator { @Autowired Messages messages; @Autowired ModelManager modelManager; /** * Generate the java script code with a form schema to be executed by the browser * @param form the form data, instance of {@link Form} * @param funcName the name of the function to be declared as the entry point function in the script * @return the java script code */
public String generate(Form form, String funcName) {
5
2023-10-23 13:47:54+00:00
12k
toel--/ocpp-backend-emulator
src/se/toel/ocpp/backendEmulator/Server.java
[ { "identifier": "WebSocket", "path": "src/org/java_websocket/WebSocket.java", "snippet": "public interface WebSocket {\n\n /**\n * sends the closing handshake. may be send in response to an other handshake.\n *\n * @param code the closing code\n * @param message the closing message\n */\n void close(int code, String message);\n\n /**\n * sends the closing handshake. may be send in response to an other handshake.\n *\n * @param code the closing code\n */\n void close(int code);\n\n /**\n * Convenience function which behaves like close(CloseFrame.NORMAL)\n */\n void close();\n\n /**\n * This will close the connection immediately without a proper close handshake. The code and the\n * message therefore won't be transferred over the wire also they will be forwarded to\n * onClose/onWebsocketClose.\n *\n * @param code the closing code\n * @param message the closing message\n **/\n void closeConnection(int code, String message);\n\n /**\n * Send Text data to the other end.\n *\n * @param text the text data to send\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void send(String text);\n\n /**\n * Send Binary data (plain bytes) to the other end.\n *\n * @param bytes the binary data to send\n * @throws IllegalArgumentException the data is null\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void send(ByteBuffer bytes);\n\n /**\n * Send Binary data (plain bytes) to the other end.\n *\n * @param bytes the byte array to send\n * @throws IllegalArgumentException the data is null\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void send(byte[] bytes);\n\n /**\n * Send a frame to the other end\n *\n * @param framedata the frame to send to the other end\n */\n void sendFrame(Framedata framedata);\n\n /**\n * Send a collection of frames to the other end\n *\n * @param frames the frames to send to the other end\n */\n void sendFrame(Collection<Framedata> frames);\n\n /**\n * Send a ping to the other end\n *\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void sendPing();\n\n /**\n * Allows to send continuous/fragmented frames conveniently. <br> For more into on this frame type\n * see http://tools.ietf.org/html/rfc6455#section-5.4<br>\n * <p>\n * If the first frame you send is also the last then it is not a fragmented frame and will\n * received via onMessage instead of onFragmented even though it was send by this method.\n *\n * @param op This is only important for the first frame in the sequence. Opcode.TEXT,\n * Opcode.BINARY are allowed.\n * @param buffer The buffer which contains the payload. It may have no bytes remaining.\n * @param fin true means the current frame is the last in the sequence.\n **/\n void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin);\n\n /**\n * Checks if the websocket has buffered data\n *\n * @return has the websocket buffered data\n */\n boolean hasBufferedData();\n\n /**\n * Returns the address of the endpoint this socket is connected to, or {@code null} if it is\n * unconnected.\n *\n * @return the remote socket address or null, if this socket is unconnected\n */\n InetSocketAddress getRemoteSocketAddress();\n\n /**\n * Returns the address of the endpoint this socket is bound to, or {@code null} if it is not\n * bound.\n *\n * @return the local socket address or null, if this socket is not bound\n */\n InetSocketAddress getLocalSocketAddress();\n\n /**\n * Is the websocket in the state OPEN\n *\n * @return state equals ReadyState.OPEN\n */\n boolean isOpen();\n\n /**\n * Is the websocket in the state CLOSING\n *\n * @return state equals ReadyState.CLOSING\n */\n boolean isClosing();\n\n /**\n * Returns true when no further frames may be submitted<br> This happens before the socket\n * connection is closed.\n *\n * @return true when no further frames may be submitted\n */\n boolean isFlushAndClose();\n\n /**\n * Is the websocket in the state CLOSED\n *\n * @return state equals ReadyState.CLOSED\n */\n boolean isClosed();\n\n /**\n * Getter for the draft\n *\n * @return the used draft\n */\n Draft getDraft();\n\n /**\n * Retrieve the WebSocket 'ReadyState'. This represents the state of the connection. It returns a\n * numerical value, as per W3C WebSockets specs.\n *\n * @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED'\n */\n ReadyState getReadyState();\n\n /**\n * Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2<br>\n * If the opening handshake has not yet happened it will return null.\n *\n * @return Returns the decoded path component of this URI.\n **/\n String getResourceDescriptor();\n\n /**\n * Setter for an attachment on the socket connection. The attachment may be of any type.\n *\n * @param attachment The object to be attached to the user\n * @param <T> The type of the attachment\n * @since 1.3.7\n **/\n <T> void setAttachment(T attachment);\n\n /**\n * Getter for the connection attachment.\n *\n * @param <T> The type of the attachment\n * @return Returns the user attachment\n * @since 1.3.7\n **/\n <T> T getAttachment();\n\n /**\n * Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection\n *\n * @return true, if the websocket does use wss and therefore has a SSLSession\n * @since 1.4.1\n */\n boolean hasSSLSupport();\n\n /**\n * Returns the ssl session of websocket, if ssl/wss is used for this instance.\n *\n * @return the ssl session of this websocket instance\n * @throws IllegalArgumentException the underlying channel does not use ssl (use hasSSLSupport()\n * to check)\n * @since 1.4.1\n */\n SSLSession getSSLSession() throws IllegalArgumentException;\n\n /**\n * Returns the used Sec-WebSocket-Protocol for this websocket connection\n *\n * @return the Sec-WebSocket-Protocol or null, if no draft available\n * @throws IllegalArgumentException the underlying draft does not support a Sec-WebSocket-Protocol\n * @since 1.5.2\n */\n IProtocol getProtocol();\n}" }, { "identifier": "ClientHandshake", "path": "src/org/java_websocket/handshake/ClientHandshake.java", "snippet": "public interface ClientHandshake extends Handshakedata {\n\n /**\n * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2\n *\n * @return the HTTP Request-URI\n */\n String getResourceDescriptor();\n}" }, { "identifier": "WebSocketServer", "path": "src/org/java_websocket/server/WebSocketServer.java", "snippet": "public abstract class WebSocketServer extends AbstractWebSocket implements Runnable {\n\n private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();\n\n /**\n * Logger instance\n *\n * @since 1.4.0\n */\n private final Logger log = LoggerFactory.getLogger(WebSocketServer.class);\n\n /**\n * Holds the list of active WebSocket connections. \"Active\" means WebSocket handshake is complete\n * and socket can be written to, or read from.\n */\n private final Collection<WebSocket> connections;\n /**\n * The port number that this WebSocket server should listen on. Default is\n * WebSocketImpl.DEFAULT_PORT.\n */\n private final InetSocketAddress address;\n /**\n * The socket channel for this WebSocket server.\n */\n private ServerSocketChannel server;\n /**\n * The 'Selector' used to get event keys from the underlying socket.\n */\n private Selector selector;\n /**\n * The Draft of the WebSocket protocol the Server is adhering to.\n */\n private List<Draft> drafts;\n\n private Thread selectorthread;\n\n private final AtomicBoolean isclosed = new AtomicBoolean(false);\n\n protected List<WebSocketWorker> decoders;\n\n private List<WebSocketImpl> iqueue;\n private BlockingQueue<ByteBuffer> buffers;\n private int queueinvokes = 0;\n private final AtomicInteger queuesize = new AtomicInteger(0);\n\n private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory();\n\n /**\n * Attribute which allows you to configure the socket \"backlog\" parameter which determines how\n * many client connections can be queued.\n *\n * @since 1.5.0\n */\n private int maxPendingConnections = -1;\n\n /**\n * Creates a WebSocketServer that will attempt to listen on port <var>WebSocketImpl.DEFAULT_PORT</var>.\n *\n * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here\n */\n public WebSocketServer() {\n this(new InetSocketAddress(WebSocketImpl.DEFAULT_PORT), AVAILABLE_PROCESSORS, null);\n }\n\n /**\n * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>.\n *\n * @param address The address to listen to\n * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here\n */\n public WebSocketServer(InetSocketAddress address) {\n this(address, AVAILABLE_PROCESSORS, null);\n }\n\n /**\n * @param address The address (host:port) this server should listen on.\n * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the\n * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>\n * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here\n */\n public WebSocketServer(InetSocketAddress address, int decodercount) {\n this(address, decodercount, null);\n }\n\n /**\n * @param address The address (host:port) this server should listen on.\n * @param drafts The versions of the WebSocket protocol that this server instance should comply\n * to. Clients that use an other protocol version will be rejected.\n * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here\n */\n public WebSocketServer(InetSocketAddress address, List<Draft> drafts) {\n this(address, AVAILABLE_PROCESSORS, drafts);\n }\n\n /**\n * @param address The address (host:port) this server should listen on.\n * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the\n * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>\n * @param drafts The versions of the WebSocket protocol that this server instance should\n * comply to. Clients that use an other protocol version will be rejected.\n * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here\n */\n public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts) {\n this(address, decodercount, drafts, new HashSet<WebSocket>());\n }\n\n /**\n * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>, and\n * comply with <tt>Draft</tt> version <var>draft</var>.\n *\n * @param address The address (host:port) this server should listen on.\n * @param decodercount The number of {@link WebSocketWorker}s that will be used to process\n * the incoming network data. By default this will be\n * <code>Runtime.getRuntime().availableProcessors()</code>\n * @param drafts The versions of the WebSocket protocol that this server instance\n * should comply to. Clients that use an other protocol version will\n * be rejected.\n * @param connectionscontainer Allows to specify a collection that will be used to store the\n * websockets in. <br> If you plan to often iterate through the\n * currently connected websockets you may want to use a collection\n * that does not require synchronization like a {@link\n * CopyOnWriteArraySet}. In that case make sure that you overload\n * {@link #removeConnection(WebSocket)} and {@link\n * #addConnection(WebSocket)}.<br> By default a {@link HashSet} will\n * be used.\n * @see #removeConnection(WebSocket) for more control over syncronized operation\n * @see <a href=\"https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts\" > more about\n * drafts</a>\n */\n public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts,\n Collection<WebSocket> connectionscontainer) {\n if (address == null || decodercount < 1 || connectionscontainer == null) {\n throw new IllegalArgumentException(\n \"address and connectionscontainer must not be null and you need at least 1 decoder\");\n }\n\n if (drafts == null) {\n this.drafts = Collections.emptyList();\n } else {\n this.drafts = drafts;\n }\n\n this.address = address;\n this.connections = connectionscontainer;\n setTcpNoDelay(false);\n setReuseAddr(false);\n iqueue = new LinkedList<>();\n\n decoders = new ArrayList<>(decodercount);\n buffers = new LinkedBlockingQueue<>();\n for (int i = 0; i < decodercount; i++) {\n WebSocketWorker ex = new WebSocketWorker();\n decoders.add(ex);\n }\n }\n\n\n /**\n * Starts the server selectorthread that binds to the currently set port number and listeners for\n * WebSocket connection requests. Creates a fixed thread pool with the size {@link\n * WebSocketServer#AVAILABLE_PROCESSORS}<br> May only be called once.\n * <p>\n * Alternatively you can call {@link WebSocketServer#run()} directly.\n *\n * @throws IllegalStateException Starting an instance again\n */\n public void start() {\n if (selectorthread != null) {\n throw new IllegalStateException(getClass().getName() + \" can only be started once.\");\n }\n new Thread(this).start();\n }\n\n public void stop(int timeout) throws InterruptedException {\n stop(timeout, \"\");\n }\n\n /**\n * Closes all connected clients sockets, then closes the underlying ServerSocketChannel,\n * effectively killing the server socket selectorthread, freeing the port the server was bound to\n * and stops all internal workerthreads.\n * <p>\n * If this method is called before the server is started it will never start.\n *\n * @param timeout Specifies how many milliseconds the overall close handshaking may take\n * altogether before the connections are closed without proper close\n * handshaking.\n * @param closeMessage Specifies message for remote client<br>\n * @throws InterruptedException Interrupt\n */\n public void stop(int timeout, String closeMessage) throws InterruptedException {\n if (!isclosed.compareAndSet(false,\n true)) { // this also makes sure that no further connections will be added to this.connections\n return;\n }\n\n List<WebSocket> socketsToClose;\n\n // copy the connections in a list (prevent callback deadlocks)\n synchronized (connections) {\n socketsToClose = new ArrayList<>(connections);\n }\n\n for (WebSocket ws : socketsToClose) {\n ws.close(CloseFrame.GOING_AWAY, closeMessage);\n }\n\n wsf.close();\n\n synchronized (this) {\n if (selectorthread != null && selector != null) {\n selector.wakeup();\n selectorthread.join(timeout);\n }\n }\n }\n\n public void stop() throws InterruptedException {\n stop(0);\n }\n\n /**\n * Returns all currently connected clients. This collection does not allow any modification e.g.\n * removing a client.\n *\n * @return A unmodifiable collection of all currently connected clients\n * @since 1.3.8\n */\n @Override\n public Collection<WebSocket> getConnections() {\n synchronized (connections) {\n return Collections.unmodifiableCollection(new ArrayList<>(connections));\n }\n }\n\n public InetSocketAddress getAddress() {\n return this.address;\n }\n\n /**\n * Gets the port number that this server listens on.\n *\n * @return The port number.\n */\n public int getPort() {\n int port = getAddress().getPort();\n if (port == 0 && server != null) {\n port = server.socket().getLocalPort();\n }\n return port;\n }\n\n /**\n * Get the list of active drafts\n *\n * @return the available drafts for this server\n */\n public List<Draft> getDraft() {\n return Collections.unmodifiableList(drafts);\n }\n\n /**\n * Set the requested maximum number of pending connections on the socket. The exact semantics are\n * implementation specific. The value provided should be greater than 0. If it is less than or\n * equal to 0, then an implementation specific default will be used. This option will be passed as\n * \"backlog\" parameter to {@link ServerSocket#bind(SocketAddress, int)}\n *\n * @since 1.5.0\n * @param numberOfConnections the new number of allowed pending connections\n */\n public void setMaxPendingConnections(int numberOfConnections) {\n maxPendingConnections = numberOfConnections;\n }\n\n /**\n * Returns the currently configured maximum number of pending connections.\n *\n * @see #setMaxPendingConnections(int)\n * @since 1.5.0\n * @return the maximum number of pending connections\n */\n public int getMaxPendingConnections() {\n return maxPendingConnections;\n }\n\n // Runnable IMPLEMENTATION /////////////////////////////////////////////////\n public void run() {\n if (!doEnsureSingleThread()) {\n return;\n }\n if (!doSetupSelectorAndServerThread()) {\n return;\n }\n try {\n int shutdownCount = 5;\n int selectTimeout = 0;\n while (!selectorthread.isInterrupted() && shutdownCount != 0) {\n SelectionKey key = null;\n try {\n if (isclosed.get()) {\n selectTimeout = 5;\n }\n int keyCount = selector.select(selectTimeout);\n if (keyCount == 0 && isclosed.get()) {\n shutdownCount--;\n }\n Set<SelectionKey> keys = selector.selectedKeys();\n Iterator<SelectionKey> i = keys.iterator();\n\n while (i.hasNext()) {\n key = i.next();\n\n if (!key.isValid()) {\n continue;\n }\n\n if (key.isAcceptable()) {\n doAccept(key, i);\n continue;\n }\n\n if (key.isReadable() && !doRead(key, i)) {\n continue;\n }\n\n if (key.isWritable()) {\n doWrite(key);\n }\n }\n doAdditionalRead();\n } catch (CancelledKeyException e) {\n // an other thread may cancel the key\n } catch (ClosedByInterruptException e) {\n return; // do the same stuff as when InterruptedException is thrown\n } catch (WrappedIOException ex) {\n handleIOException(key, ex.getConnection(), ex.getIOException());\n } catch (IOException ex) {\n handleIOException(key, null, ex);\n } catch (InterruptedException e) {\n // FIXME controlled shutdown (e.g. take care of buffermanagement)\n Thread.currentThread().interrupt();\n }\n }\n } catch (RuntimeException e) {\n // should hopefully never occur\n handleFatal(null, e);\n } finally {\n doServerShutdown();\n }\n }\n\n /**\n * Do an additional read\n *\n * @throws InterruptedException thrown by taking a buffer\n * @throws IOException if an error happened during read\n */\n private void doAdditionalRead() throws InterruptedException, IOException {\n WebSocketImpl conn;\n while (!iqueue.isEmpty()) {\n conn = iqueue.remove(0);\n WrappedByteChannel c = ((WrappedByteChannel) conn.getChannel());\n ByteBuffer buf = takeBuffer();\n try {\n if (SocketChannelIOHelper.readMore(buf, conn, c)) {\n iqueue.add(conn);\n }\n if (buf.hasRemaining()) {\n conn.inQueue.put(buf);\n queue(conn);\n } else {\n pushBuffer(buf);\n }\n } catch (IOException e) {\n pushBuffer(buf);\n throw e;\n }\n }\n }\n\n /**\n * Execute a accept operation\n *\n * @param key the selectionkey to read off\n * @param i the iterator for the selection keys\n * @throws InterruptedException thrown by taking a buffer\n * @throws IOException if an error happened during accept\n */\n private void doAccept(SelectionKey key, Iterator<SelectionKey> i)\n throws IOException, InterruptedException {\n if (!onConnect(key)) {\n key.cancel();\n return;\n }\n\n SocketChannel channel = server.accept();\n if (channel == null) {\n return;\n }\n channel.configureBlocking(false);\n Socket socket = channel.socket();\n socket.setTcpNoDelay(isTcpNoDelay());\n socket.setKeepAlive(true);\n WebSocketImpl w = wsf.createWebSocket(this, drafts);\n w.setSelectionKey(channel.register(selector, SelectionKey.OP_READ, w));\n try {\n w.setChannel(wsf.wrapChannel(channel, w.getSelectionKey()));\n i.remove();\n allocateBuffers(w);\n } catch (IOException ex) {\n if (w.getSelectionKey() != null) {\n w.getSelectionKey().cancel();\n }\n\n handleIOException(w.getSelectionKey(), null, ex);\n }\n }\n\n /**\n * Execute a read operation\n *\n * @param key the selectionkey to read off\n * @param i the iterator for the selection keys\n * @return true, if the read was successful, or false if there was an error\n * @throws InterruptedException thrown by taking a buffer\n * @throws IOException if an error happened during read\n */\n private boolean doRead(SelectionKey key, Iterator<SelectionKey> i)\n throws InterruptedException, WrappedIOException {\n WebSocketImpl conn = (WebSocketImpl) key.attachment();\n ByteBuffer buf = takeBuffer();\n if (conn.getChannel() == null) {\n key.cancel();\n\n handleIOException(key, conn, new IOException());\n return false;\n }\n try {\n if (SocketChannelIOHelper.read(buf, conn, conn.getChannel())) {\n if (buf.hasRemaining()) {\n conn.inQueue.put(buf);\n queue(conn);\n i.remove();\n if (conn.getChannel() instanceof WrappedByteChannel && ((WrappedByteChannel) conn\n .getChannel()).isNeedRead()) {\n iqueue.add(conn);\n }\n } else {\n pushBuffer(buf);\n }\n } else {\n pushBuffer(buf);\n }\n } catch (IOException e) {\n pushBuffer(buf);\n throw new WrappedIOException(conn, e);\n }\n return true;\n }\n\n /**\n * Execute a write operation\n *\n * @param key the selectionkey to write on\n * @throws IOException if an error happened during batch\n */\n private void doWrite(SelectionKey key) throws WrappedIOException {\n WebSocketImpl conn = (WebSocketImpl) key.attachment();\n try {\n if (SocketChannelIOHelper.batch(conn, conn.getChannel()) && key.isValid()) {\n key.interestOps(SelectionKey.OP_READ);\n }\n } catch (IOException e) {\n throw new WrappedIOException(conn, e);\n }\n }\n\n /**\n * Setup the selector thread as well as basic server settings\n *\n * @return true, if everything was successful, false if some error happened\n */\n private boolean doSetupSelectorAndServerThread() {\n selectorthread.setName(\"WebSocketSelector-\" + selectorthread.getId());\n try {\n server = ServerSocketChannel.open();\n server.configureBlocking(false);\n ServerSocket socket = server.socket();\n socket.setReceiveBufferSize(WebSocketImpl.RCVBUF);\n socket.setReuseAddress(isReuseAddr());\n socket.bind(address, getMaxPendingConnections());\n selector = Selector.open();\n server.register(selector, server.validOps());\n startConnectionLostTimer();\n for (WebSocketWorker ex : decoders) {\n ex.start();\n }\n onStart();\n } catch (IOException ex) {\n handleFatal(null, ex);\n return false;\n }\n return true;\n }\n\n /**\n * The websocket server can only be started once\n *\n * @return true, if the server can be started, false if already a thread is running\n */\n private boolean doEnsureSingleThread() {\n synchronized (this) {\n if (selectorthread != null) {\n throw new IllegalStateException(getClass().getName() + \" can only be started once.\");\n }\n selectorthread = Thread.currentThread();\n if (isclosed.get()) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Clean up everything after a shutdown\n */\n private void doServerShutdown() {\n stopConnectionLostTimer();\n if (decoders != null) {\n for (WebSocketWorker w : decoders) {\n w.interrupt();\n }\n }\n if (selector != null) {\n try {\n selector.close();\n } catch (IOException e) {\n log.error(\"IOException during selector.close\", e);\n onError(null, e);\n }\n }\n if (server != null) {\n try {\n server.close();\n } catch (IOException e) {\n log.error(\"IOException during server.close\", e);\n onError(null, e);\n }\n }\n }\n\n protected void allocateBuffers(WebSocket c) throws InterruptedException {\n if (queuesize.get() >= 2 * decoders.size() + 1) {\n return;\n }\n queuesize.incrementAndGet();\n buffers.put(createBuffer());\n }\n\n protected void releaseBuffers(WebSocket c) throws InterruptedException {\n // queuesize.decrementAndGet();\n // takeBuffer();\n }\n\n public ByteBuffer createBuffer() {\n return ByteBuffer.allocate(WebSocketImpl.RCVBUF);\n }\n\n protected void queue(WebSocketImpl ws) throws InterruptedException {\n if (ws.getWorkerThread() == null) {\n ws.setWorkerThread(decoders.get(queueinvokes % decoders.size()));\n queueinvokes++;\n }\n ws.getWorkerThread().put(ws);\n }\n\n private ByteBuffer takeBuffer() throws InterruptedException {\n return buffers.take();\n }\n\n private void pushBuffer(ByteBuffer buf) throws InterruptedException {\n if (buffers.size() > queuesize.intValue()) {\n return;\n }\n buffers.put(buf);\n }\n\n private void handleIOException(SelectionKey key, WebSocket conn, IOException ex) {\n // onWebsocketError( conn, ex );// conn may be null here\n if (key != null) {\n key.cancel();\n }\n if (conn != null) {\n conn.closeConnection(CloseFrame.ABNORMAL_CLOSE, ex.getMessage());\n } else if (key != null) {\n SelectableChannel channel = key.channel();\n if (channel != null && channel\n .isOpen()) { // this could be the case if the IOException ex is a SSLException\n try {\n channel.close();\n } catch (IOException e) {\n // there is nothing that must be done here\n }\n log.trace(\"Connection closed because of exception\", ex);\n }\n }\n }\n\n private void handleFatal(WebSocket conn, Exception e) {\n log.error(\"Shutdown due to fatal error\", e);\n onError(conn, e);\n\n String causeMessage = e.getCause() != null ? \" caused by \" + e.getCause().getClass().getName() : \"\";\n String errorMessage = \"Got error on server side: \" + e.getClass().getName() + causeMessage;\n try {\n stop(0, errorMessage);\n } catch (InterruptedException e1) {\n Thread.currentThread().interrupt();\n log.error(\"Interrupt during stop\", e);\n onError(null, e1);\n }\n\n //Shutting down WebSocketWorkers, see #222\n if (decoders != null) {\n for (WebSocketWorker w : decoders) {\n w.interrupt();\n }\n }\n if (selectorthread != null) {\n selectorthread.interrupt();\n }\n }\n\n @Override\n public final void onWebsocketMessage(WebSocket conn, String message) {\n onMessage(conn, message);\n }\n\n\n @Override\n public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob) {\n onMessage(conn, blob);\n }\n\n @Override\n public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake) {\n if (addConnection(conn)) {\n onOpen(conn, (ClientHandshake) handshake);\n }\n }\n\n @Override\n public final void onWebsocketClose(WebSocket conn, int code, String reason, boolean remote) {\n selector.wakeup();\n try {\n if (removeConnection(conn)) {\n onClose(conn, code, reason, remote);\n }\n } finally {\n try {\n releaseBuffers(conn);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n }\n\n /**\n * This method performs remove operations on the connection and therefore also gives control over\n * whether the operation shall be synchronized\n * <p>\n * {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a\n * collection which will be used to store current connections in.<br> Depending on the type on the\n * connection, modifications of that collection may have to be synchronized.\n *\n * @param ws The Websocket connection which should be removed\n * @return Removing connection successful\n */\n protected boolean removeConnection(WebSocket ws) {\n boolean removed = false;\n synchronized (connections) {\n if (this.connections.contains(ws)) {\n removed = this.connections.remove(ws);\n } else {\n //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512\n log.trace(\n \"Removing connection which is not in the connections collection! Possible no handshake received! {}\",\n ws);\n }\n }\n if (isclosed.get() && connections.isEmpty()) {\n selectorthread.interrupt();\n }\n return removed;\n }\n\n /**\n * @param ws the Websocket connection which should be added\n * @return Adding connection successful\n * @see #removeConnection(WebSocket)\n */\n protected boolean addConnection(WebSocket ws) {\n if (!isclosed.get()) {\n synchronized (connections) {\n return this.connections.add(ws);\n }\n } else {\n // This case will happen when a new connection gets ready while the server is already stopping.\n ws.close(CloseFrame.GOING_AWAY);\n return true;// for consistency sake we will make sure that both onOpen will be called\n }\n }\n\n @Override\n public final void onWebsocketError(WebSocket conn, Exception ex) {\n onError(conn, ex);\n }\n\n @Override\n public final void onWriteDemand(WebSocket w) {\n WebSocketImpl conn = (WebSocketImpl) w;\n try {\n conn.getSelectionKey().interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);\n } catch (CancelledKeyException e) {\n // the thread which cancels key is responsible for possible cleanup\n conn.outQueue.clear();\n }\n selector.wakeup();\n }\n\n @Override\n public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason) {\n onCloseInitiated(conn, code, reason);\n }\n\n @Override\n public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote) {\n onClosing(conn, code, reason, remote);\n\n }\n\n public void onCloseInitiated(WebSocket conn, int code, String reason) {\n }\n\n public void onClosing(WebSocket conn, int code, String reason, boolean remote) {\n\n }\n\n public final void setWebSocketFactory(WebSocketServerFactory wsf) {\n if (this.wsf != null) {\n this.wsf.close();\n }\n this.wsf = wsf;\n }\n\n public final WebSocketFactory getWebSocketFactory() {\n return wsf;\n }\n\n /**\n * Returns whether a new connection shall be accepted or not.<br> Therefore method is well suited\n * to implement some kind of connection limitation.<br>\n *\n * @param key the SelectionKey for the new connection\n * @return Can this new connection be accepted\n * @see #onOpen(WebSocket, ClientHandshake)\n * @see #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)\n **/\n protected boolean onConnect(SelectionKey key) {\n return true;\n }\n\n /**\n * Getter to return the socket used by this specific connection\n *\n * @param conn The specific connection\n * @return The socket used by this connection\n */\n private Socket getSocket(WebSocket conn) {\n WebSocketImpl impl = (WebSocketImpl) conn;\n return ((SocketChannel) impl.getSelectionKey().channel()).socket();\n }\n\n @Override\n public InetSocketAddress getLocalSocketAddress(WebSocket conn) {\n return (InetSocketAddress) getSocket(conn).getLocalSocketAddress();\n }\n\n @Override\n public InetSocketAddress getRemoteSocketAddress(WebSocket conn) {\n return (InetSocketAddress) getSocket(conn).getRemoteSocketAddress();\n }\n\n /**\n * Called after an opening handshake has been performed and the given websocket is ready to be\n * written on.\n *\n * @param conn The <tt>WebSocket</tt> instance this event is occurring on.\n * @param handshake The handshake of the websocket instance\n */\n public abstract void onOpen(WebSocket conn, ClientHandshake handshake);\n\n /**\n * Called after the websocket connection has been closed.\n *\n * @param conn The <tt>WebSocket</tt> instance this event is occurring on.\n * @param code The codes can be looked up here: {@link CloseFrame}\n * @param reason Additional information string\n * @param remote Returns whether or not the closing of the connection was initiated by the remote\n * host.\n **/\n public abstract void onClose(WebSocket conn, int code, String reason, boolean remote);\n\n /**\n * Callback for string messages received from the remote host\n *\n * @param conn The <tt>WebSocket</tt> instance this event is occurring on.\n * @param message The UTF-8 decoded message that was received.\n * @see #onMessage(WebSocket, ByteBuffer)\n **/\n public abstract void onMessage(WebSocket conn, String message);\n\n /**\n * Called when errors occurs. If an error causes the websocket connection to fail {@link\n * #onClose(WebSocket, int, String, boolean)} will be called additionally.<br> This method will be\n * called primarily because of IO or protocol errors.<br> If the given exception is an\n * RuntimeException that probably means that you encountered a bug.<br>\n *\n * @param conn Can be null if there error does not belong to one specific websocket. For example\n * if the servers port could not be bound.\n * @param ex The exception causing this error\n **/\n public abstract void onError(WebSocket conn, Exception ex);\n\n /**\n * Called when the server started up successfully.\n * <p>\n * If any error occurred, onError is called instead.\n */\n public abstract void onStart();\n\n /**\n * Callback for binary messages received from the remote host\n *\n * @param conn The <tt>WebSocket</tt> instance this event is occurring on.\n * @param message The binary message that was received.\n * @see #onMessage(WebSocket, ByteBuffer)\n **/\n public void onMessage(WebSocket conn, ByteBuffer message) {\n }\n\n /**\n * Send a text to all connected endpoints\n *\n * @param text the text to send to the endpoints\n */\n public void broadcast(String text) {\n broadcast(text, connections);\n }\n\n /**\n * Send a byte array to all connected endpoints\n *\n * @param data the data to send to the endpoints\n */\n public void broadcast(byte[] data) {\n broadcast(data, connections);\n }\n\n /**\n * Send a ByteBuffer to all connected endpoints\n *\n * @param data the data to send to the endpoints\n */\n public void broadcast(ByteBuffer data) {\n broadcast(data, connections);\n }\n\n /**\n * Send a byte array to a specific collection of websocket connections\n *\n * @param data the data to send to the endpoints\n * @param clients a collection of endpoints to whom the text has to be send\n */\n public void broadcast(byte[] data, Collection<WebSocket> clients) {\n if (data == null || clients == null) {\n throw new IllegalArgumentException();\n }\n broadcast(ByteBuffer.wrap(data), clients);\n }\n\n /**\n * Send a ByteBuffer to a specific collection of websocket connections\n *\n * @param data the data to send to the endpoints\n * @param clients a collection of endpoints to whom the text has to be send\n */\n public void broadcast(ByteBuffer data, Collection<WebSocket> clients) {\n if (data == null || clients == null) {\n throw new IllegalArgumentException();\n }\n doBroadcast(data, clients);\n }\n\n /**\n * Send a text to a specific collection of websocket connections\n *\n * @param text the text to send to the endpoints\n * @param clients a collection of endpoints to whom the text has to be send\n */\n public void broadcast(String text, Collection<WebSocket> clients) {\n if (text == null || clients == null) {\n throw new IllegalArgumentException();\n }\n doBroadcast(text, clients);\n }\n\n /**\n * Private method to cache all the frames to improve memory footprint and conversion time\n *\n * @param data the data to broadcast\n * @param clients the clients to send the message to\n */\n private void doBroadcast(Object data, Collection<WebSocket> clients) {\n String strData = null;\n if (data instanceof String) {\n strData = (String) data;\n }\n ByteBuffer byteData = null;\n if (data instanceof ByteBuffer) {\n byteData = (ByteBuffer) data;\n }\n if (strData == null && byteData == null) {\n return;\n }\n Map<Draft, List<Framedata>> draftFrames = new HashMap<>();\n List<WebSocket> clientCopy;\n synchronized (clients) {\n clientCopy = new ArrayList<>(clients);\n }\n for (WebSocket client : clientCopy) {\n if (client != null) {\n Draft draft = client.getDraft();\n fillFrames(draft, draftFrames, strData, byteData);\n try {\n client.sendFrame(draftFrames.get(draft));\n } catch (WebsocketNotConnectedException e) {\n //Ignore this exception in this case\n }\n }\n }\n }\n\n /**\n * Fills the draftFrames with new data for the broadcast\n *\n * @param draft The draft to use\n * @param draftFrames The list of frames per draft to fill\n * @param strData the string data, can be null\n * @param byteData the byte buffer data, can be null\n */\n private void fillFrames(Draft draft, Map<Draft, List<Framedata>> draftFrames, String strData,\n ByteBuffer byteData) {\n if (!draftFrames.containsKey(draft)) {\n List<Framedata> frames = null;\n if (strData != null) {\n frames = draft.createFrames(strData, false);\n }\n if (byteData != null) {\n frames = draft.createFrames(byteData, false);\n }\n if (frames != null) {\n draftFrames.put(draft, frames);\n }\n }\n }\n\n /**\n * This class is used to process incoming data\n */\n public class WebSocketWorker extends Thread {\n\n private BlockingQueue<WebSocketImpl> iqueue;\n\n public WebSocketWorker() {\n iqueue = new LinkedBlockingQueue<>();\n setName(\"WebSocketWorker-\" + getId());\n setUncaughtExceptionHandler(new UncaughtExceptionHandler() {\n @Override\n public void uncaughtException(Thread t, Throwable e) {\n log.error(\"Uncaught exception in thread {}: {}\", t.getName(), e);\n }\n });\n }\n\n public void put(WebSocketImpl ws) throws InterruptedException {\n iqueue.put(ws);\n }\n\n @Override\n public void run() {\n WebSocketImpl ws = null;\n try {\n while (true) {\n ByteBuffer buf;\n ws = iqueue.take();\n buf = ws.inQueue.poll();\n assert (buf != null);\n doDecode(ws, buf);\n ws = null;\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n } catch (VirtualMachineError | ThreadDeath | LinkageError e) {\n log.error(\"Got fatal error in worker thread {}\", getName());\n Exception exception = new Exception(e);\n handleFatal(ws, exception);\n } catch (Throwable e) {\n log.error(\"Uncaught exception in thread {}: {}\", getName(), e);\n if (ws != null) {\n Exception exception = new Exception(e);\n onWebsocketError(ws, exception);\n ws.close();\n }\n }\n }\n\n /**\n * call ws.decode on the byteBuffer\n *\n * @param ws the Websocket\n * @param buf the buffer to decode to\n * @throws InterruptedException thrown by pushBuffer\n */\n private void doDecode(WebSocketImpl ws, ByteBuffer buf) throws InterruptedException {\n try {\n ws.decode(buf);\n } catch (Exception e) {\n log.error(\"Error while reading from remote connection\", e);\n } finally {\n pushBuffer(buf);\n }\n }\n }\n}" } ]
import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import se.toel.util.Dev;
10,717
/* * Server part of the OCPP relay */ package se.toel.ocpp.backendEmulator; /** * * @author toel */ public class Server extends WebSocketServer { /*************************************************************************** * Constants and variables **************************************************************************/ Map<WebSocket, Emulator> connections = new HashMap<>(); private String scenario; /*************************************************************************** * Constructor **************************************************************************/ public Server(int port, String scenario) throws UnknownHostException { super(new InetSocketAddress(port)); this.scenario = scenario; } /*************************************************************************** * Public methods **************************************************************************/ public void shutdown() { for (Map.Entry<WebSocket, Emulator> connection : connections.entrySet()) { connection.getKey().close(); connection.getValue().shutdown(); } try { this.stop(); } catch (Exception e) {} } @Override
/* * Server part of the OCPP relay */ package se.toel.ocpp.backendEmulator; /** * * @author toel */ public class Server extends WebSocketServer { /*************************************************************************** * Constants and variables **************************************************************************/ Map<WebSocket, Emulator> connections = new HashMap<>(); private String scenario; /*************************************************************************** * Constructor **************************************************************************/ public Server(int port, String scenario) throws UnknownHostException { super(new InetSocketAddress(port)); this.scenario = scenario; } /*************************************************************************** * Public methods **************************************************************************/ public void shutdown() { for (Map.Entry<WebSocket, Emulator> connection : connections.entrySet()) { connection.getKey().close(); connection.getValue().shutdown(); } try { this.stop(); } catch (Exception e) {} } @Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
1
2023-10-16 23:10:55+00:00
12k
weibocom/rill-flow
rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/runners/AbstractTaskRunner.java
[ { "identifier": "Mapping", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/mapping/Mapping.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@ToString\n/**\n * 映射规则\n * 1. source 代表源集合以json path表示的值\n * 2. target 代表目标集合以json path表示的key\n *\n * 映射的过程是将 源集合中以source为key的value赋值到目标集合以target为key的值上\n * 如:\n * 集合 input {\"key1\": \"value1\"} context {\"key1\": \"value2\"}\n * 其中规则为:\n * - source: 'key1'\n * target: 'key3'\n *映射结果为:\n * 集合 input {\"key1\": \"value1\"} context {\"key1\": \"value2\", \"key3\": \"value1\"}\n *\n */\npublic class Mapping {\n private String reference;\n private Boolean tolerance;\n private String source;\n private String transform;\n private String target;\n private String variable;\n\n public Mapping(String source, String target) {\n this.source = source;\n this.target = target;\n }\n}" }, { "identifier": "Degrade", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/strategy/Degrade.java", "snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class Degrade {\n private Boolean followings;\n private Boolean current;\n}" }, { "identifier": "Progress", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/strategy/Progress.java", "snippet": "@Setter\n@Getter\npublic class Progress {\n private Integer weight;\n private String calculation;\n private List<Mapping> args;\n\n @JsonCreator\n public Progress(@JsonProperty(\"weight\") Integer weight,\n @JsonProperty(\"calculation\") String calculation,\n @JsonProperty(\"args\") List<Mapping> args) {\n this.weight = weight;\n this.calculation = calculation;\n this.args = args;\n }\n}" }, { "identifier": "DAGWalkHelper", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/helper/DAGWalkHelper.java", "snippet": "@Slf4j\npublic class DAGWalkHelper {\n\n private static final DAGWalkHelper INSTANCE = new DAGWalkHelper();\n\n private DAGWalkHelper() {\n // do nothing\n }\n\n public static DAGWalkHelper getInstance() {\n return INSTANCE;\n }\n\n public Set<TaskInfo> getReadyToRunTasks(Collection<TaskInfo> taskInfos) {\n Set<TaskInfo> readyToRunTasks = taskInfos.stream()\n .filter(taskInfo -> taskInfo != null && taskInfo.getTaskStatus() == TaskStatus.NOT_STARTED)\n .filter(taskInfo -> !taskInfo.getTask().isKeyCallback())\n .filter(taskInfo -> CollectionUtils.isEmpty(taskInfo.getDependencies()) || taskInfo.getDependencies().stream().allMatch(i -> i.getTaskStatus().isSuccessOrSkip()))\n .collect(Collectors.toSet());\n\n if (isKeyMode(taskInfos)) {\n Set<TaskInfo> keyCallbackTasks = taskInfos.stream()\n .filter(taskInfo -> taskInfo != null && taskInfo.getTaskStatus() == TaskStatus.NOT_STARTED)\n .filter(taskInfo -> taskInfo.getTask().isKeyCallback()) // 此类型任务只需前置依赖节点关键路径完成即可执行\n .filter(taskInfo -> CollectionUtils.isEmpty(taskInfo.getDependencies()) || taskInfo.getDependencies().stream().allMatch(i -> i.getTaskStatus().isSuccessOrKeySuccessOrSkip()))\n .collect(Collectors.toSet());\n readyToRunTasks.addAll(keyCallbackTasks);\n }\n\n return readyToRunTasks;\n }\n\n private boolean isKeyMode(Collection<TaskInfo> allTasks) {\n return allTasks.stream().map(TaskInfo::getTaskStatus).anyMatch(TaskStatus::isKeyModeStatus);\n }\n\n public TaskStatus calculateTaskStatus(Collection<TaskInfo> taskInfos) {\n if (CollectionUtils.isEmpty(taskInfos) ||\n taskInfos.stream().allMatch(taskInfo -> taskInfo.getTaskStatus().isSuccessOrSkip())) {\n return TaskStatus.SUCCEED;\n }\n if (taskInfos.stream().anyMatch(taskInfo -> taskInfo.getTaskStatus().isFailed())) {\n return TaskStatus.FAILED;\n }\n\n if (taskInfos.stream()\n .anyMatch(taskInfo -> taskInfo.getTaskStatus() == TaskStatus.RUNNING ||\n taskInfo.getTaskStatus() == TaskStatus.READY)) {\n return TaskStatus.RUNNING;\n }\n\n return TaskStatus.NOT_STARTED;\n }\n\n public TaskStatus calculateParentStatus(TaskInfo parentTask) {\n if (!Objects.equals(parentTask.getTask().getCategory(), TaskCategory.CHOICE.getValue())\n && !Objects.equals(parentTask.getTask().getCategory(), TaskCategory.FOREACH.getValue())) {\n return parentTask.getTaskStatus();\n }\n\n Map<String, TaskStatus> subGroupIndexToStatus = parentTask.getSubGroupIndexToStatus();\n if (MapUtils.isEmpty(subGroupIndexToStatus) ||\n subGroupIndexToStatus.values().stream().allMatch(TaskStatus::isSuccessOrSkip)) {\n return TaskStatus.SUCCEED;\n }\n\n if (isForeachTaskKeySucceed(parentTask)){\n return TaskStatus.KEY_SUCCEED;\n }\n if (subGroupIndexToStatus.values().stream().anyMatch(it -> it == TaskStatus.RUNNING || it == TaskStatus.READY)) {\n return TaskStatus.RUNNING;\n }\n if (subGroupIndexToStatus.values().stream().anyMatch(TaskStatus::isFailed)) {\n return TaskStatus.FAILED;\n }\n\n return parentTask.getTaskStatus();\n }\n\n private boolean isForeachTaskKeySucceed(TaskInfo foreachTaskInfo) {\n Map<String, TaskStatus> subGroupIndexToStatus = foreachTaskInfo.getSubGroupIndexToStatus();\n Map<String, Boolean> subGroupKeyJudgementMapping = foreachTaskInfo.getSubGroupKeyJudgementMapping();\n List<String> keyIdxes = Optional.ofNullable(subGroupKeyJudgementMapping).orElse(new HashMap<>())\n .entrySet().stream()\n .filter(it -> it.getValue().equals(true))\n .map(Map.Entry::getKey)\n .toList();\n boolean keyAllCompleted = keyIdxes.stream()\n .map(subGroupIndexToStatus::get)\n .allMatch(taskStatus -> taskStatus != null && taskStatus.isSuccessOrKeySuccessOrSkip());\n return CollectionUtils.isNotEmpty(keyIdxes) && keyAllCompleted;\n }\n\n public DAGStatus calculateDAGStatus(DAGInfo dagInfo) {\n Collection<TaskInfo> taskInfos = dagInfo.getTasks().values();\n\n List<String> runnableTaskNames = getReadyToRunTasks(taskInfos).stream().map(TaskInfo::getName).toList();\n List<String> runningTaskNames = taskInfos.stream()\n .filter(taskInfo -> taskInfo.getTaskStatus() == TaskStatus.RUNNING || taskInfo.getTaskStatus() == TaskStatus.READY)\n .map(TaskInfo::getName)\n .toList();\n\n if (isKeyMode(taskInfos)\n && CollectionUtils.isEmpty(runnableTaskNames)\n && CollectionUtils.isEmpty(runningTaskNames)\n && taskInfos.stream().noneMatch(taskInfo -> taskInfo.getTaskStatus().isFailed())) {\n return DAGStatus.KEY_SUCCEED;\n }\n\n if (CollectionUtils.isNotEmpty(runnableTaskNames) || CollectionUtils.isNotEmpty(runningTaskNames)) {\n log.info(\"getDAGStatus dag has runnable task {}, running task {}\", runnableTaskNames, runningTaskNames);\n return DAGStatus.RUNNING;\n }\n\n if (taskInfos.stream().anyMatch(taskInfo -> taskInfo.getTaskStatus().isFailed())) {\n return DAGStatus.FAILED;\n }\n\n if (taskInfos.stream().allMatch(taskInfo -> taskInfo.getTaskStatus().isSuccessOrSkip())) {\n return DAGStatus.SUCCEED;\n }\n\n return dagInfo.getDagStatus();\n }\n\n public TaskInfo getTaskInfoByName(DAGInfo dagInfo, String taskName) {\n if (StringUtils.isEmpty(taskName)) {\n return null;\n }\n return getTaskInfoByName(dagInfo.getTasks(), taskName, 1);\n }\n\n private TaskInfo getTaskInfoByName(Map<String, TaskInfo> taskInfos, String taskName, int depth) {\n if (depth > SystemConfig.getTaskMaxDepth()) {\n return null;\n }\n\n TaskInfo result = taskInfos.get(taskName);\n\n if (result == null) {\n result = taskInfos.values().stream()\n .map(TaskInfo::getChildren)\n .filter(MapUtils::isNotEmpty)\n .map(it -> getTaskInfoByName(it, taskName, depth + 1))\n .filter(Objects::nonNull)\n .findAny()\n .orElse(null);\n }\n return result;\n }\n\n public boolean isAncestorTask(String taskInfoName) {\n return !taskInfoName.contains(ReservedConstant.ROUTE_NAME_CONNECTOR);\n }\n\n public String getAncestorTaskName(String taskName) {\n if (StringUtils.isEmpty(taskName)) {\n return taskName;\n }\n return taskName.split(ReservedConstant.ROUTE_NAME_CONNECTOR)[0];\n }\n\n public String getBaseTaskName(TaskInfo taskInfo) {\n return getBaseTaskName(taskInfo.getName());\n }\n\n public String getBaseTaskName(String taskInfoName) {\n if (StringUtils.isEmpty(taskInfoName)) {\n return null;\n }\n\n int index = taskInfoName.lastIndexOf(ReservedConstant.TASK_NAME_CONNECTOR);\n return index < 0 ? taskInfoName : taskInfoName.substring(index + 1);\n }\n\n public String getTaskInfoGroupIndex(String taskInfoName) {\n if (StringUtils.isEmpty(taskInfoName)) {\n return null;\n }\n\n int routeConnectorIndex = taskInfoName.lastIndexOf(ReservedConstant.ROUTE_NAME_CONNECTOR);\n int taskConnectorIndex = taskInfoName.lastIndexOf(ReservedConstant.TASK_NAME_CONNECTOR);\n return routeConnectorIndex < 0 || taskConnectorIndex < 0 ? null : taskInfoName.substring(routeConnectorIndex + 1, taskConnectorIndex);\n }\n\n public String getRootName(String taskInfoName) {\n if (StringUtils.isEmpty(taskInfoName)) {\n return null;\n }\n\n int index = taskInfoName.lastIndexOf(ReservedConstant.TASK_NAME_CONNECTOR);\n return index < 0 ? null : taskInfoName.substring(0, index);\n }\n\n public List<String> taskInfoNamesCurrentChain(String name) {\n List<String> chainNames = Lists.newArrayList();\n for (int i = 0; i < name.length(); i++) {\n if (name.charAt(i) == ReservedConstant.ROUTE_NAME_CONNECTOR.charAt(0)) {\n chainNames.add(name.substring(0, i));\n }\n }\n chainNames.add(name);\n return chainNames;\n }\n\n public String buildTaskInfoRouteName(String parentName, String groupIndex) {\n return parentName == null ? null : parentName + ReservedConstant.ROUTE_NAME_CONNECTOR + groupIndex;\n }\n\n public String buildTaskInfoName(String routeName, String baseTaskName) {\n return baseTaskName == null ? null : Optional.ofNullable(routeName).map(it -> it + ReservedConstant.TASK_NAME_CONNECTOR + baseTaskName).orElse(baseTaskName);\n }\n\n public Set<String> buildSubTaskContextFieldNameInCurrentTask(TaskInfo parentTaskInfo) {\n if (MapUtils.isEmpty(parentTaskInfo.getSubGroupIndexToStatus())) {\n return Sets.newHashSet();\n }\n\n return parentTaskInfo.getSubGroupIndexToStatus().keySet().stream()\n .map(groupIndex -> buildSubTaskContextFieldName(buildTaskInfoRouteName(parentTaskInfo.getName(), groupIndex)))\n .collect(Collectors.toSet());\n }\n\n public Set<String> buildSubTaskContextFieldName(Collection<TaskInfo> taskInfos) {\n return taskInfos.stream()\n .map(taskInfo -> buildSubTaskContextFieldName(taskInfo.getRouteName()))\n .collect(Collectors.toSet());\n }\n\n public String buildSubTaskContextFieldName(String taskInfoRouteName) {\n if (StringUtils.isEmpty(taskInfoRouteName)) {\n return null;\n }\n return ReservedConstant.SUB_CONTEXT_PREFIX + taskInfoRouteName;\n }\n\n public boolean isSubContextFieldName(String fieldName) {\n return fieldName.startsWith(ReservedConstant.SUB_CONTEXT_PREFIX);\n }\n\n public List<TaskInfo> getFailedTasks(DAGInfo dagInfo) {\n return getFailedTasks(1, dagInfo.getTasks());\n }\n\n public List<TaskInfo> getFailedTasks(Map<String, TaskInfo> tasks) {\n return getFailedTasks(1, tasks);\n }\n\n private List<TaskInfo> getFailedTasks(int depth, Map<String, TaskInfo> tasks) {\n List<TaskInfo> failedTasks = Lists.newArrayList();\n if (depth > SystemConfig.getTaskMaxDepth() || MapUtils.isEmpty(tasks)) {\n return failedTasks;\n }\n\n tasks.values().stream()\n .filter(taskInfo -> taskInfo.getTaskStatus() == TaskStatus.FAILED)\n .forEach(failedTasks::add);\n tasks.values().stream()\n .map(TaskInfo::getChildren)\n .filter(MapUtils::isNotEmpty)\n .forEach(it -> failedTasks.addAll(getFailedTasks(depth + 1, it)));\n\n return failedTasks;\n }\n\n public Map<String, List<String>> getDependedResources(DAG dag) {\n Map<String, List<String>> resourceToTaskNameMap = Maps.newHashMap();\n getDependedResources(1, resourceToTaskNameMap, dag.getTasks());\n Optional.ofNullable(dag.getCallbackConfig()).map(CallbackConfig::getResourceName).ifPresent(resourceName -> {\n List<String> names = resourceToTaskNameMap.computeIfAbsent(resourceName, it -> Lists.newArrayList());\n names.add(\"flow_completed_callback\");\n });\n return resourceToTaskNameMap;\n }\n\n private void getDependedResources(int depth, Map<String, List<String>> resourceToTaskNameMap, List<BaseTask> tasks) {\n if (depth > SystemConfig.getTaskMaxDepth() || CollectionUtils.isEmpty(tasks)) {\n return;\n }\n\n tasks.stream()\n .filter(task -> task instanceof FunctionTask)\n .map(task -> (FunctionTask) task)\n .forEach(task -> {\n List<String> taskNames = resourceToTaskNameMap.computeIfAbsent(task.getResourceName(), it -> Lists.newArrayList());\n taskNames.add(task.getName());\n });\n tasks.stream()\n .map(BaseTask::subTasks)\n .filter(CollectionUtils::isNotEmpty)\n .forEach(it -> getDependedResources(depth + 1, resourceToTaskNameMap, it));\n }\n}" }, { "identifier": "LockerKey", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/lock/LockerKey.java", "snippet": "public class LockerKey {\n public static String buildDagInfoLockName(String executionId) {\n return \"lock_dag_info_\" + executionId;\n }\n\n public static String buildTaskInfoLockName(String executionId, String taskInfoName) {\n return \"lock_task_info_\" + executionId + \"_\" + taskInfoName;\n }\n\n public static String getLockId(String instanceId) {\n return instanceId + \":\" + Thread.currentThread().getId();\n }\n\n private LockerKey() {\n\n }\n}" }, { "identifier": "NotifyInfo", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/NotifyInfo.java", "snippet": "@Data\n@Builder\npublic class NotifyInfo {\n private String parentTaskInfoName;\n\n private String taskInfoName;\n\n private List<String> taskInfoNames;\n\n private TaskStatus taskStatus;\n\n private String completedGroupIndex;\n\n private TaskStatus groupTaskStatus;\n\n private TaskInvokeMsg taskInvokeMsg;\n\n private Map<String, TaskInfo> tasks;\n\n private String parentDAGExecutionId;\n\n private String parentDAGTaskInfoName;\n\n private FunctionPattern parentDAGTaskExecutionType;\n\n private RetryContext retryContext;\n\n private CallbackConfig callbackConfig;\n\n private Map<String, Object> ext;\n}" }, { "identifier": "DAGInfo", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/dag/DAGInfo.java", "snippet": "@Getter\n@Setter\npublic class DAGInfo {\n private String executionId;\n private DAG dag;\n private DAGInvokeMsg dagInvokeMsg;\n private DAGStatus dagStatus;\n private Map<String, TaskInfo> tasks = new LinkedHashMap<>();\n\n @Override\n public String toString() {\n return \"DAGInfo{\" +\n \"executionId='\" + executionId + '\\'' +\n \", dag=\" + dag +\n \", dagStatus=\" + dagStatus +\n \", tasks=\" + tasks +\n '}';\n }\n\n public void updateInvokeMsg(DAGInvokeMsg dagInvokeMsg) {\n if (dagInvokeMsg == null || this.dagInvokeMsg == dagInvokeMsg) {\n return;\n }\n\n if (this.dagInvokeMsg == null) {\n this.dagInvokeMsg = dagInvokeMsg;\n } else {\n this.dagInvokeMsg.updateInvokeMsg(dagInvokeMsg);\n }\n }\n\n public void updateInvokeMsg() {\n if (dagInvokeMsg == null) {\n dagInvokeMsg = new DAGInvokeMsg();\n }\n Optional.ofNullable(DAGWalkHelper.getInstance().getFailedTasks(this))\n .filter(CollectionUtils::isNotEmpty)\n .map(it -> it.get(0))\n .map(TaskInfo::getTaskInvokeMsg)\n .ifPresent(failedTaskInvokeMsg -> dagInvokeMsg.updateInvokeMsg(failedTaskInvokeMsg));\n }\n\n public void update(DAGInfo dagInfo) {\n if (dagInfo == null) {\n return;\n }\n\n Optional.ofNullable(dagInfo.getExecutionId()).ifPresent(this::setExecutionId);\n Optional.ofNullable(dagInfo.getDag()).ifPresent(this::setDag);\n Optional.ofNullable(dagInfo.getDagInvokeMsg()).ifPresent(this::setDagInvokeMsg);\n Optional.ofNullable(dagInfo.getDagStatus()).ifPresent(this::setDagStatus);\n if (this.tasks == null) {\n this.tasks = new LinkedHashMap<>();\n }\n Optional.ofNullable(dagInfo.getTasks()).filter(MapUtils::isNotEmpty)\n .ifPresent(taskInfos -> taskInfos.forEach((taskName, taskInfo) -> {\n if (this.tasks.containsKey(taskName)) {\n this.tasks.get(taskName).update(taskInfo);\n } else {\n this.tasks.put(taskName, taskInfo);\n }\n }));\n }\n\n public TaskInfo getTask(String taskName) {\n return tasks.get(taskName);\n }\n\n public void setTask(String taskName, TaskInfo taskInfo) {\n tasks.put(taskName, taskInfo);\n }\n\n public static DAGInfo cloneToSave(DAGInfo dagInfo) {\n if (dagInfo == null) {\n return null;\n }\n\n DAGInfo dagInfoClone = new DAGInfo();\n dagInfoClone.setExecutionId(dagInfo.getExecutionId());\n dagInfoClone.setDag(dagInfo.getDag());\n dagInfoClone.setDagInvokeMsg(DAGInvokeMsg.cloneToSave(dagInfo.getDagInvokeMsg()));\n dagInfoClone.setDagStatus(dagInfo.getDagStatus());\n Map<String, TaskInfo> tasks = new LinkedHashMap<>();\n if (MapUtils.isNotEmpty(dagInfo.getTasks())) {\n dagInfo.getTasks().forEach((taskName, taskInfo) -> tasks.put(taskName, TaskInfo.cloneToSave(taskInfo)));\n }\n dagInfoClone.setTasks(tasks);\n return dagInfoClone;\n }\n}" }, { "identifier": "ExecutionResult", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/task/ExecutionResult.java", "snippet": "@Builder\n@Getter\n@Setter\npublic class ExecutionResult {\n private boolean needRetry;\n private int retryIntervalInSeconds;\n private TaskStatus taskStatus;\n private Map<String, Object> context;\n private Map<String, Object> input;\n private TaskInfo taskInfo;\n private DAGInfo dagInfo;\n private List<Pair<Set<TaskInfo>, Map<String, Object>>> subTaskInfosAndContext;\n private String taskNameNeedToTraversal;\n}" }, { "identifier": "ReturnTask", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/task/ReturnTask.java", "snippet": "@Getter\n@Setter\n@JsonTypeName(\"return\")\npublic class ReturnTask extends BaseTask {\n List<String> conditions;\n\n public ReturnTask(@JsonProperty(\"name\") String name,\n @JsonProperty(\"category\") String category,\n @JsonProperty(\"next\") String next,\n @JsonProperty(\"inputMappings\") List<Mapping> inputMappings,\n @JsonProperty(\"outputMappings\") List<Mapping> outputMappings,\n @JsonProperty(\"conditions\") List<String> conditions,\n @JsonProperty(\"progress\") Progress progress,\n @JsonProperty(\"degrade\") Degrade degrade,\n @JsonProperty(\"timeline\") Timeline timeline,\n @JsonProperty(\"isKeyCallback\") boolean isKeyCallback,\n @JsonProperty(\"keyExp\") String keyExp,\n @JsonProperty(\"parameters\") Map<String, Object> parameters) {\n super(name, category, next, false, inputMappings, outputMappings, progress, degrade, timeline, isKeyCallback, keyExp, parameters);\n Optional.ofNullable(timeline).ifPresent(it -> it.setTimeoutInSeconds(null));\n this.conditions = conditions;\n }\n\n @Override\n public List<BaseTask> subTasks() {\n return new ArrayList<>();\n }\n}" }, { "identifier": "DAGContextStorage", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/runtime/DAGContextStorage.java", "snippet": "public interface DAGContextStorage {\n\n void updateContext(String executionId, Map<String, Object> context);\n\n Map<String, Object> getContext(String executionId);\n\n Map<String, Object> getContext(String executionId, Collection<String> fields);\n\n void clearContext(String executionId);\n}" }, { "identifier": "DAGInfoStorage", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/runtime/DAGInfoStorage.java", "snippet": "public interface DAGInfoStorage {\n\n void saveDAGInfo(String executionId, DAGInfo dagInfo);\n\n void saveTaskInfos(String executionId, Set<TaskInfo> taskInfos);\n\n DAGInfo getDAGInfo(String executionId);\n\n /**\n * 获取dag基础信息(不返回子任务)\n */\n DAGInfo getBasicDAGInfo(String executionId);\n\n /**\n * 获取taskInfo基础信息(不返回子任务)\n */\n TaskInfo getBasicTaskInfo(String executionId, String taskName);\n\n /**\n * 获取当前任务及其子任务\n */\n TaskInfo getTaskInfo(String executionId, String taskName);\n\n TaskInfo getParentTaskInfoWithSibling(String executionId, String taskName);\n\n void clearDAGInfo(String executionId);\n\n void clearDAGInfo(String executionId, int expireTimeInSecond);\n\n public DAG getDAGDescriptor(String executionId);\n\n public void updateDAGDescriptor(String executionId, DAG dag);\n}" }, { "identifier": "DAGStorageProcedure", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/runtime/DAGStorageProcedure.java", "snippet": "public interface DAGStorageProcedure {\n void lockAndRun(String lockName, Runnable runnable);\n}" }, { "identifier": "SwitcherManager", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/switcher/SwitcherManager.java", "snippet": "public interface SwitcherManager {\n boolean getSwitcherState(String switcher);\n}" }, { "identifier": "TraversalErrorCode", "path": "rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/constant/TraversalErrorCode.java", "snippet": "public enum TraversalErrorCode {\n\n DAG_ILLEGAL_STATE(1, \"dag illegal state.\"),\n DAG_NOT_FOUND(2, \"dag not found.\"),\n TRAVERSAL_FAILED(3, \"traversal failed.\"),\n DAG_ALREADY_EXIST(4, \"execution %s is already running.\"),\n DAG_EXECUTION_NOT_FOUND(5, \"execution %s not found.\"),\n OPERATION_UNSUPPORTED(6, \"operation unsupported\")\n ;\n\n private static final int BASE_ERROR_CODE = 30600;\n private final int code;\n private final String message;\n\n TraversalErrorCode(final int code, final String causeMsg) {\n this.code = code;\n this.message = causeMsg;\n }\n\n public int getCode() {\n return BASE_ERROR_CODE + code;\n }\n\n public String getMessage() {\n return message;\n }\n\n}" }, { "identifier": "DAGTraversalException", "path": "rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/exception/DAGTraversalException.java", "snippet": "public class DAGTraversalException extends DAGException {\n\n public DAGTraversalException(int errorCode, String errorMsg) {\n super(errorCode, errorMsg);\n }\n\n public DAGTraversalException(TraversalErrorCode errorCode) {\n super(errorCode.getCode(), errorCode.getMessage());\n }\n\n public DAGTraversalException(TraversalErrorCode errorCode, Throwable cause) {\n super(errorCode.getCode(), errorCode.getMessage(), cause);\n }\n\n public DAGTraversalException(int errorCode, String errorMsg, Throwable cause) {\n super(errorCode, errorMsg, cause);\n }\n\n public DAGTraversalException(int errorCode, Throwable cause) {\n super(errorCode, cause);\n }\n}" }, { "identifier": "ContextHelper", "path": "rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/helper/ContextHelper.java", "snippet": "public class ContextHelper {\n private static final ContextHelper INSTANCE = new ContextHelper();\n\n public static ContextHelper getInstance() {\n return INSTANCE;\n }\n\n @Getter\n @Setter\n private volatile boolean independentContext = true;\n\n @SuppressWarnings(\"unchecked\")\n public Map<String, Object> getContext(DAGContextStorage dagContextStorage, String executionId, TaskInfo taskInfo) {\n Map<String, Object> context;\n if (taskInfo != null && !DAGWalkHelper.getInstance().isAncestorTask(taskInfo.getName())) {\n String filed = DAGWalkHelper.getInstance().buildSubTaskContextFieldName(taskInfo.getRouteName());\n Map<String, Object> subContext = dagContextStorage.getContext(executionId, ImmutableSet.of(filed));\n\n context = Maps.newConcurrentMap();\n context.putAll((Map<String, Object>) subContext.get(filed));\n } else {\n context = dagContextStorage.getContext(executionId);\n }\n\n return Optional.ofNullable(context)\n .orElseThrow(() -> new DAGTraversalException(TraversalErrorCode.TRAVERSAL_FAILED.getCode(), \"context is null\"));\n }\n\n public List<Pair<TaskInfo, Map<String, Object>>> getContext(DAGContextStorage dagContextStorage, String executionId, Set<TaskInfo> taskInfos) {\n Map<String, Object> groupedContext = groupedContextByTaskInfos(dagContextStorage, executionId, taskInfos);\n return getContext(taskInfos, groupedContext);\n }\n\n public List<Pair<TaskInfo, Map<String, Object>>> getContext(Set<TaskInfo> taskInfos, Map<String, Object> groupedContext) {\n Map<String, Object> gContext = Optional.ofNullable(groupedContext).orElse(Maps.newHashMap());\n return independentContext ? getIndependentContext(taskInfos, gContext) : getSharedContext(taskInfos, gContext);\n }\n\n @SuppressWarnings(\"unchecked\")\n private List<Pair<TaskInfo, Map<String, Object>>> getSharedContext(Set<TaskInfo> taskInfos, Map<String, Object> gContext) {\n return taskInfos.stream().map(taskInfo -> {\n Map<String, Object> context;\n if (DAGWalkHelper.getInstance().isAncestorTask(taskInfo.getName())) {\n context = gContext.entrySet().stream()\n .filter(entry -> !DAGWalkHelper.getInstance().isSubContextFieldName(entry.getKey()))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n } else {\n context = Maps.newHashMap();\n String field = DAGWalkHelper.getInstance().buildSubTaskContextFieldName(taskInfo.getRouteName());\n Optional.ofNullable(gContext.get(field)).map(it -> (Map<String, Object>) it).ifPresent(context::putAll);\n }\n return Pair.of(taskInfo, context);\n }).toList();\n }\n\n @SuppressWarnings(\"unchecked\")\n private List<Pair<TaskInfo, Map<String, Object>>> getIndependentContext(Set<TaskInfo> taskInfos, Map<String, Object> gContext) {\n List<TaskInfo> ancestorTasks = Lists.newArrayList();\n Map<String, List<TaskInfo>> fieldToSubTasks = Maps.newHashMap();\n taskInfos.forEach(taskInfo -> {\n if (DAGWalkHelper.getInstance().isAncestorTask(taskInfo.getName())) {\n ancestorTasks.add(taskInfo);\n } else {\n String field = DAGWalkHelper.getInstance().buildSubTaskContextFieldName(taskInfo.getRouteName());\n List<TaskInfo> subTasks = fieldToSubTasks.computeIfAbsent(field, it -> Lists.newArrayList());\n subTasks.add(taskInfo);\n }\n });\n\n List<Pair<TaskInfo, Map<String, Object>>> ret = Lists.newArrayList();\n if (CollectionUtils.isNotEmpty(ancestorTasks)) {\n Map<String, Object> ancestorContext = gContext.entrySet().stream()\n .filter(entry -> !DAGWalkHelper.getInstance().isSubContextFieldName(entry.getKey()))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n ret.addAll(calculateIndependentContext(ancestorTasks, ancestorContext));\n }\n fieldToSubTasks.forEach((field, subTaskInfos) -> {\n Map<String, Object> fieldContext = Maps.newHashMap();\n Optional.ofNullable(gContext.get(field)).map(it -> (Map<String, Object>) it).ifPresent(fieldContext::putAll);\n ret.addAll(calculateIndependentContext(subTaskInfos, fieldContext));\n });\n\n return ret;\n }\n\n @SuppressWarnings(\"unchecked\")\n private List<Pair<TaskInfo, Map<String, Object>>> calculateIndependentContext(List<TaskInfo> tasks, Map<String, Object> sharedContext) {\n if (CollectionUtils.isEmpty(tasks)) {\n return Collections.emptyList();\n }\n\n if (tasks.size() == 1) {\n return tasks.stream().map(taskInfo -> Pair.of(taskInfo, sharedContext)).toList();\n }\n\n byte[] sharedContextBytes = DAGTraversalSerializer.serializeToString(sharedContext).getBytes(StandardCharsets.UTF_8);\n return tasks.stream().map(taskInfo -> {\n Map<String, Object> context = (Map<String, Object>) DAGTraversalSerializer.deserialize(sharedContextBytes, Map.class);\n return Pair.of(taskInfo, context);\n }).toList();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List<Map<String, Object>> getSubContextList(DAGContextStorage dagContextStorage, String executionId, TaskInfo taskInfo) {\n Set<String> subContextFields = DAGWalkHelper.getInstance().buildSubTaskContextFieldNameInCurrentTask(taskInfo);\n if (CollectionUtils.isEmpty(subContextFields)) {\n return Lists.newArrayList();\n }\n\n Map<String, Object> groupedContext = dagContextStorage.getContext(executionId, subContextFields);\n return groupedContext.values().stream().map(context -> (Map<String, Object>) context).toList();\n }\n\n /**\n * 分组获取每种类型的context\n * subTask中routeName相同的对应相同的context\n * 最外层对应一种context\n */\n public Map<String, Object> groupedContextByTaskInfos(DAGContextStorage dagContextStorage, String executionId, Set<TaskInfo> readyToRunTasks) {\n Set<TaskInfo> allTaskInfos = readyToRunTasks.stream().filter(Objects::nonNull).collect(Collectors.toSet());\n Set<TaskInfo> subTaskInfos = allTaskInfos.stream()\n .filter(taskInfo -> !DAGWalkHelper.getInstance().isAncestorTask(taskInfo.getName()))\n .collect(Collectors.toSet());\n\n Map<String, Object> groupedContext = Maps.newHashMap();\n\n if (!subTaskInfos.isEmpty()) {\n groupedContext.putAll(dagContextStorage.getContext(executionId, DAGWalkHelper.getInstance().buildSubTaskContextFieldName(subTaskInfos)));\n }\n\n if (allTaskInfos.size() != subTaskInfos.size()) {\n groupedContext.putAll(dagContextStorage.getContext(executionId));\n }\n\n return groupedContext;\n }\n\n private ContextHelper() {\n\n }\n}" }, { "identifier": "InputOutputMapping", "path": "rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/mappings/InputOutputMapping.java", "snippet": "public interface InputOutputMapping {\n\n /**\n * 输入输出映射\n * 1. inputMappings通过Mappings规则将context中的值映射到input中\n * 2. outputMappings通过Mappings规则将output映射到context中\n */\n void mapping(\n Map<String, Object> context,\n Map<String, Object> input,\n Map<String, Object> output,\n List<Mapping> rules\n );\n}" } ]
import com.google.common.collect.*; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Option; import com.weibo.rill.flow.interfaces.model.mapping.Mapping; import com.weibo.rill.flow.interfaces.model.strategy.Degrade; import com.weibo.rill.flow.interfaces.model.strategy.Progress; import com.weibo.rill.flow.interfaces.model.task.*; import com.weibo.rill.flow.olympicene.core.helper.DAGWalkHelper; import com.weibo.rill.flow.olympicene.core.lock.LockerKey; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInfo; import com.weibo.rill.flow.olympicene.core.model.task.ExecutionResult; import com.weibo.rill.flow.olympicene.core.model.task.ReturnTask; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.traversal.constant.TraversalErrorCode; import com.weibo.rill.flow.olympicene.traversal.exception.DAGTraversalException; import com.weibo.rill.flow.olympicene.traversal.helper.ContextHelper; import com.weibo.rill.flow.olympicene.traversal.mappings.InputOutputMapping; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import java.util.*;
10,553
taskInfo.setChildren(subTasks); return ExecutionResult.builder().taskStatus(taskInfo.getTaskStatus()).build(); } } private void skipCurrentAndFollowingTasks(String executionId, TaskInfo taskInfo) { log.info("skipCurrentAndFollowingTasks executionId:{} taskName:{}", executionId, taskInfo.getName()); taskInfo.setTaskStatus(TaskStatus.SKIPPED); taskInfo.updateInvokeMsg(TaskInvokeMsg.builder().msg(NORMAL_SKIP_MSG).build()); Set<TaskInfo> taskInfosNeedToUpdate = Sets.newHashSet(); skipFollowingTasks(executionId, taskInfo, taskInfosNeedToUpdate); taskInfosNeedToUpdate.add(taskInfo); dagInfoStorage.saveTaskInfos(executionId, taskInfosNeedToUpdate); } /** * normalSkipTask: 因return任务条件满足或降级,导致后续被跳过的任务 */ private boolean needNormalSkip(String executionId, TaskInfo taskInfo) { try { List<TaskInfo> dependentTasks = taskInfo.getDependencies(); return CollectionUtils.isNotEmpty(dependentTasks) && dependentTasks.stream() .allMatch(dependentTask -> { if ((dependentTask.getTask() instanceof ReturnTask) && dependentTask.getTaskStatus() == TaskStatus.SUCCEED) { return true; } if (Optional.ofNullable(dependentTask.getTask()).map(BaseTask::getDegrade).map(Degrade::getFollowings).orElse(false)) { return true; } return dependentTask.getTaskStatus() == TaskStatus.SKIPPED && Optional.ofNullable(dependentTask.getTaskInvokeMsg()).map(TaskInvokeMsg::getMsg).map(NORMAL_SKIP_MSG::equals).orElse(false); }); } catch (Exception e) { log.warn("needSkip fails, executionId:{} taskName:{} errorMsg:{}", executionId, taskInfo.getName(), e.getMessage()); return false; } } private void updateProgressArgs(String executionId, TaskInfo taskInfo, Map<String, Object> input) { try { List<Mapping> args = Optional.ofNullable(taskInfo.getTask()) .map(BaseTask::getProgress) .map(Progress::getArgs) .orElse(null); if (CollectionUtils.isEmpty(args)) { return; } List<Mapping> mappings = args.stream() .map(it -> new Mapping(it.getSource(), "$.output." + it.getVariable())) .toList(); Map<String, Object> output = Maps.newHashMap(); inputMappings(new HashMap<>(), input, output, mappings); taskInfo.getTaskInvokeMsg().setProgressArgs(output); } catch (Exception e) { log.warn("updateProgressArgs fails, executionId:{}, taskName:{}, errorMsg:{}", executionId, taskInfo.getName(), e.getMessage()); } } private long getSuspenseInterval(String executionId, TaskInfo taskInfo, Map<String, Object> input) { try { List<Mapping> timeMappings = Lists.newArrayList(); Optional.ofNullable(taskInfo.getTask()).map(BaseTask::getTimeline).ifPresent(timeline -> { if (StringUtils.isNotBlank(timeline.getSuspenseTimestamp())) { timeMappings.add(new Mapping(timeline.getSuspenseTimestamp(), "$.output.timestamp")); } else if (StringUtils.isNotBlank(timeline.getSuspenseIntervalSeconds())) { timeMappings.add(new Mapping(timeline.getSuspenseIntervalSeconds(), "$.output.interval")); } }); if (CollectionUtils.isEmpty(timeMappings)) { return 0; } Map<String, Object> output = Maps.newHashMap(); inputMappings(new HashMap<>(), input, output, timeMappings); long taskInvokeTime = Optional.ofNullable(output.get("timestamp")).map(String::valueOf).map(Long::valueOf) .orElse(Optional.ofNullable(output.get("interval")) .map(intervalSeconds -> { List<InvokeTimeInfo> invokeTimeInfos = taskInfo.getTaskInvokeMsg().getInvokeTimeInfos(); long taskStartTime = invokeTimeInfos.get(invokeTimeInfos.size() - 1).getStartTimeInMillisecond(); return taskStartTime + Long.parseLong(String.valueOf(intervalSeconds)) * 1000; }).orElse(0L)); return (taskInvokeTime - System.currentTimeMillis()) / 1000; } catch (Exception e) { log.warn("taskNeedSuspense fails, executionId:{}, taskName:{}, errorMsg:{}", executionId, taskInfo.getName(), e.getMessage()); return -1L; } } private void degradeTasks(String executionId, TaskInfo taskInfo) { Set<TaskInfo> skippedTasks = Sets.newHashSet(); Optional.ofNullable(taskInfo.getTask()) .map(BaseTask::getDegrade) .map(Degrade::getFollowings) .filter(it -> it) .ifPresent(it -> { log.info("run degrade strong dependency following tasks, executionId:{}, taskName:{}", executionId, taskInfo.getName()); skipFollowingTasks(executionId, taskInfo, skippedTasks); }); Optional.ofNullable(taskInfo.getTask()) .map(BaseTask::getDegrade) .map(Degrade::getCurrent) .filter(it -> it) .ifPresent(it -> { log.info("run degrade task, executionId:{}, taskName:{}", executionId, taskInfo.getName()); taskInfo.setTaskStatus(TaskStatus.SKIPPED); skippedTasks.add(taskInfo); }); if (CollectionUtils.isNotEmpty(skippedTasks)) { dagInfoStorage.saveTaskInfos(executionId, skippedTasks); } } @Override
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public abstract class AbstractTaskRunner implements TaskRunner { private static final String NORMAL_SKIP_MSG = "skip due to dependent tasks return or degrade"; public static final String EXPECTED_COST = "expected_cost"; protected final Configuration valuePathConf = Configuration.builder() .options(Option.SUPPRESS_EXCEPTIONS) .options(Option.AS_PATH_LIST) .build(); protected final InputOutputMapping inputOutputMapping; protected final DAGInfoStorage dagInfoStorage; protected final DAGContextStorage dagContextStorage; protected final DAGStorageProcedure dagStorageProcedure; protected final SwitcherManager switcherManager; public AbstractTaskRunner(InputOutputMapping inputOutputMapping, DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGStorageProcedure dagStorageProcedure, SwitcherManager switcherManager) { this.inputOutputMapping = inputOutputMapping; this.dagInfoStorage = dagInfoStorage; this.dagContextStorage = dagContextStorage; this.dagStorageProcedure = dagStorageProcedure; this.switcherManager = switcherManager; } protected abstract ExecutionResult doRun(String executionId, TaskInfo taskInfo, Map<String, Object> input); @Override public void inputMappings(Map<String, Object> context, Map<String, Object> input, Map<String, Object> output, List<Mapping> rules) { inputOutputMapping.mapping(context, input, output, rules); } @Override public ExecutionResult run(String executionId, TaskInfo taskInfo, Map<String, Object> context) { try { if (needNormalSkip(executionId, taskInfo)) { skipCurrentAndFollowingTasks(executionId, taskInfo); return ExecutionResult.builder().taskStatus(taskInfo.getTaskStatus()).build(); } updateTaskInvokeStartTime(taskInfo); Map<String, Object> input = inputMappingCalculate(executionId, taskInfo, context); if (switcherManager.getSwitcherState("ENABLE_SET_INPUT_OUTPUT")) { taskInfo.getTaskInvokeMsg().setInput(input); updateTaskExpectedCost(taskInfo, input); } long taskSuspenseTime = getSuspenseInterval(executionId, taskInfo, input); if (taskSuspenseTime > 0) { log.info("task need wait, executionId:{}, taskName:{}, suspenseTime:{}", executionId, taskInfo.getName(), taskSuspenseTime); dagInfoStorage.saveTaskInfos(executionId, Sets.newHashSet(taskInfo)); return ExecutionResult.builder().needRetry(true).retryIntervalInSeconds((int) taskSuspenseTime) .taskStatus(taskInfo.getTaskStatus()).taskInfo(taskInfo).context(context).build(); } degradeTasks(executionId, taskInfo); if (taskInfo.getTaskStatus().isCompleted()) { return ExecutionResult.builder().taskStatus(taskInfo.getTaskStatus()).build(); } updateProgressArgs(executionId, taskInfo, input); ExecutionResult ret = doRun(executionId, taskInfo, input); if (MapUtils.isEmpty(ret.getInput())) { ret.setInput(input); } return ret; } catch (Exception e) { log.warn("run task fails, executionId:{}, taskName:{}", executionId, taskInfo.getName(), e); if (!Optional.ofNullable(taskInfo.getTaskInvokeMsg()).map(TaskInvokeMsg::getMsg).isPresent()) { taskInfo.updateInvokeMsg(TaskInvokeMsg.builder().msg(e.getMessage()).build()); } updateTaskInvokeEndTime(taskInfo); boolean tolerance = Optional.ofNullable(taskInfo.getTask()).map(BaseTask::isTolerance).orElse(false); taskInfo.setTaskStatus(tolerance ? TaskStatus.SKIPPED : TaskStatus.FAILED); Map<String, TaskInfo> subTasks = taskInfo.getChildren(); taskInfo.setChildren(new LinkedHashMap<>()); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); taskInfo.setChildren(subTasks); return ExecutionResult.builder().taskStatus(taskInfo.getTaskStatus()).build(); } } private void skipCurrentAndFollowingTasks(String executionId, TaskInfo taskInfo) { log.info("skipCurrentAndFollowingTasks executionId:{} taskName:{}", executionId, taskInfo.getName()); taskInfo.setTaskStatus(TaskStatus.SKIPPED); taskInfo.updateInvokeMsg(TaskInvokeMsg.builder().msg(NORMAL_SKIP_MSG).build()); Set<TaskInfo> taskInfosNeedToUpdate = Sets.newHashSet(); skipFollowingTasks(executionId, taskInfo, taskInfosNeedToUpdate); taskInfosNeedToUpdate.add(taskInfo); dagInfoStorage.saveTaskInfos(executionId, taskInfosNeedToUpdate); } /** * normalSkipTask: 因return任务条件满足或降级,导致后续被跳过的任务 */ private boolean needNormalSkip(String executionId, TaskInfo taskInfo) { try { List<TaskInfo> dependentTasks = taskInfo.getDependencies(); return CollectionUtils.isNotEmpty(dependentTasks) && dependentTasks.stream() .allMatch(dependentTask -> { if ((dependentTask.getTask() instanceof ReturnTask) && dependentTask.getTaskStatus() == TaskStatus.SUCCEED) { return true; } if (Optional.ofNullable(dependentTask.getTask()).map(BaseTask::getDegrade).map(Degrade::getFollowings).orElse(false)) { return true; } return dependentTask.getTaskStatus() == TaskStatus.SKIPPED && Optional.ofNullable(dependentTask.getTaskInvokeMsg()).map(TaskInvokeMsg::getMsg).map(NORMAL_SKIP_MSG::equals).orElse(false); }); } catch (Exception e) { log.warn("needSkip fails, executionId:{} taskName:{} errorMsg:{}", executionId, taskInfo.getName(), e.getMessage()); return false; } } private void updateProgressArgs(String executionId, TaskInfo taskInfo, Map<String, Object> input) { try { List<Mapping> args = Optional.ofNullable(taskInfo.getTask()) .map(BaseTask::getProgress) .map(Progress::getArgs) .orElse(null); if (CollectionUtils.isEmpty(args)) { return; } List<Mapping> mappings = args.stream() .map(it -> new Mapping(it.getSource(), "$.output." + it.getVariable())) .toList(); Map<String, Object> output = Maps.newHashMap(); inputMappings(new HashMap<>(), input, output, mappings); taskInfo.getTaskInvokeMsg().setProgressArgs(output); } catch (Exception e) { log.warn("updateProgressArgs fails, executionId:{}, taskName:{}, errorMsg:{}", executionId, taskInfo.getName(), e.getMessage()); } } private long getSuspenseInterval(String executionId, TaskInfo taskInfo, Map<String, Object> input) { try { List<Mapping> timeMappings = Lists.newArrayList(); Optional.ofNullable(taskInfo.getTask()).map(BaseTask::getTimeline).ifPresent(timeline -> { if (StringUtils.isNotBlank(timeline.getSuspenseTimestamp())) { timeMappings.add(new Mapping(timeline.getSuspenseTimestamp(), "$.output.timestamp")); } else if (StringUtils.isNotBlank(timeline.getSuspenseIntervalSeconds())) { timeMappings.add(new Mapping(timeline.getSuspenseIntervalSeconds(), "$.output.interval")); } }); if (CollectionUtils.isEmpty(timeMappings)) { return 0; } Map<String, Object> output = Maps.newHashMap(); inputMappings(new HashMap<>(), input, output, timeMappings); long taskInvokeTime = Optional.ofNullable(output.get("timestamp")).map(String::valueOf).map(Long::valueOf) .orElse(Optional.ofNullable(output.get("interval")) .map(intervalSeconds -> { List<InvokeTimeInfo> invokeTimeInfos = taskInfo.getTaskInvokeMsg().getInvokeTimeInfos(); long taskStartTime = invokeTimeInfos.get(invokeTimeInfos.size() - 1).getStartTimeInMillisecond(); return taskStartTime + Long.parseLong(String.valueOf(intervalSeconds)) * 1000; }).orElse(0L)); return (taskInvokeTime - System.currentTimeMillis()) / 1000; } catch (Exception e) { log.warn("taskNeedSuspense fails, executionId:{}, taskName:{}, errorMsg:{}", executionId, taskInfo.getName(), e.getMessage()); return -1L; } } private void degradeTasks(String executionId, TaskInfo taskInfo) { Set<TaskInfo> skippedTasks = Sets.newHashSet(); Optional.ofNullable(taskInfo.getTask()) .map(BaseTask::getDegrade) .map(Degrade::getFollowings) .filter(it -> it) .ifPresent(it -> { log.info("run degrade strong dependency following tasks, executionId:{}, taskName:{}", executionId, taskInfo.getName()); skipFollowingTasks(executionId, taskInfo, skippedTasks); }); Optional.ofNullable(taskInfo.getTask()) .map(BaseTask::getDegrade) .map(Degrade::getCurrent) .filter(it -> it) .ifPresent(it -> { log.info("run degrade task, executionId:{}, taskName:{}", executionId, taskInfo.getName()); taskInfo.setTaskStatus(TaskStatus.SKIPPED); skippedTasks.add(taskInfo); }); if (CollectionUtils.isNotEmpty(skippedTasks)) { dagInfoStorage.saveTaskInfos(executionId, skippedTasks); } } @Override
public ExecutionResult finish(String executionId, NotifyInfo notifyInfo, Map<String, Object> output) {
5
2023-11-03 03:46:01+00:00
12k
aliyun/alibabacloud-compute-nest-saas-boost
boost.serverless/src/main/java/org/example/service/impl/OrderFcServiceImpl.java
[ { "identifier": "BaseAlipayClient", "path": "boost.common/src/main/java/org/example/common/adapter/BaseAlipayClient.java", "snippet": "public interface BaseAlipayClient {\n\n /**\n * Query order.\n * @param outTradeNumber out payment trade number\n * @return AlipayTradeQueryResponse\n */\n AlipayTradeQueryResponse queryOutTrade(String outTradeNumber);\n\n /**\n * Verify if the signature is correct.\n * @param sign signature\n * @param content seller_id...\n * @return boolean\n */\n boolean verifySignature(String sign, String content);\n\n /**\n * Create transaction.\n * @param totalAmount total amount money\n * @param subject payment subject\n * @param outTradeNo out trade number\n * @return String\n */\n String createTransaction(Double totalAmount, String subject, String outTradeNo);\n\n /**\n * Order Refund.\n * @param orderId Order Id\n * @param refundAmount Refund Amount\n * @param refundRequestId Refund Request Id\n * @return {@link Boolean}\n */\n Boolean refundOrder(String orderId, Double refundAmount, String refundRequestId);\n\n /**\n * Close order.\n * @param orderId Order Id\n * @return {@link Boolean}\n */\n Boolean closeOrder(String orderId);\n\n /**\n * Create Alipay Client.\n * @param alipayConfig alipay config\n * @throws Exception Common Exception\n */\n void createClient(AlipayConfig alipayConfig) throws Exception;\n}" }, { "identifier": "ComputeNestSupplierClient", "path": "boost.common/src/main/java/org/example/common/adapter/ComputeNestSupplierClient.java", "snippet": "public interface ComputeNestSupplierClient {\n\n /**\n * List the created instances of the Compute Nest.\n * @param request request\n * @return {@link ListServiceInstancesResponse}\n * @throws Exception exception\n */\n ListServiceInstancesResponse listServiceInstances(ListServiceInstancesRequest request) throws Exception;\n\n /**\n * Get detailed information of a service instance.\n * @param request request\n * @return {@link GetServiceInstanceResponse}\n * @throws Exception exception\n */\n GetServiceInstanceResponse getServiceInstance(GetServiceInstanceRequest request) throws Exception;\n\n /**\n * Create service instance\n * @param request request\n * @return {@link CreateServiceInstanceResponse}\n * @throws Exception bizException\n */\n CreateServiceInstanceResponse createServiceInstance(CreateServiceInstanceRequest request);\n\n /**\n * Continue deploy service instance.\n * @param request request\n * @return {@link ContinueDeployServiceInstanceResponse}\n * @throws Exception exception\n */\n ContinueDeployServiceInstanceResponse continueDeployServiceInstance(ContinueDeployServiceInstanceRequest request);\n\n /**\n * Delete service instance.\n * @param deleteServiceInstancesRequest DeleteServiceInstancesRequest\n * @return DeleteServiceInstancesResponse\n */\n DeleteServiceInstancesResponse deleteServiceInstance(DeleteServiceInstancesRequest deleteServiceInstancesRequest);\n\n /**\n * Create compute nest supplier client by ecs ram role\n * @param aliyunConfig aliyun config\n * @throws Exception Common exception\n */\n void createClient(AliyunConfig aliyunConfig) throws Exception;\n\n /**\n * Create compute nest supplier client by fc header;\n * @param accessKeyId accessKeyId\n * @param accessKeySecret accessKeySecret\n * @param securityToken securityToken\n * @throws Exception Common exception\n */\n void createClient(String accessKeyId, String accessKeySecret, String securityToken) throws Exception;\n\n\n void createClient(String accessKeyId, String accessKeySecret) throws Exception;\n\n /**\n * Get compute nest service info\n * @param request request\n * @return {@link GetServiceResponse}\n */\n GetServiceResponse getService(GetServiceRequest request);\n\n /**\n * Get ROS service template parameter constraints.\n *\n * @param request request\n * @return {@link GetServiceTemplateParameterConstraintsResponse}\n */\n GetServiceTemplateParameterConstraintsResponse getServiceTemplateParameterConstraints(GetServiceTemplateParameterConstraintsRequest request);\n\n /**\n * Update service instance attribute. e.g endTime.\n *\n * @param request request\n * @return {@link GetServiceTemplateParameterConstraintsResponse}\n */\n UpdateServiceInstanceAttributeResponse updateServiceInstanceAttribute(UpdateServiceInstanceAttributeRequest request);\n}" }, { "identifier": "OrderOtsConstant", "path": "boost.common/src/main/java/org/example/common/constant/OrderOtsConstant.java", "snippet": "public interface OrderOtsConstant {\n\n /**\n * OTS table name : order.\n */\n String TABLE_NAME = \"order\";\n\n /**\n * OTS table order primary key name : id.\n */\n String PRIMARY_KEY_NAME = \"id\";\n\n /**\n * OTS search-index name: order_index.\n */\n String SEARCH_INDEX_NAME = \"order_index\";\n\n /**\n * Range filter on search-index: gmtCreateLong(order creation time).\n */\n String GMT_CREATE_LONG = \"gmtCreateLong\";\n\n String BILLING_END_DATE_MILLIS = \"billingEndDateMillis\";\n\n String SERVICE_INSTANCE_ID = \"serviceInstanceId\";\n\n /**\n * Match filter on search-index: accountId.\n */\n String ACCOUNT_ID = \"accountId\";\n\n String TRADE_STATUS = \"tradeStatus\";\n\n Set<String> MATCH_FILTERS_SET = Collections.unmodifiableSet(new HashSet<String>(){\n {\n add(GMT_CREATE_LONG);\n add(SERVICE_INSTANCE_ID);\n add(ACCOUNT_ID);\n add(TRADE_STATUS);\n }\n });\n\n Set<String> QUERY_FILTERS_SET = Collections.unmodifiableSet(new HashSet<String>(){\n {\n add(GMT_CREATE_LONG);\n add(BILLING_END_DATE_MILLIS);\n }\n });\n}" }, { "identifier": "TradeStatus", "path": "boost.common/src/main/java/org/example/common/constant/TradeStatus.java", "snippet": "public enum TradeStatus {\n\n /**\n * The actions associated with this status are as follows:\n * 1. Unpaid transaction timeout closure\n * 2. full refund after payment is completed\n */\n TRADE_CLOSED(\"交易关闭\"),\n\n /**\n * Transaction payment successfully completed.\n */\n TRADE_SUCCESS(\"支付成功\"),\n\n /**\n * Transaction created, waiting for buyer's payment.\n */\n WAIT_BUYER_PAY(\"交易创建\"),\n\n /**\n * Transaction ended, non-refundable.\n */\n TRADE_FINISHED( \"交易完结\"),\n\n /**\n * Refunded.\n */\n REFUNDED(\"已经退款\"),\n\n /**\n * Refund in progress, awaiting processing by Function Compute.\n */\n REFUNDING(\"退款中\");\n\n private final String displayName;\n\n TradeStatus(String displayName) {\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n @Override\n public String toString() {\n return name();\n }\n}" }, { "identifier": "OrderDO", "path": "boost.common/src/main/java/org/example/common/dataobject/OrderDO.java", "snippet": "@Data\npublic class OrderDO {\n\n /**\n * Primary key : Id.\n */\n private String id;\n\n /**\n * The Order ID, which corresponds to the Alipay Out Transaction Number.\n */\n private String orderId;\n\n /**\n * Alipay transaction number.\n */\n private String tradeNo;\n\n /**\n * User Id. corresponds to the aliyun uid.\n */\n private Long userId;\n\n /**\n * Account Id. corresponds to the aliyun aid.\n */\n private Long accountId;\n\n /**\n * Transaction status.\n */\n private TradeStatus tradeStatus;\n\n /**\n * Transaction creation time.\n */\n private String gmtCreate;\n\n /**\n * Transaction creation time in long timestamp format.\n */\n private Long gmtCreateLong;\n\n /**\n * Transaction payment time.\n */\n private String gmtPayment;\n\n /**\n * Buyer payment amount.\n */\n private Double buyerPayAmount;\n\n /**\n * Seller received amount.\n */\n private Double receiptAmount;\n\n /**\n * Service name of the purchase, corresponding to Alipay subject.\n */\n private ProductName productName;\n\n /**\n * Total Amount.\n */\n private Double totalAmount;\n\n /**\n * Seller Id.\n */\n private String sellerId;\n\n /**\n * Alipay appid.\n */\n private String appId;\n\n /**\n * Nest service configs.\n */\n private String productComponents;\n\n /**\n * Signature.\n */\n private String sign;\n\n /**\n * Payment type.\n */\n private PaymentType type;\n\n /**\n * Refund ID, can only be created once.\n */\n private String refundId;\n\n /**\n * Refund Date.\n */\n private String refundDate;\n\n /**\n * Refund Amount.\n */\n private Double refundAmount;\n\n /**\n * Compute nest service instance id.\n */\n private String serviceInstanceId;\n\n /**\n * Pay Period.\n */\n private Long payPeriod;\n\n /**\n * Pay Period Unit.\n */\n private PayPeriodUnit payPeriodUnit;\n\n /**\n * Specification Name.\n */\n private String specificationName;\n\n private Long billingStartDateMillis;\n\n private Long billingEndDateMillis;\n}" }, { "identifier": "OrderDTO", "path": "boost.common/src/main/java/org/example/common/dto/OrderDTO.java", "snippet": "@Data\npublic class OrderDTO {\n\n /**\n * The Order ID, which corresponds to the Alipay Out Transaction Number.\n */\n private String orderId;\n\n /**\n * Transaction status.\n */\n private TradeStatus tradeStatus;\n\n /**\n * Transaction creation time.\n */\n private String gmtCreate;\n\n /**\n * Desc:subject\n */\n private ProductName productName;\n\n /**\n * Desc:nest service configs\n */\n private String productComponents;\n\n /**\n * Total Amount.\n */\n private Double totalAmount;\n\n /**\n * Payment type.\n */\n private PaymentType type;\n\n /**\n * Refund ID, can only be created once.\n */\n private String refundId;\n\n /**\n * Refund Date.\n */\n private String refundDate;\n\n /**\n * Refund Amount.\n */\n private Double refundAmount;\n\n /**\n * Compute nest service instance id.\n */\n private String serviceInstanceId;\n\n /**\n * Transaction payment time.\n */\n private String gmtPayment;\n\n /**\n * Pay Period.\n */\n private Long payPeriod;\n\n /**\n * Pay Period Unit.\n */\n private PayPeriodUnit payPeriodUnit;\n\n /**\n * Specification Name.\n */\n private String specificationName;\n\n /**\n * Seller received amount.\n */\n private Double receiptAmount;\n\n /**\n * Account Id. corresponds to the aliyun aid.\n */\n private Long accountId;\n\n private Long billingStartDateMillis;\n\n private Long billingEndDateMillis;\n}" }, { "identifier": "OtsFilter", "path": "boost.common/src/main/java/org/example/common/helper/BaseOtsHelper.java", "snippet": "@Data\n@Builder\npublic static class OtsFilter {\n String key;\n List<Object> values;\n\n public static OtsFilter createMatchFilter(String key, Object value) {\n return OtsFilter.builder().key(key).values(Collections.singletonList(value)).build();\n }\n\n public static OtsFilter createRangeFilter(String key, Object fromValue, Object toValue) {\n return OtsFilter.builder().key(key).values(Arrays.asList(fromValue, toValue)).build();\n }\n\n public static OtsFilter createTermsFilter(String key, List<Object> values) {\n return OtsFilter.builder().key(key).values(values).build();\n }\n}" }, { "identifier": "OrderOtsHelper", "path": "boost.common/src/main/java/org/example/common/helper/OrderOtsHelper.java", "snippet": "@Component\n@Slf4j\npublic class OrderOtsHelper {\n\n @Resource\n private BaseOtsHelper baseOtsHelper;\n\n @Resource\n private WalletHelper walletHelper;\n\n public void createOrder(OrderDO order) {\n PrimaryKey primaryKey = createPrimaryKey(order.getOrderId());\n if (!StringUtils.isEmpty(order.getGmtCreate())) {\n //Default time zone is Shanghai, China.\n order.setGmtCreateLong(DateUtil.parseFromIsO8601DateString(order.getGmtCreate()));\n } else {\n String currentIs08601Time = DateUtil.getCurrentIs08601Time();\n order.setGmtCreate(currentIs08601Time);\n order.setGmtCreateLong(DateUtil.parseFromIsO8601DateString(currentIs08601Time));\n }\n List<Column> columns = OtsUtil.convertToColumnList(order);\n baseOtsHelper.createEntity(OrderOtsConstant.TABLE_NAME, primaryKey, columns);\n }\n\n public Boolean updateOrder(OrderDO orderDO) {\n PrimaryKey primaryKey = createPrimaryKey(orderDO.getOrderId());\n if (!StringUtils.isEmpty(orderDO.getGmtCreate()) && DateUtil.isValidIsO8601DateFormat(orderDO.getGmtCreate())) {\n orderDO.setGmtCreateLong(DateUtil.parseFromIsO8601DateString(orderDO.getGmtCreate()));\n }\n List<Column> columns = OtsUtil.convertToColumnList(orderDO);\n baseOtsHelper.updateEntity(OrderOtsConstant.TABLE_NAME, primaryKey, columns);\n return Boolean.TRUE;\n }\n\n public ListResult<OrderDTO> listOrders(List<OtsFilter> matchFilters, List<OtsFilter> queryFilters, List<OtsFilter> multiMatchFilters, String nextToken, List<Sort.Sorter> sorters) {\n return baseOtsHelper.listEntities(OrderOtsConstant.TABLE_NAME, OrderOtsConstant.SEARCH_INDEX_NAME, matchFilters, queryFilters, multiMatchFilters, nextToken, sorters, OrderDTO.class);\n }\n\n public OrderDTO getOrder(String orderId, Long accountId) {\n PrimaryKey primaryKey = createPrimaryKey(orderId);\n SingleColumnValueFilter singleColumnValueFilter = null;\n if (accountId != null) {\n singleColumnValueFilter =\n new SingleColumnValueFilter(OrderOtsConstant.ACCOUNT_ID, SingleColumnValueFilter.CompareOperator.EQUAL, ColumnValue.fromLong(accountId));\n singleColumnValueFilter.setPassIfMissing(true);\n singleColumnValueFilter.setLatestVersionsOnly(true);\n }\n return baseOtsHelper.getEntity(OrderOtsConstant.TABLE_NAME, primaryKey, singleColumnValueFilter, OrderDTO.class);\n }\n\n private PrimaryKey createPrimaryKey(String outTradeNo) {\n String outTradeNoMd5PrimaryKey = Md5Util.md5(outTradeNo);\n if (StringUtils.isEmpty(outTradeNoMd5PrimaryKey)) {\n return null;\n }\n return PrimaryKeyBuilder.createPrimaryKeyBuilder()\n .addPrimaryKeyColumn(OrderOtsConstant.PRIMARY_KEY_NAME, PrimaryKeyValue.fromString(outTradeNoMd5PrimaryKey)).build();\n }\n\n public Boolean validateOrderCanBeRefunded(OrderDTO order, Long accountId) {\n if (order != null && !StringUtils.isEmpty(order.getOrderId()) && accountId != null) {\n List<OrderDTO> orderDtoList = listServiceInstanceOrders(order.getServiceInstanceId(), accountId, Boolean.TRUE, TradeStatus.TRADE_SUCCESS);\n if (StringUtils.isNotEmpty(order.getOrderId()) && orderDtoList != null && orderDtoList.size() > 0) {\n return order.getOrderId().equals(orderDtoList.get(0).getOrderId());\n }\n }\n\n throw new IllegalArgumentException(\"Only the latest order is eligible for a refund.\");\n }\n\n public List<OrderDTO> listServiceInstanceOrders(String serviceInstanceId, Long accountId, Boolean reverse, TradeStatus tradeStatus) {\n OtsFilter serviceInstanceIdMatchFilter = OtsFilter.createMatchFilter(OrderOtsConstant.SERVICE_INSTANCE_ID, serviceInstanceId);\n OtsFilter tradeStatusMatchFilter = OtsFilter.createMatchFilter(OrderOtsConstant.TRADE_STATUS, tradeStatus.name());\n OtsFilter accountMatchFilter = OtsFilter.createMatchFilter(OrderOtsConstant.ACCOUNT_ID, accountId);\n FieldSort fieldSort = new FieldSort(OrderOtsConstant.BILLING_END_DATE_MILLIS, reverse ? SortOrder.DESC : SortOrder.ASC);\n\n // Initialize the list to collect all orders\n List<OrderDTO> allOrders = new ArrayList<>();\n String nextToken = null;\n\n do {\n // Fetch the list of orders using the nextToken\n ListResult<OrderDTO> orderDtoListResult = listOrders(\n Arrays.asList(serviceInstanceIdMatchFilter, accountMatchFilter, tradeStatusMatchFilter),\n null, null,\n nextToken,\n Collections.singletonList(fieldSort)\n );\n\n if (orderDtoListResult != null && orderDtoListResult.getData() != null) {\n allOrders.addAll(orderDtoListResult.getData());\n nextToken = orderDtoListResult.getNextToken();\n } else {\n break;\n }\n } while (nextToken != null && nextToken.length()>0);\n return allOrders;\n }\n\n\n public Double refundUnconsumedOrder(OrderDTO order, Boolean dryRun, String refundId, String currentIs08601Time) {\n Double totalAmount = order.getTotalAmount() == null ? order.getReceiptAmount() : order.getTotalAmount();\n if (!dryRun) {\n OrderDO refundOrder = createRefundOrder(order, refundId, totalAmount, currentIs08601Time);\n updateOrder(refundOrder);\n }\n return totalAmount;\n }\n\n public Double refundConsumingOrder(OrderDTO order, Boolean dryRun, String refundId, String currentIs08601Time) {\n // Process logic for orders that are currently being consumed or consumed.\n Double totalAmount = order.getTotalAmount() == null ? order.getReceiptAmount() : order.getTotalAmount();\n Double refundAmount = walletHelper.getRefundAmount(totalAmount, currentIs08601Time, order.getGmtPayment(), order.getPayPeriod(), order.getPayPeriodUnit());\n if (dryRun) {\n return refundAmount;\n }\n OrderDO refundOrder = createRefundOrder(order, refundId, refundAmount, currentIs08601Time);\n updateOrder(refundOrder);\n return refundAmount;\n }\n\n public Double refundPayPostOrder(OrderDTO order, Boolean dryRun, String refundId, String currentIs08601Time) {\n if (dryRun) {\n return null;\n }\n OrderDO refundOrder = createRefundOrder(order, refundId, 0.0, currentIs08601Time);\n updateOrder(refundOrder);\n return 0.0;\n }\n\n public Boolean isOrderInConsuming(OrderDTO orderDTO, Long currentLocalDateTimeMillis) {\n if (orderDTO == null || orderDTO.getBillingStartDateMillis() == null || orderDTO.getBillingEndDateMillis() == null) {\n return Boolean.TRUE;\n }\n return currentLocalDateTimeMillis >= orderDTO.getBillingStartDateMillis() && currentLocalDateTimeMillis < orderDTO.getBillingEndDateMillis();\n }\n\n private OrderDO createRefundOrder(OrderDTO order, String refundId, Double refundAmount, String refundDate) {\n OrderDO refundOrder = new OrderDO();\n BeanUtils.copyProperties(order, refundOrder);\n refundOrder.setRefundId(refundId);\n refundOrder.setRefundAmount(refundAmount);\n refundOrder.setRefundDate(refundDate);\n refundOrder.setTradeStatus(TradeStatus.REFUNDING);\n return refundOrder;\n }\n}" }, { "identifier": "DateUtil", "path": "boost.common/src/main/java/org/example/common/utils/DateUtil.java", "snippet": "public class DateUtil {\n\n public static final String ISO8601_DATE_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n\n private static final String SIMPLE_DATETIME_FORMAT = \"yyyy-MM-dd HH:mm:ss\";\n\n public static final String TIMESTAMP_FORMAT = \"yyyyMMddHHmmssSSS\";\n\n private static final Pattern ISO8601_PATTERN = Pattern.compile(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}Z$\");\n\n private static final Pattern DATE_TIME_PATTERN = Pattern.compile(\"^(\\\\d{4})-(\\\\d{2})-(\\\\d{2})\\\\s(\\\\d{2}):(\\\\d{2}):(\\\\d{2})$\");\n\n private static final ZoneOffset UTC_ZONE_OFFSET = ZoneOffset.UTC;\n\n /**\n * Mapping of Time Formatting Patterns to Formatters\n */\n private static final ConcurrentHashMap<String, DateTimeFormatter> DATE_TIME_FORMATTER_STYLE_MAP = new ConcurrentHashMap<>();\n\n /**\n * Default Time Zone: Shanghai, China\n */\n public static final ZoneId DEFAULT_ZONE_ID = ZoneId.of(\"Asia/Shanghai\");\n\n public static final ZoneId UTC_ZONE_ID = ZoneId.of(\"UTC\");\n\n public static Long parseFromSimpleDateFormat(String simpleDateString){\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(SIMPLE_DATETIME_FORMAT);\n LocalDateTime dateTime = LocalDateTime.parse(simpleDateString, formatter);\n return getUtcEpochMillis(dateTime);\n }\n\n public static Long parseFromSimpleDateFormat(String simpleDateString, String timeZone) {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(SIMPLE_DATETIME_FORMAT);\n LocalDateTime dateTime = LocalDateTime.parse(simpleDateString, formatter);\n ZoneId zoneId = ZoneId.of(timeZone);\n return dateTime.atZone(zoneId).withZoneSameInstant(ZoneOffset.UTC).toInstant().toEpochMilli();\n }\n\n public static Long parseFromIsO8601DateString(String is08601DateString){\n if (is08601DateString == null || is08601DateString.length() == 0) {\n return null;\n }\n DateTimeFormatter formatter = getIsO8601DateFormat(ISO8601_DATE_FORMAT);\n LocalDateTime dateTime = LocalDateTime.parse(is08601DateString, formatter);\n return dateTime.atZone(UTC_ZONE_ID).withZoneSameInstant(DEFAULT_ZONE_ID).toInstant().toEpochMilli();\n }\n\n public static Long getCurrentLocalDateTimeMillis(){\n LocalDateTime currentDate = LocalDateTime.now();\n return getUtcEpochMillis(currentDate);\n }\n\n public static String getCurrentIs08601Time() {\n LocalDateTime localDateTime = LocalDateTime.now();\n LocalDateTime utcDateTime = localDateTime.atZone(DEFAULT_ZONE_ID).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(ISO8601_DATE_FORMAT);\n return formatter.format(utcDateTime);\n }\n\n public static Long getIsO8601FutureDateMillis(String is08601DateString, long days) {\n DateTimeFormatter formatter = getIsO8601DateFormat(ISO8601_DATE_FORMAT);\n LocalDateTime dateTime = LocalDateTime.parse(is08601DateString, formatter);\n LocalDateTime futureDate = dateTime.plusDays(days);\n return futureDate.atZone(UTC_ZONE_ID).withZoneSameInstant(DEFAULT_ZONE_ID).toInstant().toEpochMilli();\n }\n\n public static Long getIsO8601FutureDateMillis(long utcTimestamp, long days) {\n LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(utcTimestamp), UTC_ZONE_ID);\n LocalDateTime futureDate = dateTime.plusDays(days);\n return futureDate.atZone(UTC_ZONE_ID).withZoneSameInstant(DEFAULT_ZONE_ID).toInstant().toEpochMilli();\n }\n\n public static String parseIs08601DateMillis(long utcTimestamp) {\n LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(utcTimestamp), UTC_ZONE_ID);\n return dateTime.format(DateTimeFormatter.ofPattern(ISO8601_DATE_FORMAT));\n }\n\n public static String getCurrentTimePlusMinutes(int minutes) {\n LocalDateTime currentTime = LocalDateTime.now().plusMinutes(minutes);\n return currentTime.format(DateTimeFormatter.ofPattern(SIMPLE_DATETIME_FORMAT));\n }\n\n public static Long getOneYearAgoLocalDateTimeMillis(){\n LocalDateTime currentDate = LocalDateTime.now();\n return getUtcEpochMillis(currentDate.minusYears(1));\n }\n\n private static DateTimeFormatter getIsO8601DateFormat(String pattern) {\n DateTimeFormatter formatter = DATE_TIME_FORMATTER_STYLE_MAP.get(pattern);\n if (formatter == null) {\n formatter = DateTimeFormatter.ofPattern(pattern, Locale.US)\n .withZone(DEFAULT_ZONE_ID);\n DATE_TIME_FORMATTER_STYLE_MAP.put(pattern, formatter);\n }\n return formatter;\n }\n\n public static String simpleDateStringConvertToIso8601Format(String simpleDateString) {\n if (StringUtils.isEmpty(simpleDateString)) {\n return null;\n }\n DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(SIMPLE_DATETIME_FORMAT);\n LocalDateTime dateTime = LocalDateTime.parse(simpleDateString, inputFormatter)\n .atZone(DEFAULT_ZONE_ID)\n .toOffsetDateTime()\n .withOffsetSameInstant(UTC_ZONE_OFFSET)\n .toLocalDateTime();\n\n DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(ISO8601_DATE_FORMAT);\n return dateTime.format(outputFormatter);\n }\n\n public static boolean isValidSimpleDateTimeFormat(String datetime) {\n if (StringUtils.isEmpty(datetime)) {\n return false;\n }\n return DATE_TIME_PATTERN.matcher(datetime).matches();\n }\n\n public static boolean isValidIsO8601DateFormat(String datetime) {\n if (StringUtils.isEmpty(datetime)) {\n return false;\n }\n return ISO8601_PATTERN.matcher(datetime).matches();\n }\n\n public static String getCurrentTimeString() {\n LocalDateTime now = LocalDateTime.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(TIMESTAMP_FORMAT);\n return now.format(formatter);\n }\n\n public static Long getMinutesAgoLocalDateTimeMillis(int minutes) {\n LocalDateTime currentDate = LocalDateTime.now().minusMinutes(minutes);\n return getUtcEpochMillis(currentDate);\n }\n\n public static Long getUtcEpochMillis(LocalDateTime localDateTime) {\n return localDateTime.atZone(DEFAULT_ZONE_ID).withZoneSameInstant(UTC_ZONE_OFFSET)\n .toInstant().toEpochMilli();\n }\n}" }, { "identifier": "OrderProcessor", "path": "boost.serverless/src/main/java/org/example/process/OrderProcessor.java", "snippet": "@Component\n@Slf4j\npublic class OrderProcessor {\n\n @Resource\n private OrderOtsHelper orderOtsHelper;\n\n public void doWhileLoop(List<OtsFilter> queryFilters, List<OtsFilter> rangeFilters, Consumer<OrderDTO> consumer) {\n doWhileLoopInternal(queryFilters, rangeFilters, consumer, null, (order, latch) -> {\n consumer.accept(order);\n });\n }\n\n public void doWhileLoopOfThreadTask(List<OtsFilter> queryFilters, List<OtsFilter> rangeFilters, BiConsumer<OrderDTO, CountDownLatch> consumer) {\n doWhileLoopInternal(queryFilters, rangeFilters, null, consumer, consumer);\n }\n\n private void doWhileLoopInternal(List<OtsFilter> queryFilters, List<OtsFilter> rangeFilters, Consumer<OrderDTO> consumer, BiConsumer<OrderDTO, CountDownLatch> taskConsumer, BiConsumer<OrderDTO, CountDownLatch> latchConsumer) {\n String nextToken = null;\n List<OrderDTO> orders = null;\n\n do {\n ListResult<OrderDTO> result = orderOtsHelper.listOrders(queryFilters, rangeFilters, null, nextToken, null);\n if (result != null && result.getData() != null && !result.getData().isEmpty()) {\n orders = new ArrayList<>(result.getData());\n nextToken = result.getNextToken();\n\n if (!CollectionUtils.isEmpty(orders)) {\n if (taskConsumer != null) {\n CountDownLatch innerLatch = new CountDownLatch(orders.size());\n orders.forEach(order -> {\n taskConsumer.accept(order, innerLatch);\n });\n orders.clear();\n try {\n innerLatch.await(); // 等待所有任务执行完毕\n } catch (InterruptedException e) {\n log.error(\"Interrupted while waiting for tasks to complete.\", e);\n Thread.currentThread().interrupt();\n }\n } else if (consumer != null) {\n orders.forEach(consumer);\n orders.clear();\n }\n } else {\n break;\n }\n }\n } while (!CollectionUtils.isEmpty(orders) || !StringUtils.isEmpty(nextToken));\n }\n}" }, { "identifier": "OrderFcService", "path": "boost.serverless/src/main/java/org/example/service/OrderFcService.java", "snippet": "public interface OrderFcService {\n /**\n * Batch scan table store orders and close timeout orders.\n * @return {@link Future}\n */\n Future<?> closeExpiredOrders();\n\n /**\n * Batch scan table store orders and refunds.\n * @return {@link Future}\n */\n Future<?> refundOrders();\n\n /**\n * Batch scan table store consumed orders and close.\n * @return {@link Future}\n */\n Future<?> closeFinishedOrders();\n}" }, { "identifier": "RefundOrderTask", "path": "boost.serverless/src/main/java/org/example/task/RefundOrderTask.java", "snippet": "@Builder\n@Slf4j\npublic class RefundOrderTask implements Runnable {\n\n private OrderOtsHelper orderOtsHelper;\n\n private BaseAlipayClient baseAlipayClient;\n\n private ComputeNestSupplierClient computeNestSupplierClient;\n\n private String orderId;\n\n private Double refundAmount;\n\n private String refundId;\n\n private String serviceInstanceId;\n\n private ScheduledExecutorService scheduledThreadPool;\n\n private CountDownLatch countDownLatch;\n\n private PaymentType paymentType;\n\n private static final int MAX_RETRY_TIMES = 3;\n\n @Override\n public void run() {\n int retryCount = 0;\n boolean success = false;\n while (retryCount < MAX_RETRY_TIMES && !success) {\n try {\n OrderDO orderDO = new OrderDO();\n orderDO.setTradeStatus(TradeStatus.REFUNDED);\n orderDO.setOrderId(orderId);\n Boolean alipaySuccess = Boolean.TRUE;\n if (paymentType != null && paymentType != PaymentType.PAY_POST && Double.parseDouble(String.format(\"%.2f\", refundAmount)) > 0) {\n alipaySuccess = baseAlipayClient.refundOrder(orderId, Double.parseDouble(String.format(\"%.2f\", refundAmount)), refundId);\n }\n //todo 删除服务实例+更新计算巢endTime\n OrderDTO order = orderOtsHelper.getOrder(orderId, null);\n Long currentLocalDateTimeMillis = DateUtil.getCurrentLocalDateTimeMillis();\n if (shouldDeleteServiceInstance(currentLocalDateTimeMillis, order)) {\n DeleteServiceInstancesRequest deleteServiceInstancesRequest = new DeleteServiceInstancesRequest();\n deleteServiceInstancesRequest.setServiceInstanceId(Collections.singletonList(serviceInstanceId));\n DeleteServiceInstancesResponse deleteServiceInstancesResponse = computeNestSupplierClient.deleteServiceInstance(deleteServiceInstancesRequest);\n log.info(\"Delete service instance status code = {}\", deleteServiceInstancesResponse.getStatusCode());\n }\n Boolean updateOrder = orderOtsHelper.updateOrder(orderDO);\n log.info(\"Alipay refund {}. Update order {}.\", alipaySuccess, updateOrder);\n log.info(\"Order refund success. order id = {}.\", orderDO.getOrderId());\n success = order.getTradeStatus() == TradeStatus.REFUNDED;\n } catch (Exception e) {\n retryCount++;\n log.error(\"Failed to execute code. Retry count: {}\", retryCount, e);\n try {\n Thread.sleep(3000);\n } catch (InterruptedException ex) {\n Thread.currentThread().interrupt();\n }\n } finally {\n countDownLatch.countDown();\n }\n }\n if (!success) {\n log.error(\"Failed to execute refund after multiple retries.\");\n }\n }\n\n\n private Boolean shouldDeleteServiceInstance(Long currentLocalDateTimeMillis, OrderDTO order) {\n if (order.getType() == PaymentType.PAY_POST) {\n return Boolean.TRUE;\n }\n\n if (order.getBillingStartDateMillis() != null && order.getBillingEndDateMillis() != null) {\n return currentLocalDateTimeMillis >= order.getBillingStartDateMillis() && currentLocalDateTimeMillis <= order.getBillingEndDateMillis();\n }\n return Boolean.FALSE;\n }\n}" } ]
import lombok.extern.slf4j.Slf4j; import org.example.common.adapter.BaseAlipayClient; import org.example.common.adapter.ComputeNestSupplierClient; import org.example.common.constant.OrderOtsConstant; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.helper.BaseOtsHelper.OtsFilter; import org.example.common.helper.OrderOtsHelper; import org.example.common.utils.DateUtil; import org.example.process.OrderProcessor; import org.example.service.OrderFcService; import org.example.task.RefundOrderTask; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService;
8,102
/* *Copyright (c) Alibaba Group; *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.example.service.impl; @Service @Slf4j public class OrderFcServiceImpl implements OrderFcService { private OrderOtsHelper orderOtsHelper; private BaseAlipayClient baseAlipayClient; private ComputeNestSupplierClient computeNestSupplierClient; private ScheduledExecutorService scheduledThreadPool; private OrderProcessor orderProcessor; public OrderFcServiceImpl(OrderOtsHelper orderOtsHelper, BaseAlipayClient baseAlipayClient, ComputeNestSupplierClient computeNestSupplierClient, ScheduledExecutorService scheduledThreadPool, OrderProcessor orderProcessor) { this.orderOtsHelper = orderOtsHelper; this.baseAlipayClient = baseAlipayClient; this.computeNestSupplierClient = computeNestSupplierClient; this.scheduledThreadPool = scheduledThreadPool; this.orderProcessor = orderProcessor; } @Override public Future<?> closeExpiredOrders() { return CompletableFuture.runAsync(() -> {
/* *Copyright (c) Alibaba Group; *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.example.service.impl; @Service @Slf4j public class OrderFcServiceImpl implements OrderFcService { private OrderOtsHelper orderOtsHelper; private BaseAlipayClient baseAlipayClient; private ComputeNestSupplierClient computeNestSupplierClient; private ScheduledExecutorService scheduledThreadPool; private OrderProcessor orderProcessor; public OrderFcServiceImpl(OrderOtsHelper orderOtsHelper, BaseAlipayClient baseAlipayClient, ComputeNestSupplierClient computeNestSupplierClient, ScheduledExecutorService scheduledThreadPool, OrderProcessor orderProcessor) { this.orderOtsHelper = orderOtsHelper; this.baseAlipayClient = baseAlipayClient; this.computeNestSupplierClient = computeNestSupplierClient; this.scheduledThreadPool = scheduledThreadPool; this.orderProcessor = orderProcessor; } @Override public Future<?> closeExpiredOrders() { return CompletableFuture.runAsync(() -> {
OtsFilter queryFilter = OtsFilter.createMatchFilter(OrderOtsConstant.TRADE_STATUS, TradeStatus.WAIT_BUYER_PAY.name());
3
2023-11-01 08:19:34+00:00
12k
mioclient/oyvey-ported
src/main/java/me/alpha432/oyvey/features/gui/items/buttons/Button.java
[ { "identifier": "OyVey", "path": "src/main/java/me/alpha432/oyvey/OyVey.java", "snippet": "public class OyVey implements ModInitializer, ClientModInitializer {\n public static final String NAME = \"OyVey\";\n public static final String VERSION = \"0.0.3 - 1.20.1\";\n\n public static float TIMER = 1f;\n\n public static final Logger LOGGER = LogManager.getLogger(\"OyVey\");\n public static ServerManager serverManager;\n public static ColorManager colorManager;\n public static RotationManager rotationManager;\n public static PositionManager positionManager;\n public static HoleManager holeManager;\n public static EventManager eventManager;\n public static SpeedManager speedManager;\n public static CommandManager commandManager;\n public static FriendManager friendManager;\n public static ModuleManager moduleManager;\n public static ConfigManager configManager;\n\n\n @Override public void onInitialize() {\n eventManager = new EventManager();\n serverManager = new ServerManager();\n rotationManager = new RotationManager();\n positionManager = new PositionManager();\n friendManager = new FriendManager();\n colorManager = new ColorManager();\n commandManager = new CommandManager();\n moduleManager = new ModuleManager();\n speedManager = new SpeedManager();\n holeManager = new HoleManager();\n }\n\n\n @Override public void onInitializeClient() {\n eventManager.init();\n moduleManager.init();\n\n configManager = new ConfigManager();\n configManager.load();\n colorManager.init();\n Runtime.getRuntime().addShutdownHook(new Thread(() -> configManager.save()));\n }\n}" }, { "identifier": "Component", "path": "src/main/java/me/alpha432/oyvey/features/gui/Component.java", "snippet": "public class Component\n extends Feature {\n public static int[] counter1 = new int[]{1};\n protected DrawContext context;\n private final List<Item> items = new ArrayList<>();\n public boolean drag;\n private int x;\n private int y;\n private int x2;\n private int y2;\n private int width;\n private int height;\n private boolean open;\n private boolean hidden = false;\n\n public Component(String name, int x, int y, boolean open) {\n super(name);\n this.x = x;\n this.y = y;\n this.width = 88;\n this.height = 18;\n this.open = open;\n this.setupItems();\n }\n\n public void setupItems() {\n }\n\n private void drag(int mouseX, int mouseY) {\n if (!this.drag) {\n return;\n }\n this.x = this.x2 + mouseX;\n this.y = this.y2 + mouseY;\n }\n\n public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {\n this.context = context;\n this.drag(mouseX, mouseY);\n counter1 = new int[]{1};\n float totalItemHeight = this.open ? this.getTotalItemHeight() - 2.0f : 0.0f;\n int color = ColorUtil.toARGB(ClickGui.getInstance().topRed.getValue(), ClickGui.getInstance().topGreen.getValue(), ClickGui.getInstance().topBlue.getValue(), 255);\n context.fill(this.x, this.y - 1, this.x + this.width, this.y + this.height - 6, ClickGui.getInstance().rainbow.getValue() ? ColorUtil.rainbow(ClickGui.getInstance().rainbowHue.getValue()).getRGB() : color);\n if (this.open) {\n RenderUtil.rect(context.getMatrices(), this.x, (float) this.y + 12.5f, this.x + this.width, (float) (this.y + this.height) + totalItemHeight, 0x77000000);\n }\n drawString(this.getName(), (float) this.x + 3.0f, (float) this.y - 4.0f - (float) OyVeyGui.getClickGui().getTextOffset(), -1);\n if (this.open) {\n float y = (float) (this.getY() + this.getHeight()) - 3.0f;\n for (Item item : this.getItems()) {\n Component.counter1[0] = counter1[0] + 1;\n if (item.isHidden()) continue;\n item.setLocation((float) this.x + 2.0f, y);\n item.setWidth(this.getWidth() - 4);\n item.drawScreen(context, mouseX, mouseY, partialTicks);\n y += (float) item.getHeight() + 1.5f;\n }\n }\n }\n\n public void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n if (mouseButton == 0 && this.isHovering(mouseX, mouseY)) {\n this.x2 = this.x - mouseX;\n this.y2 = this.y - mouseY;\n OyVeyGui.getClickGui().getComponents().forEach(component -> {\n if (component.drag) {\n component.drag = false;\n }\n });\n this.drag = true;\n return;\n }\n if (mouseButton == 1 && this.isHovering(mouseX, mouseY)) {\n this.open = !this.open;\n mc.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1f));\n return;\n }\n if (!this.open) {\n return;\n }\n this.getItems().forEach(item -> item.mouseClicked(mouseX, mouseY, mouseButton));\n }\n\n public void mouseReleased(int mouseX, int mouseY, int releaseButton) {\n if (releaseButton == 0) {\n this.drag = false;\n }\n if (!this.open) {\n return;\n }\n this.getItems().forEach(item -> item.mouseReleased(mouseX, mouseY, releaseButton));\n }\n\n public void onKeyTyped(char typedChar, int keyCode) {\n if (!this.open) {\n return;\n }\n this.getItems().forEach(item -> item.onKeyTyped(typedChar, keyCode));\n }\n\n public void onKeyPressed(int key) {\n if (!open) return;\n this.getItems().forEach(item -> item.onKeyPressed(key));\n }\n\n public void addButton(Button button) {\n this.items.add(button);\n }\n\n public int getX() {\n return this.x;\n }\n\n public void setX(int x) {\n this.x = x;\n }\n\n public int getY() {\n return this.y;\n }\n\n public void setY(int y) {\n this.y = y;\n }\n\n public int getWidth() {\n return this.width;\n }\n\n public void setWidth(int width) {\n this.width = width;\n }\n\n public int getHeight() {\n return this.height;\n }\n\n public void setHeight(int height) {\n this.height = height;\n }\n\n public boolean isHidden() {\n return this.hidden;\n }\n\n public void setHidden(boolean hidden) {\n this.hidden = hidden;\n }\n\n public boolean isOpen() {\n return this.open;\n }\n\n public final List<Item> getItems() {\n return this.items;\n }\n\n private boolean isHovering(int mouseX, int mouseY) {\n return mouseX >= this.getX() && mouseX <= this.getX() + this.getWidth() && mouseY >= this.getY() && mouseY <= this.getY() + this.getHeight() - (this.open ? 2 : 0);\n }\n\n private float getTotalItemHeight() {\n float height = 0.0f;\n for (Item item : this.getItems()) {\n height += (float) item.getHeight() + 1.5f;\n }\n return height;\n }\n\n protected void drawString(String text, double x, double y, Color color) {\n drawString(text, x, y, color.hashCode());\n }\n\n protected void drawString(String text, double x, double y, int color) {\n context.drawTextWithShadow(mc.textRenderer, text, (int) x, (int) y, color);\n }\n}" }, { "identifier": "OyVeyGui", "path": "src/main/java/me/alpha432/oyvey/features/gui/OyVeyGui.java", "snippet": "public class OyVeyGui extends Screen {\n private static OyVeyGui oyveyGui;\n private static OyVeyGui INSTANCE;\n\n static {\n INSTANCE = new OyVeyGui();\n }\n\n private final ArrayList<Component> components = new ArrayList();\n\n public OyVeyGui() {\n super(Text.literal(\"OyVey\"));\n setInstance();\n load();\n }\n\n public static OyVeyGui getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new OyVeyGui();\n }\n return INSTANCE;\n }\n\n public static OyVeyGui getClickGui() {\n return OyVeyGui.getInstance();\n }\n\n private void setInstance() {\n INSTANCE = this;\n }\n\n private void load() {\n int x = -84;\n for (final Module.Category category : OyVey.moduleManager.getCategories()) {\n this.components.add(new Component(category.getName(), x += 90, 4, true) {\n\n @Override\n public void setupItems() {\n counter1 = new int[]{1};\n OyVey.moduleManager.getModulesByCategory(category).forEach(module -> {\n if (!module.hidden) {\n this.addButton(new ModuleButton(module));\n }\n });\n }\n });\n }\n this.components.forEach(components -> components.getItems().sort(Comparator.comparing(Feature::getName)));\n }\n\n public void updateModule(Module module) {\n for (Component component : this.components) {\n for (Item item : component.getItems()) {\n if (!(item instanceof ModuleButton)) continue;\n ModuleButton button = (ModuleButton) item;\n Module mod = button.getModule();\n if (module == null || !module.equals(mod)) continue;\n button.initSettings();\n }\n }\n }\n\n @Override public void render(DrawContext context, int mouseX, int mouseY, float delta) {\n Item.context = context;\n context.fill(0, 0, context.getScaledWindowWidth(), context.getScaledWindowHeight(), new Color(0, 0, 0, 120).hashCode());\n this.components.forEach(components -> components.drawScreen(context, mouseX, mouseY, delta));\n }\n\n @Override public boolean mouseClicked(double mouseX, double mouseY, int clickedButton) {\n this.components.forEach(components -> components.mouseClicked((int) mouseX, (int) mouseY, clickedButton));\n return super.mouseClicked(mouseX, mouseY, clickedButton);\n }\n\n @Override public boolean mouseReleased(double mouseX, double mouseY, int releaseButton) {\n this.components.forEach(components -> components.mouseReleased((int) mouseX, (int) mouseY, releaseButton));\n return super.mouseReleased(mouseX, mouseY, releaseButton);\n }\n\n @Override public boolean mouseScrolled(double mouseX, double mouseY, double dWheel) {\n if (dWheel < 0) {\n this.components.forEach(component -> component.setY(component.getY() - 10));\n } else if (dWheel > 0) {\n this.components.forEach(component -> component.setY(component.getY() + 10));\n }\n return super.mouseScrolled(mouseX, mouseY, dWheel);\n }\n\n @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) {\n this.components.forEach(component -> component.onKeyPressed(keyCode));\n return super.keyPressed(keyCode, scanCode, modifiers);\n }\n\n @Override public boolean charTyped(char chr, int modifiers) {\n this.components.forEach(component -> component.onKeyTyped(chr, modifiers));\n return super.charTyped(chr, modifiers);\n }\n\n @Override public boolean shouldPause() {\n return false;\n }\n\n public final ArrayList<Component> getComponents() {\n return this.components;\n }\n\n public int getTextOffset() {\n return -6;\n }\n\n public Component getComponentByName(String name) {\n for (Component component : this.components) {\n if (!component.getName().equalsIgnoreCase(name)) continue;\n return component;\n }\n return null;\n }\n}" }, { "identifier": "Item", "path": "src/main/java/me/alpha432/oyvey/features/gui/items/Item.java", "snippet": "public class Item\n extends Feature {\n public static DrawContext context;\n protected float x;\n protected float y;\n protected int width;\n protected int height;\n private boolean hidden;\n\n public Item(String name) {\n super(name);\n }\n\n public void setLocation(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {\n }\n\n public void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n }\n\n public void mouseReleased(int mouseX, int mouseY, int releaseButton) {\n }\n\n public void update() {\n }\n\n public void onKeyTyped(char typedChar, int keyCode) {\n }\n\n public void onKeyPressed(int key) {\n }\n\n public float getX() {\n return this.x;\n }\n\n public float getY() {\n return this.y;\n }\n\n public int getWidth() {\n return this.width;\n }\n\n public void setWidth(int width) {\n this.width = width;\n }\n\n public int getHeight() {\n return this.height;\n }\n\n public void setHeight(int height) {\n this.height = height;\n }\n\n public boolean isHidden() {\n return this.hidden;\n }\n\n public boolean setHidden(boolean hidden) {\n this.hidden = hidden;\n return this.hidden;\n }\n\n protected void drawString(String text, double x, double y, Color color) {\n drawString(text, x, y, color.hashCode());\n }\n\n protected void drawString(String text, double x, double y, int color) {\n context.drawTextWithShadow(mc.textRenderer, text, (int) x, (int) y, color);\n }\n}" }, { "identifier": "ClickGui", "path": "src/main/java/me/alpha432/oyvey/features/modules/client/ClickGui.java", "snippet": "public class ClickGui\n extends Module {\n private static ClickGui INSTANCE = new ClickGui();\n public Setting<String> prefix = this.register(new Setting<>(\"Prefix\", \".\"));\n public Setting<Boolean> customFov = this.register(new Setting<>(\"CustomFov\", false));\n public Setting<Float> fov = this.register(new Setting<>(\"Fov\", 150f, -180f, 180f));\n public Setting<Integer> red = this.register(new Setting<>(\"Red\", 0, 0, 255));\n public Setting<Integer> green = this.register(new Setting<>(\"Green\", 0, 0, 255));\n public Setting<Integer> blue = this.register(new Setting<>(\"Blue\", 255, 0, 255));\n public Setting<Integer> hoverAlpha = this.register(new Setting<>(\"Alpha\", 180, 0, 255));\n public Setting<Integer> topRed = this.register(new Setting<>(\"SecondRed\", 0, 0, 255));\n public Setting<Integer> topGreen = this.register(new Setting<>(\"SecondGreen\", 0, 0, 255));\n public Setting<Integer> topBlue = this.register(new Setting<>(\"SecondBlue\", 150, 0, 255));\n public Setting<Integer> alpha = this.register(new Setting<>(\"HoverAlpha\", 240, 0, 255));\n public Setting<Boolean> rainbow = this.register(new Setting<>(\"Rainbow\", false));\n public Setting<rainbowMode> rainbowModeHud = this.register(new Setting<>(\"HRainbowMode\", rainbowMode.Static, v -> this.rainbow.getValue()));\n public Setting<rainbowModeArray> rainbowModeA = this.register(new Setting<>(\"ARainbowMode\", rainbowModeArray.Static, v -> this.rainbow.getValue()));\n public Setting<Integer> rainbowHue = this.register(new Setting<>(\"Delay\", 240, 0, 600, v -> this.rainbow.getValue()));\n public Setting<Float> rainbowBrightness = this.register(new Setting<>(\"Brightness \", 150.0f, 1.0f, 255.0f, v -> this.rainbow.getValue()));\n public Setting<Float> rainbowSaturation = this.register(new Setting<>(\"Saturation\", 150.0f, 1.0f, 255.0f, v -> this.rainbow.getValue()));\n private OyVeyGui click;\n\n public ClickGui() {\n super(\"ClickGui\", \"Opens the ClickGui\", Module.Category.CLIENT, true, false, false);\n setBind(GLFW.GLFW_KEY_RIGHT_SHIFT);\n this.setInstance();\n }\n\n public static ClickGui getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new ClickGui();\n }\n return INSTANCE;\n }\n\n private void setInstance() {\n INSTANCE = this;\n }\n\n @Override\n public void onUpdate() {\n if (this.customFov.getValue().booleanValue()) {\n mc.options.getFov().setValue(this.fov.getValue().intValue());\n }\n }\n\n @Subscribe\n public void onSettingChange(ClientEvent event) {\n if (event.getStage() == 2 && event.getSetting().getFeature().equals(this)) {\n if (event.getSetting().equals(this.prefix)) {\n OyVey.commandManager.setPrefix(this.prefix.getPlannedValue());\n Command.sendMessage(\"Prefix set to \" + Formatting.DARK_GRAY + OyVey.commandManager.getPrefix());\n }\n OyVey.colorManager.setColor(this.red.getPlannedValue(), this.green.getPlannedValue(), this.blue.getPlannedValue(), this.hoverAlpha.getPlannedValue());\n }\n }\n\n @Override\n public void onEnable() {\n mc.setScreen(OyVeyGui.getClickGui());\n }\n\n @Override\n public void onLoad() {\n OyVey.colorManager.setColor(this.red.getValue(), this.green.getValue(), this.blue.getValue(), this.hoverAlpha.getValue());\n OyVey.commandManager.setPrefix(this.prefix.getValue());\n }\n\n @Override\n public void onTick() {\n if (!(ClickGui.mc.currentScreen instanceof OyVeyGui)) {\n this.disable();\n }\n }\n\n public enum rainbowModeArray {\n Static,\n Up\n\n }\n\n public enum rainbowMode {\n Static,\n Sideway\n\n }\n}" }, { "identifier": "RenderUtil", "path": "src/main/java/me/alpha432/oyvey/util/RenderUtil.java", "snippet": "public class RenderUtil implements Util {\n\n public static void rect(MatrixStack stack, float x1, float y1, float x2, float y2, int color) {\n rectFilled(stack, x1, y1, x2, y2, color);\n }\n\n public static void rect(MatrixStack stack, float x1, float y1, float x2, float y2, int color, float width) {\n drawHorizontalLine(stack, x1, x2, y1, color, width);\n drawVerticalLine(stack, x2, y1, y2, color, width);\n drawHorizontalLine(stack, x1, x2, y2, color, width);\n drawVerticalLine(stack, x1, y1, y2, color, width);\n }\n\n protected static void drawHorizontalLine(MatrixStack matrices, float x1, float x2, float y, int color) {\n if (x2 < x1) {\n float i = x1;\n x1 = x2;\n x2 = i;\n }\n\n rectFilled(matrices, x1, y, x2 + 1, y + 1, color);\n }\n\n protected static void drawVerticalLine(MatrixStack matrices, float x, float y1, float y2, int color) {\n if (y2 < y1) {\n float i = y1;\n y1 = y2;\n y2 = i;\n }\n\n rectFilled(matrices, x, y1 + 1, x + 1, y2, color);\n }\n\n protected static void drawHorizontalLine(MatrixStack matrices, float x1, float x2, float y, int color, float width) {\n if (x2 < x1) {\n float i = x1;\n x1 = x2;\n x2 = i;\n }\n\n rectFilled(matrices, x1, y, x2 + width, y + width, color);\n }\n\n protected static void drawVerticalLine(MatrixStack matrices, float x, float y1, float y2, int color, float width) {\n if (y2 < y1) {\n float i = y1;\n y1 = y2;\n y2 = i;\n }\n\n rectFilled(matrices, x, y1 + width, x + width, y2, color);\n }\n\n public static void rectFilled(MatrixStack matrix, float x1, float y1, float x2, float y2, int color) {\n float i;\n if (x1 < x2) {\n i = x1;\n x1 = x2;\n x2 = i;\n }\n\n if (y1 < y2) {\n i = y1;\n y1 = y2;\n y2 = i;\n }\n\n float f = (float) (color >> 24 & 255) / 255.0F;\n float g = (float) (color >> 16 & 255) / 255.0F;\n float h = (float) (color >> 8 & 255) / 255.0F;\n float j = (float) (color & 255) / 255.0F;\n BufferBuilder bufferBuilder = Tessellator.getInstance().getBuffer();\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n RenderSystem.setShader(GameRenderer::getPositionColorProgram);\n bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR);\n bufferBuilder.vertex(matrix.peek().getPositionMatrix(), x1, y2, 0.0F).color(g, h, j, f).next();\n bufferBuilder.vertex(matrix.peek().getPositionMatrix(), x2, y2, 0.0F).color(g, h, j, f).next();\n bufferBuilder.vertex(matrix.peek().getPositionMatrix(), x2, y1, 0.0F).color(g, h, j, f).next();\n bufferBuilder.vertex(matrix.peek().getPositionMatrix(), x1, y1, 0.0F).color(g, h, j, f).next();\n BufferRenderer.drawWithGlobalProgram(bufferBuilder.end());\n RenderSystem.disableBlend();\n }\n\n // 3d\n\n\n public static void drawBoxFilled(MatrixStack stack, Box box, Color c) {\n float minX = (float) (box.minX - mc.getEntityRenderDispatcher().camera.getPos().getX());\n float minY = (float) (box.minY - mc.getEntityRenderDispatcher().camera.getPos().getY());\n float minZ = (float) (box.minZ - mc.getEntityRenderDispatcher().camera.getPos().getZ());\n float maxX = (float) (box.maxX - mc.getEntityRenderDispatcher().camera.getPos().getX());\n float maxY = (float) (box.maxY - mc.getEntityRenderDispatcher().camera.getPos().getY());\n float maxZ = (float) (box.maxZ - mc.getEntityRenderDispatcher().camera.getPos().getZ());\n\n Tessellator tessellator = Tessellator.getInstance();\n BufferBuilder bufferBuilder = tessellator.getBuffer();\n\n setup3D();\n RenderSystem.setShader(GameRenderer::getPositionColorProgram);\n bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR);\n\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, maxZ).color(c.getRGB()).next();\n\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, minZ).color(c.getRGB()).next();\n\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, minZ).color(c.getRGB()).next();\n\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, maxZ).color(c.getRGB()).next();\n\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, maxZ).color(c.getRGB()).next();\n\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, minZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, maxZ).color(c.getRGB()).next();\n bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, minZ).color(c.getRGB()).next();\n\n tessellator.draw();\n clean3D();\n }\n\n public static void drawBoxFilled(MatrixStack stack, Vec3d vec, Color c) {\n drawBoxFilled(stack, Box.from(vec), c);\n }\n\n public static void drawBoxFilled(MatrixStack stack, BlockPos bp, Color c) {\n drawBoxFilled(stack, new Box(bp), c);\n }\n\n public static void drawBox(MatrixStack stack, Box box, Color c, double lineWidth) {\n float minX = (float) (box.minX - mc.getEntityRenderDispatcher().camera.getPos().getX());\n float minY = (float) (box.minY - mc.getEntityRenderDispatcher().camera.getPos().getY());\n float minZ = (float) (box.minZ - mc.getEntityRenderDispatcher().camera.getPos().getZ());\n float maxX = (float) (box.maxX - mc.getEntityRenderDispatcher().camera.getPos().getX());\n float maxY = (float) (box.maxY - mc.getEntityRenderDispatcher().camera.getPos().getY());\n float maxZ = (float) (box.maxZ - mc.getEntityRenderDispatcher().camera.getPos().getZ());\n\n Tessellator tessellator = Tessellator.getInstance();\n BufferBuilder bufferBuilder = tessellator.getBuffer();\n setup3D();\n RenderSystem.lineWidth(( float ) lineWidth);\n RenderSystem.setShader(GameRenderer::getRenderTypeLinesProgram);\n\n RenderSystem.defaultBlendFunc();\n\n bufferBuilder.begin(VertexFormat.DrawMode.LINES, VertexFormats.LINES);\n\n WorldRenderer.drawBox(stack, bufferBuilder, minX, minY, minZ, maxX, maxY, maxZ, c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, c.getAlpha() / 255f);\n\n tessellator.draw();\n clean3D();\n }\n\n public static void drawBox(MatrixStack stack, Vec3d vec, Color c, double lineWidth) {\n drawBox(stack, Box.from(vec), c, lineWidth);\n }\n\n public static void drawBox(MatrixStack stack, BlockPos bp, Color c, double lineWidth) {\n drawBox(stack, new Box(bp), c, lineWidth);\n }\n\n public static MatrixStack matrixFrom(Vec3d pos) {\n MatrixStack matrices = new MatrixStack();\n Camera camera = mc.gameRenderer.getCamera();\n matrices.multiply(RotationAxis.POSITIVE_X.rotationDegrees(camera.getPitch()));\n matrices.multiply(RotationAxis.POSITIVE_Y.rotationDegrees(camera.getYaw() + 180.0F));\n matrices.translate(pos.getX() - camera.getPos().x, pos.getY() - camera.getPos().y, pos.getZ() - camera.getPos().z);\n return matrices;\n }\n\n public static void setup() {\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n }\n\n public static void setup3D() {\n setup();\n RenderSystem.disableDepthTest();\n RenderSystem.depthMask(false);\n RenderSystem.disableCull();\n }\n\n public static void clean() {\n RenderSystem.disableBlend();\n }\n\n public static void clean3D() {\n clean();\n RenderSystem.enableDepthTest();\n RenderSystem.depthMask(true);\n RenderSystem.enableCull();\n }\n\n}" } ]
import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.features.gui.Component; import me.alpha432.oyvey.features.gui.OyVeyGui; import me.alpha432.oyvey.features.gui.items.Item; import me.alpha432.oyvey.features.modules.client.ClickGui; import me.alpha432.oyvey.util.RenderUtil; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.sound.PositionedSoundInstance; import net.minecraft.sound.SoundEvents;
7,233
package me.alpha432.oyvey.features.gui.items.buttons; public class Button extends Item { private boolean state; public Button(String name) { super(name); this.height = 15; } @Override public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {
package me.alpha432.oyvey.features.gui.items.buttons; public class Button extends Item { private boolean state; public Button(String name) { super(name); this.height = 15; } @Override public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {
RenderUtil.rect(context.getMatrices(), this.x, this.y, this.x + (float) this.width, this.y + (float) this.height - 0.5f, this.getState() ? (!this.isHovering(mouseX, mouseY) ? OyVey.colorManager.getColorWithAlpha(OyVey.moduleManager.getModuleByClass(ClickGui.class).hoverAlpha.getValue()) : OyVey.colorManager.getColorWithAlpha(OyVey.moduleManager.getModuleByClass(ClickGui.class).alpha.getValue())) : (!this.isHovering(mouseX, mouseY) ? 0x11555555 : -2007673515));
4
2023-11-05 18:10:28+00:00
12k
EB-wilson/TooManyItems
src/main/java/tmi/recipe/types/FactoryRecipe.java
[ { "identifier": "Recipe", "path": "src/main/java/tmi/recipe/Recipe.java", "snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeType;\n /**配方的标准耗时,具体来说即该配方在100%的工作效率下执行一次生产的耗时,任意小于0的数字都被认为生产过程是连续的*/\n //meta\n public float time = -1;\n\n /**配方的产出物列表\n * @see RecipeItemStack*/\n public final OrderedMap<RecipeItem<?>, RecipeItemStack> productions = new OrderedMap<>();\n /**配方的输入材料列表\n * @see RecipeItemStack*/\n public final OrderedMap<RecipeItem<?>, RecipeItemStack> materials = new OrderedMap<>();\n\n /**配方的效率计算函数,用于给定一个输入环境参数和配方数据,计算出该配方在这个输入环境下的工作效率*/\n public EffFunc efficiency = getOneEff();\n\n //infos\n /**执行该配方的建筑/方块*/\n public RecipeItem<?> block;\n /**该配方在显示时的附加显示内容构建函数,若不设置则认为不添加任何附加信息*/\n @Nullable public Cons<Table> subInfoBuilder;\n\n public Recipe(RecipeType recipeType) {\n this.recipeType = recipeType;\n }\n\n /**用配方当前使用的效率计算器计算该配方在给定的环境参数下的运行效率*/\n public float calculateEfficiency(EnvParameter parameter) {\n return efficiency.calculateEff(this, parameter, calculateMultiple(parameter));\n }\n\n public float calculateEfficiency(EnvParameter parameter, float multiplier) {\n return efficiency.calculateEff(this, parameter, multiplier);\n }\n\n public float calculateMultiple(EnvParameter parameter) {\n return efficiency.calculateMultiple(this, parameter);\n }\n\n //utils\n\n public RecipeItemStack addMaterial(RecipeItem<?> item, int amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setIntegerFormat(time):\n new RecipeItemStack(item, amount).setIntegerFormat();\n\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterial(RecipeItem<?> item, float amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setFloatFormat(time):\n new RecipeItemStack(item, amount).setFloatFormat();\n\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterialPresec(RecipeItem<?> item, float preSeq){\n RecipeItemStack res = new RecipeItemStack(item, preSeq).setPresecFormat();\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterialRaw(RecipeItem<?> item, float amount){\n RecipeItemStack res = new RecipeItemStack(item, amount);\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProduction(RecipeItem<?> item, int amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setIntegerFormat(time):\n new RecipeItemStack(item, amount).setIntegerFormat();\n\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProduction(RecipeItem<?> item, float amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setFloatFormat(time):\n new RecipeItemStack(item, amount).setFloatFormat();\n\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProductionPresec(RecipeItem<?> item, float preSeq){\n RecipeItemStack res = new RecipeItemStack(item, preSeq).setPresecFormat();\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProductionRaw(RecipeItem<?> item, float amount){\n RecipeItemStack res = new RecipeItemStack(item, amount);\n productions.put(item, res);\n return res;\n }\n\n public Recipe setBlock(RecipeItem<?> block){\n this.block = block;\n return this;\n }\n\n public Recipe setTime(float time){\n this.time = time;\n return this;\n }\n\n public Recipe setEfficiency(EffFunc func){\n efficiency = func;\n return this;\n }\n\n public boolean containsProduction(RecipeItem<?> production) {\n return productions.containsKey(production);\n }\n\n public boolean containsMaterial(RecipeItem<?> material) {\n return materials.containsKey(material);\n }\n\n /**@see Recipe#getDefaultEff(float) */\n public static EffFunc getOneEff(){\n return ONE_BASE;\n }\n\n /**@see Recipe#getDefaultEff(float) */\n public static EffFunc getZeroEff(){\n return ZERO_BASE;\n }\n\n /**生成一个适用于vanilla绝大多数工厂与设备的效率计算器,若{@linkplain RecipeParser 配方解析器}正确的解释了方块,这个函数应当能够正确计算方块的实际工作效率*/\n public static EffFunc getDefaultEff(float baseEff){\n ObjectFloatMap<Object> attrGroups = new ObjectFloatMap<>();\n\n return new EffFunc() {\n @Override\n public float calculateEff(Recipe recipe, EnvParameter env, float mul) {\n float eff = 1;\n\n attrGroups.clear();\n\n for (RecipeItemStack stack : recipe.materials.values()) {\n if (stack.isBooster || stack.isAttribute) continue;\n\n if (stack.attributeGroup != null){\n float e = attrGroups.get(stack.attributeGroup, 1)*stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/(stack.amount*mul));\n if (stack.maxAttr) {\n attrGroups.put(stack.attributeGroup, Math.max(attrGroups.get(stack.attributeGroup, 0), e));\n }\n else attrGroups.increment(stack.attributeGroup, 0, e);\n }\n else eff *= Math.max(stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/(stack.amount*mul)), stack.optionalCons? 1: 0);\n }\n\n ObjectFloatMap.Values v = attrGroups.values();\n while (v.hasNext()) {\n eff *= v.next();\n }\n\n return eff*mul;\n }\n\n @Override\n public float calculateMultiple(Recipe recipe, EnvParameter env) {\n attrGroups.clear();\n\n float attr = 0;\n float boost = 1;\n\n for (RecipeItemStack stack : recipe.materials.values()) {\n if (!stack.isBooster && !stack.isAttribute) continue;\n\n if (stack.isAttribute){\n float a = stack.efficiency*Mathf.clamp(env.getAttribute(stack.item)/stack.amount);\n if (stack.maxAttr) attr = Math.max(attr, a);\n else attr += a;\n }\n else {\n if (stack.attributeGroup != null){\n float e = attrGroups.get(stack.attributeGroup, 1)*stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/stack.amount);\n if (stack.maxAttr) {\n attrGroups.put(stack.attributeGroup, Math.max(attrGroups.get(stack.attributeGroup, 0), e));\n }\n else attrGroups.increment(stack.attributeGroup, 0, e);\n }\n else boost *= Math.max(stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/stack.amount), stack.optionalCons? 1: 0);\n }\n }\n\n ObjectFloatMap.Values v = attrGroups.values();\n while (v.hasNext()) {\n boost *= v.next();\n }\n return boost*(baseEff + attr);\n }\n };\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (!(object instanceof Recipe r)) return false;\n if (r.recipeType != recipeType || r.block != block) return false;\n\n if (r.materials.size != materials.size || r.productions.size != productions.size) return false;\n\n return r.materials.equals(materials) && r.productions.equals(productions);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(recipeType, productions.orderedKeys(), materials.orderedKeys(), block);\n }\n\n public interface EffFunc{\n float calculateEff(Recipe recipe, EnvParameter env, float mul);\n float calculateMultiple(Recipe recipe, EnvParameter env);\n }\n}" }, { "identifier": "RecipeItemStack", "path": "src/main/java/tmi/recipe/RecipeItemStack.java", "snippet": "public class RecipeItemStack {\n /**该条目表示的{@link UnlockableContent}*/\n public final RecipeItem<?> item;\n /**条目附加的数量信息,这将被用作生产计算和显示数据的文本格式化*/\n public float amount;\n\n /**条目数据显示的文本格式化函数,这里返回的文本将显示在条目上以表示数量信息*/\n public AmountFormatter amountFormat = f -> \"\";\n\n /**此条目的效率系数,应当绑定为该条目在生产工作中可用时的最高效率倍率,以参与生产计算*/\n public float efficiency = 1;\n /**该条目是否为可选消耗项,应当与实际情况同步*/\n public boolean optionalCons = false;\n /**该条目是否为属性项目,通常用于计算覆盖/关联的方块提供的属性增益*/\n public boolean isAttribute = false;\n /**该条目是否是增幅项目,若为增幅项目则被单独计算boost倍率,该倍率将影响输入物数量计算并直接乘在最终效率上*/\n public boolean isBooster = false;\n /**条目从属的属性组,一个属性组内的项目在工作效率计算时,会以最高的那一个作为计算结果。\n * <br>\n * 属性组的划分按照提供的对象确定,任意时候当两个条目的属性组对象{@link Object#equals(Object)}为真时就会被视为从属于同一属性组。\n * 该字段默认空,为空时表示该条目不从属于任何属性组*/\n @Nullable public Object attributeGroup = null;\n /**若为真,此消耗项的属性效率计算会按属性组的最大效率计算,否则会对属性效率求和*/\n public boolean maxAttr = false;\n\n public RecipeItemStack(RecipeItem<?> item, float amount) {\n this.item = item;\n this.amount = amount;\n }\n\n public RecipeItemStack(RecipeItem<?> item) {\n this(item, 0);\n }\n\n public RecipeItem<?> item() {\n return item;\n }\n\n public float amount(){\n return amount;\n }\n\n /**获取经过格式化的表示数量的文本信息*/\n public String getAmount() {\n return amountFormat.format(amount);\n }\n\n //属性设置的工具方法\n\n public RecipeItemStack setEfficiency(float efficiency) {\n this.efficiency = efficiency;\n return this;\n }\n\n public RecipeItemStack setOptionalCons(boolean optionalCons) {\n this.optionalCons = optionalCons;\n return this;\n }\n\n public RecipeItemStack setOptionalCons() {\n return setOptionalCons(true);\n }\n\n public RecipeItemStack setAttribute(){\n this.isAttribute = true;\n return this;\n }\n\n public RecipeItemStack setBooster() {\n isBooster = true;\n return this;\n }\n\n public RecipeItemStack setBooster(boolean boost) {\n isBooster = boost;\n return this;\n }\n\n public RecipeItemStack setMaxAttr(){\n this.maxAttr = true;\n return this;\n }\n\n public RecipeItemStack setAttribute(Object group){\n this.attributeGroup = group;\n return this;\n }\n\n public RecipeItemStack setFormat(AmountFormatter format){\n this.amountFormat = format;\n return this;\n }\n\n public RecipeItemStack setEmptyFormat(){\n this.amountFormat = f -> \"\";\n return this;\n }\n\n public RecipeItemStack setFloatFormat(float mul) {\n setFormat(f -> f*mul > 1000? UI.formatAmount(Mathf.round(f*mul)): Strings.autoFixed(f*mul, 1));\n return this;\n }\n\n public RecipeItemStack setIntegerFormat(float mul) {\n setFormat(f -> f*mul > 1000? UI.formatAmount(Mathf.round(f*mul)): Integer.toString(Mathf.round(f*mul)));\n return this;\n }\n\n public RecipeItemStack setFloatFormat() {\n setFormat(f -> f > 1000? UI.formatAmount((long) f): Strings.autoFixed(f, 1));\n return this;\n }\n\n public RecipeItemStack setIntegerFormat() {\n setFormat(f -> f > 1000? UI.formatAmount((long) f): Integer.toString((int) f));\n return this;\n }\n\n public RecipeItemStack setPresecFormat() {\n setFormat(f -> (f*60 > 1000? UI.formatAmount((long) (f*60)): Strings.autoFixed(f*60, 2)) + \"/\" + StatUnit.seconds.localized());\n return this;\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (object == null || getClass() != object.getClass()) return false;\n RecipeItemStack stack = (RecipeItemStack) object;\n return Float.compare(amount, stack.amount) == 0 && isAttribute == stack.isAttribute && isBooster == stack.isBooster && maxAttr == stack.maxAttr && Objects.equals(item, stack.item) && Objects.equals(attributeGroup, stack.attributeGroup);\n }\n\n public interface AmountFormatter {\n String format(float f);\n }\n}" }, { "identifier": "RecipeType", "path": "src/main/java/tmi/recipe/RecipeType.java", "snippet": "public abstract class RecipeType {\n public static final Seq<RecipeType> all = new Seq<>();\n\n public static RecipeType factory,\n building,\n collecting,\n generator;\n\n /**生成{@linkplain RecipeView 配方视图}前对上下文数据进行初始化,并计算布局尺寸\n *\n * @return 表示该布局的长宽尺寸的二元向量*/\n public abstract Vec2 initial(Recipe recipe);\n /**为参数传入的{@link RecipeNode}设置坐标以完成布局*/\n public abstract void layout(RecipeNode recipeNode);\n /**生成从给定起始节点到目标节点的{@linkplain tmi.ui.RecipeView.LineMeta 线条信息}*/\n public abstract RecipeView.LineMeta line(RecipeNode from, RecipeNode to);\n public abstract int id();\n /**向配方显示器内添加显示部件的入口*/\n public void buildView(Group view){}\n\n public static void init() {\n factory = new FactoryRecipe();\n building = new BuildingRecipe();\n collecting = new CollectingRecipe();\n generator = new GeneratorRecipe();\n }\n\n public RecipeType(){\n all.add(this);\n }\n\n public void drawLine(RecipeView recipeView) {\n Draw.scl(recipeView.scaleX, recipeView.scaleY);\n\n for (RecipeView.LineMeta line : recipeView.lines) {\n if (line.vertices.size < 2) continue;\n\n float a = Draw.getColor().a;\n Lines.stroke(Scl.scl(5)*recipeView.scaleX, line.color.get());\n Draw.alpha(Draw.getColor().a*a);\n\n if (line.vertices.size <= 4){\n float x1 = line.vertices.items[0] - recipeView.getWidth()/2;\n float y1 = line.vertices.items[1] - recipeView.getHeight()/2;\n float x2 = line.vertices.items[2] - recipeView.getWidth()/2;\n float y2 = line.vertices.items[3] - recipeView.getHeight()/2;\n Lines.line(\n recipeView.x + recipeView.getWidth()/2 + x1*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y1*recipeView.scaleY,\n recipeView.x + recipeView.getWidth()/2 + x2*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y2*recipeView.scaleY\n );\n continue;\n }\n\n Lines.beginLine();\n for (int i = 0; i < line.vertices.size; i += 2) {\n float x1 = line.vertices.items[i] - recipeView.getWidth()/2;\n float y1 = line.vertices.items[i + 1] - recipeView.getHeight()/2;\n\n Lines.linePoint(recipeView.x + recipeView.getWidth()/2 + x1*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y1*recipeView.scaleY);\n }\n Lines.endLine();\n }\n\n Draw.reset();\n }\n\n @Override\n public int hashCode() {\n return id();\n }\n}" }, { "identifier": "NodeType", "path": "src/main/java/tmi/ui/NodeType.java", "snippet": "public enum NodeType {\n material,\n block,\n production\n}" }, { "identifier": "RecipeNode", "path": "src/main/java/tmi/ui/RecipeNode.java", "snippet": "public class RecipeNode extends Button {\n public static final float SIZE = Scl.scl(80);\n\n public final RecipeItemStack stack;\n\n public final NodeType type;\n\n float progress, alpha;\n boolean activity, touched;\n float time;\n int clicked;\n\n @Nullable Cons2<RecipeItem<?>, RecipesDialog.Mode> click;\n\n public RecipeNode(NodeType type, RecipeItemStack stack, Cons2<RecipeItem<?>, RecipesDialog.Mode> click){\n this.type = type;\n this.click = click;\n\n setBackground(Tex.button);\n this.stack = stack;\n\n touchable = Touchable.enabled;\n\n defaults().padLeft(8).padRight(8);\n\n setSize(SIZE);\n\n addListener(new Tooltip(t -> t.add(stack.item().localizedName(), Styles.outlineLabel)){{ allowMobile = true; }});\n\n hovered(() -> activity = true);\n exited(() -> activity = false);\n tapped(() -> {\n touched = true;\n time = Time.globalTime;\n });\n released(() -> {\n touched = false;\n\n if (click != null && Time.globalTime - time < 12){\n if (!mobile || Core.settings.getBool(\"keyboard\")) {\n click.get(stack.item(), Core.input.keyDown(binds.hotKey) ? type == NodeType.block ? RecipesDialog.Mode.factory : RecipesDialog.Mode.usage : RecipesDialog.Mode.recipe);\n }\n else {\n clicked++;\n if (clicked >= 2){\n click.get(stack.item(), type == NodeType.block ? RecipesDialog.Mode.factory : RecipesDialog.Mode.usage);\n clicked = 0;\n }\n }\n }\n else {\n if (stack.item.hasDetails() && (progress >= 0.95f || click == null)){\n stack.item.displayDetails();\n }\n }\n });\n\n stack(\n new Table(t -> t.image(stack.item.icon()).size(SIZE/Scl.scl()*0.62f).scaling(Scaling.fit)),\n\n new Table(t -> {\n t.left().bottom();\n t.add(stack.getAmount(), Styles.outlineLabel);\n t.pack();\n }),\n\n new Table(t -> {\n if (!stack.item.locked()) return;\n t.right().bottom().defaults().right().bottom().pad(4);\n t.image(Icon.lock).scaling(Scaling.fit).size(10).color(Color.lightGray);\n })\n ).grow().pad(5);\n }\n\n @Override\n public void act(float delta) {\n super.act(delta);\n\n alpha = Mathf.lerpDelta(alpha, touched || activity ? 1 : 0, 0.08f);\n progress = Mathf.approachDelta(progress, stack.item.hasDetails() && click != null && touched? 1.01f : 0, 1/60f);\n if (click != null && Time.globalTime - time > 12 && clicked == 1){\n click.get(stack.item(), RecipesDialog.Mode.recipe);\n clicked = 0;\n }\n }\n\n @Override\n protected void drawBackground(float x, float y) {\n super.drawBackground(x, y);\n Lines.stroke(Scl.scl(34), Color.lightGray);\n Draw.alpha(0.5f);\n\n Lines.arc(x + width/2, y + height/2, Scl.scl(18), progress, 90);\n }\n}" }, { "identifier": "RecipeView", "path": "src/main/java/tmi/ui/RecipeView.java", "snippet": "public class RecipeView extends Group {\n private final Vec2 bound = new Vec2();\n private final Seq<RecipeNode> nodes = new Seq<>();\n public final Seq<LineMeta> lines = new Seq<>();\n public final Recipe recipe;\n\n final Group childGroup;\n\n public RecipeView(Recipe recipe, Cons2<RecipeItem<?>, RecipesDialog.Mode> nodeClicked) {\n this.recipe = recipe;\n childGroup = new Group() {};\n\n for (RecipeItemStack content : recipe.materials.values()) {\n nodes.add(new RecipeNode(NodeType.material, content, nodeClicked));\n }\n for (RecipeItemStack content : recipe.productions.values()) {\n nodes.add(new RecipeNode(NodeType.production, content, nodeClicked));\n }\n\n if (recipe.block != null) nodes.add(new RecipeNode(NodeType.block, new RecipeItemStack(recipe.block), nodeClicked));\n\n nodes.each(this::addChild);\n\n addChild(childGroup);\n }\n\n @Override\n public void layout() {\n super.layout();\n childGroup.clear();\n childGroup.invalidate();\n\n lines.clear();\n bound.set(recipe.recipeType.initial(recipe));\n\n RecipeNode center = nodes.find(e -> e.type == NodeType.block);\n for (RecipeNode node : nodes) {\n recipe.recipeType.layout(node);\n LineMeta line = recipe.recipeType.line(node, center);\n if (line != null) lines.add(line);\n }\n\n recipe.recipeType.buildView(childGroup);\n }\n\n @Override\n public void draw() {\n validate();\n\n Draw.alpha(parentAlpha);\n recipe.recipeType.drawLine(this);\n super.draw();\n }\n\n @Override\n public float getPrefWidth() {\n return bound.x;\n }\n\n @Override\n public float getPrefHeight() {\n return bound.y;\n }\n\n public static class LineMeta{\n public final FloatSeq vertices = new FloatSeq();\n public Prov<Color> color = () -> Color.white;\n\n public void setVertices(float... vert){\n vertices.clear();\n vertices.addAll(vert);\n }\n\n public void addVertex(float x, float y){\n vertices.add(x, y);\n }\n }\n}" }, { "identifier": "SIZE", "path": "src/main/java/tmi/ui/RecipeNode.java", "snippet": "public static final float SIZE = Scl.scl(80);" } ]
import arc.Core; import arc.graphics.Color; import arc.math.Mathf; import arc.math.geom.Vec2; import arc.scene.Group; import arc.scene.ui.Label; import arc.scene.ui.layout.Scl; import arc.struct.ObjectMap; import arc.struct.Seq; import arc.util.Align; import arc.util.Strings; import arc.util.Time; import arc.util.Tmp; import mindustry.core.UI; import mindustry.ctype.UnlockableContent; import mindustry.graphics.Pal; import mindustry.ui.Styles; import mindustry.world.meta.Stat; import mindustry.world.meta.StatUnit; import tmi.recipe.Recipe; import tmi.recipe.RecipeItemStack; import tmi.recipe.RecipeType; import tmi.ui.NodeType; import tmi.ui.RecipeNode; import tmi.ui.RecipeView; import static tmi.ui.RecipeNode.SIZE;
7,356
optionals.setPosition(optPos.x, optPos.y - optionals.getHeight(), Align.center); view.addChild(optionals); } @Override public Vec2 initial(Recipe recipe) { time = recipe.time; consPos.clear(); prodPos.clear(); optPos.setZero(); blockPos.setZero(); Seq<RecipeItemStack> mats = recipe.materials.values().toSeq().select(e -> !e.optionalCons); Seq<RecipeItemStack> opts = recipe.materials.values().toSeq().select(e -> e.optionalCons); int materialNum = mats.size; int productionNum = recipe.productions.size; hasOptionals = opts.size > 0; doubleInput = materialNum > DOUBLE_LIMIT; doubleOutput = productionNum > DOUBLE_LIMIT; bound.setZero(); float wOpt = 0, wMat = 0, wProd = 0; if (hasOptionals){ wOpt = handleBound(opts.size, false); bound.y += ROW_PAD; } if (materialNum > 0) { wMat = handleBound(materialNum, doubleInput); bound.y += ROW_PAD; } bound.y += SIZE; if (productionNum > 0) { bound.y += ROW_PAD; wProd = handleBound(productionNum, doubleOutput); } float offOptX = (bound.x - wOpt)/2, offMatX = (bound.x - wMat)/2, offProdX = (bound.x - wProd)/2; float centX = bound.x / 2f; float offY = SIZE/2; if (hasOptionals){ offY = handleNode(opts, consPos, offOptX, offY, false, false); optPos.set(bound.x/2, offY); offY += ROW_PAD; } if (materialNum > 0){ offY = handleNode(mats, consPos, offMatX, offY, doubleInput, false); offY += ROW_PAD; } blockPos.set(centX, offY); offY += SIZE; if (productionNum > 0){ offY += ROW_PAD; Seq<RecipeItemStack> seq = recipe.productions.values().toSeq(); handleNode(seq, prodPos, offProdX, offY, doubleOutput, true); } return bound; } protected float handleNode(Seq<RecipeItemStack> seq, ObjectMap<RecipeItem<?>, Vec2> pos, float offX, float offY, boolean isDouble, boolean turn) { float dx = SIZE / 2; if (isDouble) { for (int i = 0; i < seq.size; i++) { if (turn) { if (i % 2 == 0) pos.put(seq.get(i).item(), new Vec2(offX + dx, offY + SIZE + ITEM_PAD)); else pos.put(seq.get(i).item(), new Vec2(offX + dx, offY)); } if (i % 2 == 0) pos.put(seq.get(i).item(), new Vec2(offX + dx, offY)); else pos.put(seq.get(i).item(), new Vec2(offX + dx, offY + SIZE + ITEM_PAD)); dx += SIZE / 2 + ITEM_PAD; } offY += SIZE * 2 + ITEM_PAD; } else { for (int i = 0; i < seq.size; i++) { pos.put(seq.get(i).item(), new Vec2(offX + dx, offY)); dx += SIZE + ITEM_PAD; } offY += SIZE; } return offY; } protected float handleBound(int num, boolean isDouble) { float res; if (isDouble) { int n = Mathf.ceil(num/2f); bound.x = Math.max(bound.x, res = SIZE*n + 2*ITEM_PAD*(n - 1) + (1 - num%2)*(SIZE/2 + ITEM_PAD/2)); bound.y += SIZE*2 + ITEM_PAD; } else { bound.x = Math.max(bound.x, res = SIZE*num + ITEM_PAD*(num - 1)); bound.y += SIZE; } return res; } @Override public void layout(RecipeNode recipeNode) { if (recipeNode.type == NodeType.material){ Vec2 pos = consPos.get(recipeNode.stack.item()); recipeNode.setPosition(pos.x, pos.y, Align.center); } else if (recipeNode.type == NodeType.production){ Vec2 pos = prodPos.get(recipeNode.stack.item()); recipeNode.setPosition(pos.x, pos.y, Align.center); } else if (recipeNode.type == NodeType.block){ recipeNode.setPosition(blockPos.x, blockPos.y, Align.center); } } @Override
package tmi.recipe.types; public class FactoryRecipe extends RecipeType { public static final float ROW_PAD = Scl.scl(60); public static final float ITEM_PAD = Scl.scl(10); public static final int DOUBLE_LIMIT = 5; final Vec2 bound = new Vec2(); final Vec2 blockPos = new Vec2(); final ObjectMap<RecipeItem<?>, Vec2> consPos = new ObjectMap<>(), prodPos = new ObjectMap<>(); final Vec2 optPos = new Vec2(); boolean doubleInput, doubleOutput, hasOptionals; float time; @Override public void buildView(Group view) { Label label = new Label(Core.bundle.get("misc.factory"), Styles.outlineLabel); label.validate(); label.setPosition(blockPos.x + SIZE/2 + ITEM_PAD + label.getPrefWidth()/2, blockPos.y, Align.center); view.addChild(label); buildOpts(view); buildTime(view, label.getHeight()); } protected void buildTime(Group view, float offY) { if (time > 0){ Label time = new Label(Stat.productionTime.localized() + ": " + (this.time > 3600? UI.formatTime(this.time): Strings.autoFixed(this.time/60, 2) + StatUnit.seconds.localized()), Styles.outlineLabel); time.validate(); time.setPosition(blockPos.x + SIZE/2 + ITEM_PAD + time.getPrefWidth()/2, blockPos.y - offY - 4, Align.center); view.addChild(time); } } protected void buildOpts(Group view) { if (!hasOptionals) return; Label optionals = new Label(Core.bundle.get("misc.optional"), Styles.outlineLabel); optionals.setColor(Pal.accent); optionals.validate(); optionals.setPosition(optPos.x, optPos.y - optionals.getHeight(), Align.center); view.addChild(optionals); } @Override public Vec2 initial(Recipe recipe) { time = recipe.time; consPos.clear(); prodPos.clear(); optPos.setZero(); blockPos.setZero(); Seq<RecipeItemStack> mats = recipe.materials.values().toSeq().select(e -> !e.optionalCons); Seq<RecipeItemStack> opts = recipe.materials.values().toSeq().select(e -> e.optionalCons); int materialNum = mats.size; int productionNum = recipe.productions.size; hasOptionals = opts.size > 0; doubleInput = materialNum > DOUBLE_LIMIT; doubleOutput = productionNum > DOUBLE_LIMIT; bound.setZero(); float wOpt = 0, wMat = 0, wProd = 0; if (hasOptionals){ wOpt = handleBound(opts.size, false); bound.y += ROW_PAD; } if (materialNum > 0) { wMat = handleBound(materialNum, doubleInput); bound.y += ROW_PAD; } bound.y += SIZE; if (productionNum > 0) { bound.y += ROW_PAD; wProd = handleBound(productionNum, doubleOutput); } float offOptX = (bound.x - wOpt)/2, offMatX = (bound.x - wMat)/2, offProdX = (bound.x - wProd)/2; float centX = bound.x / 2f; float offY = SIZE/2; if (hasOptionals){ offY = handleNode(opts, consPos, offOptX, offY, false, false); optPos.set(bound.x/2, offY); offY += ROW_PAD; } if (materialNum > 0){ offY = handleNode(mats, consPos, offMatX, offY, doubleInput, false); offY += ROW_PAD; } blockPos.set(centX, offY); offY += SIZE; if (productionNum > 0){ offY += ROW_PAD; Seq<RecipeItemStack> seq = recipe.productions.values().toSeq(); handleNode(seq, prodPos, offProdX, offY, doubleOutput, true); } return bound; } protected float handleNode(Seq<RecipeItemStack> seq, ObjectMap<RecipeItem<?>, Vec2> pos, float offX, float offY, boolean isDouble, boolean turn) { float dx = SIZE / 2; if (isDouble) { for (int i = 0; i < seq.size; i++) { if (turn) { if (i % 2 == 0) pos.put(seq.get(i).item(), new Vec2(offX + dx, offY + SIZE + ITEM_PAD)); else pos.put(seq.get(i).item(), new Vec2(offX + dx, offY)); } if (i % 2 == 0) pos.put(seq.get(i).item(), new Vec2(offX + dx, offY)); else pos.put(seq.get(i).item(), new Vec2(offX + dx, offY + SIZE + ITEM_PAD)); dx += SIZE / 2 + ITEM_PAD; } offY += SIZE * 2 + ITEM_PAD; } else { for (int i = 0; i < seq.size; i++) { pos.put(seq.get(i).item(), new Vec2(offX + dx, offY)); dx += SIZE + ITEM_PAD; } offY += SIZE; } return offY; } protected float handleBound(int num, boolean isDouble) { float res; if (isDouble) { int n = Mathf.ceil(num/2f); bound.x = Math.max(bound.x, res = SIZE*n + 2*ITEM_PAD*(n - 1) + (1 - num%2)*(SIZE/2 + ITEM_PAD/2)); bound.y += SIZE*2 + ITEM_PAD; } else { bound.x = Math.max(bound.x, res = SIZE*num + ITEM_PAD*(num - 1)); bound.y += SIZE; } return res; } @Override public void layout(RecipeNode recipeNode) { if (recipeNode.type == NodeType.material){ Vec2 pos = consPos.get(recipeNode.stack.item()); recipeNode.setPosition(pos.x, pos.y, Align.center); } else if (recipeNode.type == NodeType.production){ Vec2 pos = prodPos.get(recipeNode.stack.item()); recipeNode.setPosition(pos.x, pos.y, Align.center); } else if (recipeNode.type == NodeType.block){ recipeNode.setPosition(blockPos.x, blockPos.y, Align.center); } } @Override
public RecipeView.LineMeta line(RecipeNode from, RecipeNode to) {
5
2023-11-05 11:39:21+00:00
12k
373675032/xw-fast
xw-fast-crud/src/main/java/world/xuewei/fast/crud/controller/BaseController.java
[ { "identifier": "BusinessRunTimeException", "path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/BusinessRunTimeException.java", "snippet": "@Setter\n@Getter\npublic class BusinessRunTimeException extends RuntimeException {\n\n private static final long serialVersionUID = -4879677283847539655L;\n\n protected int code;\n\n protected String message;\n\n public BusinessRunTimeException(int code, String message) {\n super(message);\n this.code = code;\n this.message = message;\n }\n\n public BusinessRunTimeException(String message, Object... objects) {\n super(message);\n for (Object o : objects) {\n message = message.replaceFirst(\"\\\\{\\\\}\", o.toString());\n }\n this.message = message;\n }\n\n /**\n * 设置原因\n *\n * @param cause 原因\n */\n public BusinessRunTimeException setCause(Throwable cause) {\n this.initCause(cause);\n return this;\n }\n}" }, { "identifier": "ParamEmptyException", "path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/ParamEmptyException.java", "snippet": "public class ParamEmptyException extends BusinessRunTimeException {\n\n private static final long serialVersionUID = -4879677283847539655L;\n\n public ParamEmptyException(int code, String message) {\n super(code, message);\n this.code = code;\n this.message = message;\n }\n\n public ParamEmptyException(String message, Object... objects) {\n super(\"\");\n for (Object o : objects) {\n message = message.replaceFirst(\"\\\\{\\\\}\", o.toString());\n }\n super.setMessage(message);\n this.message = message;\n }\n\n public static ParamEmptyException build(String param) {\n throw new ParamEmptyException(\"参数<\" + param + \">为空\");\n }\n\n /**\n * 设置原因\n *\n * @param cause 原因\n */\n public ParamEmptyException setCause(Throwable cause) {\n this.initCause(cause);\n return this;\n }\n}" }, { "identifier": "ReqBody", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/dto/request/ReqBody.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ReqBody<T> {\n\n /**\n * 实体对象\n */\n private T obj;\n\n /**\n * 实体对象列表\n */\n private List<T> objs;\n\n /**\n * ID\n */\n private Serializable id;\n\n /**\n * ID 数组\n */\n private List<Serializable> ids;\n\n /**\n * 字段名\n */\n private String field;\n\n /**\n * 值\n */\n private Object value;\n\n /**\n * 值数组\n */\n private List<Object> values;\n\n /**\n * 自定义查询体\n */\n private QueryBody<T> queryBody;\n}" }, { "identifier": "QueryBody", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/query/QueryBody.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class QueryBody<T> {\n\n /**\n * 关键词查询内容\n */\n private String keyword;\n\n /**\n * 关键字查询字段\n */\n private List<String> keywordFields;\n\n /**\n * 结果返回指定字段\n */\n private List<String> includeFields;\n\n /**\n * 查询条件\n */\n private List<QueryCondition> conditions;\n\n /**\n * 排序信息\n */\n private List<QueryOrder> orderBy;\n\n /**\n * 分页信息\n */\n private QueryPage pageBy;\n\n /**\n * 参数合法性检查\n */\n public void check() {\n if (ObjectUtil.isNotEmpty(keyword) && ObjectUtil.isEmpty(keywordFields)) {\n throw new BusinessRunTimeException(\"关键词查询时必须指定 keywordFields,且必须指定为字符类型字段\");\n }\n if (ObjectUtil.isNotEmpty(conditions)) {\n conditions.forEach(QueryCondition::check);\n }\n if (ObjectUtil.isNotEmpty(orderBy)) {\n orderBy.forEach(QueryOrder::check);\n }\n }\n\n /**\n * 构建 QueryWrapper\n *\n * @return QueryWrapper\n */\n public QueryWrapper<T> buildWrapper() {\n QueryWrapper<T> wrapper = new QueryWrapper<>();\n // 关键词\n if (ObjectUtil.isNotEmpty(keywordFields) && ObjectUtil.isNotEmpty(keyword)) {\n wrapper.and(orWrapper -> {\n for (String keywordField : keywordFields) {\n orWrapper.like(VariableNameUtils.humpToLine(keywordField), keyword).or();\n }\n });\n }\n // 指定查询字段\n if (ObjectUtil.isNotEmpty(includeFields)) {\n String[] array = includeFields.stream().map(VariableNameUtils::humpToLine).collect(Collectors.toList()).toArray(new String[]{});\n wrapper.select(array);\n }\n // 查询条件\n if (ObjectUtil.isNotEmpty(conditions)) {\n for (QueryCondition condition : conditions) {\n String field = VariableNameUtils.humpToLine(condition.getField());\n String type = condition.getType();\n Object value = condition.getValue();\n if (\"ALL_DATA\".equals(value)) {\n continue;\n }\n switch (type) {\n case \"eq\": // 等于 =\n wrapper.eq(field, value);\n break;\n case \"ne\": // 不等于 <>\n wrapper.ne(field, value);\n break;\n case \"gt\": // 大于 >\n wrapper.gt(field, value);\n break;\n case \"ge\": // 大于等于 >=\n wrapper.ge(field, value);\n break;\n case \"lt\": // 小于 <\n wrapper.lt(field, value);\n break;\n case \"le\": // 小于等于 <=\n wrapper.le(field, value);\n break;\n case \"contain\": // LIKE '%值%'\n wrapper.like(field, value);\n break;\n case \"notContain\": // NOT LIKE '%值%'\n wrapper.notLike(field, value);\n break;\n case \"startWith\": // LIKE '%值'\n wrapper.likeLeft(field, value);\n break;\n case \"endWith\": // LIKE '值%'\n wrapper.likeRight(field, value);\n break;\n case \"isNull\": // 字段 IS NULL\n wrapper.isNull(field);\n break;\n case \"isNotNull\": // 字段 IS NOT NULL\n wrapper.isNotNull(field);\n break;\n case \"in\": // 字段 IN (value.get(0), value.get(1), ...)\n try {\n wrapper.in(field, parseValue2List(value).toArray());\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"in 操作的值必须为数组\");\n }\n break;\n case \"notIn\": // 字段 NOT IN (value.get(0), value.get(1), ...)\n try {\n wrapper.notIn(field, parseValue2List(value).toArray());\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"notIn 操作的值必须为数组\");\n }\n break;\n case \"between\": // BETWEEN 值1 AND 值2\n try {\n List<Object> betweenList = parseValue2List(value);\n if (betweenList.size() != 2) {\n throw new BusinessRunTimeException(\"between 操作的值必须为数组且长度为 2\");\n }\n wrapper.between(field, betweenList.get(0), betweenList.get(1));\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"between 操作的值必须为数组且长度为 2\");\n }\n break;\n case \"notBetween\": // NOT BETWEEN 值1 AND 值2\n try {\n List<Object> betweenList = parseValue2List(value);\n if (betweenList.size() != 2) {\n throw new BusinessRunTimeException(\"notBetween 操作的值必须为数组且长度为 2\");\n }\n wrapper.notBetween(field, betweenList.get(0), betweenList.get(1));\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"notBetween 操作的值必须为数组且长度为 2\");\n }\n break;\n default:\n throw new BusinessRunTimeException(\"不支持的查询操作:\" + type);\n }\n }\n }\n // 排序\n if (ObjectUtil.isNotEmpty(orderBy)) {\n for (QueryOrder queryOrder : orderBy) {\n String field = VariableNameUtils.humpToLine(queryOrder.getField());\n String type = queryOrder.getType().toLowerCase();\n switch (type) {\n case \"asc\":\n wrapper.orderByAsc(field);\n break;\n case \"desc\":\n wrapper.orderByDesc(field);\n break;\n default:\n throw new BusinessRunTimeException(\"不支持的排序操作:\" + type);\n }\n }\n }\n return wrapper;\n }\n\n /**\n * 构建 IPage\n *\n * @return IPage\n */\n public IPage<T> buildPage() {\n if (ObjectUtil.isEmpty(pageBy) || (ObjectUtil.isEmpty(pageBy.getPageNum()) && ObjectUtil.isEmpty(pageBy.getPageSize()))) {\n return null;\n }\n if (ObjectUtil.isEmpty(pageBy.getPageNum()) || ObjectUtil.isEmpty(pageBy.getPageSize())) {\n throw new BusinessRunTimeException(\"pageNum 与 pageSize 必须同时指定\");\n }\n return new Page<>(pageBy.getPageNum(), pageBy.getPageSize());\n }\n\n /**\n * 将 Object 类型的对象(实际上是 JsonArray) 转为 List\n *\n * @param value 对象\n * @return List\n * @throws IOException JSON 解析异常\n */\n private List<Object> parseValue2List(Object value) throws IOException {\n ObjectMapper objectMapper = new ObjectMapper();\n CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, Object.class);\n return objectMapper.readValue(String.valueOf(value), listType);\n }\n}" }, { "identifier": "ResultPage", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/query/ResultPage.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(callSuper = true)\npublic class ResultPage<T> extends QueryPage {\n\n /**\n * 总记录数\n */\n private Long totalRecord;\n\n /**\n * 总页数\n */\n private Long totalPage;\n\n /**\n * 记录结果\n */\n private List<T> records;\n\n /**\n * 转换分页信息\n *\n * @param wrapperPage Mybatis Pulse分页信息\n */\n public ResultPage(IPage<T> wrapperPage) {\n if (ObjectUtil.isNotEmpty(wrapperPage)) {\n this.pageNum = wrapperPage.getCurrent();\n this.pageSize = wrapperPage.getSize();\n this.totalPage = wrapperPage.getPages();\n this.totalRecord = wrapperPage.getTotal();\n this.records = wrapperPage.getRecords();\n }\n }\n}" }, { "identifier": "BaseDBService", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/service/BaseDBService.java", "snippet": "public class BaseDBService<T> extends ServiceImpl<BaseMapper<T>, T> implements BaseDBInterface<T> {\n\n private final BaseMapper<T> mapper;\n\n public BaseDBService(BaseMapper<T> mapper) {\n this.mapper = mapper;\n }\n\n @Override\n public T saveData(T obj) {\n super.saveOrUpdate(obj);\n return obj;\n }\n\n @Override\n public List<T> saveBatchData(T[] array) {\n List<T> objList = Arrays.stream(array).collect(Collectors.toList());\n return this.saveBatchData(objList);\n }\n\n @Transactional(rollbackFor = Exception.class)\n @Override\n public List<T> saveBatchData(Collection<T> list) {\n // 循环新增,若数据量大可自行扩展\n list.forEach(this::saveData);\n return new ArrayList<>(list);\n }\n\n @Override\n public T insert(T obj) {\n mapper.insert(obj);\n return obj;\n }\n\n @Override\n public List<T> insertBatch(T[] array) {\n List<T> objList = Arrays.stream(array).collect(Collectors.toList());\n return this.insertBatch(objList);\n }\n\n @Override\n public List<T> insertBatch(Collection<T> list) {\n super.saveBatch(list);\n return new ArrayList<>(list);\n }\n\n @Override\n public T update(T obj) {\n mapper.updateById(obj);\n return obj;\n }\n\n @Override\n public List<T> updateBatch(T[] array) {\n List<T> objList = Arrays.stream(array).collect(Collectors.toList());\n return this.updateBatch(objList);\n }\n\n @Override\n public List<T> updateBatch(Collection<T> list) {\n super.updateBatchById(list);\n return new ArrayList<>(list);\n }\n\n @Override\n public int delete(Serializable id) {\n return mapper.deleteById(id);\n }\n\n @Override\n public int deleteBatch(Serializable[] ids) {\n List<Serializable> idList = Arrays.stream(ids).collect(Collectors.toList());\n return this.deleteBatch(idList);\n }\n\n @Override\n public int deleteBatch(Collection<? extends Serializable> ids) {\n return mapper.deleteBatchIds(ids);\n }\n\n @Override\n public int deleteByField(String field, Object value) {\n return mapper.delete(new QueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public int deleteBatchByField(String field, Object[] values) {\n return mapper.delete(new QueryWrapper<T>().in(field, values));\n }\n\n @Override\n public int deleteBatchByField(String field, List<Object> values) {\n return this.deleteBatchByField(field, values.toArray());\n }\n\n @Override\n public T getById(Serializable id) {\n return mapper.selectById(id);\n }\n\n @Override\n public List<T> getByIds(Serializable[] ids) {\n List<Serializable> idList = Arrays.stream(ids).collect(Collectors.toList());\n return this.getByIds(idList);\n }\n\n @Override\n public List<T> getByIds(Collection<? extends Serializable> ids) {\n return mapper.selectBatchIds(ids);\n }\n\n @Override\n public List<T> getAll() {\n return super.list();\n }\n\n @Override\n public List<T> getByWrapper(Wrapper<T> wrapper) {\n return mapper.selectList(wrapper);\n }\n\n @Override\n public List<T> getByField(String field, Object value) {\n return mapper.selectList(new QueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public List<T> getBatchByField(String field, Object[] values) {\n return mapper.selectList(new QueryWrapper<T>().in(field, values));\n }\n\n @Override\n public List<T> getBatchByField(String field, List<Object> values) {\n return this.getBatchByField(field, values.toArray());\n }\n\n @Override\n public List<T> getByObj(T obj) {\n if (ObjectUtil.isEmpty(obj)) {\n return getAll();\n }\n Map<String, Object> bean2Map = BeanUtil.beanToMap(obj);\n return getByMap(bean2Map);\n }\n\n @Override\n public List<T> getByMap(Map<String, Object> map) {\n Map<String, Object> newMap = new HashMap<>();\n for (String key : map.keySet()) {\n if (ObjectUtil.isEmpty(map.get(key))) {\n continue;\n }\n newMap.put(VariableNameUtils.humpToLine(key), map.get(key));\n }\n return mapper.selectByMap(newMap);\n }\n\n @Override\n public int countAll() {\n return super.count();\n }\n\n @Override\n public int countByField(String field, Object value) {\n return mapper.selectCount(new QueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public int countByWrapper(Wrapper<T> wrapper) {\n return mapper.selectCount(wrapper);\n }\n\n @Override\n public int countByObj(T obj) {\n return this.countByMap(BeanUtil.beanToMap(obj));\n }\n\n @Override\n public int countByMap(Map<String, Object> map) {\n return mapper.selectCount(createWrapperFromMap(map));\n }\n\n @Override\n public IPage<T> getByWrapperPage(Wrapper<T> wrapper, IPage<T> page) {\n return mapper.selectPage(page, wrapper);\n }\n\n @Override\n public IPage<T> getByObjPage(T obj, IPage<T> page) {\n return this.getByMapPage(BeanUtil.beanToMap(obj), page);\n }\n\n @Override\n public IPage<T> getByMapPage(Map<String, Object> map, IPage<T> page) {\n return this.getByWrapperPage(createWrapperFromMap(map), page);\n }\n\n /**\n * 通过 Map 创建 QueryWrapper 查询对象\n *\n * @param map 映射\n * @return QueryWrapper\n */\n private QueryWrapper<T> createWrapperFromMap(Map<String, Object> map) {\n QueryWrapper<T> wrapper = new QueryWrapper<>();\n for (Map.Entry<String, Object> temp : map.entrySet()) {\n String key = temp.getKey();\n if (ObjectUtil.isEmpty(temp.getValue())) {\n continue;\n }\n wrapper.eq(VariableNameUtils.humpToLine(key), map.get(key));\n }\n return wrapper;\n }\n}" }, { "identifier": "RespResult", "path": "xw-fast-web/src/main/java/world/xuewei/fast/web/dto/response/RespResult.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class RespResult {\n\n /**\n * 响应编码\n */\n protected String code;\n\n /**\n * 响应信息\n */\n protected String message;\n\n /**\n * 响应数据\n */\n protected Object data;\n\n /**\n * 请求成功\n */\n public static RespResult success() {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(\"请求成功\")\n .build();\n }\n\n /**\n * 请求成功\n */\n public static RespResult success(String message) {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(message)\n .build();\n }\n\n /**\n * 请求成功\n */\n public static RespResult success(String message, Object data) {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(message)\n .data(data)\n .build();\n }\n\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound() {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(\"请求资源不存在\")\n .build();\n }\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound(String message) {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(String.format(\"%s不存在\", message))\n .build();\n }\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound(String message, Object data) {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(String.format(\"%s不存在\", message))\n .data(data)\n .build();\n }\n\n /**\n * 请求参数不能为空\n */\n public static RespResult paramEmpty() {\n return RespResult.builder()\n .code(\"PARAM_EMPTY\")\n .message(\"请求参数为空\")\n .build();\n }\n\n /**\n * 请求参数不能为空\n */\n public static RespResult paramEmpty(String message) {\n return RespResult.builder()\n .code(\"PARAM_EMPTY\")\n .message(String.format(\"%s参数为空\", message))\n .build();\n }\n\n /**\n * 请求参数不能为空\n */\n public static RespResult paramEmpty(String message, Object data) {\n return RespResult.builder()\n .code(\"PARAM_EMPTY\")\n .message(String.format(\"%s参数为空\", message))\n .data(data)\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail() {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(\"请求失败\")\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail(String message) {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(message)\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail(String message, Object data) {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(message)\n .data(data)\n .build();\n }\n\n /**\n * 请求是否成功\n */\n public boolean yesSuccess() {\n return \"SUCCESS\".equals(code);\n }\n\n /**\n * 请求是否成功并有数据返回\n */\n public boolean yesSuccessWithDateResp() {\n return \"SUCCESS\".equals(code) && ObjectUtil.isNotEmpty(data);\n }\n\n /**\n * 请求是否成功\n */\n public boolean notSuccess() {\n return !yesSuccess();\n }\n}" } ]
import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import world.xuewei.fast.core.exception.BusinessRunTimeException; import world.xuewei.fast.core.exception.ParamEmptyException; import world.xuewei.fast.crud.dto.request.ReqBody; import world.xuewei.fast.crud.query.QueryBody; import world.xuewei.fast.crud.query.ResultPage; import world.xuewei.fast.crud.service.BaseDBService; import world.xuewei.fast.web.dto.response.RespResult; import java.io.Serializable; import java.util.List;
7,229
package world.xuewei.fast.crud.controller; /** * 基础控制器 * * @author XUEW * @since 2023/11/1 18:02 */ public class BaseController<T> { protected final BaseDBService<T> baseService; public BaseController(BaseDBService<T> baseService) { this.baseService = baseService; } /** * 保存实体 * * @param reqBody 通用请求体 * @return 实体对象 */ @PostMapping("/saveData") @ResponseBody public RespResult saveData(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("新增成功", baseService.saveData(obj)); } /** * 批量保存实体 * * @param reqBody 通用请求体 * @return 实体对象列表 */ @PostMapping("/saveBatchData") @ResponseBody public RespResult saveBatchData(@RequestBody ReqBody<T> reqBody) { List<T> objs = Assert.notEmpty(reqBody.getObjs(), () -> ParamEmptyException.build("实体数组[objs]")); return RespResult.success("新增成功", baseService.saveBatchData(objs)); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/delete") @ResponseBody public RespResult delete(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); int deleted = baseService.delete(id); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteBatch") @ResponseBody public RespResult deleteBatch(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); int deleted = baseService.deleteBatch(ids); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteByField") @ResponseBody public RespResult deleteByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); int deleted = baseService.deleteByField(field, value); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/deleteBatchByField") @ResponseBody public RespResult deleteBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); int deleted = baseService.deleteBatchByField(field, values); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getById") @ResponseBody public RespResult getById(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); T t = baseService.getById(id); return ObjectUtil.isEmpty(t) ? RespResult.notFound("目标") : RespResult.success("查询成功", t); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByIds") @ResponseBody public RespResult getByIds(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); return RespResult.success("查询成功", baseService.getByIds(ids)); } /** * 通过实体查询数据集合 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByObj") @ResponseBody public RespResult getByObj(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("查询成功", baseService.getByObj(obj)); } /** * 通过指定字段和值查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByField") @ResponseBody public RespResult getByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); return RespResult.success("查询成功", baseService.getByField(field, value)); } /** * 通过指定字段及对应值查询数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getBatchByField") @ResponseBody public RespResult getBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); return RespResult.success("查询成功", baseService.getBatchByField(field, values)); } /** * 查询全部 * * @return 出参 */ @PostMapping("/getAll") @ResponseBody public RespResult getAll() { return RespResult.success("查询成功", baseService.getAll()); } /** * 自定义查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/customQuery") @ResponseBody public RespResult customQuery(@RequestBody ReqBody<T> reqBody) { QueryBody<T> queryBody = Assert.notNull(reqBody.getQueryBody(), () -> ParamEmptyException.build("查询策略[queryBody]")); // 参数合法性检查 queryBody.check(); QueryWrapper<T> queryWrapper = queryBody.buildWrapper(); IPage<T> page = queryBody.buildPage(); try { if (ObjectUtil.isNotEmpty(page)) { IPage<T> wrapperPage = baseService.getByWrapperPage(queryWrapper, page); ResultPage<T> resultPage = new ResultPage<>(wrapperPage); return RespResult.success("查询成功", resultPage); } else { List<T> byWrapper = baseService.getByWrapper(queryWrapper); return RespResult.success("查询成功", byWrapper); } } catch (BadSqlGrammarException e) {
package world.xuewei.fast.crud.controller; /** * 基础控制器 * * @author XUEW * @since 2023/11/1 18:02 */ public class BaseController<T> { protected final BaseDBService<T> baseService; public BaseController(BaseDBService<T> baseService) { this.baseService = baseService; } /** * 保存实体 * * @param reqBody 通用请求体 * @return 实体对象 */ @PostMapping("/saveData") @ResponseBody public RespResult saveData(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("新增成功", baseService.saveData(obj)); } /** * 批量保存实体 * * @param reqBody 通用请求体 * @return 实体对象列表 */ @PostMapping("/saveBatchData") @ResponseBody public RespResult saveBatchData(@RequestBody ReqBody<T> reqBody) { List<T> objs = Assert.notEmpty(reqBody.getObjs(), () -> ParamEmptyException.build("实体数组[objs]")); return RespResult.success("新增成功", baseService.saveBatchData(objs)); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/delete") @ResponseBody public RespResult delete(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); int deleted = baseService.delete(id); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteBatch") @ResponseBody public RespResult deleteBatch(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); int deleted = baseService.deleteBatch(ids); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteByField") @ResponseBody public RespResult deleteByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); int deleted = baseService.deleteByField(field, value); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/deleteBatchByField") @ResponseBody public RespResult deleteBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); int deleted = baseService.deleteBatchByField(field, values); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getById") @ResponseBody public RespResult getById(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); T t = baseService.getById(id); return ObjectUtil.isEmpty(t) ? RespResult.notFound("目标") : RespResult.success("查询成功", t); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByIds") @ResponseBody public RespResult getByIds(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); return RespResult.success("查询成功", baseService.getByIds(ids)); } /** * 通过实体查询数据集合 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByObj") @ResponseBody public RespResult getByObj(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("查询成功", baseService.getByObj(obj)); } /** * 通过指定字段和值查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByField") @ResponseBody public RespResult getByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); return RespResult.success("查询成功", baseService.getByField(field, value)); } /** * 通过指定字段及对应值查询数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getBatchByField") @ResponseBody public RespResult getBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); return RespResult.success("查询成功", baseService.getBatchByField(field, values)); } /** * 查询全部 * * @return 出参 */ @PostMapping("/getAll") @ResponseBody public RespResult getAll() { return RespResult.success("查询成功", baseService.getAll()); } /** * 自定义查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/customQuery") @ResponseBody public RespResult customQuery(@RequestBody ReqBody<T> reqBody) { QueryBody<T> queryBody = Assert.notNull(reqBody.getQueryBody(), () -> ParamEmptyException.build("查询策略[queryBody]")); // 参数合法性检查 queryBody.check(); QueryWrapper<T> queryWrapper = queryBody.buildWrapper(); IPage<T> page = queryBody.buildPage(); try { if (ObjectUtil.isNotEmpty(page)) { IPage<T> wrapperPage = baseService.getByWrapperPage(queryWrapper, page); ResultPage<T> resultPage = new ResultPage<>(wrapperPage); return RespResult.success("查询成功", resultPage); } else { List<T> byWrapper = baseService.getByWrapper(queryWrapper); return RespResult.success("查询成功", byWrapper); } } catch (BadSqlGrammarException e) {
throw new BusinessRunTimeException("查询失败:{}", e.getMessage());
0
2023-11-07 11:45:40+00:00
12k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/LibraryFragment.java
[ { "identifier": "MyViewPagerAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/viewpager/MyViewPagerAdapter.java", "snippet": "public class MyViewPagerAdapter extends FragmentStatePagerAdapter {\n public MyViewPagerAdapter(@NonNull FragmentManager fm, int behavior) {\n super(fm, behavior);\n }\n\n @NonNull\n @Override\n public Fragment getItem(int position) {\n return switch (position) {\n case 1 -> new FoldersFragment();\n case 2 -> new MyClassesFragment();\n default -> new StudySetsFragment();\n };\n }\n\n @Override\n public int getCount() {\n return 3;\n }\n\n @Nullable\n @Override\n public CharSequence getPageTitle(int position) {\n return switch (position) {\n case 0 -> \"Study sets\";\n case 1 -> \"Folders\";\n case 2 -> \"Classes\";\n default -> \"\";\n };\n }\n}" }, { "identifier": "UserDAO", "path": "app/src/main/java/com/daominh/quickmem/data/dao/UserDAO.java", "snippet": "public class UserDAO {\n\n private final QMDatabaseHelper qmDatabaseHelper;\n private SQLiteDatabase sqLiteDatabase;\n\n public UserDAO(Context context) {\n qmDatabaseHelper = new QMDatabaseHelper(context);\n }\n\n //insert user\n public long insertUser(User user) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"id\", user.getId());\n contentValues.put(\"name\", user.getName());\n contentValues.put(\"email\", user.getEmail());\n contentValues.put(\"username\", user.getUsername());\n contentValues.put(\"password\", user.getPassword());\n contentValues.put(\"avatar\", user.getAvatar());\n contentValues.put(\"role\", user.getRole());\n contentValues.put(\"created_at\", user.getCreated_at());\n contentValues.put(\"updated_at\", user.getUpdated_at());\n contentValues.put(\"status\", user.getStatus());\n\n try {\n return sqLiteDatabase.insert(QMDatabaseHelper.TABLE_USERS, null, contentValues);\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"insertUser: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //check email is exist\n public boolean checkEmail(String email) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE email = '\" + email + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n return cursor.getCount() > 0;\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkEmail: \" + e);\n return false;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //check username exists\n public boolean checkUsername(String username) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE username = '\" + username + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n return cursor.getCount() > 0;\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkUsername: \" + e);\n return false;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //check if username is existed\n\n //check password with email\n public boolean checkPasswordEmail(String email, String password) {\n return checkPassword(email, password);\n }\n\n //check password with username\n public boolean checkPasswordUsername(String username, String password) {\n return checkPassword(username, password);\n }\n\n private boolean checkPassword(String identifier, String password) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n password = PasswordHasher.hashPassword(password);\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE email = '\" + identifier + \"' OR username = '\" + identifier + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n int passwordIndex = cursor.getColumnIndex(\"password\");\n if (passwordIndex != -1) {\n String hashedPassword = cursor.getString(passwordIndex);\n assert password != null;\n return password.equals(hashedPassword);\n }\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkPassword: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return false;\n }\n\n //get user by email not contain password\n public User getUserByEmail(String email) {\n return getUserByIdentifier(email);\n }\n\n //get email by username\n public String getEmailByUsername(String username) {\n User user = getUserByIdentifier(username);\n return user != null ? user.getEmail() : null;\n }\n\n @SuppressLint(\"Range\")\n private User getUserByIdentifier(String identifier) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE email = '\" + identifier + \"' OR username = '\" + identifier + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n String email = cursor.getString(cursor.getColumnIndex(\"email\"));\n String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n int role = cursor.getInt(cursor.getColumnIndex(\"role\"));\n String created_at = cursor.getString(cursor.getColumnIndex(\"created_at\"));\n String updated_at = cursor.getString(cursor.getColumnIndex(\"updated_at\"));\n int status = cursor.getInt(cursor.getColumnIndex(\"status\"));\n\n return new User(id, name, email, username, null, avatar, role, created_at, updated_at, status);\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getUserByIdentifier: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n //get password by id user\n @SuppressLint(\"Range\")\n public String getPasswordUser(String id) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id = '\" + id + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n return cursor.getString(cursor.getColumnIndex(\"password\"));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getPasswordUser: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n //update status user by id\n public long updateUser(String id, ContentValues contentValues) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n\n try {\n return sqLiteDatabase.update(QMDatabaseHelper.TABLE_USERS, contentValues, \"id = ?\", new String[]{id});\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"updateUser: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //update email by id user\n public long updateEmailUser(String id, String email) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"email\", email);\n return updateUser(id, contentValues);\n }\n\n //update username by id user\n public long updateUsernameUser(String id, String username) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"username\", username);\n return updateUser(id, contentValues);\n }\n\n //update password by id user\n public long updatePasswordUser(String id, String password) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"password\", password);\n return updateUser(id, contentValues);\n }\n\n //update status by id user\n public void updateStatusUser(String id, int status) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"status\", status);\n updateUser(id, contentValues);\n }\n\n @SuppressLint(\"Range\")\n //get all user to not contain password\n public ArrayList<User> getAllUser() {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n ArrayList<User> users = new ArrayList<>();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS;\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n while (cursor.moveToNext()) {\n String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n String email = cursor.getString(cursor.getColumnIndex(\"email\"));\n String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n int role = cursor.getInt(cursor.getColumnIndex(\"role\"));\n String created_at = cursor.getString(cursor.getColumnIndex(\"created_at\"));\n String updated_at = cursor.getString(cursor.getColumnIndex(\"updated_at\"));\n int status = cursor.getInt(cursor.getColumnIndex(\"status\"));\n\n users.add(new User(id, name, email, username, null, avatar, role, created_at, updated_at, status));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getAllUser: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return users;\n }\n\n @SuppressLint(\"Range\")\n //get user by id not contain password\n public User getUserById(String id) {\n\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id = '\" + id + \"'\";\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n String email = cursor.getString(cursor.getColumnIndex(\"email\"));\n String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n int role = cursor.getInt(cursor.getColumnIndex(\"role\"));\n String created_at = cursor.getString(cursor.getColumnIndex(\"created_at\"));\n String updated_at = cursor.getString(cursor.getColumnIndex(\"updated_at\"));\n int status = cursor.getInt(cursor.getColumnIndex(\"status\"));\n\n return new User(id, name, email, username, null, avatar, role, created_at, updated_at, status);\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getUserById: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n //get list user by id class just need id, username, avatar\n public ArrayList<User> getListUserByIdClass(String idClass) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n ArrayList<User> users = new ArrayList<>();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id IN (SELECT user_id FROM \" + QMDatabaseHelper.TABLE_CLASSES_USERS + \" WHERE class_id = '\" + idClass + \"')\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n while (cursor.moveToNext()) {\n @SuppressLint(\"Range\") String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n @SuppressLint(\"Range\") String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n @SuppressLint(\"Range\") String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n\n users.add(new User(id, null, null, username, null, avatar, 0, null, null, 0));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getListUserByIdClass: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return users;\n }\n\n //get all user just need id, username, avatar\n public ArrayList<User> getAllUserJustNeed() {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n ArrayList<User> users = new ArrayList<>();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS;\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n while (cursor.moveToNext()) {\n @SuppressLint(\"Range\") String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n @SuppressLint(\"Range\") String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n @SuppressLint(\"Range\") String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n Log.e(\"UserDAO\", \"getAllUserJustNeed: \" + id + \" \" + username + \" \" + avatar);\n\n users.add(new User(id, null, null, username, null, avatar, 0, null, null, 0));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getAllUserJustNeed: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n for (User user : users) {\n if (user.getUsername().equals(\"admin\")) {\n users.remove(user);\n break;\n }\n\n }\n return users;\n }\n\n //get user by id class just need username, avatar by id\n public User getUserByIdClass(String id) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id = '\" + id + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n @SuppressLint(\"Range\") String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n @SuppressLint(\"Range\") String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n\n return new User(id, null, null, username, null, avatar, 0, null, null, 0);\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getUserByIdClass: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n // check if user is in class\n public boolean checkUserInClass(String userId, String classId) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_CLASSES_USERS + \" WHERE user_id = '\" + userId + \"' AND class_id = '\" + classId + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n return cursor.getCount() > 0;\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkUserInClass: \" + e);\n return false;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n // remove user from class\n public long removeUserFromClass(String userId, String classId) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n String query = \"DELETE FROM \" + QMDatabaseHelper.TABLE_CLASSES_USERS + \" WHERE user_id = '\" + userId + \"' AND class_id = '\" + classId + \"'\";\n\n try {\n return sqLiteDatabase.delete(QMDatabaseHelper.TABLE_CLASSES_USERS, \"user_id = ? AND class_id = ?\", new String[]{userId, classId});\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"removeUserFromClass: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n // add user to class\n public long addUserToClass(String userId, String classId) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"user_id\", userId);\n contentValues.put(\"class_id\", classId);\n\n try {\n return sqLiteDatabase.insert(QMDatabaseHelper.TABLE_CLASSES_USERS, null, contentValues);\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"addUserToClass: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n}" }, { "identifier": "User", "path": "app/src/main/java/com/daominh/quickmem/data/model/User.java", "snippet": "public class User {\n private String id;\n private String name;\n private String email;\n private String username;\n private String password;\n private String avatar;\n private int role;\n private String created_at;\n private String updated_at;\n private int status;\n\n public User() {\n }\n\n public User(String id, String name, String email, String username, String password, String avatar, int role, String created_at, String updated_at, int status) {\n this.id = id;\n this.name = name;\n this.email = email;\n this.username = username;\n this.password = password;\n this.avatar = avatar;\n this.role = role;\n this.created_at = created_at;\n this.updated_at = updated_at;\n this.status = status;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\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\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public int getRole() {\n return role;\n }\n\n public void setRole(int role) {\n this.role = role;\n }\n\n public String getCreated_at() {\n return created_at;\n }\n\n public void setCreated_at(String created_at) {\n this.created_at = created_at;\n }\n\n public String getUpdated_at() {\n return updated_at;\n }\n\n public void setUpdated_at(String updated_at) {\n this.updated_at = updated_at;\n }\n\n public int getStatus() {\n return status;\n }\n\n public void setStatus(int status) {\n this.status = status;\n }\n}" }, { "identifier": "UserSharePreferences", "path": "app/src/main/java/com/daominh/quickmem/preferen/UserSharePreferences.java", "snippet": "public class UserSharePreferences {\n\n //create variables\n public static final String KEY_LOGIN = \"login\";\n public static final String KEY_ID = \"id\";\n private static final String KEY_AVATAR = \"avatar\";\n private static final String KEY_USER_NAME = \"user_name\";\n private static final String KEY_ROLE = \"role_user\";\n private static final String KEY_STATUS = \"status\";\n private static final String KEY_EMAIL = \"email\";\n public static final String KEY_CLASS_ID = \"class_id\";\n\n private final SharedPreferences sharedPreferences;\n\n public UserSharePreferences(Context context) {\n sharedPreferences = context.getSharedPreferences(\"user\", Context.MODE_PRIVATE);\n }\n\n //set login\n public void setLogin(boolean login) {\n sharedPreferences.edit().putBoolean(KEY_LOGIN, login).apply();\n }\n\n //get login\n public boolean getLogin() {\n return sharedPreferences.getBoolean(KEY_LOGIN, false);\n }\n\n //set id\n public void setId(String id) {\n sharedPreferences.edit().putString(KEY_ID, id).apply();\n }\n\n //get id\n public String getId() {\n return sharedPreferences.getString(KEY_ID, \"\");\n }\n\n // get, set role user\n public void setRole(int role) {\n sharedPreferences.edit().putInt(KEY_ROLE, role).apply();\n }\n\n //get role user\n public int getRole() {\n return sharedPreferences.getInt(KEY_ROLE, -1);\n }\n\n //set,get status\n public void setStatus(int status) {\n sharedPreferences.edit().putInt(KEY_STATUS, status).apply();\n }\n\n //get status\n public int getStatus() {\n return sharedPreferences.getInt(KEY_STATUS, -1);\n }\n\n //set avatar\n public void setAvatar(String avatar) {\n sharedPreferences.edit().putString(KEY_AVATAR, avatar).apply();\n }\n\n //get avatar\n public String getAvatar() {\n return sharedPreferences.getString(KEY_AVATAR, \"\");\n }\n\n //set username\n public void setUserName(String userName) {\n sharedPreferences.edit().putString(KEY_USER_NAME, userName).apply();\n }\n\n //get username\n public String getUserName() {\n return sharedPreferences.getString(KEY_USER_NAME, \"\");\n }\n\n //set email\n public void setEmail(String email) {\n sharedPreferences.edit().putString(KEY_EMAIL, email).apply();\n }\n\n //get email\n public String getEmail() {\n return sharedPreferences.getString(KEY_EMAIL, \"\");\n }\n\n //set class id\n public void setClassId(String classId) {\n sharedPreferences.edit().putString(KEY_CLASS_ID, classId).apply();\n }\n\n //get class id\n public String getClassId() {\n return sharedPreferences.getString(KEY_CLASS_ID, \"\");\n }\n\n //remove class id\n public void removeClassId() {\n sharedPreferences.edit().remove(KEY_CLASS_ID).apply();\n }\n\n //set user\n public void saveUser(User user) {\n setId(user.getId());\n setUserName(user.getUsername());\n setEmail(user.getEmail());\n setAvatar(user.getAvatar());\n setRole(user.getRole());\n setStatus(user.getStatus());\n setLogin(true);\n }\n\n //clear\n public void clear() {\n sharedPreferences.edit().clear().apply();\n }\n}" }, { "identifier": "CreateClassActivity", "path": "app/src/main/java/com/daominh/quickmem/ui/activities/create/CreateClassActivity.java", "snippet": "public class CreateClassActivity extends AppCompatActivity {\n ActivityCreateClassBinding binding;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = ActivityCreateClassBinding.inflate(getLayoutInflater());\n final View view = binding.getRoot();\n setContentView(view);\n\n setSupportActionBar(binding.toolbar);\n binding.toolbar.setNavigationOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());\n\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_tick, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(@NonNull MenuItem item) {\n if (item.getItemId() == R.id.done) {\n if (validate()) {\n String name = binding.classEt.getText().toString();\n String description = binding.descriptionEt.getText().toString();\n boolean status = binding.privateSt.isChecked();\n\n String id = genUUID();\n String user_id = getUser_id();\n String created_at = getCurrentDate();\n String updated_at = getCurrentDate();\n\n GroupDAO groupDAO = new GroupDAO(this);\n Group group = new Group();\n group.setName(name);\n group.setDescription(description);\n group.setStatus(status ? 1 : 0);\n group.setId(id);\n group.setUser_id(user_id);\n group.setCreated_at(created_at);\n group.setUpdated_at(updated_at);\n\n if (groupDAO.insertGroup(group) > 0) {\n getOnBackPressedDispatcher().onBackPressed();\n Toast.makeText(this, \"Create class success\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(this, \"Create class failed\", Toast.LENGTH_SHORT).show();\n }\n } else {\n Toast.makeText(this, \"Please enter class name\", Toast.LENGTH_SHORT).show();\n }\n }\n return super.onOptionsItemSelected(item);\n }\n\n private boolean validate() {\n if (binding.classEt.getText().toString().isEmpty()) {\n binding.classTil.setHelperText(\"Please enter class name\");\n return false;\n } else {\n binding.classTil.setHelperText(\"\");\n return true;\n }\n }\n\n private String getCurrentDate() {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n return getCurrentDateNewApi();\n } else {\n return getCurrentDateOldApi();\n }\n }\n\n private String genUUID() {\n return java.util.UUID.randomUUID().toString();\n }\n\n private String getUser_id() {\n UserSharePreferences userSharePreferences = new UserSharePreferences(this);\n return userSharePreferences.getId();\n }\n\n @RequiresApi(api = Build.VERSION_CODES.O)\n private String getCurrentDateNewApi() {\n LocalDate currentDate = LocalDate.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\n return currentDate.format(formatter);\n }\n\n private String getCurrentDateOldApi() {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n return sdf.format(new Date());\n }\n}" }, { "identifier": "CreateFolderActivity", "path": "app/src/main/java/com/daominh/quickmem/ui/activities/create/CreateFolderActivity.java", "snippet": "public class CreateFolderActivity extends AppCompatActivity {\n private ActivityCreateFolderBinding binding;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = ActivityCreateFolderBinding.inflate(getLayoutInflater());\n final View view = binding.getRoot();\n setContentView(view);\n\n setSupportActionBar(binding.toolbar);\n binding.toolbar.setNavigationOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());\n\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_tick, menu);\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(@NonNull MenuItem item) {\n final int itemId = item.getItemId();\n if (itemId == R.id.done) {\n final String folderName = binding.folderEt.getText().toString().trim();\n final String description = binding.descriptionEt.getText().toString().trim();\n if (folderName.isEmpty()) {\n binding.folderTil.setError(\"\");\n binding.folderTil.setHelperText(\"Folder name cannot be empty\");\n binding.folderEt.requestFocus();\n return false;\n } else {\n final String folderId = genUUID();\n final String userId = getUser_id();\n final String createdAt = getCurrentDate();\n final String updatedAt = getCurrentDate();\n\n Folder folder = new Folder(folderId, folderName, description, userId, createdAt, updatedAt);\n FolderDAO folderDAO = new FolderDAO(this);\n if (folderDAO.insertFolder(folder) > 0) {\n Toast.makeText(this, \"Folder created\", Toast.LENGTH_SHORT).show();\n startActivity(new Intent(this, ViewFolderActivity.class).putExtra(\"id\", folderId));\n finish();\n } else {\n Toast.makeText(this, \"Folder not created\", Toast.LENGTH_SHORT).show();\n }\n\n }\n }\n return super.onOptionsItemSelected(item);\n }\n\n private String getCurrentDate() {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n return getCurrentDateNewApi();\n } else {\n return getCurrentDateOldApi();\n }\n }\n\n\n private String genUUID() {\n return java.util.UUID.randomUUID().toString();\n }\n\n private String getUser_id() {\n UserSharePreferences userSharePreferences = new UserSharePreferences(this);\n return userSharePreferences.getId();\n }\n\n @RequiresApi(api = Build.VERSION_CODES.O)\n private String getCurrentDateNewApi() {\n LocalDate currentDate = LocalDate.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\n return currentDate.format(formatter);\n }\n\n private String getCurrentDateOldApi() {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n return sdf.format(new Date());\n }\n\n}" }, { "identifier": "CreateSetActivity", "path": "app/src/main/java/com/daominh/quickmem/ui/activities/create/CreateSetActivity.java", "snippet": "public class CreateSetActivity extends AppCompatActivity {\n private CardAdapter cardAdapter;\n private ArrayList<Card> cards;\n private ActivityCreateSetBinding binding;\n private final String id = genUUID();\n\n @SuppressLint(\"NotifyDataSetChanged\")\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = ActivityCreateSetBinding.inflate(getLayoutInflater());\n final View view = binding.getRoot();\n setContentView(view);\n\n setupToolbar();\n setupSubjectEditText();\n setupDescriptionTextView();\n setupCardsList();\n setupCardAdapter();\n setupAddFab();\n setupItemTouchHelper();\n }\n\n private void setupToolbar() {\n setSupportActionBar(binding.toolbar);\n binding.toolbar.setNavigationOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());\n }\n\n private void setupSubjectEditText() {\n if (binding.subjectEt.getText().toString().isEmpty()) {\n binding.subjectEt.requestFocus();\n }\n }\n\n private void setupDescriptionTextView() {\n binding.descriptionTv.setOnClickListener(v -> {\n if (binding.descriptionTil.getVisibility() == View.GONE) {\n binding.descriptionTil.setVisibility(View.VISIBLE);\n } else {\n binding.descriptionTil.setVisibility(View.GONE);\n }\n });\n }\n\n private void setupCardsList() {\n //create list two set\n cards = new ArrayList<>();\n cards.add(new Card());\n cards.add(new Card());\n updateTotalCards();\n }\n\n private void updateTotalCards() {\n binding.totalCardsTv.setText(String.format(\"Total Cards: %s\", cards.size()));\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupCardAdapter() {\n cardAdapter = new CardAdapter(this, cards);\n binding.cardsLv.setAdapter(cardAdapter);\n binding.cardsLv.setLayoutManager(new LinearLayoutManager(this));\n binding.cardsLv.setHasFixedSize(true);\n cardAdapter.notifyDataSetChanged();\n\n }\n\n private void setupAddFab() {\n binding.addFab.setOnClickListener(v -> {\n if (!checkTwoCardsEmpty()) {\n\n Card newCard = new Card();\n cards.add(newCard);\n //scroll to last item\n binding.cardsLv.smoothScrollToPosition(cards.size() - 1);\n //notify adapter\n cardAdapter.notifyItemInserted(cards.size() - 1);\n updateTotalCards();\n\n } else {\n Toast.makeText(this, \"Please enter front and back\", Toast.LENGTH_SHORT).show();\n }\n\n });\n }\n\n\n private void setupItemTouchHelper() {\n ItemTouchHelper.SimpleCallback callback = createItemTouchHelperCallback();\n ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);\n itemTouchHelper.attachToRecyclerView(binding.cardsLv);\n }\n\n private ItemTouchHelper.SimpleCallback createItemTouchHelperCallback() {\n return new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {\n @Override\n public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {\n return false;\n }\n\n @Override\n public void onSwiped(@NotNull RecyclerView.ViewHolder viewHolder, int direction) {\n handleOnSwiped(viewHolder);\n }\n\n @Override\n public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {\n handleOnChildDraw(c, viewHolder, dX);\n }\n };\n }\n\n private void handleOnSwiped(RecyclerView.ViewHolder viewHolder) {\n int position = viewHolder.getBindingAdapterPosition();\n\n // Backup of removed item for undo purpose\n Card deletedItem = cards.get(position);\n\n // Removing item from recycler view\n cards.remove(position);\n updateTotalCards();\n cardAdapter.notifyItemRemoved(position);\n\n // Showing Snack bar with an Undo option\n Snackbar snackbar = Snackbar.make(binding.getRoot(), \"Item was removed from the list.\", Snackbar.LENGTH_LONG);\n snackbar.setAction(\"UNDO\", view -> {\n\n // Check if the position is valid before adding the item back\n if (position >= 0 && position <= cards.size()) {\n cards.add(position, deletedItem);\n cardAdapter.notifyItemInserted(position);\n updateTotalCards();\n } else {\n // If the position isn't valid, show a message or handle the error appropriately\n Toast.makeText(getApplicationContext(), \"Error restoring item\", Toast.LENGTH_LONG).show();\n }\n });\n snackbar.setActionTextColor(Color.YELLOW);\n snackbar.show();\n }\n\n private void handleOnChildDraw(@NotNull Canvas c, @NotNull RecyclerView.ViewHolder viewHolder, float dX) {\n Drawable icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_delete);\n View itemView = viewHolder.itemView;\n assert icon != null;\n int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;\n int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;\n int iconBottom = iconTop + icon.getIntrinsicHeight();\n\n if (dX < 0) { // Swiping to the left\n int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();\n int iconRight = itemView.getRight() - iconMargin;\n icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);\n\n final ColorDrawable background = new ColorDrawable(Color.WHITE);\n background.setBounds(itemView.getRight() + ((int) dX), itemView.getTop(), itemView.getRight(), itemView.getBottom());\n background.draw(c);\n } else { // No swipe\n icon.setBounds(0, 0, 0, 0);\n }\n\n icon.draw(c);\n }\n\n @Override\n public boolean onPrepareOptionsMenu(Menu menu) {\n return super.onPrepareOptionsMenu(menu);\n\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_create_set, menu);\n return true;\n\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n if (item.getItemId() == R.id.done) {\n saveChanges();\n return true;\n }\n return super.onOptionsItemSelected(item);\n\n }\n\n private void saveChanges() {\n String subject = binding.subjectEt.getText().toString();\n String description = binding.descriptionEt.getText().toString();\n\n if (subject.isEmpty()) {\n binding.subjectTil.setError(\"Please enter subject\");\n binding.subjectEt.requestFocus();\n return;\n } else {\n binding.subjectTil.setError(null);\n }\n\n if (!saveAllCards()) {\n return;\n }\n\n if (!saveFlashCard(subject, description)) {\n Toast.makeText(this, \"Insert flashcard failed\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n Intent intent = new Intent(this, ViewSetActivity.class);\n intent.putExtra(\"id\", id);\n startActivity(intent);\n finish();\n }\n\n private boolean saveAllCards() {\n for (Card card : cards) {\n if (!saveCard(card)) {\n return false;\n }\n }\n return true;\n }\n\n private boolean saveCard(Card card) {\n String front = card.getFront();\n String back = card.getBack();\n\n if (front == null || front.isEmpty()) {\n binding.cardsLv.requestFocus();\n Toast.makeText(this, \"Please enter front\", Toast.LENGTH_SHORT).show();\n return false;\n }\n\n if (back == null || back.isEmpty()) {\n binding.cardsLv.requestFocus();\n Toast.makeText(this, \"Please enter back\", Toast.LENGTH_SHORT).show();\n return false;\n }\n\n CardDAO cardDAO = new CardDAO(this);\n card.setId(genUUID());\n card.setFront(front);\n card.setBack(back);\n card.setStatus(0);\n card.setIsLearned(0);\n card.setFlashcard_id(id);\n card.setCreated_at(getCurrentDate());\n card.setUpdated_at(getCurrentDate());\n if (cardDAO.insertCard(card) <= 0) {\n Toast.makeText(this, \"Insert card failed\" + id, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n return true;\n }\n\n private boolean saveFlashCard(String subject, String description) {\n FlashCardDAO flashCardDAO = new FlashCardDAO(this);\n FlashCard flashCard = new FlashCard();\n flashCard.setName(subject);\n flashCard.setDescription(description);\n UserSharePreferences userSharePreferences = new UserSharePreferences(this);\n flashCard.setUser_id(userSharePreferences.getId());\n flashCard.setCreated_at(getCurrentDate());\n flashCard.setUpdated_at(getCurrentDate());\n flashCard.setId(id);\n binding.privateSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {\n if (isChecked) {\n Toast.makeText(this, \"Public\", Toast.LENGTH_SHORT).show();\n flashCard.setIs_public(1);\n } else {\n Toast.makeText(this, \"Private\", Toast.LENGTH_SHORT).show();\n flashCard.setIs_public(0);\n }\n });\n\n return flashCardDAO.insertFlashCard(flashCard) > 0;\n }\n\n private String getCurrentDate() {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n return getCurrentDateNewApi();\n } else {\n return getCurrentDateOldApi();\n }\n }\n\n public boolean checkTwoCardsEmpty() {\n // check if 2 cards are empty return true\n int emptyCount = 0;\n for (Card card : cards) {\n if (card.getFront() == null || card.getFront().isEmpty() || card.getBack() == null || card.getBack().isEmpty()) {\n emptyCount++;\n if (emptyCount == 2) {\n return true;\n }\n }\n }\n return false;\n }\n\n private String genUUID() {\n return java.util.UUID.randomUUID().toString();\n }\n\n @RequiresApi(api = Build.VERSION_CODES.O)\n private String getCurrentDateNewApi() {\n LocalDate currentDate = LocalDate.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\n return currentDate.format(formatter);\n }\n\n private String getCurrentDateOldApi() {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n return sdf.format(new Date());\n }\n}" } ]
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentStatePagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.daominh.quickmem.adapter.viewpager.MyViewPagerAdapter; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.data.model.User; import com.daominh.quickmem.databinding.FragmentLibraryBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateClassActivity; import com.daominh.quickmem.ui.activities.create.CreateFolderActivity; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.google.android.material.tabs.TabLayout; import org.jetbrains.annotations.NotNull;
9,503
package com.daominh.quickmem.ui.fragments.home; public class LibraryFragment extends Fragment { private FragmentLibraryBinding binding; private UserSharePreferences userSharePreferences; private int currentTabPosition = 0; private String idUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLibraryBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupViewPager(); setupTabLayout(); setupUserPreferences(); setupAddButton(); } private void setupViewPager() {
package com.daominh.quickmem.ui.fragments.home; public class LibraryFragment extends Fragment { private FragmentLibraryBinding binding; private UserSharePreferences userSharePreferences; private int currentTabPosition = 0; private String idUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLibraryBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupViewPager(); setupTabLayout(); setupUserPreferences(); setupAddButton(); } private void setupViewPager() {
MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter(
0
2023-11-07 16:56:39+00:00
12k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/commands/ArmToPoseCommand.java
[ { "identifier": "ArmSubsystem", "path": "src/main/java/org/frcteam2910/c2023/subsystems/arm/ArmSubsystem.java", "snippet": "public class ArmSubsystem extends SubsystemBase {\n // Distance from pivot point to arm base\n public static final double ARM_PIVOT_OFFSET = Units.inchesToMeters(6.75 - 0.125);\n // Distance from origin of robot to pivot point\n public static final Translation2d ORIGIN_PIVOT_OFFSET =\n new Translation2d(-Units.inchesToMeters(10.25), Units.inchesToMeters(13.25));\n public static final double MIN_EXTENSION_LENGTH = Units.inchesToMeters(22.75);\n public static final double MAX_EXTENSION_LENGTH = Units.inchesToMeters(53);\n public static final double MAX_WRIST_ANGLE_RAD = Units.degreesToRadians(113.1);\n public static final double MIN_RETRACTED_WRIST_ANGLE_RAD = Units.degreesToRadians(-73);\n public static final double MIN_EXTENDED_WRIST_ANGLE_RAD = Units.degreesToRadians(-80);\n public static final double MIN_DANGER_ZONE_WRIST_ANGLE = Units.degreesToRadians(60);\n public static final double MIN_EXTENDED_ANGLE_MIN = Units.inchesToMeters(26);\n public static final double MIN_SHOULDER_ANGLE_RAD = 0;\n public static final double MAX_SHOULDER_ANGLE_RAD = Units.degreesToRadians(200);\n private static final double AT_TARGET_THRESHOLD = Units.inchesToMeters(1);\n private static final double AT_ROTATION_THRESHOLD = Units.degreesToRadians(2.5);\n private static final double EXTENSION_FAST_ANGLE_THRESHOLD = Units.degreesToRadians(100);\n private static final double EXTENSION_SLOW_FAST_ANGLE_THRESHOLD = Units.degreesToRadians(70);\n public static final double EXTENSION_DANGER_ZONE = MIN_EXTENSION_LENGTH + Units.inchesToMeters(3);\n public static final double SHOULDER_DANGER_ZONE = Units.degreesToRadians(20);\n\n private static final double SHOULDER_LOCK_DISTANCE = Math.toRadians(120.0);\n private static final double SHOULDER_LOCK_EXTENSION_DISTANCE = Units.inchesToMeters(28);\n\n private final ArmIO io;\n private final ArmIOInputsAutoLogged armInputs = new ArmIOInputsAutoLogged();\n\n private final Mechanism2d targetMech = new Mechanism2d(8, 4);\n private final MechanismRoot2d targetRoot =\n targetMech.getRoot(\"arm\", 4 + ORIGIN_PIVOT_OFFSET.getX(), 0 + ORIGIN_PIVOT_OFFSET.getY());\n private final MechanismLigament2d targetShoulder = targetRoot.append(\n new MechanismLigament2d(\"targetShoulder\", ARM_PIVOT_OFFSET, 270, 10, new Color8Bit(Color.kRed)));\n private final MechanismLigament2d targetArm =\n targetShoulder.append(new MechanismLigament2d(\"targetArm\", 1, 90, 10, new Color8Bit(Color.kWhite)));\n private final MechanismLigament2d targetWrist = targetArm.append(new MechanismLigament2d(\"targetWrist\", .3, 0));\n\n private final Mechanism2d currentMech = new Mechanism2d(8, 4);\n private final MechanismRoot2d currentRoot =\n currentMech.getRoot(\"arm\", 4 + ORIGIN_PIVOT_OFFSET.getX(), 0 + ORIGIN_PIVOT_OFFSET.getY());\n private final MechanismLigament2d currentShoulder = targetRoot.append(\n new MechanismLigament2d(\"currentShoulder\", ARM_PIVOT_OFFSET, 270, 10, new Color8Bit(Color.kSilver)));\n private final MechanismLigament2d currentArm =\n currentShoulder.append(new MechanismLigament2d(\"currentArm\", 1, 90, 10, new Color8Bit(Color.kYellowGreen)));\n private final MechanismLigament2d currentWrist =\n currentArm.append(new MechanismLigament2d(\"currentWrist\", .3, 0, 10, new Color8Bit(Color.kAqua)));\n\n private Pose2d currentPose = new Pose2d();\n private ArmPositions targetPose;\n\n private boolean zeroed = false;\n private boolean isTeleop = false;\n private boolean isBrakeMode = true;\n\n public enum ArmStates {\n GROUND_INTAKE,\n PORTAL_INTAKE\n }\n\n public ArmSubsystem(ArmIO io) {\n this.io = io;\n }\n\n @Override\n public void periodic() {\n io.updateInputs(armInputs);\n Logger.getInstance().processInputs(\"Arm\", armInputs);\n\n if (Robot.isSimulation() || zeroed) {\n if (targetPose != null) {\n double shoulderTargetAngle = targetPose.getShoulderAngleRad();\n double extensionTargetLength = targetPose.getExtensionLengthMeters();\n double wristTargetAngle = targetPose.getWristAngleRad();\n\n Logger.getInstance().recordOutput(\"Arm/PreProcessedShoulderTargetAngle\", shoulderTargetAngle);\n Logger.getInstance().recordOutput(\"Arm/PreProcessedExtensionTargetLength\", extensionTargetLength);\n Logger.getInstance().recordOutput(\"Arm/PreProcessedWristTargetAngle\", wristTargetAngle);\n\n boolean notWithinThreshold = Math.abs(armInputs.shoulderAngleRad - shoulderTargetAngle)\n > (DriverStation.isTeleop()\n ? EXTENSION_FAST_ANGLE_THRESHOLD\n : EXTENSION_SLOW_FAST_ANGLE_THRESHOLD);\n\n Logger.getInstance().recordOutput(\"Arm/NotWithinShoulderThreshold\", notWithinThreshold);\n Logger.getInstance()\n .recordOutput(\"Arm/ShoulderDelta\", Math.abs(armInputs.shoulderAngleRad - shoulderTargetAngle));\n if (notWithinThreshold) {\n extensionTargetLength = MIN_EXTENSION_LENGTH;\n }\n\n boolean targetInDanger = isInDangerZone(targetPose);\n if (targetInDanger\n && armInputs.wristAngleRad < MIN_DANGER_ZONE_WRIST_ANGLE\n && armInputs.shoulderAngleRad < Units.degreesToRadians(15.0)) {\n extensionTargetLength = Math.max(extensionTargetLength, EXTENSION_DANGER_ZONE);\n }\n\n boolean currentInDanger = isInDangerZone(new ArmPositions(\n armInputs.shoulderAngleRad, armInputs.extensionPositionMeters, armInputs.wristAngleRad));\n\n if (currentInDanger || targetInDanger)\n wristTargetAngle =\n MathUtil.clamp(wristTargetAngle, MIN_DANGER_ZONE_WRIST_ANGLE, MAX_WRIST_ANGLE_RAD);\n\n if (extensionTargetLength < MIN_EXTENDED_ANGLE_MIN\n || armInputs.extensionPositionMeters < MIN_EXTENDED_ANGLE_MIN) {\n wristTargetAngle = Math.max(MIN_RETRACTED_WRIST_ANGLE_RAD, wristTargetAngle);\n } else {\n wristTargetAngle = Math.max(MIN_EXTENDED_WRIST_ANGLE_RAD, wristTargetAngle);\n }\n\n if (armInputs.shoulderAngleRad - targetPose.getShoulderAngleRad() > SHOULDER_LOCK_DISTANCE\n && armInputs.extensionPositionMeters > MAX_EXTENSION_LENGTH - SHOULDER_LOCK_EXTENSION_DISTANCE\n && DriverStation.isTeleop()) {\n shoulderTargetAngle = ArmPoseConstants.SECONDARY_L3_CONE.getShoulderAngleRad();\n }\n\n if (isTeleop != DriverStation.isTeleop()) {\n isTeleop = DriverStation.isTeleop();\n io.setShoulderAccelerationConstraint(isTeleop);\n }\n\n // if (shoulderTargetAngle > armInputs.shoulderAngleRad) {\n // if ((shoulderTargetAngle - armInputs.shoulderAngleRad)\n // > ((Math.abs(armInputs.shoulderAngularVelocityRadPerSec) *\n // armInputs.shoulderAngularVelocityRadPerSec)\n // / (2 * ArmIOFalcon500.SHOULDER_SLOW_ACCELERATION))) {\n // io.setShoulderAccelerationConstraint(true);\n // } else {\n // io.setShoulderAccelerationConstraint(false);\n // }\n // io.setShoulderAccelerationConstraint(true);\n // } else {\n // if (-armInputs.shoulderAngularVelocityRadPerSec >=\n // ArmIOFalcon500.SHOULDER_VELOCITY) {\n // io.setShoulderAccelerationConstraint(true);\n // } else {\n // if (Math.abs((shoulderTargetAngle - armInputs.shoulderAngleRad))\n // < (Math.pow(armInputs.shoulderAngularVelocityRadPerSec, 2)\n // / (2 * ArmIOFalcon500.SHOULDER_SLOW_ACCELERATION))) {\n // io.setShoulderAccelerationConstraint(true);\n // } else {\n // io.setShoulderAccelerationConstraint(false);\n // }\n // }\n // io.setShoulderAccelerationConstraint(false);\n // }\n\n ArmPositions validStates =\n clampValidState(shoulderTargetAngle, extensionTargetLength, wristTargetAngle);\n\n io.setTargetWristAngle(validStates.getWristAngleRad());\n io.setTargetShoulderAngle(validStates.getShoulderAngleRad());\n io.setTargetExtensionLength(validStates.getExtensionLengthMeters());\n\n if (isTargetStowed()) {\n if (atTarget()) {\n io.setExtensionCurrentLimit(false);\n }\n } else {\n io.setExtensionCurrentLimit(true);\n }\n\n targetShoulder.setAngle(270 + Units.radiansToDegrees(shoulderTargetAngle));\n targetArm.setLength(extensionTargetLength);\n targetWrist.setAngle(Units.radiansToDegrees(wristTargetAngle));\n\n Logger.getInstance().recordOutput(\"Arm/TargetInDanger\", targetInDanger);\n Logger.getInstance().recordOutput(\"Arm/CurrentInDanger\", currentInDanger);\n Logger.getInstance().recordOutput(\"Arm/ShoulderTargetAngle\", shoulderTargetAngle);\n Logger.getInstance().recordOutput(\"Arm/ExtensionTargetLength\", extensionTargetLength);\n Logger.getInstance().recordOutput(\"Arm/WristTargetAngle\", wristTargetAngle);\n\n } else {\n io.setWristVoltage(0);\n io.setExtensionVoltage(0);\n io.setShoulderVoltage(0);\n }\n }\n\n currentShoulder.setAngle(270 + Units.radiansToDegrees(armInputs.shoulderAngleRad));\n currentArm.setLength(armInputs.extensionPositionMeters);\n currentWrist.setAngle(Units.radiansToDegrees(armInputs.wristAngleRad));\n\n Logger.getInstance().recordOutput(\"Arm/Current Pose\", currentPose);\n Logger.getInstance().recordOutput(\"Arm/Mechanism\", targetMech);\n }\n\n public void setTargetPose(ArmPositions armPositions) {\n this.targetPose = armPositions;\n }\n\n public void setTargetPose(Pose3d targetPose, Pose2d currentPose) {\n double x;\n if (targetPose.getRotation().getAngle() > -Math.PI / 2\n && targetPose.getRotation().getAngle() < Math.PI / 2) {\n x = -currentPose.getX() + targetPose.getX() - ORIGIN_PIVOT_OFFSET.getX();\n } else {\n x = currentPose.getX() - targetPose.getX() - ORIGIN_PIVOT_OFFSET.getX();\n }\n double y = targetPose.getZ() - ORIGIN_PIVOT_OFFSET.getY();\n\n this.targetPose = calcTargetPose(new Pose2d(x, y, new Rotation2d(0)));\n }\n\n public void calcComponentPoses() {\n // Pose3d for component simulation\n Pose3d phaseOne = new Pose3d(\n ORIGIN_PIVOT_OFFSET.getX(),\n 0,\n ORIGIN_PIVOT_OFFSET.getY(),\n new Rotation3d(0, -armInputs.shoulderAngleRad, 0));\n Pose3d phaseTwo = new Pose3d(\n (ORIGIN_PIVOT_OFFSET.getX() + armSegmentCalc()[0] * 0.5),\n 0,\n (ORIGIN_PIVOT_OFFSET.getY() + armSegmentCalc()[1] * 0.5),\n new Rotation3d(0, -armInputs.shoulderAngleRad, 0));\n Pose3d phaseThree = new Pose3d(\n (ORIGIN_PIVOT_OFFSET.getX() + armSegmentCalc()[0]),\n 0,\n (ORIGIN_PIVOT_OFFSET.getY() + armSegmentCalc()[1]),\n new Rotation3d(0, -armInputs.shoulderAngleRad, 0));\n Pose3d wrist = new Pose3d(\n ORIGIN_PIVOT_OFFSET.getX() + currentPose.getX() + 0.05,\n 0,\n ORIGIN_PIVOT_OFFSET.getY() + currentPose.getY(),\n new Rotation3d(\n 0, Units.degreesToRadians(currentPose.getRotation().getDegrees() + 90), 0));\n\n Logger.getInstance().recordOutput(\"Arm/Arm Phase One\", phaseOne);\n Logger.getInstance().recordOutput(\"Arm/Arm Phase Two\", phaseTwo);\n Logger.getInstance().recordOutput(\"Arm/Arm Phase Three\", phaseThree);\n Logger.getInstance().recordOutput(\"Arm/Wrist Pose3d\", wrist);\n }\n\n /**\n * @return Pose2d of wrist from origin of robot and angle from ground (X, Y, Theta)\n **/\n private Pose2d calcCurrentPose(double armLengthMeters, double shoulderAngleRad, double wristAngleRad) {\n Translation2d wristCoord;\n Rotation2d wristAngle;\n\n double wristShoulderDist = Math.sqrt(Math.pow(ARM_PIVOT_OFFSET, 2) + Math.pow(armLengthMeters, 2));\n\n double vectorAngle = shoulderAngleRad - Math.asin(ARM_PIVOT_OFFSET / wristShoulderDist);\n\n // Calculate vector components\n double x = Math.cos(vectorAngle) * wristShoulderDist + ORIGIN_PIVOT_OFFSET.getX();\n double y = Math.sin(vectorAngle) * wristShoulderDist + ORIGIN_PIVOT_OFFSET.getY();\n\n // Apply origin pivot offset\n wristCoord = new Translation2d(x, y);\n\n wristAngle = new Rotation2d(shoulderAngleRad + wristAngleRad);\n return new Pose2d(wristCoord, wristAngle);\n }\n\n /**\n * @param target pose of wrist location and rotation\n * @return Pose2d of measurements required to get to a set point [Shoulder Angle, Arm Length, Wrist Angle (Rad)]\n **/\n private ArmPositions calcTargetPose(Pose2d target) {\n double x = target.getX() - ORIGIN_PIVOT_OFFSET.getX();\n double y = target.getY() - ORIGIN_PIVOT_OFFSET.getY();\n double wristShoulderDist = Math.hypot(x, y);\n double targetExtensionLength = Math.sqrt(Math.pow(wristShoulderDist, 2) - Math.pow(ARM_PIVOT_OFFSET, 2));\n double targetShoulderAngle = Math.asin(ARM_PIVOT_OFFSET / wristShoulderDist);\n targetShoulderAngle -= Math.atan2(x, y);\n targetShoulderAngle += Units.degreesToRadians(90);\n double wristAngle = target.getRotation().getRadians() - targetShoulderAngle;\n\n return new ArmPositions(targetShoulderAngle, targetExtensionLength, wristAngle);\n }\n\n private boolean checkValidState(double targetShoulderAngle, double targetExtensionLength, double wristAngle) {\n if (wristAngle > MAX_WRIST_ANGLE_RAD) {\n return false;\n }\n if (targetExtensionLength < MIN_EXTENDED_ANGLE_MIN && wristAngle < MIN_RETRACTED_WRIST_ANGLE_RAD) {\n return false;\n }\n if (targetExtensionLength > MIN_EXTENDED_ANGLE_MIN && wristAngle < MIN_EXTENDED_WRIST_ANGLE_RAD) {\n return false;\n }\n if (targetShoulderAngle < MIN_SHOULDER_ANGLE_RAD || targetShoulderAngle > MAX_SHOULDER_ANGLE_RAD) {\n return false;\n }\n if (targetExtensionLength < MIN_EXTENSION_LENGTH || targetExtensionLength > MAX_EXTENSION_LENGTH) {\n return false;\n }\n return true;\n }\n\n private ArmPositions clampValidState(double targetShoulderAngle, double targetExtensionLength, double wristAngle) {\n targetShoulderAngle = MathUtil.clamp(targetShoulderAngle, MIN_SHOULDER_ANGLE_RAD, MAX_SHOULDER_ANGLE_RAD);\n targetExtensionLength = MathUtil.clamp(targetExtensionLength, MIN_EXTENSION_LENGTH, MAX_EXTENSION_LENGTH);\n wristAngle = MathUtil.clamp(wristAngle, MIN_EXTENDED_WRIST_ANGLE_RAD, MAX_WRIST_ANGLE_RAD);\n return new ArmPositions(targetShoulderAngle, targetExtensionLength, wristAngle);\n }\n\n /**\n * @param length calculated length of arm to reach target\n * @return arm length clamped down to min and max length of telescoping arm (0.578, 1.3275)\n */\n public double applyArmClamp(double length) {\n return MathUtil.clamp(length, MIN_EXTENSION_LENGTH, MAX_EXTENSION_LENGTH);\n }\n\n /**\n * @return x and y coordinates of telescoping section of arm without the fixed minimum length\n */\n private double[] armSegmentCalc() {\n double tele = armInputs.extensionPositionMeters - MIN_EXTENSION_LENGTH;\n double x = Math.cos(armInputs.shoulderAngleRad) * tele;\n double y = Math.sin(armInputs.shoulderAngleRad) * tele;\n return new double[] {x, y};\n }\n\n public void setJointVoltage(ArmJoint joint, double voltage) {\n switch (joint) {\n case SHOULDER:\n io.setShoulderVoltage(voltage);\n break;\n case EXTENSION:\n io.setExtensionVoltage(voltage);\n break;\n case WRIST:\n io.setWristVoltage(voltage);\n break;\n }\n }\n\n public void setZeroed(boolean zero) {\n this.zeroed = zero;\n }\n\n public boolean isZeroed() {\n return zeroed;\n }\n /**\n * @return radians per second for the shoulder and wrist, meters per second for the extension\n */\n public double getVelocity(ArmJoint joint) {\n switch (joint) {\n case SHOULDER:\n return armInputs.shoulderAngularVelocityRadPerSec;\n case EXTENSION:\n return armInputs.extensionVelocityMetersPerSec;\n case WRIST:\n return armInputs.wristAngularVelocityRadPerSec;\n default:\n return 0.0;\n }\n }\n\n public boolean atTarget() {\n if (targetPose == null) {\n return false;\n }\n return Math.abs(targetPose.getShoulderAngleRad() - armInputs.shoulderAngleRad) < AT_ROTATION_THRESHOLD\n && Math.abs(targetPose.getExtensionLengthMeters() - armInputs.extensionPositionMeters)\n < AT_TARGET_THRESHOLD\n && Math.abs(targetPose.getWristAngleRad() - armInputs.wristAngleRad) < AT_ROTATION_THRESHOLD;\n }\n\n public void setAllSensorPositionsFromMeasurement(ArmPositions positions) {\n io.setSensorPositionFromMeasurement(ArmJoint.SHOULDER, positions.getShoulderAngleRad());\n io.setSensorPositionFromMeasurement(ArmJoint.EXTENSION, positions.getExtensionLengthMeters());\n io.setSensorPositionFromMeasurement(ArmJoint.WRIST, positions.getWristAngleRad());\n }\n\n public void setSensorPositionFromMeasurement(ArmJoint joint, double position) {\n io.setSensorPositionFromMeasurement(joint, position);\n }\n\n public void toggleBrakeMode() {\n isBrakeMode = !isBrakeMode;\n io.setNeutralMode(isBrakeMode);\n }\n\n private boolean isInDangerZone(ArmPositions positions) {\n return positions.getShoulderAngleRad() < SHOULDER_DANGER_ZONE\n && positions.getExtensionLengthMeters() < EXTENSION_DANGER_ZONE;\n }\n\n private boolean isTargetStowed() {\n return targetPose.equals(ArmPoseConstants.STOW);\n }\n}" }, { "identifier": "IntakeSubsystem", "path": "src/main/java/org/frcteam2910/c2023/subsystems/intake/IntakeSubsystem.java", "snippet": "public class IntakeSubsystem extends SubsystemBase {\n private static final double BEAM_BREAK_THRESHOLD_VOLTAGE = 1.0;\n private static final double HAS_PIECE_CURRENT_THRESHOLD_AMPS = 5.0;\n private static final double HAS_PIECE_VELOCITY_THRESHOLD = 25.0;\n\n /**\n * Feature flag for using ToF or Beam Break sensor\n */\n private static final boolean IS_USING_TOF_SENSOR = true;\n\n private static final double INTAKE_WIDTH_METERS = Units.inchesToMeters(15.0);\n\n private static final double CONE_RADIUS_METERS = Units.inchesToMeters(7.5 / 2.0);\n\n private static final double MAX_TIMEOFFLIGHT_DISTANCE = INTAKE_WIDTH_METERS;\n\n private static final double TIMEOFFLIGHT_OFFSET = -(INTAKE_WIDTH_METERS / 2.0);\n\n private final OperatorDashboard operatorDashboard;\n\n private final IntakeIO io;\n private final IntakeIOInputsAutoLogged intakeInputs = new IntakeIOInputsAutoLogged();\n\n private GamePiece targetPiece = GamePiece.CONE;\n private double intakeVoltage = 0;\n\n private TargetIntakeStates targetState = TargetIntakeStates.STOP;\n private CurrentIntakeStates currentState = CurrentIntakeStates.STOPPED;\n\n private double lastDetectedHasGamePieceTimestamp;\n private double lastAtLowAmpsTimestamp;\n\n public IntakeSubsystem(IntakeIO io, OperatorDashboard operatorDashboard) {\n this.io = io;\n this.operatorDashboard = operatorDashboard;\n }\n\n @Override\n public void periodic() {\n io.updateInputs(intakeInputs);\n Logger.getInstance().processInputs(\"Intake\", intakeInputs);\n Logger.getInstance().recordOutput(\"Intake/Beam Break\", hasGamePiece());\n Logger.getInstance().recordOutput(\"Intake/Target State\", targetState.name());\n Logger.getInstance().recordOutput(\"Intake/Current State\", currentState.name());\n Logger.getInstance().recordOutput(\"Intake/Has Piece (Velocity)\", hasGamePiece());\n Logger.getInstance().recordOutput(\"Intake/Current Draw Piece\", getCurrentDrawHasPiece());\n Logger.getInstance().recordOutput(\"Intake/Cone Offset\", getConeOffset().getY());\n\n // setTargetPiece(operatorDashboard.getSelectedGamePiece());\n\n checkIntakeState(targetState);\n applyStates(currentState);\n // advanceStates(currentState);\n\n io.setMotorVoltage(intakeVoltage);\n\n Logger.getInstance().recordOutput(\"Target Piece\", targetPiece.toString());\n Logger.getInstance()\n .recordOutput(\n \"Target Level\", operatorDashboard.getSelectedGridLevel().name());\n }\n\n public void setTargetState(TargetIntakeStates targetState) {\n this.targetState = targetState;\n }\n\n private void checkIntakeState(TargetIntakeStates targetIntakeStates) {\n // reset offset every loop\n switch (targetIntakeStates) {\n case COLLECT:\n switch (targetPiece) {\n case CONE:\n currentState = CurrentIntakeStates.COLLECTING_CONE;\n break;\n case CUBE:\n currentState = CurrentIntakeStates.COLLECTING_CUBE;\n break;\n }\n break;\n case EJECT:\n switch (targetPiece) {\n case CONE:\n currentState = CurrentIntakeStates.EJECTING_CONE;\n break;\n case CUBE:\n currentState = CurrentIntakeStates.EJECTING_CUBE;\n break;\n default:\n break;\n }\n break;\n case HOLDING:\n switch (targetPiece) {\n case CONE:\n currentState = CurrentIntakeStates.HOLDING_CONE;\n break;\n case CUBE:\n currentState = CurrentIntakeStates.HOLDING_CUBE;\n break;\n }\n break;\n case STOP:\n currentState = CurrentIntakeStates.STOPPED;\n break;\n case FAST_EJECT:\n switch (targetPiece) {\n case CONE:\n currentState = CurrentIntakeStates.EJECTING_CONE;\n break;\n case CUBE:\n currentState = CurrentIntakeStates.FAST_EJECTING_CUBE;\n break;\n }\n }\n }\n\n private void advanceStates(CurrentIntakeStates currentState) {\n switch (currentState) {\n // case HOLDING_CONE:\n // case HOLDING_CUBE:\n // if (Timer.getFPGATimestamp() - lastDetectedBeamBreakTimestamp > 0.25) {\n // this.currentState = CurrentIntakeStates.STOPPED;\n // this.targetState = TargetIntakeStates.STOP;\n // }\n // break;\n case COLLECTING_CONE:\n if (hasGamePiece()) {\n this.currentState = CurrentIntakeStates.HOLDING_CONE;\n }\n break;\n case COLLECTING_CUBE:\n if (hasGamePiece() && Math.abs(lastAtLowAmpsTimestamp - Timer.getFPGATimestamp()) > 0.1) {\n this.currentState = CurrentIntakeStates.HOLDING_CUBE;\n }\n break;\n case EJECTING_CONE:\n case EJECTING_CUBE:\n if (!hasGamePiece()) {\n this.currentState = CurrentIntakeStates.STOPPED;\n this.targetState = TargetIntakeStates.STOP;\n }\n break;\n default:\n break;\n }\n }\n\n private void applyStates(CurrentIntakeStates currentState) {\n switch (currentState) {\n case COLLECTING_CONE:\n intakeVoltage = -12;\n break;\n case COLLECTING_CUBE:\n if (intakeInputs.intakeCurrentDrawAmps < HAS_PIECE_CURRENT_THRESHOLD_AMPS) {\n lastAtLowAmpsTimestamp = Timer.getFPGATimestamp();\n }\n intakeVoltage = 10;\n break;\n case EJECTING_CONE:\n // if (operatorDashboard.getSelectedGridLevel() == GridLevel.LOW) {\n // intakeVoltage = 12.0;\n // }\n // intakeVoltage = 10.0;\n intakeVoltage = 12.0;\n break;\n case EJECTING_CUBE:\n intakeVoltage = -3.0;\n break;\n case HOLDING_CONE:\n if (hasGamePiece()) {\n lastDetectedHasGamePieceTimestamp = Timer.getFPGATimestamp();\n }\n intakeVoltage = -1.0;\n break;\n case HOLDING_CUBE:\n if (hasGamePiece()) {\n lastDetectedHasGamePieceTimestamp = Timer.getFPGATimestamp();\n }\n intakeVoltage = 0.7;\n break;\n case STOPPED:\n intakeVoltage = 0;\n break;\n case FAST_EJECTING_CUBE:\n intakeVoltage = -6.0;\n break;\n }\n }\n\n public void setTargetPiece(GamePiece targetPiece) {\n this.targetPiece = targetPiece;\n }\n\n public GamePiece getTargetPiece() {\n return targetPiece;\n }\n\n public boolean hasGamePiece() {\n return Math.abs(intakeInputs.intakeAngularVelocityRadPerSec) < HAS_PIECE_VELOCITY_THRESHOLD;\n }\n\n /**\n * Get the offset to the center of the cone in the robot relative frame.\n *\n * @return The offset to the center of the cone in the robot relative frame.\n */\n public Translation2d getConeOffset() {\n double y = 0.0;\n if (IS_USING_TOF_SENSOR) {\n // Get edge measurement and add the cone radius.\n var offset = intakeInputs.timeOfFlightMeters + CONE_RADIUS_METERS;\n // if mount location is in positive y direction subtract the offset,\n // otherwise add the offset.\n y = TIMEOFFLIGHT_OFFSET + offset;\n }\n return new Translation2d(\n 0.0,\n MathUtil.clamp(\n y,\n -((INTAKE_WIDTH_METERS / 2) - CONE_RADIUS_METERS),\n (INTAKE_WIDTH_METERS / 2) - CONE_RADIUS_METERS));\n }\n\n public boolean isHolding() {\n return currentState == CurrentIntakeStates.HOLDING_CONE || currentState == CurrentIntakeStates.HOLDING_CUBE;\n }\n\n public boolean getCurrentDrawHasPiece() {\n return intakeInputs.intakeCurrentDrawAmps > HAS_PIECE_CURRENT_THRESHOLD_AMPS;\n }\n\n public enum TargetIntakeStates {\n COLLECT,\n EJECT,\n HOLDING,\n STOP,\n FAST_EJECT,\n }\n\n private enum CurrentIntakeStates {\n COLLECTING_CUBE,\n HOLDING_CUBE,\n EJECTING_CUBE,\n COLLECTING_CONE,\n HOLDING_CONE,\n EJECTING_CONE,\n STOPPED,\n FAST_EJECTING_CUBE\n }\n}" }, { "identifier": "ArmPositions", "path": "src/main/java/org/frcteam2910/c2023/util/ArmPositions.java", "snippet": "public class ArmPositions {\n private double shoulderAngleRad = 0;\n private double extensionLengthMeters = 0;\n private double wristAngleRad = 0;\n\n public ArmPositions(double shoulderAngleRad, double extensionLengthMeters, double wristAngleRad) {\n this.shoulderAngleRad = shoulderAngleRad;\n this.extensionLengthMeters = extensionLengthMeters;\n this.wristAngleRad = wristAngleRad;\n }\n\n public double getShoulderAngleRad() {\n return shoulderAngleRad;\n }\n\n public double getExtensionLengthMeters() {\n return extensionLengthMeters;\n }\n\n public double getWristAngleRad() {\n return wristAngleRad;\n }\n}" }, { "identifier": "GamePiece", "path": "src/main/java/org/frcteam2910/c2023/util/GamePiece.java", "snippet": "public enum GamePiece {\n CONE,\n CUBE\n}" }, { "identifier": "GridLevel", "path": "src/main/java/org/frcteam2910/c2023/util/GridLevel.java", "snippet": "public enum GridLevel {\n HIGH,\n MIDDLE,\n LOW\n}" }, { "identifier": "OperatorDashboard", "path": "src/main/java/org/frcteam2910/c2023/util/OperatorDashboard.java", "snippet": "public class OperatorDashboard {\n RobotContainer container;\n\n private final GenericEntry[] rowButtons = new GenericEntry[3];\n private static final boolean[] rowBooleansArray = new boolean[3];\n\n private final GenericEntry[] nodeButtons = new GenericEntry[2];\n private final boolean[] nodeTypeBooleanArray = new boolean[2];\n\n private final GenericEntry[] shouldUseVision = new GenericEntry[1];\n private final GenericEntry[] shouldUseAutoScore = new GenericEntry[1];\n private final GenericEntry[] uprightGroundIntakeButton = new GenericEntry[1];\n private final GenericEntry[] singleCubeIntakeButton = new GenericEntry[1];\n private final GenericEntry[] shouldSupercharge = new GenericEntry[1];\n\n private final SimpleWidget rotationOffsetEntry;\n private final SimpleWidget translationOffsetEntry;\n\n private int scoringPositionOffset = 0;\n private double rotationOffset = 0.0;\n private double yOffset = 0.0;\n private boolean offsetChangePositive = true;\n\n public OperatorDashboard(RobotContainer container) {\n this.container = container;\n\n ShuffleboardTab version1 = Shuffleboard.getTab(\"Version 1 Grid\");\n\n rowButtons[0] = version1.add(\"High Node?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(0, 0)\n .withSize(3, 2)\n .getEntry();\n rowButtons[1] = version1.add(\"Middle Node?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(0, 2)\n .withSize(3, 2)\n .getEntry();\n rowButtons[2] = version1.add(\"Low Node?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(0, 4)\n .withSize(3, 2)\n .getEntry();\n version1.addString(\"Level: \", () -> String.valueOf(getSelectedGridLevel()))\n .withWidget(BuiltInWidgets.kTextView)\n .withPosition(0, 6)\n .withSize(3, 1);\n\n nodeButtons[0] = version1.add(\"▲ Cone\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(3, 0)\n .withSize(3, 2)\n .getEntry();\n nodeButtons[1] = version1.add(\"◼ Cube\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(3, 2)\n .withSize(3, 2)\n .getEntry();\n uprightGroundIntakeButton[0] = version1.add(\"Upright Ground Intake?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(6, 0)\n .withSize(3, 2)\n .getEntry();\n singleCubeIntakeButton[0] = version1.add(\"Single Sub Cube Intake?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(6, 2)\n .withSize(3, 2)\n .getEntry();\n version1.addString(\"Game Piece: \", this::getSelectedGamePieceString)\n .withWidget(BuiltInWidgets.kTextView)\n .withPosition(3, 4)\n .withSize(3, 1);\n\n // version1.add(\"-\", new InstantCommand(() -> {\n // scoringPositionOffset = MathUtil.clamp(scoringPositionOffset - 1, -8, 8);\n // offsetChangePositive = false;\n // }))\n // .withPosition(6, 2)\n // .withSize(2, 2);\n // version1.add(\"+\", new InstantCommand(() -> {\n // scoringPositionOffset = MathUtil.clamp(scoringPositionOffset + 1, -8, 8);\n // offsetChangePositive = true;\n // }))\n // .withPosition(8, 2)\n // .withSize(2, 2);\n\n version1.addNumber(\"Offset\", () -> scoringPositionOffset)\n .withPosition(6, 4)\n .withSize(3, 2);\n\n rotationOffsetEntry = version1.add(\"Auto Align Rotation Offset\", 0.0)\n .withSize(5, 2)\n .withPosition(9, 2)\n .withWidget(BuiltInWidgets.kNumberSlider)\n .withProperties(Map.of(\"min\", -10.0, \"max\", 10.0, \"block increment\", 1.0));\n\n translationOffsetEntry = version1.add(\"Auto Align Y Offset\", 0.0)\n .withSize(5, 2)\n .withPosition(14, 2)\n .withWidget(BuiltInWidgets.kNumberSlider)\n .withProperties(Map.of(\"min\", -5.0, \"max\", 5.0, \"block increment\", 0.5));\n\n // version1.add(\"Zero Gyro\", new InstantCommand(container.getDrivetrainSubsystem()::resetPose))\n // .withPosition(18, 0)\n // .withSize(3, 2);\n // version1.add(\"Home Arm\", new SimultaneousHomeArmCommand(container.getArmSubsystem()))\n // .withPosition(18, 2)\n // .withSize(3, 2);\n\n shouldUseVision[0] = version1.add(\"Use vision?\", true)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(9, 4)\n .withSize(3, 2)\n .getEntry();\n\n shouldUseAutoScore[0] = version1.add(\"Use auto-eject?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(12, 4)\n .withSize(3, 2)\n .getEntry();\n\n shouldSupercharge[0] = version1.add(\"Supercharge?\", false)\n .withWidget(BuiltInWidgets.kToggleButton)\n .withPosition(3, 5)\n .withSize(3, 2)\n .getEntry();\n }\n\n public void update() {\n rotationOffset = rotationOffsetEntry.getEntry().getDouble(rotationOffset);\n yOffset = translationOffsetEntry.getEntry().getDouble(yOffset);\n // update for row buttons\n for (int i = 0; i < 3; i++) {\n if (rowButtons[i].getBoolean(false) != rowBooleansArray[i] & rowButtons[i].getBoolean(false)) {\n rowButtons[0].setBoolean(false);\n rowBooleansArray[0] = false;\n rowButtons[1].setBoolean(false);\n rowBooleansArray[1] = false;\n rowButtons[2].setBoolean(false);\n rowBooleansArray[2] = false;\n rowButtons[i].setBoolean(true);\n rowBooleansArray[i] = true;\n } else if (rowButtons[i].getBoolean(false) != rowBooleansArray[i]) {\n rowBooleansArray[i] = false;\n }\n }\n\n // update for node buttons\n for (int i = 0; i < 2; i++) {\n if (nodeButtons[i].getBoolean(false) != nodeTypeBooleanArray[i] & nodeButtons[i].getBoolean(false)) {\n nodeButtons[0].setBoolean(false);\n nodeTypeBooleanArray[0] = false;\n nodeButtons[1].setBoolean(false);\n nodeTypeBooleanArray[1] = false;\n nodeButtons[i].setBoolean(true);\n nodeTypeBooleanArray[i] = true;\n } else if (nodeButtons[i].getBoolean(false) != nodeTypeBooleanArray[i]) {\n nodeTypeBooleanArray[i] = false;\n }\n }\n container.getDrivetrainSubsystem().setShouldUseVisionData(getShouldUseVision());\n }\n\n public void setSelectedGamePiece(GamePiece piece) {\n nodeButtons[piece == GamePiece.CONE ? 0 : 1].setBoolean(true);\n }\n\n public void setSelectedScoringLevel(GridLevel level) {\n switch (level) {\n case HIGH:\n rowButtons[0].setBoolean(true);\n break;\n case MIDDLE:\n rowButtons[1].setBoolean(true);\n break;\n case LOW:\n rowButtons[2].setBoolean(true);\n }\n }\n\n public GamePiece getSelectedGamePiece() {\n for (int i = 0; i < 2; i++) {\n if (nodeTypeBooleanArray[i]) {\n if (i == 0) {\n return GamePiece.CONE;\n } else {\n return GamePiece.CUBE;\n }\n }\n }\n return GamePiece.CONE;\n }\n\n public String getSelectedGamePieceString() {\n for (int i = 0; i < 2; i++) {\n if (nodeTypeBooleanArray[i]) {\n if (i == 0) {\n String isUpright = getShouldUprightGroundIntake() ? \"Upright\" : \"Flat\";\n return \"Cone \" + isUpright;\n } else {\n String isSingleSub = getSingleSubCube() ? \" Single Substation\" : \"\";\n return \"Cube\" + isSingleSub;\n }\n }\n }\n return \"\";\n }\n\n public GridLevel getSelectedGridLevel() {\n for (int i = 0; i < 3; i++) {\n if (OperatorDashboard.rowBooleansArray[i]) {\n if (i == 2) {\n return GridLevel.LOW;\n } else if (i == 1) {\n return GridLevel.MIDDLE;\n } else {\n return GridLevel.HIGH;\n }\n }\n }\n return GridLevel.HIGH;\n }\n\n public void setScoringPositionOffset(int scoringPositionOffset) {\n this.scoringPositionOffset = scoringPositionOffset;\n }\n\n public int getScoringPositionOffset() {\n return scoringPositionOffset;\n }\n\n public double getRotationOffset() {\n return rotationOffset;\n }\n\n public double getTranslationOffset() {\n return yOffset;\n }\n\n public void changeRotationOffset(double offsetChange) {\n rotationOffset = MathUtil.clamp(rotationOffset + offsetChange, -10, 10);\n rotationOffsetEntry.getEntry().set(NetworkTableValue.makeDouble(rotationOffset));\n }\n\n public void changeTranslationOffset(double offsetChange) {\n yOffset = MathUtil.clamp(yOffset + offsetChange, -5.0, 5.0);\n translationOffsetEntry.getEntry().set(NetworkTableValue.makeDouble(yOffset));\n }\n\n public void changeScoringPositionOffset(int offsetChange) {\n scoringPositionOffset = MathUtil.clamp(scoringPositionOffset + offsetChange, -8, 8);\n }\n\n public boolean isOffsetChangePositive() {\n return offsetChangePositive;\n }\n\n public boolean getShouldUseVision() {\n return shouldUseVision[0].getBoolean(true);\n }\n\n public void setShouldUseAutoScore(boolean useAutoScore) {\n shouldUseAutoScore[0].setBoolean(useAutoScore);\n }\n\n public boolean getShouldUseAutoScore() {\n return shouldUseAutoScore[0].getBoolean(false);\n }\n\n public void setGroundCone(boolean groundCone) {\n uprightGroundIntakeButton[0].setBoolean(groundCone);\n }\n\n public boolean getShouldUprightGroundIntake() {\n return uprightGroundIntakeButton[0].getBoolean(false);\n }\n\n public void setSingleSubCube(boolean singleSubCube) {\n singleCubeIntakeButton[0].setBoolean(singleSubCube);\n }\n\n public boolean getSingleSubCube() {\n return singleCubeIntakeButton[0].getBoolean(false);\n }\n\n public void setShouldSupercharge(boolean supercharge) {\n shouldSupercharge[0].setBoolean(supercharge);\n }\n\n public boolean getShouldSupercharge() {\n return shouldSupercharge[0].getBoolean(false);\n }\n\n public void toggleGroundCone() {\n uprightGroundIntakeButton[0].setBoolean(!uprightGroundIntakeButton[0].getBoolean(false));\n }\n}" } ]
import java.util.function.BooleanSupplier; import java.util.function.Supplier; import edu.wpi.first.math.util.Units; import edu.wpi.first.wpilibj2.command.CommandBase; import org.frcteam2910.c2023.subsystems.arm.ArmSubsystem; import org.frcteam2910.c2023.subsystems.intake.IntakeSubsystem; import org.frcteam2910.c2023.util.ArmPositions; import org.frcteam2910.c2023.util.GamePiece; import org.frcteam2910.c2023.util.GridLevel; import org.frcteam2910.c2023.util.OperatorDashboard;
10,696
package org.frcteam2910.c2023.commands; public class ArmToPoseCommand extends CommandBase { private static final double HIGH_SHOULDER_OFFSET = Units.degreesToRadians(1.0); private static final double MID_SHOULDER_OFFSET = Units.degreesToRadians(1.5); private static final double HIGH_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double MID_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double HIGH_WRIST_OFFSET = Units.degreesToRadians(0.0); private static final double MID_WRIST_OFFSET = Units.degreesToRadians(0.0); private final ArmSubsystem arm; private Supplier<ArmPositions> targetPoseSupplier; private final boolean perpetual; private final BooleanSupplier aButton; private final OperatorDashboard dashboard; private final IntakeSubsystem intake; public ArmToPoseCommand(ArmSubsystem arm, ArmPositions targetPose) { this(arm, () -> targetPose, false, () -> false, null, null); } public ArmToPoseCommand(ArmSubsystem arm, Supplier<ArmPositions> targetPoseSupplier) { this(arm, targetPoseSupplier, false, () -> false, null, null); } public ArmToPoseCommand(ArmSubsystem arm, Supplier<ArmPositions> targetPoseSupplier, boolean perpetual) { this(arm, targetPoseSupplier, perpetual, () -> false, null, null); } public ArmToPoseCommand( ArmSubsystem arm, Supplier<ArmPositions> targetPoseSupplier, boolean perpetual, BooleanSupplier aButton, OperatorDashboard dashboard, IntakeSubsystem intake) { this.arm = arm; this.targetPoseSupplier = targetPoseSupplier; this.perpetual = perpetual; this.aButton = aButton; this.dashboard = dashboard; this.intake = intake; addRequirements(arm); } @Override public void execute() { ArmPositions targetPose; targetPose = targetPoseSupplier.get(); if (dashboard != null) { if (aButton.getAsBoolean() && intake.getTargetPiece() == GamePiece.CONE
package org.frcteam2910.c2023.commands; public class ArmToPoseCommand extends CommandBase { private static final double HIGH_SHOULDER_OFFSET = Units.degreesToRadians(1.0); private static final double MID_SHOULDER_OFFSET = Units.degreesToRadians(1.5); private static final double HIGH_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double MID_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double HIGH_WRIST_OFFSET = Units.degreesToRadians(0.0); private static final double MID_WRIST_OFFSET = Units.degreesToRadians(0.0); private final ArmSubsystem arm; private Supplier<ArmPositions> targetPoseSupplier; private final boolean perpetual; private final BooleanSupplier aButton; private final OperatorDashboard dashboard; private final IntakeSubsystem intake; public ArmToPoseCommand(ArmSubsystem arm, ArmPositions targetPose) { this(arm, () -> targetPose, false, () -> false, null, null); } public ArmToPoseCommand(ArmSubsystem arm, Supplier<ArmPositions> targetPoseSupplier) { this(arm, targetPoseSupplier, false, () -> false, null, null); } public ArmToPoseCommand(ArmSubsystem arm, Supplier<ArmPositions> targetPoseSupplier, boolean perpetual) { this(arm, targetPoseSupplier, perpetual, () -> false, null, null); } public ArmToPoseCommand( ArmSubsystem arm, Supplier<ArmPositions> targetPoseSupplier, boolean perpetual, BooleanSupplier aButton, OperatorDashboard dashboard, IntakeSubsystem intake) { this.arm = arm; this.targetPoseSupplier = targetPoseSupplier; this.perpetual = perpetual; this.aButton = aButton; this.dashboard = dashboard; this.intake = intake; addRequirements(arm); } @Override public void execute() { ArmPositions targetPose; targetPose = targetPoseSupplier.get(); if (dashboard != null) { if (aButton.getAsBoolean() && intake.getTargetPiece() == GamePiece.CONE
&& (dashboard.getSelectedGridLevel() == GridLevel.HIGH
4
2023-11-03 02:12:12+00:00
12k
YunaBraska/type-map
src/main/java/berlin/yuna/typemap/logic/TypeConverter.java
[ { "identifier": "FunctionOrNull", "path": "src/main/java/berlin/yuna/typemap/model/FunctionOrNull.java", "snippet": "@FunctionalInterface\npublic interface FunctionOrNull<S, T> {\n\n /**\n * Applies this function to the given argument, allowing exceptions to be thrown.\n *\n * @param source the function argument.\n * @return the function result.\n * @throws Exception if an error occurs during function application.\n */\n @SuppressWarnings(\"java:S112\")\n T applyWithException(S source) throws Exception;\n\n /**\n * Applies this function to the given argument and handles any exceptions.\n * If an exception occurs, this method returns null.\n *\n * @param source the function argument.\n * @return the function result or null if an exception occurs.\n */\n default T apply(final S source) {\n try {\n return applyWithException(source);\n } catch (final Exception ignored) {\n return null;\n }\n }\n}" }, { "identifier": "TypeList", "path": "src/main/java/berlin/yuna/typemap/model/TypeList.java", "snippet": "public class TypeList extends ArrayList<Object> implements TypeListI<TypeList> {\n\n /**\n * Default constructor for creating an empty {@link TypeList}.\n */\n public TypeList() {\n this((Collection<?>) null);\n }\n\n /**\n * Constructs a new {@link TypeList} of the specified json.\n */\n public TypeList(final String json) {\n this(JsonDecoder.jsonListOf(json));\n }\n\n /**\n * Constructs a new {@link TypeList} with the same mappings as the specified map.\n *\n * @param map The initial map to copy mappings from, can be null.\n */\n public TypeList(final Collection<?> map) {\n ofNullable(map).ifPresent(super::addAll);\n }\n\n /**\n * Adds the specified value\n *\n * @param value the value to be added\n * @return the updated TypeList instance for chaining.\n */\n @Override\n public TypeList addd(final Object value) {\n super.add(value);\n return this;\n }\n\n /**\n * Adds the specified value\n *\n * @param index the index whose associated value is to be returned.\n * @param value the value to be added\n * @return the updated {@link TypeList} instance for chaining.\n */\n @Override\n public TypeList addd(final int index, final Object value) {\n if (index >= 0 && index < this.size()) {\n super.add(index, value);\n } else {\n super.add(value);\n }\n return this;\n }\n\n /**\n * Adds the specified value\n *\n * @param index the index whose associated value is to be returned.\n * @param value the value to be added\n * @return the updated {@link TypeList} instance for chaining.\n */\n public TypeList addd(final Object index, final Object value) {\n if (index == null) {\n super.add(value);\n } else if (index instanceof Number) {\n this.addd(((Number) index).intValue(), value);\n }\n return this;\n }\n\n /**\n * Adds all entries to this specified List\n *\n * @param collection which provides all entries to add\n * @return the updated {@link TypeList} instance for chaining.\n */\n @Override\n public TypeList adddAll(final Collection<?> collection) {\n super.addAll(collection);\n return this;\n }\n\n /**\n * Returns the element at the specified position in this list.\n *\n * @param index index of the element to return\n * @return the element at the specified position in this list\n */\n @Override\n public Object get(final int index) {\n return index >= 0 && index < this.size() ? super.get(index) : null;\n }\n\n /**\n * Retrieves the value to which the specified index, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param index the index whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return value if present and convertible, else null.\n */\n public <T> T get(final int index, final Class<T> type) {\n return gett(index, type).orElse(null);\n }\n\n /**\n * Retrieves the value to which the specified index, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param index the index whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return an Optional containing the value if present and convertible, else empty.\n */\n @Override\n public <T> Optional<T> gett(final int index, final Class<T> type) {\n return ofNullable(treeGet(this, index)).map(object -> convertObj(object, type));\n }\n\n /**\n * Retrieves the value to which the specified key is mapped, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param path the key whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return an Optional containing the value if present and convertible, else empty.\n */\n @Override\n public <T> Optional<T> gett(final Class<T> type, final Object... path) {\n return ofNullable(treeGet(this, path)).map(object -> convertObj(object, type));\n }\n\n /**\n * This method converts the retrieved map to a list of the specified key and value types.\n *\n * @param path The key whose associated value is to be returned.\n * @return a {@link TypeList} of the specified key and value types.\n */\n public TypeList getList(final Object... path) {\n return getList(TypeList::new, Object.class, path);\n }\n\n /**\n * Retrieves a collection associated at the specified index and converts it to\n * the specified element type.\n *\n * @param <E> The type of elements in the collection.\n * @param index The index whose associated value is to be returned.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n public <E> List<E> getList(final int index, final Class<E> itemType) {\n return getList(ArrayList::new, itemType, index);\n }\n\n /**\n * Retrieves a collection associated at the specified index and converts it to\n * the specified element type.\n *\n * @param <E> The type of elements in the collection.\n * @param path The index whose associated value is to be returned.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n public <E> List<E> getList(final Class<E> itemType, final Object... path) {\n return getList(ArrayList::new, itemType, path);\n }\n\n /**\n * Retrieves a collection associated at the specified index and converts it to\n * the specified collection type and element type.\n *\n * @param <T> The type of the collection to be returned.\n * @param <E> The type of elements in the collection.\n * @param index The index whose associated value is to be returned.\n * @param output The supplier providing a new collection instance.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n @Override\n public <T extends Collection<E>, E> T getList(final int index, final Supplier<? extends T> output, final Class<E> itemType) {\n return collectionOf(super.get(index), output, itemType);\n }\n\n /**\n * Retrieves a collection associated with the specified key and converts it to\n * the specified collection type and element type.\n *\n * @param <T> The type of the collection to be returned.\n * @param <E> The type of elements in the collection.\n * @param path The key whose associated value is to be returned.\n * @param output The supplier providing a new collection instance.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n @Override\n public <T extends Collection<E>, E> T getList(final Supplier<? extends T> output, final Class<E> itemType, final Object... path) {\n return collectionOf(treeGet(this, path), output, itemType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param path The key whose associated value is to be returned.\n * @return a map of the specified key and value types.\n */\n @Override\n public LinkedTypeMap getMap(final Object... path) {\n return getMap(LinkedTypeMap::new, Object.class, Object.class, path);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param index The key whose associated value is to be returned.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n public <K, V> Map<K, V> getMap(final int index, final Class<K> keyType, final Class<V> valueType) {\n return convertAndMap(treeGet(this, index), LinkedHashMap::new, keyType, valueType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param path The key whose associated value is to be returned.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n public <K, V> Map<K, V> getMap(final Class<K> keyType, final Class<V> valueType, final Object... path) {\n return convertAndMap(treeGet(this, path), LinkedHashMap::new, keyType, valueType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param <M> The type of the map to be returned.\n * @param index The key whose associated value is to be returned.\n * @param output A supplier providing a new map instance.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n @Override\n public <K, V, M extends Map<K, V>> M getMap(final int index, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) {\n return convertAndMap(treeGet(this, index), output, keyType, valueType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param <M> The type of the map to be returned.\n * @param path The key whose associated value is to be returned.\n * @param output A supplier providing a new map instance.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n @Override\n public <K, V, M extends Map<K, V>> M getMap(final Supplier<M> output, final Class<K> keyType, final Class<V> valueType, final Object... path) {\n return convertAndMap(treeGet(this, path), output, keyType, valueType);\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method is useful for cases where the type indicator is an array instance.\n *\n * @param <E> The component type of the array.\n * @param index The index whose associated value is to be returned.\n * @param typeIndicator An array instance indicating the type of array to return.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n public <E> E[] getArray(final int index, final E[] typeIndicator, final Class<E> componentType) {\n final ArrayList<E> result = getList(index, ArrayList::new, componentType);\n return result.toArray(Arrays.copyOf(typeIndicator, result.size()));\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method is useful for cases where the type indicator is an array instance.\n *\n * @param <E> The component type of the array.\n * @param path The key whose associated value is to be returned.\n * @param typeIndicator An array instance indicating the type of array to return.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n @Override\n public <E> E[] getArray(final E[] typeIndicator, final Class<E> componentType, final Object... path) {\n final ArrayList<E> result = getList(ArrayList::new, componentType, path);\n return result.toArray(Arrays.copyOf(typeIndicator, result.size()));\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method allows for custom array generation using a generator function.\n *\n * @param <E> The component type of the array.\n * @param index The key whose associated value is to be returned.\n * @param generator A function to generate the array of the required size.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n @Override\n public <E> E[] getArray(final int index, final IntFunction<E[]> generator, final Class<E> componentType) {\n return getList(index, ArrayList::new, componentType).stream().toArray(generator);\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method allows for custom array generation using a generator function.\n *\n * @param <E> The component type of the array.\n * @param path The key whose associated value is to be returned.\n * @param generator A function to generate the array of the required size.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n @Override\n public <E> E[] getArray(final IntFunction<E[]> generator, final Class<E> componentType, final Object... path) {\n return getList(ArrayList::new, componentType, path).stream().toArray(generator);\n }\n\n /**\n * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeMapI}\n *\n * @return {@link Optional#empty()} if current object is not a {@link TypeMapI}, else returns self.\n */\n @SuppressWarnings(\"java:S1452\")\n public Optional<TypeMapI<?>> typeMap() {\n return Optional.empty();\n }\n\n /**\n * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeListI}\n *\n * @return {@link Optional#empty()} if current object is not a {@link TypeListI}, else returns self.\n */\n @SuppressWarnings(\"java:S1452\")\n public Optional<TypeListI<?>> typeList() {\n return Optional.of(this);\n }\n\n /**\n * Converts any object to its JSON representation.\n * This method intelligently dispatches the conversion task based on the type of the object,\n * handling Maps, Collections, Arrays (both primitive and object types), and other objects.\n *\n * @param path The key whose associated value is to be returned.\n * @return A JSON representation of the key value as a String.\n */\n @Override\n public String toJson(final Object... path) {\n return JsonEncoder.toJson(treeGet(this, path));\n }\n\n /**\n * Converts any object to its JSON representation.\n * This method intelligently dispatches the conversion task based on the type of the object,\n * handling Maps, Collections, Arrays (both primitive and object types), and other objects.\n *\n * @return A JSON representation of itself as a String.\n */\n @Override\n public String toJson() {\n return JsonEncoder.toJson(this);\n }\n}" }, { "identifier": "TypeMap", "path": "src/main/java/berlin/yuna/typemap/model/TypeMap.java", "snippet": "public class TypeMap extends HashMap<Object, Object> implements TypeMapI<TypeMap> {\n\n /**\n * Default constructor for creating an empty {@link TypeMap}.\n */\n public TypeMap() {\n this((Map<?, ?>) null);\n }\n\n /**\n * Constructs a new {@link TypeMap} of the specified json.\n */\n public TypeMap(final String json) {\n this(JsonDecoder.jsonMapOf(json));\n }\n\n /**\n * Constructs a new {@link TypeMap} of the specified command line arguments.\n */\n public TypeMap(final String[] cliArgs) {\n this(ArgsDecoder.argsOf(String.join(\" \", cliArgs)));\n }\n\n /**\n * Constructs a new {@link TypeMap} with the same mappings as the specified map.\n *\n * @param map The initial map to copy mappings from, can be null.\n */\n public TypeMap(final Map<?, ?> map) {\n ofNullable(map).ifPresent(super::putAll);\n }\n\n /**\n * Retrieves the value to which the specified key is mapped, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param path the key whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return the value if present and convertible, else null.\n */\n public <T> T get(final Class<T> type, final Object... path) {\n return gett(type, path).orElse(null);\n }\n\n /**\n * Associates the specified value with the specified key in this map.\n *\n * @param key the key with which the specified value is to be associated.\n * @param value the value to be associated with the specified key.\n * @return the updated {@link TypeMap} instance for chaining.\n */\n public TypeMap putt(final Object key, final Object value) {\n super.put(key, value);\n return this;\n }\n\n /**\n * Associates the specified value with the specified key in this map.\n *\n * @param key the key with which the specified value is to be associated.\n * @param value the value to be associated with the specified key.\n * @return the updated {@link ConcurrentTypeMap} instance for chaining.\n */\n public TypeMap addd(final Object key, final Object value) {\n super.put(key, value);\n return this;\n }\n\n /**\n * Retrieves the value to which the specified key is mapped, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param path the key whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return an Optional containing the value if present and convertible, else empty.\n */\n public <T> Optional<T> gett(final Class<T> type, final Object... path) {\n return ofNullable(treeGet(this, path)).map(object -> convertObj(object, type));\n }\n\n /**\n * Retrieves the value to which the specified key is mapped, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param key the key whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return an Optional containing the value if present and convertible, else empty.\n */\n public <T> T get(final Object key, final Class<T> type) {\n return gett(key, type).orElse(null);\n }\n\n /**\n * Retrieves the value to which the specified key is mapped, and attempts to\n * convert it to the specified type.\n *\n * @param <T> The target type for conversion.\n * @param key the key whose associated value is to be returned.\n * @param type the Class object of the type to convert to.\n * @return an Optional containing the value if present and convertible, else empty.\n */\n public <T> Optional<T> gett(final Object key, final Class<T> type) {\n return ofNullable(super.get(key)).map(object -> convertObj(object, type));\n }\n\n /**\n * This method converts the retrieved map to a list of the specified key and value types.\n *\n * @param path The key whose associated value is to be returned.\n * @return a {@link LinkedTypeMap} of the specified key and value types.\n */\n public TypeList getList(final Object... path) {\n return getList(TypeList::new, Object.class, path);\n }\n\n /**\n * Retrieves a collection associated at the specified index and converts it to\n * the specified element type.\n *\n * @param <E> The type of elements in the collection.\n * @param key The index whose associated value is to be returned.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n public <E> List<E> getList(final Object key, final Class<E> itemType) {\n return getList(ArrayList::new, itemType, key);\n }\n\n /**\n * Retrieves a collection associated at the specified index and converts it to\n * the specified element type.\n *\n * @param <E> The type of elements in the collection.\n * @param path The index whose associated value is to be returned.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n public <E> List<E> getList(final Class<E> itemType, final Object... path) {\n return getList(ArrayList::new, itemType, path);\n }\n\n /**\n * Retrieves a collection associated with the specified key and converts it to\n * the specified collection type and element type.\n *\n * @param <T> The type of the collection to be returned.\n * @param <E> The type of elements in the collection.\n * @param path The key whose associated value is to be returned.\n * @param output The supplier providing a new collection instance.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n public <T extends Collection<E>, E> T getList(final Supplier<? extends T> output, final Class<E> itemType, final Object... path) {\n return collectionOf(treeGet(this, path), output, itemType);\n }\n\n /**\n * Retrieves a collection associated with the specified key and converts it to\n * the specified collection type and element type.\n *\n * @param <T> The type of the collection to be returned.\n * @param <E> The type of elements in the collection.\n * @param key The key whose associated value is to be returned.\n * @param output The supplier providing a new collection instance.\n * @param itemType The class of the items in the collection.\n * @return a collection of the specified type and element type.\n */\n public <T extends Collection<E>, E> T getList(final Object key, final Supplier<? extends T> output, final Class<E> itemType) {\n return collectionOf(super.get(key), output, itemType);\n }\n\n /**\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param path The key whose associated value is to be returned.\n * @return a {@link LinkedTypeMap} of the specified key and value types.\n */\n public LinkedTypeMap getMap(final Object... path) {\n return getMap(LinkedTypeMap::new, Object.class, Object.class, path);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param key The key whose associated value is to be returned.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n public <K, V> Map<K, V> getMap(final Object key, final Class<K> keyType, final Class<V> valueType) {\n return convertAndMap(treeGet(this, key), LinkedHashMap::new, keyType, valueType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param path The key whose associated value is to be returned.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n public <K, V> Map<K, V> getMap(final Class<K> keyType, final Class<V> valueType, final Object... path) {\n return convertAndMap(treeGet(this, path), LinkedHashMap::new, keyType, valueType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param <M> The type of the map to be returned.\n * @param path The key whose associated value is to be returned.\n * @param output A supplier providing a new map instance.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n public <K, V, M extends Map<K, V>> M getMap(final Supplier<M> output, final Class<K> keyType, final Class<V> valueType, final Object... path) {\n return convertAndMap(treeGet(this, path), output, keyType, valueType);\n }\n\n /**\n * Retrieves a map of a specific type associated with the specified key.\n * This method converts the retrieved map to a map of the specified key and value types.\n *\n * @param <K> The type of keys in the returned map.\n * @param <V> The type of values in the returned map.\n * @param <M> The type of the map to be returned.\n * @param key The key whose associated value is to be returned.\n * @param output A supplier providing a new map instance.\n * @param keyType The class of the map's key type.\n * @param valueType The class of the map's value type.\n * @return a map of the specified key and value types.\n */\n public <K, V, M extends Map<K, V>> M getMap(final Object key, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) {\n return convertAndMap(super.get(key), output, keyType, valueType);\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method is useful for cases where the type indicator is an array instance.\n *\n * @param <E> The component type of the array.\n * @param path The key whose associated value is to be returned.\n * @param typeIndicator An array instance indicating the type of array to return.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n public <E> E[] getArray(final E[] typeIndicator, final Class<E> componentType, final Object... path) {\n final ArrayList<E> result = getList(ArrayList::new, componentType, path);\n return result.toArray(Arrays.copyOf(typeIndicator, result.size()));\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method is useful for cases where the type indicator is an array instance.\n *\n * @param <E> The component type of the array.\n * @param key The key whose associated value is to be returned.\n * @param typeIndicator An array instance indicating the type of array to return.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n public <E> E[] getArray(final Object key, final E[] typeIndicator, final Class<E> componentType) {\n final ArrayList<E> result = getList(key, ArrayList::new, componentType);\n return result.toArray(Arrays.copyOf(typeIndicator, result.size()));\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method allows for custom array generation using a generator function.\n *\n * @param <E> The component type of the array.\n * @param path The key whose associated value is to be returned.\n * @param generator A function to generate the array of the required size.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n public <E> E[] getArray(final IntFunction<E[]> generator, final Class<E> componentType, final Object... path) {\n return getList(ArrayList::new, componentType, path).stream().toArray(generator);\n }\n\n /**\n * Retrieves an array of a specific type associated with the specified key.\n * This method allows for custom array generation using a generator function.\n *\n * @param <E> The component type of the array.\n * @param key The key whose associated value is to be returned.\n * @param generator A function to generate the array of the required size.\n * @param componentType The class of the array's component type.\n * @return an array of the specified component type.\n */\n public <E> E[] getArray(final Object key, final IntFunction<E[]> generator, final Class<E> componentType) {\n return getList(key, ArrayList::new, componentType).stream().toArray(generator);\n }\n\n /**\n * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeMapI}\n *\n * @return {@link Optional#empty()} if current object is not a {@link TypeMapI}, else returns self.\n */\n public Optional<TypeMapI<?>> typeMap() {\n return Optional.of(this);\n }\n\n /**\n * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeListI}\n *\n * @return {@link Optional#empty()} if current object is not a {@link TypeListI}, else returns self.\n */\n public Optional<TypeListI<?>> typeList() {\n return Optional.empty();\n }\n\n /**\n * Converts any object to its JSON representation.\n * This method intelligently dispatches the conversion task based on the type of the object,\n * handling Maps, Collections, Arrays (both primitive and object types), and other objects.\n *\n * @param path The key whose associated value is to be returned.\n * @return A JSON representation of the key value as a String.\n */\n public String toJson(final Object... path) {\n return JsonEncoder.toJson(treeGet(this, path));\n }\n\n /**\n * Converts any object to its JSON representation.\n * This method intelligently dispatches the conversion task based on the type of the object,\n * handling Maps, Collections, Arrays (both primitive and object types), and other objects.\n *\n * @return A JSON representation of itself as a String.\n */\n public String toJson() {\n return JsonEncoder.toJson(this);\n }\n\n protected static Object treeGet(final Object mapOrCollection, final Object... path) {\n if (path == null || path.length == 0) {\n return null;\n }\n\n Object value = mapOrCollection;\n for (final Object key : path) {\n if (key == null || value == null) {\n return null;\n } else if (value instanceof Map<?, ?>) {\n value = ((Map<?, ?>) value).get(key);\n } else if (value instanceof Collection<?> && key instanceof Number) {\n final int index = ((Number) key).intValue();\n final List<?> list = (List<?>) value;\n value = (index >= 0 && index < list.size()) ? list.get(index) : null;\n } else if (value.getClass().isArray() && key instanceof Number) {\n final int index = ((Number) key).intValue();\n final AtomicInteger itemCount = new AtomicInteger(0);\n final AtomicReference<Object> result = new AtomicReference<>(null);\n iterateOverArray(value, item -> {\n if (result.get() == null && index == itemCount.getAndIncrement())\n result.set(item);\n });\n return result.get();\n } else {\n value = null;\n }\n }\n return value;\n }\n\n protected static <K, V, M extends Map<K, V>> M convertAndMap(final Object value, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) {\n if (output != null && keyType != null && valueType != null && value instanceof Map<?, ?>) {\n final Map<?, ?> input = (Map<?, ?>) value;\n return mapOf(input, output, keyType, valueType);\n }\n return ofNullable(output).map(Supplier::get).orElse(null);\n }\n}" }, { "identifier": "TYPE_CONVERSIONS", "path": "src/main/java/berlin/yuna/typemap/config/TypeConversionRegister.java", "snippet": "@SuppressWarnings({\"rawtypes\", \"java:S2386\"})\npublic static final Map<Class<?>, Map<Class<?>, FunctionOrNull>> TYPE_CONVERSIONS = new ConcurrentHashMap<>();" } ]
import berlin.yuna.typemap.model.FunctionOrNull; import berlin.yuna.typemap.model.TypeList; import berlin.yuna.typemap.model.TypeMap; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.IntFunction; import java.util.function.Supplier; import java.util.stream.Collectors; import static berlin.yuna.typemap.config.TypeConversionRegister.TYPE_CONVERSIONS;
9,566
package berlin.yuna.typemap.logic; @SuppressWarnings("java:S1168") public class TypeConverter { /** * Safely converts an object to the specified target typeId. * <p> * This method provides a way to convert between common types such as String, Boolean, LocalDateTime, Numbers, Collections, and Maps. * If the value is already of the target typeId, it will simply be cast and returned. * Otherwise, the method attempts to safely convert the value to the desired typeId. * </p> * <ul> * <li>If the target typeId is {@code String}, the method converts the value using {@code toString()}.</li> * <li>If the target typeId is {@code Boolean} and the value is a string representation of a boolean, the method converts it using {@code Boolean.valueOf()}.</li> * <li>If the target typeId is {@code LocalDateTime} and the value is a {@code Date}, it converts it to {@code LocalDateTime}.</li> * <li>If the target typeId is {@code Byte} and the value is a number, it casts it to byte.</li> * <li>If the target typeId is a subclass of {@code Number} and the value is a number, it invokes {@code numberOf} to convert it.</li> * <li>If the target typeId is a {@code Collection} or {@code Map}, and the value is already of that typeId, it will simply be cast and returned.</li> * </ul> * * @param <T> The target typeId to convert the value to. * @param value The object value to convert. * @param targetType The class of the target typeId. * @return The converted object of typeId {@code T}, or {@code null} if the conversion is not supported. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> T convertObj(final Object value, final Class<T> targetType) { if (value == null) return null; if (targetType.isInstance(value)) { return targetType.cast(value); } // Handle non-empty arrays, collections, map final Object firstValue = getFirstItem(value); if (firstValue != null) { return convertObj(firstValue, targetType); } // Enums if (targetType.isEnum()) { return (T) enumOf(String.valueOf(value), (Class<Enum>) targetType); } final Class<?> sourceType = value.getClass(); final Map<Class<?>, FunctionOrNull> conversions = TYPE_CONVERSIONS.getOrDefault(targetType, Collections.emptyMap()); // First try to find exact match final FunctionOrNull exactMatch = conversions.get(sourceType); if (exactMatch != null) { return targetType.cast(exactMatch.apply(value)); } // Fallback to more general converters for (final Map.Entry<Class<?>, FunctionOrNull> entry : conversions.entrySet()) { if (entry.getKey().isAssignableFrom(sourceType)) { return targetType.cast(entry.getValue().apply(value)); } } // Fallback to string convert if (!String.class.equals(sourceType)) { return convertObj(String.valueOf(value), targetType); } return null; } /** * Creates a new map of typeId {@code M} from the given {@code input} map. The keys and values are converted * to types {@code K} and {@code V} respectively. * * @param input The input map containing keys and values to be converted. * @return A new map of typeId {@code M} with keys and values converted to types {@code K} and {@code V}. Returns {@code null} if the output map is {@code null}. */
package berlin.yuna.typemap.logic; @SuppressWarnings("java:S1168") public class TypeConverter { /** * Safely converts an object to the specified target typeId. * <p> * This method provides a way to convert between common types such as String, Boolean, LocalDateTime, Numbers, Collections, and Maps. * If the value is already of the target typeId, it will simply be cast and returned. * Otherwise, the method attempts to safely convert the value to the desired typeId. * </p> * <ul> * <li>If the target typeId is {@code String}, the method converts the value using {@code toString()}.</li> * <li>If the target typeId is {@code Boolean} and the value is a string representation of a boolean, the method converts it using {@code Boolean.valueOf()}.</li> * <li>If the target typeId is {@code LocalDateTime} and the value is a {@code Date}, it converts it to {@code LocalDateTime}.</li> * <li>If the target typeId is {@code Byte} and the value is a number, it casts it to byte.</li> * <li>If the target typeId is a subclass of {@code Number} and the value is a number, it invokes {@code numberOf} to convert it.</li> * <li>If the target typeId is a {@code Collection} or {@code Map}, and the value is already of that typeId, it will simply be cast and returned.</li> * </ul> * * @param <T> The target typeId to convert the value to. * @param value The object value to convert. * @param targetType The class of the target typeId. * @return The converted object of typeId {@code T}, or {@code null} if the conversion is not supported. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> T convertObj(final Object value, final Class<T> targetType) { if (value == null) return null; if (targetType.isInstance(value)) { return targetType.cast(value); } // Handle non-empty arrays, collections, map final Object firstValue = getFirstItem(value); if (firstValue != null) { return convertObj(firstValue, targetType); } // Enums if (targetType.isEnum()) { return (T) enumOf(String.valueOf(value), (Class<Enum>) targetType); } final Class<?> sourceType = value.getClass(); final Map<Class<?>, FunctionOrNull> conversions = TYPE_CONVERSIONS.getOrDefault(targetType, Collections.emptyMap()); // First try to find exact match final FunctionOrNull exactMatch = conversions.get(sourceType); if (exactMatch != null) { return targetType.cast(exactMatch.apply(value)); } // Fallback to more general converters for (final Map.Entry<Class<?>, FunctionOrNull> entry : conversions.entrySet()) { if (entry.getKey().isAssignableFrom(sourceType)) { return targetType.cast(entry.getValue().apply(value)); } } // Fallback to string convert if (!String.class.equals(sourceType)) { return convertObj(String.valueOf(value), targetType); } return null; } /** * Creates a new map of typeId {@code M} from the given {@code input} map. The keys and values are converted * to types {@code K} and {@code V} respectively. * * @param input The input map containing keys and values to be converted. * @return A new map of typeId {@code M} with keys and values converted to types {@code K} and {@code V}. Returns {@code null} if the output map is {@code null}. */
public static TypeMap mapOf(final Map<?, ?> input) {
2
2023-11-09 14:40:13+00:00
12k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCore.java
[ { "identifier": "ActivationCode", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/ActivationCode.java", "snippet": "public class ActivationCode implements Parcelable {\n private String activationCode;\n\n private final Boolean isValid;\n private String acFormat;\n private String smdpServer;\n private String matchingId;\n private String smdpOid;\n private String confirmationCodeRequiredFlag;\n\n public ActivationCode(String barcode) {\n this.isValid = parseActivationCode(barcode);\n }\n\n protected ActivationCode(Parcel in) {\n activationCode = in.readString();\n this.isValid = parseActivationCode(activationCode);\n }\n\n public Boolean isValid() {\n return isValid;\n }\n\n public String getAcFormat() {\n return acFormat;\n }\n\n public String getSmdpServer() {\n return smdpServer;\n }\n\n public String getMatchingId() {\n return matchingId;\n }\n\n public String getSmdpOid() {\n return smdpOid;\n }\n\n public String getConfirmationCodeRequiredFlag() {\n return confirmationCodeRequiredFlag;\n }\n\n // Example\n // Input activation code:\n // LPA:1$trl.prod.ondemandconnectivity.com$KJ912512WD7N5NMZ\n //\n // Output\n // prefix: LPA:1\n // matchingId: KJ912512WD7N5NMZ\n // smdpServer: trl.prod.ondemandconnectivity.com\n // rspServerUrl: https://trl.prod.ondemandconnectivity.com\n private Boolean parseActivationCode(String barcode) {\n boolean validity = false;\n\n // Remove trailing \"LPA:\" if present\n this.activationCode = barcode.replace(\"LPA:\", \"\");\n\n String[] parts = activationCode.split(\"\\\\$\");\n if((parts.length >= 3) && (parts.length <= 5)) {\n acFormat = parts[0];\n smdpServer = parts[1];\n matchingId = parts[2];\n\n // AC_Format must be \"1\"\n validity = (acFormat.compareTo(\"1\") == 0);\n\n // All first three parts must be non-empty\n validity &= !acFormat.isEmpty() && !smdpServer.isEmpty() && !matchingId.isEmpty();\n\n if(parts.length >= 4) {\n smdpOid = parts[3];\n }\n\n // If AC has 4 $s the SMDP OID must be non-empty\n if(parts.length == 4) {\n validity &= !smdpOid.isEmpty();\n }\n\n // If AC has 5 $s the CC required flag must be non-empty\n if(parts.length == 5) {\n confirmationCodeRequiredFlag = parts[4];\n validity &= !confirmationCodeRequiredFlag.isEmpty();\n }\n\n // Last character shall not be a $\n String lastCharacter = activationCode.substring(activationCode.length() - 1);\n validity &= (lastCharacter.compareTo(\"$\") != 0);\n }\n\n return validity;\n }\n\n @Override\n @NonNull\n public String toString() {\n if(activationCode != null) {\n return activationCode;\n } else {\n return \"N/A\";\n }\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator<ActivationCode> CREATOR = new Creator<ActivationCode>() {\n @Override\n public ActivationCode createFromParcel(Parcel in) {\n return new ActivationCode(in);\n }\n\n @Override\n public ActivationCode[] newArray(int size) {\n return new ActivationCode[size];\n }\n };\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(activationCode);\n }\n}" }, { "identifier": "EuiccInfo", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/EuiccInfo.java", "snippet": "public class EuiccInfo {\n private static final String TAG = EuiccInfo.class.getName();\n\n private String eid;\n private final String profileVersion;\n private final String svn;\n private final String euiccFirmwareVer;\n private final String globalplatformVersion;\n private final String sasAcreditationNumber;\n private final List<String> pkiIdsForSign;\n private final List<String> pkiIdsForVerify;\n private final PprIds forbiddenProfilePolicyRules;\n private final BerOctetString extCardResource;\n\n public EuiccInfo(EUICCInfo2 euiccInfo2) {\n this(null, euiccInfo2);\n }\n\n public EuiccInfo(String eid, EUICCInfo2 euiccInfo2) {\n this.eid = eid;\n this.profileVersion = versionTypeToString(euiccInfo2.getProfileVersion());\n this.svn = versionTypeToString(euiccInfo2.getSvn());\n this.euiccFirmwareVer = versionTypeToString(euiccInfo2.getEuiccFirmwareVer());\n this.globalplatformVersion = versionTypeToString(euiccInfo2.getGlobalplatformVersion());\n\n this.sasAcreditationNumber = euiccInfo2.getSasAcreditationNumber().toString();\n\n this.pkiIdsForSign = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForSigning());\n this.pkiIdsForVerify = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForVerification());\n\n this.forbiddenProfilePolicyRules = euiccInfo2.getForbiddenProfilePolicyRules();\n\n this.extCardResource = euiccInfo2.getExtCardResource();\n }\n\n public void setEid(String eid) {\n this.eid = eid;\n }\n\n public String getEid() {\n return eid;\n }\n\n public String getProfileVersion() {\n return profileVersion;\n }\n\n public String getSvn() {\n return svn;\n }\n\n public String getEuiccFirmwareVer() {\n return euiccFirmwareVer;\n }\n\n\n public String getGlobalplatformVersion() {\n return globalplatformVersion;\n }\n\n public String getSasAcreditationNumber() {\n return sasAcreditationNumber;\n }\n\n public List<String> getPkiIdsForSign() {\n return pkiIdsForSign;\n }\n\n public List<String> getPkiIdsForVerify() {\n return pkiIdsForVerify;\n }\n\n public String getPkiIdsForSignAsString(){\n StringBuilder sb = new StringBuilder();\n if (!pkiIdsForSign.isEmpty()) {\n for(String pkiId : pkiIdsForSign) {\n sb.append(pkiId);\n sb.append(\"\\n\");\n }\n } else {\n return \"Not Found\";\n }\n return sb.subSequence(0, sb.length() - 1).toString();\n }\n\n public String getPkiIdsForVerifyAsString(){\n StringBuilder sb = new StringBuilder();\n if (!pkiIdsForVerify.isEmpty()) {\n for(String pkiId : pkiIdsForVerify) {\n sb.append(pkiId);\n sb.append(\"\\n\");\n }\n } else {\n return \"Not Found\";\n }\n return sb.subSequence(0, sb.length() - 1).toString();\n }\n\n public String getForbiddenProfilePolicyRules() {\n return forbiddenProfilePolicyRules.toString();\n }\n\n public String getExtCardResource() {\n return extCardResource.toString();\n }\n\n private static String versionTypeToString(VersionType versionType) {\n if(versionType != null) {\n String vts = versionType.toString();\n Log.debug(TAG, \"Raw version number: \\\"\" + vts + \"\\\".\" );\n if (vts.length() == 6) {\n int major = Integer.parseInt(vts.substring(0, 2));\n int middle = Integer.parseInt(vts.substring(2, 4));\n int minor = Integer.parseInt(vts.substring(4, 6));\n\n return major + \".\" + middle + \".\" + minor;\n }\n }\n\n return \"N/A\";\n }\n\n private static List<String> euiccPkiIdList(EUICCInfo2.EuiccCiPKIdListForSigning pkiIdListIn) {\n List<String> pkiIdList = new ArrayList<>();\n\n for(SubjectKeyIdentifier ski : pkiIdListIn.getSubjectKeyIdentifier()) {\n pkiIdList.add(ski.toString());\n }\n\n return pkiIdList;\n }\n\n private static List<String> euiccPkiIdList(EUICCInfo2.EuiccCiPKIdListForVerification pkiIdListIn) {\n List<String> pkiIdList = new ArrayList<>();\n\n for(SubjectKeyIdentifier ski : pkiIdListIn.getSubjectKeyIdentifier()) {\n pkiIdList.add(ski.toString());\n }\n\n return pkiIdList;\n }\n\n\n}" }, { "identifier": "ProfileMetadata", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/profile/ProfileMetadata.java", "snippet": "final public class ProfileMetadata implements Parcelable {\n private static final String TAG = ProfileMetadata.class.getName();\n\n public static final String STATE_ENABLED = \"Enabled\";\n public static final String STATE_DISABLED = \"Disabled\";\n\n private static final String ICCID = \"ICCID\";\n private static final String STATE = \"STATE\";\n private static final String PROFILECLASS = \"CLASS\";\n private static final String NAME = \"NAME\";\n private static final String PROVIDER_NAME = \"PROVIDER_NAME\";\n private static final String NICKNAME = \"NICKNAME\";\n private static final String ICON = \"ICON\";\n\n private final Map<String, String> profileMetadataMap;\n\n static public String formatIccidUserString(String iccidRawString) {\n // swap the odd/even characters to form a new string\n // ignoring the second last char\n int i = 0;\n StringBuilder newText = new StringBuilder();\n\n while(i < iccidRawString.length() - 1) {\n newText.append(iccidRawString.charAt(i + 1));\n newText.append(iccidRawString.charAt(i));\n i += 2;\n }\n\n if (newText.charAt(newText.length() -1) == 'F') {\n newText.deleteCharAt(newText.length() -1);\n }\n\n return newText.toString();\n }\n\n static public String formatProfileClassString(String profileclass) {\n StringBuilder newText = new StringBuilder();\n if (profileclass != null) {\n switch (profileclass) {\n case \"0\":\n newText.append(\"Testing\");\n break;\n case \"1\":\n newText.append(\"Provisioning\");\n break;\n case \"2\":\n newText.append(\"Operational\");\n break;\n default:\n newText.append(\"Unknown\");\n break;\n }\n } else {\n newText.append(\"Null\");\n }\n\n return newText.toString();\n }\n\n public ProfileMetadata(Map<String, String> profileMetadataMap) {\n this.profileMetadataMap = new HashMap<>(profileMetadataMap);\n }\n\n public ProfileMetadata(@NonNull String iccid,\n @NonNull String profileState,\n @NonNull String profileName,\n @NonNull String serviceProviderName,\n @Nullable String profileclass,\n @Nullable String profileNickname,\n @Nullable String icon) {\n profileMetadataMap = new HashMap<>();\n initialize(iccid, profileState, profileName, serviceProviderName, profileclass, profileNickname, icon);\n }\n\n public ProfileMetadata(@NonNull Iccid iccid,\n @NonNull ProfileState profileState,\n @NonNull BerUTF8String profileName,\n @NonNull BerUTF8String serviceProviderName,\n @Nullable ProfileClass profileClass,\n @Nullable BerUTF8String profileNickname,\n @Nullable BerOctetString icon) {\n profileMetadataMap = new HashMap<>();\n\n String nicknameString = null;\n String iconString = null;\n String profileClassString = null;\n if(profileNickname != null) {\n nicknameString = profileNickname.toString();\n }\n if(icon != null) {\n iconString = icon.toString();\n }\n if(profileClass != null) {\n profileClassString = profileClass.toString();\n }\n initialize(iccid.toString(),\n ProfileStates.getString(profileState),\n profileName.toString(),\n serviceProviderName.toString(),\n profileClassString,\n nicknameString,\n iconString);\n }\n\n public ProfileMetadata(@NonNull ProfileInfo profileInfo) {\n this(profileInfo.getIccid(),\n profileInfo.getProfileState(),\n profileInfo.getProfileName(),\n profileInfo.getServiceProviderName(),\n profileInfo.getProfileClass(),\n profileInfo.getProfileNickname(),\n profileInfo.getIcon());\n }\n\n public ProfileMetadata(StoreMetadataRequest storeMetadataRequest) {\n this(storeMetadataRequest.getIccid(),\n new ProfileState(0),\n storeMetadataRequest.getProfileName(),\n storeMetadataRequest.getServiceProviderName(),\n storeMetadataRequest.getProfileClass(),\n null,\n null);\n }\n\n private void initialize(@NonNull String iccid,\n @NonNull String state,\n @NonNull String name,\n @NonNull String provider,\n @Nullable String profileclass,\n @Nullable String nickname,\n @Nullable String icon) {\n\n profileMetadataMap.put(NAME, name);\n profileMetadataMap.put(ICCID, iccid);\n profileMetadataMap.put(STATE, state);\n profileMetadataMap.put(PROVIDER_NAME, provider);\n\n if(nickname != null) {\n profileMetadataMap.put(NICKNAME, nickname);\n }\n if(icon != null) {\n profileMetadataMap.put(ICON, icon);\n }\n if(profileclass != null){\n profileMetadataMap.put(PROFILECLASS, profileclass);\n }\n }\n\n public Boolean hasNickname() {\n return (getNickname() != null) && (!getNickname().equals(\"\"));\n }\n\n public void setEnabled(boolean isEnabled) {\n if(isEnabled) {\n profileMetadataMap.replace(STATE, STATE_ENABLED);\n } else {\n profileMetadataMap.replace(STATE, STATE_DISABLED);\n }\n }\n\n public Boolean isEnabled() {\n return getState().equals(STATE_ENABLED);\n }\n\n public String getName() {\n return profileMetadataMap.get(NAME);\n }\n\n public String getIccid() {\n return profileMetadataMap.get(ICCID);\n }\n\n public String getState() {\n return profileMetadataMap.get(STATE);\n }\n\n public String getProfileclass() {\n return profileMetadataMap.get(PROFILECLASS);\n }\n\n public String getProvider() {\n return profileMetadataMap.get(PROVIDER_NAME);\n }\n\n public String getNickname() {\n return profileMetadataMap.get(NICKNAME);\n }\n\n private String getIconString() {\n return profileMetadataMap.get(ICON);\n }\n\n public void setNickname(String nickname) {\n profileMetadataMap.put(NICKNAME, nickname);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeString(getName());\n out.writeString(getIccid());\n out.writeString(getState());\n out.writeString(getProfileclass());\n out.writeString(getProvider());\n out.writeString(getNickname());\n out.writeString(getIconString());\n }\n\n public static final Parcelable.Creator<ProfileMetadata> CREATOR = new Parcelable.Creator<ProfileMetadata>() {\n public ProfileMetadata createFromParcel(Parcel in) {\n return new ProfileMetadata(in);\n }\n\n public ProfileMetadata[] newArray(int size) {\n return new ProfileMetadata[size];\n }\n };\n\n private ProfileMetadata(Parcel in) {\n profileMetadataMap = new HashMap<>();\n profileMetadataMap.put(NAME, in.readString());\n profileMetadataMap.put(ICCID, in.readString());\n profileMetadataMap.put(STATE, in.readString());\n profileMetadataMap.put(PROFILECLASS, in.readString());\n profileMetadataMap.put(PROVIDER_NAME, in.readString());\n profileMetadataMap.put(NICKNAME, in.readString());\n profileMetadataMap.put(ICON, in.readString());\n }\n\n @NonNull\n @Override\n public String toString() {\n return \"Profile{\" +\n \"profileMetadataMap=\" + profileMetadataMap +\n '}';\n }\n\n public Icon getIcon() {\n String iconBytesHex = profileMetadataMap.get(ICON);\n\n if(iconBytesHex != null) {\n byte[] iconBytes = Bytes.decodeHexString(iconBytesHex);\n return Icon.createWithData(iconBytes, 0, iconBytes.length);\n } else {\n return null;\n }\n }\n}" }, { "identifier": "ClearNotificationsResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/ClearNotificationsResult.java", "snippet": "public class ClearNotificationsResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_NOT_FOUND = 1;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_NOT_FOUND, \"ICCID not found.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final List<Integer> values;\n\n public ClearNotificationsResult(List<Integer> results) {\n this.values = results;\n }\n\n @Override\n public boolean isOk() {\n for(Integer value : values) {\n if(value != OK) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean equals(int value) {\n for(Integer internalValue : values) {\n if(value == internalValue) {\n return true;\n }\n }\n\n return false;\n }\n\n @Override\n public String getDescription() {\n StringBuilder description = new StringBuilder();\n\n for(Integer value : values) {\n description.append(lookup.get(value)).append(\"\\n\");\n }\n\n return description.toString();\n }\n}" }, { "identifier": "DeleteResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/DeleteResult.java", "snippet": "public class DeleteResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_OR_AID_NOT_FOUND = 1;\n public static final int PROFILE_NOT_IN_DISABLED_STATE = 2;\n public static final int DISALLOWED_BY_POLICY = 3;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_OR_AID_NOT_FOUND, \"ICCID or AID not found.\");\n lookup.put(PROFILE_NOT_IN_DISABLED_STATE, \"Profile not in disabled state.\");\n lookup.put(DISALLOWED_BY_POLICY, \"Disallowed by policy.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public DeleteResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}" }, { "identifier": "DisableResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/DisableResult.java", "snippet": "public class DisableResult implements OperationResult{\n public static final int OK = 0;\n public static final int ICCID_OR_AID_NOT_FOUND = 1;\n public static final int PROFILE_NOT_IN_ENABLED_STATE = 2;\n public static final int DISALLOWED_BY_POLICY = 3;\n public static final int CAT_BUSY = 5;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_OR_AID_NOT_FOUND, \"ICCID or AID not found.\");\n lookup.put(PROFILE_NOT_IN_ENABLED_STATE, \"Profile not in enabled state.\");\n lookup.put(DISALLOWED_BY_POLICY, \"Disallowed by policy.\");\n lookup.put(CAT_BUSY, \"CAT busy.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public DisableResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}" }, { "identifier": "EnableResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/EnableResult.java", "snippet": "public class EnableResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_OR_AID_NOT_FOUND = 1;\n public static final int PROFILE_NOT_IN_DISABLED_STATE = 2;\n public static final int DISALLOWED_BY_POLICY = 3;\n public static final int WRONG_PROFILE_REENABLING = 4;\n public static final int CAT_BUSY = 5;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_OR_AID_NOT_FOUND, \"ICCID or AID not found.\");\n lookup.put(PROFILE_NOT_IN_DISABLED_STATE, \"Profile not in disabled state.\");\n lookup.put(DISALLOWED_BY_POLICY, \"Disallowed by policy.\");\n lookup.put(WRONG_PROFILE_REENABLING, \"Wrong profile reenabling.\");\n lookup.put(CAT_BUSY, \"CAT busy.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public EnableResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}" }, { "identifier": "SetNicknameResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/SetNicknameResult.java", "snippet": "public class SetNicknameResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_NOT_FOUND = 1;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_NOT_FOUND, \"ICCID not found.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public SetNicknameResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}" }, { "identifier": "AuthenticateResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/AuthenticateResult.java", "snippet": "public class AuthenticateResult extends RemoteOperationResult {\n private final Boolean isCcRequired;\n private final ProfileMetadata profileMetadata;\n\n public AuthenticateResult(Boolean isCcRequired, ProfileMetadata profileMetadata) {\n super();\n this.isCcRequired = isCcRequired;\n this.profileMetadata = profileMetadata;\n }\n\n public AuthenticateResult(RemoteError remoteError) {\n super(remoteError);\n this.isCcRequired = null;\n this.profileMetadata = null;\n }\n\n public Boolean getCcRequired() {\n return isCcRequired;\n }\n\n public ProfileMetadata getProfileMetadata() {\n return profileMetadata;\n }\n}" }, { "identifier": "CancelSessionResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/CancelSessionResult.java", "snippet": "public class CancelSessionResult extends RemoteOperationResult {\n\n public CancelSessionResult() {\n super();\n }\n\n public CancelSessionResult(String genericError) {\n super(genericError);\n\n }\n\n public CancelSessionResult(RemoteError remoteError) {\n super(remoteError);\n }\n}" }, { "identifier": "DownloadResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/DownloadResult.java", "snippet": "public class DownloadResult extends RemoteOperationResult {\n\n public DownloadResult() {\n super();\n }\n\n public DownloadResult(RemoteError remoteError) {\n super(remoteError);\n }\n}" }, { "identifier": "HandleNotificationsResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/HandleNotificationsResult.java", "snippet": "public class HandleNotificationsResult extends RemoteOperationResult {\n\n public HandleNotificationsResult() {\n super();\n }\n\n public HandleNotificationsResult(RemoteError remoteError) {\n super(remoteError);\n }\n}" }, { "identifier": "RemoteError", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/RemoteError.java", "snippet": "public class RemoteError {\n private final String status;\n private final String subjectCode;\n private final String reasonCode;\n private final String message;\n\n public RemoteError() {\n this(\"No error\",null, null, null);\n }\n\n public RemoteError(FunctionExecutionStatus functionExecutionStatus) {\n if(functionExecutionStatus == null) {\n this.status = \"No error\";\n this.subjectCode = null;\n this.reasonCode = null;\n this.message = null;\n } else {\n this.status = functionExecutionStatus.getStatus();\n if(functionExecutionStatus.getStatusCodeData() != null) {\n this.subjectCode = functionExecutionStatus.getStatusCodeData().getSubjectCode();\n this.reasonCode = functionExecutionStatus.getStatusCodeData().getReasonCode();\n this.message = functionExecutionStatus.getStatusCodeData().getMessage();\n } else {\n this.subjectCode = null;\n this.reasonCode = null;\n this.message = null;\n }\n }\n }\n\n public RemoteError(String status, String subjectCode, String reasonCode, String message) {\n this.status = status;\n this.subjectCode = subjectCode;\n this.reasonCode = reasonCode;\n this.message = message;\n }\n\n public String getStatus() {\n return status;\n }\n\n public String getSubjectCode() {\n return subjectCode;\n }\n\n public String getReasonCode() {\n return reasonCode;\n }\n\n public String getMessage() {\n return message;\n }\n\n @Override\n @NonNull\n public String toString() {\n return \"RspError{\" +\n \"status='\" + status + '\\'' +\n \", subjectCode='\" + subjectCode + '\\'' +\n \", reasonCode='\" + reasonCode + '\\'' +\n \", message='\" + message + '\\'' +\n '}';\n }\n}" } ]
import com.infineon.esim.lpa.core.dtos.result.local.SetNicknameResult; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult; import com.infineon.esim.lpa.core.dtos.result.remote.RemoteError; import java.util.List; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.local.ClearNotificationsResult; import com.infineon.esim.lpa.core.dtos.result.local.DeleteResult; import com.infineon.esim.lpa.core.dtos.result.local.DisableResult; import com.infineon.esim.lpa.core.dtos.result.local.EnableResult;
7,441
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core; public interface LocalProfileAssistantCore { // Profile management String getEID() throws Exception; EuiccInfo getEuiccInfo2() throws Exception; List<ProfileMetadata> getProfiles() throws Exception; // Profile operations EnableResult enableProfile(String iccid, boolean refreshFlag) throws Exception; DisableResult disableProfile(String iccid) throws Exception; DeleteResult deleteProfile(String iccid) throws Exception; SetNicknameResult setNickname(String iccid, String nickname) throws Exception; // Profile download AuthenticateResult authenticate(ActivationCode activationCode) throws Exception; DownloadResult downloadProfile(String confirmationCode) throws Exception;
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core; public interface LocalProfileAssistantCore { // Profile management String getEID() throws Exception; EuiccInfo getEuiccInfo2() throws Exception; List<ProfileMetadata> getProfiles() throws Exception; // Profile operations EnableResult enableProfile(String iccid, boolean refreshFlag) throws Exception; DisableResult disableProfile(String iccid) throws Exception; DeleteResult deleteProfile(String iccid) throws Exception; SetNicknameResult setNickname(String iccid, String nickname) throws Exception; // Profile download AuthenticateResult authenticate(ActivationCode activationCode) throws Exception; DownloadResult downloadProfile(String confirmationCode) throws Exception;
CancelSessionResult cancelSession(long cancelSessionReasonValue) throws Exception;
9
2023-11-06 02:41:13+00:00
12k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/user/service/impl/UserServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": "EmailLoginDTO", "path": "src/main/java/com/jerry/pilipala/application/dto/EmailLoginDTO.java", "snippet": "@Data\npublic class EmailLoginDTO {\n @NotBlank(message = \"邮箱不得为空\")\n private String email;\n @NotBlank(message = \"验证码不得为空\")\n private String verifyCode;\n}" }, { "identifier": "LoginDTO", "path": "src/main/java/com/jerry/pilipala/application/dto/LoginDTO.java", "snippet": "@Data\npublic class LoginDTO {\n @NotBlank(message = \"手机号不得为空\")\n private String tel;\n @NotBlank(message = \"验证码不得为空\")\n private String verifyCode;\n}" }, { "identifier": "UserVO", "path": "src/main/java/com/jerry/pilipala/application/vo/user/UserVO.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class UserVO extends PreviewUserVO {\n private int fansCount = 0;\n private int followCount = 0;\n}" }, { "identifier": "MessageTrigger", "path": "src/main/java/com/jerry/pilipala/domain/common/template/MessageTrigger.java", "snippet": "@Slf4j\n@Component\npublic class MessageTrigger {\n private final MongoTemplate mongoTemplate;\n private final TemplateResolver templateResolver;\n\n public MessageTrigger(MongoTemplate mongoTemplate,\n TemplateResolver templateResolver) {\n this.mongoTemplate = mongoTemplate;\n this.templateResolver = templateResolver;\n }\n\n public void trigger(String templateName,\n MessageType type,\n String senderId,\n String receiveId,\n Map<String, String> variables) {\n CompletableFuture.runAsync(() -> {\n try {\n handle(templateName,\n type,\n senderId,\n receiveId,\n variables);\n } catch (Exception e) {\n log.error(\"站内信触发失败,\", e);\n }\n });\n }\n\n public void triggerSystemMessage(String templateName,\n String receiveId,\n Map<String, String> variables) {\n trigger(templateName,\n MessageType.SYSTEM,\n \"\",\n receiveId,\n variables);\n }\n\n public void handle(String templateName,\n MessageType type,\n String senderId,\n String receiveId,\n Map<String, String> variables) {\n Template template = mongoTemplate.findOne(\n new Query(Criteria.where(\"_id\").is(templateName)),\n Template.class);\n if (Objects.isNull(template)) {\n log.error(\"消息模板:{} -> 不存在\", templateName);\n return;\n }\n String content = template.getContent();\n String messageContent = templateResolver.fillVariable(content, variables);\n Message message = new Message();\n message.setSenderId(senderId)\n .setReceiverId(receiveId)\n .setContent(messageContent)\n .setType(type.getType());\n mongoTemplate.save(message);\n }\n}" }, { "identifier": "SmsService", "path": "src/main/java/com/jerry/pilipala/domain/message/service/SmsService.java", "snippet": "public interface SmsService {\n void sendCode(String tel, String code, Integer expireMinutes);\n\n void sendEmailCode(String email, String code, Integer expireMinutes);\n}" }, { "identifier": "Role", "path": "src/main/java/com/jerry/pilipala/domain/user/entity/mongo/Role.java", "snippet": "@Data\n@Accessors(chain = true)\n@Document(\"role\")\npublic class Role {\n @Id\n private ObjectId id;\n @Indexed(unique = true)\n private String name = \"\";\n private List<String> permissionIds = new ArrayList<>();\n private Boolean deleted = false;\n private Long ctime = System.currentTimeMillis();\n}" }, { "identifier": "User", "path": "src/main/java/com/jerry/pilipala/domain/user/entity/mongo/User.java", "snippet": "@Data\n@Document(\"user\")\n@Accessors(chain = true)\npublic class User {\n @Id\n private ObjectId uid;\n private String tel;\n private String email;\n @TextIndexed\n private String nickname = \"unknown\";\n private String intro = \"\";\n private String avatar = \"/file/cover/nav_icon_avatar_nor.svg\";\n private String roleId = \"\";\n private Long ctime = System.currentTimeMillis();\n private Long mtime = System.currentTimeMillis();\n\n public static User UNKNOWN = new User()\n .setUid(new ObjectId())\n .setTel(\"\")\n .setEmail(\"\")\n .setNickname(\"unknown\")\n .setAvatar(\"\")\n .setRoleId(\"\");\n}" }, { "identifier": "UserEntity", "path": "src/main/java/com/jerry/pilipala/domain/user/entity/neo4j/UserEntity.java", "snippet": "@Data\n@Node(\"user\")\n@Accessors(chain = true)\npublic class UserEntity {\n @Id\n private String uid = \"\";\n private String tel = \"\";\n private String email = \"\";\n private Long ctime = System.currentTimeMillis();\n @Relationship(\"Followed\")\n private List<UserEntity> followUps = new ArrayList<>();\n}" }, { "identifier": "UserEntityRepository", "path": "src/main/java/com/jerry/pilipala/domain/user/repository/UserEntityRepository.java", "snippet": "public interface UserEntityRepository extends Neo4jRepository<UserEntity, String> {\n UserEntity findUserEntityByTel(String tel);\n\n /**\n * 获取粉丝数据\n *\n * @param uid 用户ID\n * @return list\n */\n @Query(\"MATCH (follower:`user`)-[:Followed]->(user:`user` {uid: $uid}) RETURN follower\")\n List<UserEntity> findFollowersByUserId(String uid);\n\n /**\n * 获取粉丝数据\n *\n * @param uid 用户ID\n * @return list\n */\n @Query(\"MATCH (follower:`user`)-[:Followed]->(user:`user` {uid: $uid}) RETURN follower SKIP $skip LIMIT $limit\")\n List<UserEntity> findFollowersByUserId(String uid, int skip, int limit);\n\n /**\n * 获取粉丝数量\n *\n * @param uid 用户ID\n * @return count\n */\n @Query(\"MATCH (follower:`user`)-[:Followed]->(user:`user` {uid: $uid}) RETURN COUNT(follower)\")\n int countFollowersByUserId(String uid);\n\n\n /**\n * 获取我关注的 up\n *\n * @param userId 用户ID\n * @return up\n */\n @Query(\"MATCH (user:`user` {uid: $userId})-[:Followed]->(followed:`user`) RETURN followed SKIP $skip LIMIT $limit\")\n List<UserEntity> getFollowedUsers(@Param(\"userId\") String userId, @Param((\"skip\")) int skip, @Param(\"limit\") int limit);\n\n /**\n * 获取我关注的 up 数量\n *\n * @param userId 用户ID\n * @return count\n */\n @Query(\"MATCH (user:`user` {uid: $userId})-[:Followed]->(followed:`user`) RETURN COUNT(followed)\")\n int getFollowedUsersCount(@Param(\"userId\") String userId);\n\n @Query(\"MATCH (u:`user` {uid: $userId})-[r:Followed]->(f:`user` {uid: $followedUserId}) DELETE r\")\n void removeFollowUpRelation(@Param(\"userId\") String userId, @Param(\"followedUserId\") String followedUserId);\n}" }, { "identifier": "UserService", "path": "src/main/java/com/jerry/pilipala/domain/user/service/UserService.java", "snippet": "public interface UserService {\n UserVO login(LoginDTO loginDTO);\n\n void code(String tel);\n\n UserVO userVO(String uid, boolean forceQuery);\n\n List<UserVO> userVoList(Collection<String> uidSet);\n\n Page<UserVO> page(Integer pageNo, Integer pageSize);\n\n void emailCode(String email);\n\n UserVO emailLogin(EmailLoginDTO loginDTO);\n}" }, { "identifier": "BusinessException", "path": "src/main/java/com/jerry/pilipala/infrastructure/common/errors/BusinessException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class BusinessException extends RuntimeException implements IResponse {\n private final int code;\n private final String message;\n private final IResponse response;\n\n public BusinessException(IResponse response) {\n this(\"\", response, null);\n }\n\n public BusinessException(String message, IResponse response) {\n this(message, response, null);\n }\n\n public BusinessException(String message, IResponse response, Object[] args) {\n super(message == null ? response.getMessage() : message);\n this.code = response.getCode();\n this.response = response;\n this.message = MessageFormat.format(super.getMessage(), args);\n }\n\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n public static BusinessException businessError(String message) {\n return new BusinessException(message, StandardResponse.ERROR);\n }\n}" }, { "identifier": "StandardResponse", "path": "src/main/java/com/jerry/pilipala/infrastructure/common/response/StandardResponse.java", "snippet": "public enum StandardResponse implements IResponse {\n OK(200, \"success\"),\n BAD_REQUEST(400, \"Bad Request\"),\n FORBIDDEN(403, \"Access Denied\"),\n NOT_FOUND(404, \"Not Found\"),\n ERROR(500, \"Business Error\");\n private final int code;\n private final String message;\n\n StandardResponse(int code, String message) {\n this.code = code;\n this.message = message;\n }\n\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}" }, { "identifier": "TemplateNameEnum", "path": "src/main/java/com/jerry/pilipala/infrastructure/enums/message/TemplateNameEnum.java", "snippet": "public interface TemplateNameEnum {\n String LOGIN_NOTIFY = \"login_notify\";\n String APPLY_PASSED_NOTIFY = \"apply_passed_notify\";\n String POST_VOD_NOTIFY = \"post_vod_notify\";\n String REVIEW_DENIED_NOTIFY = \"review_denied_notify\";\n String REVIEW_PASSED_NOTIFY = \"review_passed_notify\";\n\n String LIKE_NOTIFY = \"like_notify\";\n String COMMENT_NOTIFY = \"comment_notify\";\n\n String REPLY_NOTIFY = \"reply_notify\";\n String AT_NOTIFY = \"at_notify\";\n String AT_TEMPLATE = \"at_template\";\n}" }, { "identifier": "UserCacheKeyEnum", "path": "src/main/java/com/jerry/pilipala/infrastructure/enums/redis/UserCacheKeyEnum.java", "snippet": "public interface UserCacheKeyEnum {\n interface StringKey {\n String USER_CACHE_KEY = \"user-entity-\";\n }\n\n interface HashKey {\n String USER_VO_HASH_KEY = \"user-vo-hash\";\n String ROLE_CACHE_KEY = \"role-hash\";\n String PERMISSION_CACHE_KEY = \"permission-hash\";\n }\n\n interface SetKey {\n String COLLECT_VOD_SET = \"collect-\";\n }\n\n}" }, { "identifier": "CaptchaUtil", "path": "src/main/java/com/jerry/pilipala/infrastructure/utils/CaptchaUtil.java", "snippet": "public class CaptchaUtil {\n public static class CharacterConstant {\n /**\n * 小写字符数组\n */\n public static final char[] LOWER_CASE = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};\n /**\n * 大写字母数组\n */\n public static final char[] UPPER_CASE = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};\n /**\n * 数字数组\n */\n public static final char[] DIGIT = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};\n /**\n * 特殊符号数组\n */\n public static final char[] SPECIAL_CHARACTER = {'~', ';', '<', '@', '#', ':', '>', '%', '^'};\n }\n \n //图片宽高\n private static final int WIDTH = 200;\n private static final int HEIGHT = 50;\n //噪点\n private static final float YAWN_RATE = 0.05f;\n\n public static String generatorCaptchaWithCharAndNumberByLength(int length) {\n int lowerLength = ThreadLocalRandom.current().nextInt(length);\n int upperLength = ThreadLocalRandom.current().nextInt(length - lowerLength);\n int numberLength = length - lowerLength - upperLength;\n StringBuilder builder = new StringBuilder(length);\n int randomIndex;\n for (int i = 0; i < lowerLength; i++) {\n randomIndex = ThreadLocalRandom.current().nextInt(LOWER_CASE.length);\n builder.append(LOWER_CASE[randomIndex]);\n }\n\n for (int i = 0; i < upperLength; i++) {\n randomIndex = ThreadLocalRandom.current().nextInt(UPPER_CASE.length);\n builder.append(UPPER_CASE[randomIndex]);\n }\n for (int i = 0; i < numberLength; i++) {\n randomIndex = ThreadLocalRandom.current().nextInt(DIGIT.length);\n builder.append(DIGIT[randomIndex]);\n }\n return builder.toString();\n }\n\n public static String generatorCaptchaNumberByLength(int length) {\n StringBuilder result = new StringBuilder();\n int randomIndex;\n for (int i = 0; i < length; i++) {\n randomIndex = ThreadLocalRandom.current().nextInt(DIGIT.length);\n result.append(DIGIT[randomIndex]);\n }\n return result.toString();\n }\n\n public static Pair<String, String> generatorBase64CaptchaStringByLength(int length) throws Exception {\n String captchaWithCharAndNumberByLength = generatorCaptchaWithCharAndNumberByLength(length);\n BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);\n Graphics2D graphics = image.createGraphics();\n graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n\n //绘制边框\n graphics.setColor(Color.GRAY);\n graphics.fillRect(0, 0, WIDTH, HEIGHT);\n\n //设置背景色 bc > fc\n int fc = ThreadLocalRandom.current().nextInt(185) + 50;\n int bc = ThreadLocalRandom.current().nextInt(20) + 205;\n if (fc >= bc) {\n bc += fc - bc + 5;\n }\n Color c = getRandomColor(fc, bc);\n graphics.setColor(c);\n graphics.fillRect(0, 2, WIDTH, HEIGHT - 4);\n\n //绘制干扰线\n graphics.setColor(getRandomColor(160, 200));\n int lineCount = ThreadLocalRandom.current().nextInt(20);\n for (int i = 0; i < lineCount; i++) {\n int x = ThreadLocalRandom.current().nextInt(WIDTH - 1);\n int y = ThreadLocalRandom.current().nextInt(HEIGHT - 1);\n int x1 = ThreadLocalRandom.current().nextInt(6) + 1;\n int y1 = ThreadLocalRandom.current().nextInt(12) + 1;\n graphics.drawLine(x, y, x + x1 + 40, y + y1 + 20);\n }\n\n //添加噪点\n int area = (int) (YAWN_RATE * WIDTH * HEIGHT);\n for (int i = 0; i < area; i++) {\n int x = ThreadLocalRandom.current().nextInt(WIDTH);\n int y = ThreadLocalRandom.current().nextInt(HEIGHT);\n int rgb = getRandomIntColor();\n image.setRGB(x, y, rgb);\n }\n\n //扭曲图片\n shear(graphics, c);\n\n graphics.setColor(getRandomColor(100, 160));\n int fontSize = HEIGHT - 4;\n// Font font = new Font(\"Algerian\", Font.PLAIN, fontSize);\n Font font = new Font(\"宋体\", Font.PLAIN, fontSize);\n graphics.setFont(font);\n char[] chars = captchaWithCharAndNumberByLength.toCharArray();\n for (int i = 0; i < length; i++) {\n AffineTransform affineTransform = new AffineTransform();\n affineTransform.setToRotation(Math.PI / 4 * ThreadLocalRandom.current().nextDouble() * (ThreadLocalRandom.current().nextBoolean() ? 1 : -1),\n (WIDTH / (length * 1.0)) * i + fontSize / 2.0, HEIGHT / 2.0);\n graphics.setTransform(affineTransform);\n graphics.drawChars(chars, i, 1, ((WIDTH - 10) / length) * i + 5, HEIGHT / 2 + fontSize / 2 - 10);\n }\n graphics.dispose();\n\n InputStream inputStream = null;\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n ImageOutputStream imageOutputStream = null;\n\n StringBuilder result = new StringBuilder();\n try {\n imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);\n ImageIO.write(image, \"png\", imageOutputStream);\n inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());\n String base64 = Base64Util.generateBase64Jpeg(inputStream);\n result.append(base64);\n return new Pair<>(captchaWithCharAndNumberByLength, result.toString());\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (inputStream != null) {\n inputStream.close();\n }\n byteArrayOutputStream.close();\n if (imageOutputStream != null) {\n imageOutputStream.close();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n throw new Exception(\"生成验证码失败\");\n\n }\n\n private static Color getRandomColor(int fc, int bc) {\n fc &= 255;\n bc &= 255;\n// System.out.printf(\"fc: %s\\tbc: %s\\t bc>fc:%s \\n\", fc, bc, bc > fc);\n int r = fc + ThreadLocalRandom.current().nextInt(bc - fc);\n int g = fc + ThreadLocalRandom.current().nextInt(bc - fc);\n int b = fc + ThreadLocalRandom.current().nextInt(bc - fc);\n return new Color(r, g, b);\n }\n\n private static int getRandomIntColor() {\n int[] rgb = getRandomRgb();\n int color = 0;\n for (int c : rgb) {\n color = color << 8;\n color |= c;\n }\n return color;\n }\n\n private static int[] getRandomRgb() {\n int[] rgb = new int[3];\n for (int i = 0; i < 3; i++) {\n rgb[i] = ThreadLocalRandom.current().nextInt(255);\n }\n return rgb;\n }\n\n private static void shear(Graphics g, Color color) {\n shearX(g, color);\n shearY(g, color);\n }\n\n private static void shearX(Graphics g, Color color) {\n\n int period = ThreadLocalRandom.current().nextInt(4);\n\n int frames = 1;\n int phase = ThreadLocalRandom.current().nextInt(2);\n\n for (int i = 0; i < CaptchaUtil.HEIGHT; i++) {\n double d = (double) (period / 2)\n * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);\n g.copyArea(0, i, CaptchaUtil.WIDTH, 1, (int) d, 0);\n g.setColor(color);\n g.drawLine((int) d, i, 0, i);\n g.drawLine((int) d + CaptchaUtil.WIDTH, i, CaptchaUtil.WIDTH, i);\n }\n\n }\n\n private static void shearY(Graphics g, Color color) {\n // 50;\n int period = ThreadLocalRandom.current().nextInt(40) + 10;\n\n boolean borderGap = true;\n int frames = 20;\n int phase = 7;\n for (int i = 0; i < CaptchaUtil.WIDTH; i++) {\n double d = (double) (period >> 1)\n * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);\n g.copyArea(i, 0, 1, CaptchaUtil.HEIGHT, 0, (int) d);\n g.setColor(color);\n g.drawLine(i, (int) d, i, 0);\n g.drawLine(i, (int) d + CaptchaUtil.HEIGHT, i, CaptchaUtil.HEIGHT);\n }\n }\n\n}" }, { "identifier": "JsonHelper", "path": "src/main/java/com/jerry/pilipala/infrastructure/utils/JsonHelper.java", "snippet": "@Slf4j\n@Component\npublic class JsonHelper {\n private final ObjectMapper mapper;\n\n public JsonHelper(ObjectMapper mapper) {\n this.mapper = mapper;\n }\n\n public <T> T parse(String json, Class<T> clazz) {\n try {\n return mapper.readValue(json, clazz);\n } catch (JsonProcessingException e) {\n log.error(\"json 解析失败,\", e);\n throw BusinessException.businessError(\"json 解析失败\");\n }\n }\n\n public <T> T parse(String json, TypeReference<T> type) {\n try {\n return mapper.readValue(json, type);\n } catch (JsonProcessingException e) {\n log.error(\"json 解析失败,\", e);\n throw BusinessException.businessError(\"json 解析失败\");\n }\n }\n\n public <T> T convert(Object obj, Class<T> clazz) {\n try {\n return mapper.convertValue(obj, clazz);\n } catch (Exception e) {\n throw BusinessException.businessError(\"类型转换失败\");\n }\n }\n\n public String as(Object obj) {\n try {\n return mapper.writeValueAsString(obj);\n } catch (Exception e) {\n log.error(\"json 转换失败\",e);\n throw BusinessException.businessError(\"json 转换失败\");\n }\n }\n}" }, { "identifier": "Page", "path": "src/main/java/com/jerry/pilipala/infrastructure/utils/Page.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class Page<T> {\n private int pageNo = 1;\n private int pageSize = 10;\n private Long total = 0L;\n private List<T> page = new ArrayList<>();\n}" }, { "identifier": "RequestUtil", "path": "src/main/java/com/jerry/pilipala/infrastructure/utils/RequestUtil.java", "snippet": "@Slf4j\npublic class RequestUtil {\n private static final String[] HEADER_CONFIG = {\n \"x-forwarded-for\",\n \"Proxy-Client-IP\",\n \"WL-Proxy-Client-IP\",\n \"HTTP_CLIENT_IP\",\n \"HTTP_X_FORWARDED_FOR\",\n\n };\n private static String serverIp;\n\n static {\n InetAddress ia = null;\n try {\n ia = InetAddress.getLocalHost();\n serverIp = ia.getHostAddress();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static String getIpAddress(HttpServletRequest request) {\n String ip = null;\n for (String config : HEADER_CONFIG) {\n ip = request.getHeader(config);\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n break;\n }\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getRemoteAddr();\n }\n if (\"0:0:0:0:0:0:0:1\".equals(ip)) {\n ip = serverIp;\n }\n return ip;\n }\n\n public static String getLocalHostAddress() {\n try {\n InetAddress backupHost = null;\n Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();\n while (networkInterfaces.hasMoreElements()) {\n NetworkInterface networkInterface = networkInterfaces.nextElement();\n Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();\n while (inetAddresses.hasMoreElements()) {\n InetAddress inetAddress = inetAddresses.nextElement();\n if (inetAddress.isLoopbackAddress()) {\n continue;\n }\n if (inetAddress.isSiteLocalAddress()) {\n return inetAddress.getHostAddress();\n }\n if (Objects.isNull(backupHost)) {\n backupHost = inetAddress;\n }\n }\n }\n return Objects.isNull(backupHost) ? InetAddress.getLocalHost().getHostAddress() : backupHost.getHostAddress();\n } catch (Exception e) {\n throw new RuntimeException(\"获取本机 ip 信息失败\");\n }\n }\n\n}" } ]
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.date.DateUtil; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.EmailLoginDTO; import com.jerry.pilipala.application.dto.LoginDTO; import com.jerry.pilipala.application.vo.user.UserVO; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.SmsService; import com.jerry.pilipala.domain.user.entity.mongo.Role; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.user.service.UserService; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.UserCacheKeyEnum; import com.jerry.pilipala.infrastructure.utils.CaptchaUtil; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.RequestUtil; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
7,997
} } UserInfoBO userInfoBO = new UserInfoBO() .setUid(user.getUid().toString()) .setRoleId(roleId) .setPermissionIdList(role.getPermissionIds()); StpUtil.getSession().set("user-info", userInfoBO); return userVO(user.getUid().toString(), false); } @Override public void code(String tel) { String loginCodeKey = "login-%s".formatted(tel); String code = (String) redisTemplate.opsForValue().get(loginCodeKey); if (StringUtils.isNotBlank(code)) { throw BusinessException.businessError("验证码已发送"); } // redis 不存在,生成一个新的 code = CaptchaUtil.generatorCaptchaNumberByLength(6); int expireMinutes = 1; smsService.sendCode(tel, code, expireMinutes); redisTemplate.opsForValue().set(loginCodeKey, code, expireMinutes * 60, TimeUnit.SECONDS); } @Override public void emailCode(String email) { String emailCodeKey = "login-email-%s".formatted(email); String code = (String) redisTemplate.opsForValue().get(emailCodeKey); if (StringUtils.isNotBlank(code)) { throw BusinessException.businessError("验证码已发送"); } // redis 不存在,生成一个新的 code = CaptchaUtil.generatorCaptchaNumberByLength(6); int expireMinutes = 1; smsService.sendEmailCode(email, code, expireMinutes); redisTemplate.opsForValue().set(emailCodeKey, code, expireMinutes * 60, TimeUnit.SECONDS); } @Override public UserVO emailLogin(EmailLoginDTO loginDTO) { String loginCodeKey = "login-email-%s".formatted(loginDTO.getEmail()); String code = (String) redisTemplate.opsForValue().get(loginCodeKey); if (StringUtils.isBlank(code) || !code.equals(loginDTO.getVerifyCode())) { throw new BusinessException("验证码错误", StandardResponse.ERROR); } redisTemplate.delete(loginCodeKey); // 密文存储手机号 String encodeEmail = Base64.getEncoder().encodeToString(loginDTO.getEmail().getBytes()); User user = mongoTemplate.findOne( new Query(Criteria.where("email").is(encodeEmail)), User.class); return loginLogic(user, "", encodeEmail); } @Override public UserVO userVO(String uid, boolean forceQuery) { if (StringUtils.isBlank(uid)) { uid = StpUtil.getLoginId(""); if (StringUtils.isBlank(uid)) { throw new BusinessException("用户不存在", StandardResponse.ERROR); } } UserVO userVO; if (!forceQuery) { // 如果缓存有,直接走缓存 userVO = jsonHelper.convert(redisTemplate.opsForHash() .get(UserCacheKeyEnum.HashKey.USER_VO_HASH_KEY, uid), UserVO.class); if (Objects.nonNull(userVO)) { return userVO; } } User user = mongoTemplate.findById(new ObjectId(uid), User.class); if (Objects.isNull(user)) { throw new BusinessException("用户不存在", StandardResponse.ERROR); } int fansCount = userEntityRepository.countFollowersByUserId(uid); int upCount = userEntityRepository.getFollowedUsersCount(uid); userVO = new UserVO(); userVO.setFansCount(fansCount) .setFollowCount(upCount) .setUid(user.getUid().toString()) .setAvatar(user.getAvatar()) .setNickName(user.getNickname()); // 存入缓存 redisTemplate.opsForHash() .put(UserCacheKeyEnum.HashKey.USER_VO_HASH_KEY, uid, userVO); return userVO; } @Override public List<UserVO> userVoList(Collection<String> uidSet) { Map<String, UserVO> userVoMap = redisTemplate.opsForHash() .multiGet(UserCacheKeyEnum.HashKey.USER_VO_HASH_KEY, Arrays.asList(uidSet.toArray())) .stream() .filter(Objects::nonNull) .map(u -> jsonHelper.convert(u, UserVO.class)) .collect(Collectors.toMap(UserVO::getUid, u -> u)); uidSet.forEach(uid -> { if (!userVoMap.containsKey(uid)) { UserVO userVO = userVO(uid, true); userVoMap.put(uid, userVO); } }); return userVoMap.values().stream().toList(); } @Override
package com.jerry.pilipala.domain.user.service.impl; @Service public class UserServiceImpl implements UserService { private final RedisTemplate<String, Object> redisTemplate; private final MongoTemplate mongoTemplate; private final SmsService smsService; private final UserEntityRepository userEntityRepository; private final HttpServletRequest request; private final JsonHelper jsonHelper; private final MessageTrigger messageTrigger; public UserServiceImpl(RedisTemplate<String, Object> redisTemplate, MongoTemplate mongoTemplate, SmsService smsService, UserEntityRepository userEntityRepository, HttpServletRequest request, JsonHelper jsonHelper, MessageTrigger messageTrigger) { this.redisTemplate = redisTemplate; this.mongoTemplate = mongoTemplate; this.smsService = smsService; this.userEntityRepository = userEntityRepository; this.request = request; this.jsonHelper = jsonHelper; this.messageTrigger = messageTrigger; } @Override public UserVO login(LoginDTO loginDTO) { String loginCodeKey = "login-%s".formatted(loginDTO.getTel()); String code = (String) redisTemplate.opsForValue().get(loginCodeKey); if (StringUtils.isBlank(code) || !code.equals(loginDTO.getVerifyCode())) { throw new BusinessException("验证码错误", StandardResponse.ERROR); } redisTemplate.delete(loginCodeKey); // 密文存储手机号 String encodeTel = Base64.getEncoder().encodeToString(loginDTO.getTel().getBytes()); User user = mongoTemplate.findOne( new Query(Criteria.where("tel").is(encodeTel)), User.class); return loginLogic(user, encodeTel, ""); } private User register(String tel, String email) { String uid = UUID.randomUUID().toString().replace("-", ""); String end = uid.substring(0, 8); User user = new User().setNickname("user_".concat(end)) .setTel(tel) .setEmail(email) .setIntro(""); user = mongoTemplate.save(user); UserEntity userEntity = new UserEntity() .setUid(user.getUid().toString()) .setTel(user.getTel()) .setEmail(user.getEmail()); userEntityRepository.save(userEntity); return user; } private UserVO loginLogic(User user, String tel, String email) { if (Objects.isNull(user)) { user = register(tel, email); } // 登录成功 StpUtil.login(user.getUid().toString()); // 推送站内信 Map<String, String> variables = new HashMap<>(); variables.put("user_name", user.getNickname()); variables.put("time", DateUtil.format(LocalDateTime.now(),"yyyy-mm-dd hh:MM:ss")); variables.put("ip", RequestUtil.getIpAddress(request)); variables.put("user_id", user.getUid().toString()); messageTrigger.triggerSystemMessage( TemplateNameEnum.LOGIN_NOTIFY, user.getUid().toString(), variables ); String roleId = user.getRoleId(); Role role; if (StringUtils.isBlank(roleId)) { role = new Role(); } else { role = mongoTemplate.findById(new ObjectId(roleId), Role.class); if (Objects.isNull(role)) { role = new Role(); } } UserInfoBO userInfoBO = new UserInfoBO() .setUid(user.getUid().toString()) .setRoleId(roleId) .setPermissionIdList(role.getPermissionIds()); StpUtil.getSession().set("user-info", userInfoBO); return userVO(user.getUid().toString(), false); } @Override public void code(String tel) { String loginCodeKey = "login-%s".formatted(tel); String code = (String) redisTemplate.opsForValue().get(loginCodeKey); if (StringUtils.isNotBlank(code)) { throw BusinessException.businessError("验证码已发送"); } // redis 不存在,生成一个新的 code = CaptchaUtil.generatorCaptchaNumberByLength(6); int expireMinutes = 1; smsService.sendCode(tel, code, expireMinutes); redisTemplate.opsForValue().set(loginCodeKey, code, expireMinutes * 60, TimeUnit.SECONDS); } @Override public void emailCode(String email) { String emailCodeKey = "login-email-%s".formatted(email); String code = (String) redisTemplate.opsForValue().get(emailCodeKey); if (StringUtils.isNotBlank(code)) { throw BusinessException.businessError("验证码已发送"); } // redis 不存在,生成一个新的 code = CaptchaUtil.generatorCaptchaNumberByLength(6); int expireMinutes = 1; smsService.sendEmailCode(email, code, expireMinutes); redisTemplate.opsForValue().set(emailCodeKey, code, expireMinutes * 60, TimeUnit.SECONDS); } @Override public UserVO emailLogin(EmailLoginDTO loginDTO) { String loginCodeKey = "login-email-%s".formatted(loginDTO.getEmail()); String code = (String) redisTemplate.opsForValue().get(loginCodeKey); if (StringUtils.isBlank(code) || !code.equals(loginDTO.getVerifyCode())) { throw new BusinessException("验证码错误", StandardResponse.ERROR); } redisTemplate.delete(loginCodeKey); // 密文存储手机号 String encodeEmail = Base64.getEncoder().encodeToString(loginDTO.getEmail().getBytes()); User user = mongoTemplate.findOne( new Query(Criteria.where("email").is(encodeEmail)), User.class); return loginLogic(user, "", encodeEmail); } @Override public UserVO userVO(String uid, boolean forceQuery) { if (StringUtils.isBlank(uid)) { uid = StpUtil.getLoginId(""); if (StringUtils.isBlank(uid)) { throw new BusinessException("用户不存在", StandardResponse.ERROR); } } UserVO userVO; if (!forceQuery) { // 如果缓存有,直接走缓存 userVO = jsonHelper.convert(redisTemplate.opsForHash() .get(UserCacheKeyEnum.HashKey.USER_VO_HASH_KEY, uid), UserVO.class); if (Objects.nonNull(userVO)) { return userVO; } } User user = mongoTemplate.findById(new ObjectId(uid), User.class); if (Objects.isNull(user)) { throw new BusinessException("用户不存在", StandardResponse.ERROR); } int fansCount = userEntityRepository.countFollowersByUserId(uid); int upCount = userEntityRepository.getFollowedUsersCount(uid); userVO = new UserVO(); userVO.setFansCount(fansCount) .setFollowCount(upCount) .setUid(user.getUid().toString()) .setAvatar(user.getAvatar()) .setNickName(user.getNickname()); // 存入缓存 redisTemplate.opsForHash() .put(UserCacheKeyEnum.HashKey.USER_VO_HASH_KEY, uid, userVO); return userVO; } @Override public List<UserVO> userVoList(Collection<String> uidSet) { Map<String, UserVO> userVoMap = redisTemplate.opsForHash() .multiGet(UserCacheKeyEnum.HashKey.USER_VO_HASH_KEY, Arrays.asList(uidSet.toArray())) .stream() .filter(Objects::nonNull) .map(u -> jsonHelper.convert(u, UserVO.class)) .collect(Collectors.toMap(UserVO::getUid, u -> u)); uidSet.forEach(uid -> { if (!userVoMap.containsKey(uid)) { UserVO userVO = userVO(uid, true); userVoMap.put(uid, userVO); } }); return userVoMap.values().stream().toList(); } @Override
public Page<UserVO> page(Integer pageNo, Integer pageSize) {
17
2023-11-03 10:05:02+00:00
12k
viego1999/xuecheng-plus-project
xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/impl/CoursePublishServiceImpl.java
[ { "identifier": "XueChengPlusException", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java", "snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private String errMessage;\n\n public XueChengPlusException() {\n super();\n }\n\n public XueChengPlusException(String errMessage) {\n super(errMessage);\n this.errMessage = errMessage;\n }\n\n public String getErrMessage() {\n return errMessage;\n }\n\n public static void cast(CommonError commonError) {\n throw new XueChengPlusException(commonError.getErrMessage());\n }\n\n public static void cast(String errMessage) {\n throw new XueChengPlusException(errMessage);\n }\n}" }, { "identifier": "MultipartSupportConfig", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/config/MultipartSupportConfig.java", "snippet": "@Configuration\npublic class MultipartSupportConfig {\n @Autowired\n private ObjectFactory<HttpMessageConverters> messageConverters;\n\n @Bean\n @Primary// 注入相同类型的bean时优先使用\n @Scope(\"prototype\")\n public Encoder feignEncoder() {\n return new SpringFormEncoder(new SpringEncoder(messageConverters));\n }\n\n // 将file转为Multipart\n public static MultipartFile getMultipartFile(File file) {\n FileItem item = new DiskFileItemFactory()\n .createItem(\"file\", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());\n try (FileInputStream inputStream = new FileInputStream(file);\n\n OutputStream outputStream = item.getOutputStream();) {\n IOUtils.copy(inputStream, outputStream);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return new CommonsMultipartFile(item);\n }\n}" }, { "identifier": "MediaServiceClient", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/feignclient/MediaServiceClient.java", "snippet": "@FeignClient(value = \"media-api\",\n configuration = MultipartSupportConfig.class,\n fallbackFactory = MediaServiceClient.MediaServiceClientFallbackFactory.class)\npublic interface MediaServiceClient {\n\n /**\n * 上传文件\n */\n @RequestMapping(value = \"/media/upload/coursefile\", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})\n String uploadFile(@RequestPart(\"filedata\") MultipartFile filedata,\n @RequestParam(value = \"folder\", required = false) String folder,\n @RequestParam(value = \"objectName\", required = false) String objectName);\n\n // 服务降级处理,可以获取异常信息\n @Slf4j\n class MediaServiceClientFallbackFactory implements FallbackFactory<MediaServiceClient> {\n // 降级方法\n @Override\n public MediaServiceClient create(Throwable cause) {\n log.error(\"远程调用媒资管理服务上传文件时发生熔断,熔断异常是:{}\", cause.getMessage());\n return null;\n }\n }\n}" }, { "identifier": "SearchServiceClient", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/feignclient/SearchServiceClient.java", "snippet": "@FeignClient(value = \"search\",\n fallbackFactory = SearchServiceClient.SearchServiceClientFallbackFactory.class)\npublic interface SearchServiceClient {\n\n /**\n * 添加课程\n */\n @PostMapping(\"/search/index/course\")\n Boolean add(@RequestBody CourseIndex courseIndex);\n\n @Slf4j\n class SearchServiceClientFallbackFactory implements FallbackFactory<SearchServiceClient> {\n\n @Override\n public SearchServiceClient create(Throwable cause) {\n log.error(\"远程调用课程索引添加服务时发生熔断,熔断异常是:{}\", cause.getMessage());\n return null;\n }\n }\n\n}" }, { "identifier": "CourseIndex", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/feignclient/po/CourseIndex.java", "snippet": "@Data\npublic class CourseIndex implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n\n /**\n * 发布时间\n */\n @JSONField(format = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime createDate;\n\n /**\n * 状态\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n}" }, { "identifier": "CourseBaseMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CourseBaseMapper.java", "snippet": "public interface CourseBaseMapper extends BaseMapper<CourseBase> {\n\n}" }, { "identifier": "CourseMarketMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CourseMarketMapper.java", "snippet": "public interface CourseMarketMapper extends BaseMapper<CourseMarket> {\n\n}" }, { "identifier": "CoursePublishMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CoursePublishMapper.java", "snippet": "public interface CoursePublishMapper extends BaseMapper<CoursePublish> {\n\n}" }, { "identifier": "CoursePublishPreMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CoursePublishPreMapper.java", "snippet": "public interface CoursePublishPreMapper extends BaseMapper<CoursePublishPre> {\n\n}" }, { "identifier": "CourseBaseInfoDto", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/CourseBaseInfoDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class CourseBaseInfoDto extends CourseBase {\n\n /**\n * 收费规则,对应数据字典\n */\n private String charge;\n\n /**\n * 价格\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 咨询qq\n */\n private String qq;\n\n /**\n * 微信\n */\n private String wechat;\n\n /**\n * 电话\n */\n private String phone;\n\n /**\n * 有效期天数\n */\n private Integer validDays;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n}" }, { "identifier": "CoursePreviewDto", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/CoursePreviewDto.java", "snippet": "@Data\npublic class CoursePreviewDto {\n\n /**\n * 课程基本信息,课程营销信息\n */\n CourseBaseInfoDto courseBase;\n\n /**\n * 课程计划信息\n */\n List<TeachplanDto> teachplans;\n\n // 师资信息暂时不加...\n\n}" }, { "identifier": "TeachplanDto", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/TeachplanDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Slf4j\n@Data\npublic class TeachplanDto extends Teachplan {\n\n /**\n * 关联的媒资信息\n */\n TeachplanMedia teachplanMedia;\n\n /**\n * 子目录\n */\n List<TeachplanDto> teachPlanTreeNodes;\n\n}" }, { "identifier": "CourseBase", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CourseBase.java", "snippet": "@Data\n@TableName(\"course_base\")\npublic class CourseBase implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 机构名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 课程标签\n */\n private String tags;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式(common普通,record 录播,live直播等)\n */\n private String teachmode;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 修改时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime changeDate;\n\n /**\n * 创建人\n */\n private String createPeople;\n\n /**\n * 更新人\n */\n private String changePeople;\n\n /**\n * 审核状态<p>\n * {\"202001\":\"审核未通过\"},{\"202002\":\"未提交\"},{\"202003\":\"已提交\"},{\"202004\":\"审核通过\"}\n */\n private String auditStatus;\n\n /**\n * 课程发布状态 未发布 已发布 下线<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n}" }, { "identifier": "CourseMarket", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CourseMarket.java", "snippet": "@Data\n@TableName(\"course_market\")\npublic class CourseMarket implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键,课程id\n */\n private Long id;\n\n /**\n * 收费规则,对应数据字典\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 咨询qq\n */\n private String qq;\n\n /**\n * 微信\n */\n private String wechat;\n\n /**\n * 电话\n */\n private String phone;\n\n /**\n * 有效期天数\n */\n private Integer validDays;\n\n}" }, { "identifier": "CoursePublish", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublish.java", "snippet": "@Data\n@TableName(\"course_publish\")\npublic class CoursePublish implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键(课程id)\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 发布时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 上架时间\n */\n private LocalDateTime onlineDate;\n\n /**\n * 下架时间\n */\n private LocalDateTime offlineDate;\n\n /**\n * 发布状态<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "CoursePublishPre", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublishPre.java", "snippet": "@Data\n@TableName(\"course_publish_pre\")\npublic class CoursePublishPre implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 提交时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 审核时间\n */\n private LocalDateTime auditDate;\n\n /**\n * 状态\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "CourseBaseInfoService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/CourseBaseInfoService.java", "snippet": "public interface CourseBaseInfoService {\n\n /**\n * 课程查询\n *\n * @param companyId 机构id\n * @param params 分页参数\n * @param queryCourseParams 查询条件\n * @return 分页结果\n */\n PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams params, QueryCourseParamsDto queryCourseParams);\n\n /**\n * 新增课程\n *\n * @param companyId 培训机构 id\n * @param addCourseDto 新增课程的信息\n * @return 课程信息包括基本信息,营销信息\n */\n CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto);\n\n /**\n * 根据课程id查询课程基本信息,包括基本信息和营销信息\n *\n * @param courseId 课程id\n * @return 返回对应的课程信息\n */\n CourseBaseInfoDto queryCourseBaseById(Long courseId);\n\n /**\n * 修改课程信息\n *\n * @param companyId 机构id(校验:本机构只能修改本机构的课程)\n * @param dto 课程信息\n * @return 返回修改后的课程信息\n */\n CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto);\n\n /**\n * 删除课程\n *\n * @param courseId 课程 id\n * @return 删除结果\n */\n RestResponse<Boolean> deleteCourseBase(Long courseId);\n\n}" }, { "identifier": "CoursePublishService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/CoursePublishService.java", "snippet": "public interface CoursePublishService {\n\n /**\n * 获取课程预览信息\n *\n * @param courseId 课程 id\n * @return {@link com.xuecheng.content.model.dto.CoursePreviewDto}\n * @author Wuxy\n * @since 2022/9/16 15:36\n */\n CoursePreviewDto getCoursePreviewInfo(Long courseId);\n\n /**\n * 通过 /open 接口获取课程预览信息\n *\n * @param courseId 课程 id\n * @return {@link com.xuecheng.content.model.dto.CoursePreviewDto}\n * @author Wuxy\n * @since 2022/9/16 15:36\n */\n CoursePreviewDto getOpenCoursePreviewInfo(Long courseId);\n\n /**\n * 提交审核\n *\n * @param courseId 课程 id\n * @author Wuxy\n * @since 2022/9/18 10:31\n */\n void commitAudit(Long companyId, Long courseId);\n\n /**\n * 课程发布接口\n *\n * @param companyId 机构 id\n * @param courseId 课程 id\n * @author Wuxy\n * @since 2022/9/20 16:23\n */\n void publish(Long companyId, Long courseId);\n\n /**\n * 课程静态化\n *\n * @param courseId 课程 id\n * @return {@link File} 静态化文件\n * @author Wuxy\n * @since 2022/9/23 16:59\n */\n File generateCourseHtml(Long courseId);\n\n /**\n * 上传课程静态化页面\n *\n * @param courseId 课程 id\n * @param file 静态化文件\n * @author Wuxy\n * @since 2022/9/23 16:59\n */\n void uploadCourseHtml(Long courseId, File file);\n\n /**\n * 新增课程索引\n *\n * @param courseId 课程id\n * @return 新增成功返回 true,否则 false\n */\n Boolean saveCourseIndex(Long courseId);\n\n /**\n * 根据课程id查询课程发布信息\n *\n * @param courseId 课程id\n * @return 课程发布信息\n */\n CoursePublish getCoursePublish(Long courseId);\n\n /**\n * 根据课程 id 查询缓存(Redis等)中的课程发布信息\n * <ol>\n * <li>基于缓存空值解决缓存穿透问题</li>\n * <li>基于redisson分布式锁解决缓存击穿问题</li>\n * </ol>\n *\n * @param courseId 课程id\n * @return 课程发布信息\n */\n CoursePublish getCoursePublishCache(Long courseId);\n\n}" }, { "identifier": "TeachplanService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/TeachplanService.java", "snippet": "public interface TeachplanService {\n\n /**\n * 查询课程计划树形结构\n *\n * @param courseId 课程id\n * @return 课程计划树形结构\n */\n List<TeachplanDto> findTeachplanTree(Long courseId);\n\n /**\n * 保存课程计划(新增/修改)\n *\n * @param teachplan 课程计划\n */\n void saveTeachplan(SaveTeachplanDto teachplan);\n\n /**\n * 教学计划绑定媒资\n *\n * @param bindTeachplanMediaDto 教学计划-媒资管理绑定数据\n * @return {@link com.xuecheng.content.model.po.TeachplanMedia}\n * @author Mr.M\n * @since 2022/9/14 22:20\n */\n TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto);\n\n /**\n * 删除指定教学计划-媒资绑定信息\n *\n * @param teachplanId 教学计划id\n * @param mediaId 媒资id\n */\n void deleteTeachplanMedia(Long teachplanId, String mediaId);\n\n}" }, { "identifier": "MqMessage", "path": "xuecheng-plus-message-sdk/src/main/java/com/xuecheng/messagesdk/model/po/MqMessage.java", "snippet": "@Data\n@ToString\n@TableName(\"mq_message\")\npublic class MqMessage implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 消息id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 消息类型代码: course_publish , media_test,\n */\n private String messageType;\n\n /**\n * 关联业务信息\n */\n private String businessKey1;\n\n /**\n * 关联业务信息\n */\n private String businessKey2;\n\n /**\n * 关联业务信息\n */\n private String businessKey3;\n\n /**\n * 执行次数\n */\n private Integer executeNum;\n\n /**\n * 处理状态,0:初始,1:成功\n */\n private String state;\n\n /**\n * 回复失败时间\n */\n private LocalDateTime returnfailureDate;\n\n /**\n * 回复成功时间\n */\n private LocalDateTime returnsuccessDate;\n\n /**\n * 回复失败内容\n */\n private String returnfailureMsg;\n\n /**\n * 最近执行时间\n */\n private LocalDateTime executeDate;\n\n /**\n * 阶段1处理状态, 0:初始,1:成功\n */\n private String stageState1;\n\n /**\n * 阶段2处理状态, 0:初始,1:成功\n */\n private String stageState2;\n\n /**\n * 阶段3处理状态, 0:初始,1:成功\n */\n private String stageState3;\n\n /**\n * 阶段4处理状态, 0:初始,1:成功\n */\n private String stageState4;\n\n\n}" }, { "identifier": "MqMessageService", "path": "xuecheng-plus-message-sdk/src/main/java/com/xuecheng/messagesdk/service/MqMessageService.java", "snippet": "public interface MqMessageService extends IService<MqMessage> {\n\n /**\n * 扫描消息表记录,采用与扫描视频处理表相同的思路\n *\n * @param shardIndex 分片序号\n * @param shardTotal 分片总数\n * @param count 扫描记录数\n * @return {@link java.util.List}<{@link MqMessage}> 消息记录\n * @author Wuxy\n * @since 2022/9/21 18:55\n */\n List<MqMessage> getMessageList(int shardIndex, int shardTotal, String messageType, int count);\n\n /**\n * 添加消息\n *\n * @param messageType 消息类型(例如:支付结果、课程发布等)\n * @param businessKey1 业务id\n * @param businessKey2 业务id\n * @param businessKey3 业务id\n * @return {@link com.xuecheng.messagesdk.model.po.MqMessage} 消息内容\n * @author Wuxy\n * @since 2022/9/23 13:45\n */\n MqMessage addMessage(String messageType, String businessKey1, String businessKey2, String businessKey3);\n\n /**\n * 完成任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completed(long id);\n\n /**\n * 完成阶段一任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageOne(long id);\n\n /**\n * 完成阶段二任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageTwo(long id);\n\n /**\n * 完成阶段三任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageThree(long id);\n\n /**\n * 完成阶段四任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageFour(long id);\n\n /**\n * 查询阶段一状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n public int getStageOne(long id);\n\n /**\n * 查询阶段二状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageTwo(long id);\n\n /**\n * 查询阶段三状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageThree(long id);\n\n /**\n * 查询阶段四状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageFour(long id);\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.content.config.MultipartSupportConfig; import com.xuecheng.content.feignclient.MediaServiceClient; import com.xuecheng.content.feignclient.SearchServiceClient; import com.xuecheng.content.feignclient.po.CourseIndex; import com.xuecheng.content.mapper.CourseBaseMapper; import com.xuecheng.content.mapper.CourseMarketMapper; import com.xuecheng.content.mapper.CoursePublishMapper; import com.xuecheng.content.mapper.CoursePublishPreMapper; import com.xuecheng.content.model.dto.CourseBaseInfoDto; import com.xuecheng.content.model.dto.CoursePreviewDto; import com.xuecheng.content.model.dto.TeachplanDto; import com.xuecheng.content.model.po.CourseBase; import com.xuecheng.content.model.po.CourseMarket; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.content.model.po.CoursePublishPre; import com.xuecheng.content.service.CourseBaseInfoService; import com.xuecheng.content.service.CoursePublishService; import com.xuecheng.content.service.TeachplanService; import com.xuecheng.messagesdk.model.po.MqMessage; import com.xuecheng.messagesdk.service.MqMessageService; import freemarker.template.Configuration; import freemarker.template.Template; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
10,779
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); // 将静态化内容输出到文件中 InputStream inputStream = IOUtils.toInputStream(content, StandardCharsets.UTF_8); // 创建静态化文件 file = File.createTempFile("course", "html"); log.debug("课程静态化,生成静态化文件:{}", file.getAbsolutePath()); // 输出流 FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); } catch (Exception e) { e.printStackTrace(); } return file; } @Override public void uploadCourseHtml(Long courseId, File file) { MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file); String course = mediaServiceClient.uploadFile(multipartFile, "course", courseId + ".html"); if (course == null) { XueChengPlusException.cast("远程调用媒资服务上传文件失败"); } } @Override public Boolean saveCourseIndex(Long courseId) { // 1.取出课程发布信息 CoursePublish coursePublish = coursePublishMapper.selectById(courseId); // 2.拷贝至课程索引对象 CourseIndex courseIndex = new CourseIndex(); BeanUtils.copyProperties(coursePublish, courseIndex); // 3.远程调用搜索服务 api 添加课程信息到索引 Boolean success = searchServiceClient.add(courseIndex); if (!success) { XueChengPlusException.cast("添加课程索引失败"); } return true; } @Override public CoursePublish getCoursePublish(Long courseId) { return coursePublishMapper.selectById(courseId); } @Override public CoursePublish getCoursePublishCache(Long courseId) { // 查询缓存 String key = "course_" + courseId; String jsonStr = stringRedisTemplate.opsForValue().get(key); // 缓存命中 if (StringUtils.isNotEmpty(jsonStr)) { if (jsonStr.equals("null")) { // 如果为null字符串,表明数据库中不存在此课程,直接返回(解决缓存穿透) return null; } return JSON.parseObject(jsonStr, CoursePublish.class); } // 缓存未命中,查询数据库并添加到缓存中 // 每一门课程设置一个锁 RLock lock = redissonClient.getLock("coursequerylock:" + courseId); // 阻塞等待获取锁 lock.lock(); try { // 检查是否已经存在(双从检查) jsonStr = stringRedisTemplate.opsForValue().get(key); if (StringUtils.isNotEmpty(jsonStr)) { return JSON.parseObject(jsonStr, CoursePublish.class); } // 查询数据库 CoursePublish coursePublish = getCoursePublish(courseId); // 当 coursePublish 为空时,缓存 null 字符串 stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(coursePublish), 1, TimeUnit.DAYS); return coursePublish; } catch (Exception e) { log.error("查询课程发布信息失败:", e); throw new XueChengPlusException("课程发布信息查询异常:" + e.getMessage()); } finally { // 释放锁 lock.unlock(); } } /** * 保存课程发布信息 * * @param courseId 课程 id * @author Wuxy * @since 2022/9/20 16:32 */ private void saveCoursePublish(Long courseId) { // 查询课程预发布信息 CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId); if (coursePublishPre == null) { XueChengPlusException.cast("课程预发布数据为空"); } CoursePublish coursePublish = new CoursePublish(); // 属性拷贝 BeanUtils.copyProperties(coursePublishPre, coursePublish); coursePublish.setStatus("203002"); CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId); if (coursePublishUpdate == null) { // 插入新的课程发布记录 coursePublishMapper.insert(coursePublish); } else { // 更新课程发布记录 coursePublishMapper.updateById(coursePublish); } // 更新课程基本表的发布状态 CourseBase courseBase = courseBaseMapper.selectById(courseId); courseBase.setStatus("203002"); courseBaseMapper.updateById(courseBase); } /** * 保存消息表记录,稍后实现 * * @param courseId 课程 id * @author Mr.W * @since 2022/9/20 16:32 */ private void saveCoursePublishMessage(Long courseId) {
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CoursePublishServiceImpl * @since 2023/1/30 15:45 */ @Slf4j @Service public class CoursePublishServiceImpl implements CoursePublishService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource private CoursePublishMapper coursePublishMapper; @Resource private CoursePublishPreMapper coursePublishPreMapper; @Autowired private CourseBaseInfoService courseBaseInfoService; @Autowired private TeachplanService teachplanService; @Autowired private MqMessageService mqMessageService; @Autowired private MediaServiceClient mediaServiceClient; @Autowired private SearchServiceClient searchServiceClient; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedissonClient redissonClient; @Override public CoursePreviewDto getCoursePreviewInfo(Long courseId) { // 查询课程发布信息 CoursePublish coursePublish = getCoursePublishCache(courseId); // 课程基本信息 CourseBaseInfoDto courseBaseInfo = new CourseBaseInfoDto(); BeanUtils.copyProperties(coursePublish, courseBaseInfo); // 课程计划信息 List<TeachplanDto> teachplans = JSON.parseArray(coursePublish.getTeachplan(), TeachplanDto.class); // 创建课程预览信息 CoursePreviewDto coursePreviewDto = new CoursePreviewDto(); coursePreviewDto.setCourseBase(courseBaseInfo); coursePreviewDto.setTeachplans(teachplans); return coursePreviewDto; } @Override public CoursePreviewDto getOpenCoursePreviewInfo(Long courseId) { // 课程基本信息 CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.queryCourseBaseById(courseId); // 课程计划信息 List<TeachplanDto> teachplans = teachplanService.findTeachplanTree(courseId); // 创建课程预览信息 CoursePreviewDto coursePreviewDto = new CoursePreviewDto(); coursePreviewDto.setCourseBase(courseBaseInfo); coursePreviewDto.setTeachplans(teachplans); return coursePreviewDto; } @Override public void commitAudit(Long companyId, Long courseId) { // 课程基本信息 CourseBase courseBase = courseBaseMapper.selectById(courseId); // 课程审核状态 String auditStatus = courseBase.getAuditStatus(); if ("202003".equals(auditStatus)) { XueChengPlusException.cast("当前为等待审核状态,审核完成可以再次提交。"); } // 本机构只允许提交本机构的课程 if (!companyId.equals(courseBase.getCompanyId())) { XueChengPlusException.cast("不允许提交其它机构的课程。"); } // 课程图片是否填写 if (StringUtils.isEmpty(courseBase.getPic())) { XueChengPlusException.cast("提交失败,请上传课程图片"); } // 添加课程预发布记录 CoursePublishPre coursePublishPre = new CoursePublishPre(); // 课程基本信息和营销信息 CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.queryCourseBaseById(courseId); BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre); // 课程营销信息 CourseMarket courseMarket = courseMarketMapper.selectById(courseId); // 转为 JSON String courseMarketJson = JSON.toJSONString(courseMarket); // 将课程营销信息放入课程预发布表 coursePublishPre.setMarket(courseMarketJson); // 查询课程计划信息 List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId); if (teachplanTree == null || teachplanTree.isEmpty()) { XueChengPlusException.cast("提交失败,还没有添加课程计划"); } // 转 json String teachplanJson = JSON.toJSONString(teachplanTree); coursePublishPre.setTeachplan(teachplanJson); // 设置预发布记录状态 coursePublishPre.setStatus("202003"); // 教学机构id coursePublishPre.setCompanyId(companyId); // 提交时间 coursePublishPre.setCreateDate(LocalDateTime.now()); CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(companyId); if (coursePublishPreUpdate == null) { // 添加课程预发布记录 coursePublishPreMapper.insert(coursePublishPre); } else { // 更新课程预发布记录 coursePublishPreMapper.updateById(coursePublishPre); } // 更新课程基本表的审核状态 courseBase.setAuditStatus("202003"); courseBaseMapper.updateById(courseBase); } @Transactional @Override public void publish(Long companyId, Long courseId) { // 查询课程预发布表 CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId); if (coursePublishPre == null) { XueChengPlusException.cast("请先提交课程审核,审核通过才可以发布"); } // 本机构只允许提交本机构的课程 if (!companyId.equals(coursePublishPre.getCompanyId())) { XueChengPlusException.cast("不允许提交其它机构的课程。"); } // 获得课程审核状态 String status = coursePublishPre.getStatus(); // 审核通过才可以进行发布 if (!"202004".equals(status)) { XueChengPlusException.cast("操作失败,课程审核通过方可发布。"); } // 保存课程发布信息 saveCoursePublish(courseId); // 保存消息表 saveCoursePublishMessage(courseId); // 删除课程预发布表记录 coursePublishPreMapper.deleteById(courseId); } @Override public File generateCourseHtml(Long courseId) { // 静态化文件 File file = null; try { // 配置 freemarker Configuration configuration = new Configuration(Configuration.getVersion()); // 加载模板,选指定模板路径,classpath 下 templates 下 // 得到 classpath String classpath = this.getClass().getResource("/").getPath(); configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/")); // 设置字符编码 configuration.setDefaultEncoding("utf-8"); // 指定模板文件名称 Template template = configuration.getTemplate("course_template.ftl"); // 准备数据 CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId); Map<String, Object> map = new HashMap<>(); map.put("model", coursePreviewInfo); // 静态化 String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); // 将静态化内容输出到文件中 InputStream inputStream = IOUtils.toInputStream(content, StandardCharsets.UTF_8); // 创建静态化文件 file = File.createTempFile("course", "html"); log.debug("课程静态化,生成静态化文件:{}", file.getAbsolutePath()); // 输出流 FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); } catch (Exception e) { e.printStackTrace(); } return file; } @Override public void uploadCourseHtml(Long courseId, File file) { MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file); String course = mediaServiceClient.uploadFile(multipartFile, "course", courseId + ".html"); if (course == null) { XueChengPlusException.cast("远程调用媒资服务上传文件失败"); } } @Override public Boolean saveCourseIndex(Long courseId) { // 1.取出课程发布信息 CoursePublish coursePublish = coursePublishMapper.selectById(courseId); // 2.拷贝至课程索引对象 CourseIndex courseIndex = new CourseIndex(); BeanUtils.copyProperties(coursePublish, courseIndex); // 3.远程调用搜索服务 api 添加课程信息到索引 Boolean success = searchServiceClient.add(courseIndex); if (!success) { XueChengPlusException.cast("添加课程索引失败"); } return true; } @Override public CoursePublish getCoursePublish(Long courseId) { return coursePublishMapper.selectById(courseId); } @Override public CoursePublish getCoursePublishCache(Long courseId) { // 查询缓存 String key = "course_" + courseId; String jsonStr = stringRedisTemplate.opsForValue().get(key); // 缓存命中 if (StringUtils.isNotEmpty(jsonStr)) { if (jsonStr.equals("null")) { // 如果为null字符串,表明数据库中不存在此课程,直接返回(解决缓存穿透) return null; } return JSON.parseObject(jsonStr, CoursePublish.class); } // 缓存未命中,查询数据库并添加到缓存中 // 每一门课程设置一个锁 RLock lock = redissonClient.getLock("coursequerylock:" + courseId); // 阻塞等待获取锁 lock.lock(); try { // 检查是否已经存在(双从检查) jsonStr = stringRedisTemplate.opsForValue().get(key); if (StringUtils.isNotEmpty(jsonStr)) { return JSON.parseObject(jsonStr, CoursePublish.class); } // 查询数据库 CoursePublish coursePublish = getCoursePublish(courseId); // 当 coursePublish 为空时,缓存 null 字符串 stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(coursePublish), 1, TimeUnit.DAYS); return coursePublish; } catch (Exception e) { log.error("查询课程发布信息失败:", e); throw new XueChengPlusException("课程发布信息查询异常:" + e.getMessage()); } finally { // 释放锁 lock.unlock(); } } /** * 保存课程发布信息 * * @param courseId 课程 id * @author Wuxy * @since 2022/9/20 16:32 */ private void saveCoursePublish(Long courseId) { // 查询课程预发布信息 CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId); if (coursePublishPre == null) { XueChengPlusException.cast("课程预发布数据为空"); } CoursePublish coursePublish = new CoursePublish(); // 属性拷贝 BeanUtils.copyProperties(coursePublishPre, coursePublish); coursePublish.setStatus("203002"); CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId); if (coursePublishUpdate == null) { // 插入新的课程发布记录 coursePublishMapper.insert(coursePublish); } else { // 更新课程发布记录 coursePublishMapper.updateById(coursePublish); } // 更新课程基本表的发布状态 CourseBase courseBase = courseBaseMapper.selectById(courseId); courseBase.setStatus("203002"); courseBaseMapper.updateById(courseBase); } /** * 保存消息表记录,稍后实现 * * @param courseId 课程 id * @author Mr.W * @since 2022/9/20 16:32 */ private void saveCoursePublishMessage(Long courseId) {
MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
19
2023-11-04 07:15:26+00:00
12k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \n\t\t@Override\n\t\tpublic Date convert(String source) {\n\t\t\tpatterns.add(\"yyyy-MM-dd HH:mm:ss\");\n\t\t\tpatterns.add(\"yyyy-MM-dd HH:mm\");\n\t\t\t patterns.add(\"yyyy-MM-dd\");\n\t\t\t patterns.add(\"HH:mm\");\n\t\t\t patterns.add(\"yyyy-MM\");\n\t\t\tDate date=null;\n\t\t\tfor (String p : patterns) {\n\t\t\t\ttry {\n\t\t\t\t\tsdf.applyPattern(p);\n\t\t\t\t\tdate=sdf.parse(source);\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (ParseException e) {}\n\t\t\t}\n\t\t\tif(date==null){\n\t\t\t\tthrow new IllegalArgumentException(\"日期格式错误![\" + source + \"]\");\n\t\t\t}\n\t\t\treturn date;\n\t\t}\n\n\t\tpublic void setPatterns(List<String> patterns) {\n\t\t\tthis.patterns = patterns;\n\t\t}\n\n}" }, { "identifier": "AttendceDao", "path": "src/main/java/cn/gson/oasys/model/dao/attendcedao/AttendceDao.java", "snippet": "@Repository\npublic interface AttendceDao extends JpaRepository<Attends, Long>{\n\t\t@Query(\"update Attends a set a.attendsTime=?1 ,a.attendHmtime=?2 ,a.statusId=?3 where a.attendsId=?4 \")\n\t@Modifying(clearAutomatically=true)\n\tInteger updateatttime(Date date,String hourmin,Long statusIdlong ,long attid);\n\t\n\t\t@Query(\"delete from Attends a where a.attendsId=?1\")\n\t\t@Modifying\n\t\tInteger delete(long aid);\n\t\t\n\t//查找某用户当天下班的考勤记录id\n\t@Query(nativeQuery=true,value=\"select a.attends_id from aoa_attends_list a WHERE DATE_format(a.attends_time,'%Y-%m-%d') like %?1% and a.attends_user_id=?2 and a.type_id=9 \")\n\tLong findoffworkid(String date,long userid);\n\t\n\t//查找某用户某天总共的记录\n\t@Query(nativeQuery=true,value=\"SELECT COUNT(*) from aoa_attends_list a WHERE DATE_format(a.attends_time,'%Y-%m-%d') like %?1% and a.attends_user_id=?2 \")\n\tInteger countrecord(String date,long userid);\n\t\n\t//查找某用户某天最新记录用来显示用户最新的类型和考勤时间\n@Query(nativeQuery=true,value=\"SELECT * from aoa_attends_list a WHERE DATE_format(a.attends_time,'%Y-%m-%d') like %?1% and a.attends_user_id=?2 ORDER BY a.attends_time DESC LIMIT 1\")\nAttends findlastest(String date,long userid);\n\n\n@Query(\"from Attends a where a.user.userId=:userId ORDER BY a.attendsTime DESC\")\n Page<Attends> findByUserOrderByAttendsTimeDesc(@Param(\"userId\")long userid,Pageable pa);\n\n//按照某个用户模糊查找\n@Query(\"from Attends a where (a.attendsRemark like %?1% or DATE_format(a.attendsTime,'%Y-%m-%d') like %?1% or a.user.userName like %?1% or \"\n \t\t+ \"a.typeId in (select t.typeId from SystemTypeList t where t.typeName like %?1%) or \"\n \t\t+ \"a.statusId in (select s.statusId from SystemStatusList s where s.statusName like %?1%)) and a.user.userId=?2\")\nPage<Attends> findonemohu(String baseKey,long userid,Pageable pa);\n\n\n\n @Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.attendsTime DESC \")\n Page<Attends> findByUserOrderByAttendsTimeDesc(@Param(\"ids\") List<Long> user,Pageable pa);\n \n //按一些用户模糊查找\n @Query(\"from Attends a where (a.attendsRemark like %?1% or DATE_format(a.attendsTime,'%Y-%m-%d') like %?1% or a.user.userName like %?1% or \"\n \t\t+ \"a.typeId in (select t.typeId from SystemTypeList t where t.typeName like %?1%) or \"\n \t\t+ \"a.statusId in (select s.statusId from SystemStatusList s where s.statusName like %?1%)) and a.user.userId in ?2\")\n Page<Attends> findsomemohu(String baseKey, List<Long> user,Pageable pa);\n//类型\n //通过类型降序排序\n\t@Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.typeId DESC \")\n\tPage<Attends> findByUserOrderByTypeIdDesc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t\n\t//通过类型升序排序\n\t@Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.typeId ASC \")\n\t\tPage<Attends> findByUserOrderByTypeIdAsc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t\n\t//状态\n\t //通过状态降序排序\n\t\t@Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.statusId DESC \")\n\t\tPage<Attends> findByUserOrderByStatusIdDesc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t\t\n\t//通过状态升序排序\n\t @Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.statusId ASC \")\n\t\t\tPage<Attends> findByUserOrderByStatusIdAsc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t \n\t //时间\n\t \t\t//时间降序在开始的时候就已经默认了\n\t //通过时间升序排序\n\t @Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.attendsTime ASC \")\n\t \t\t\tPage<Attends> findByUserOrderByAttendsTimeAsc(@Param(\"ids\") List<Long> user,Pageable pa);\n \n \n @Query(\"SELECT count(*) from Attends a where DATE_FORMAT(a.attendsTime,'%Y-%m') like %?1% and a.statusId=?2 and a.user.userId=?3\")\n Integer countnum(String month,long statusId,long userid);\n \n @Query(\"SELECT sum(a.holidayDays) from Attends a where DATE_FORMAT(a.holidayStart,'%Y-%m') like %?1% and a.statusId=?2 and a.user.userId=?3\")\n Integer countothernum(String month,long statusId,long userid);\n \n //统计当月上班次数\n @Query(\"SELECT count(*) from Attends a where DATE_FORMAT(a.attendsTime,'%Y-%m') like %?1% and a.user.userId=?2 and a.typeId=8\")\n Integer counttowork(String month,long userid);\n \n //统计当月下班次数\n @Query(\"SELECT count(*) from Attends a where DATE_FORMAT(a.attendsTime,'%Y-%m') like %?1% and a.user.userId=?2 and a.typeId=9\")\n Integer countoffwork(String month,long userid);\n \n @Query(\"FROM Attends a where a.attendsTime>?1 and a.attendsTime<?2 and a.user.userId in ?3\")\n List<Attends> findoneweek(Date start,Date end,List<Long> user);\n \n //更改备注\n @Query(\"update Attends a set a.attendsRemark=?1 where a.attendsId=?2\")\n @Modifying\n Integer updateremark(String attendsRemark,long attendsId);\n \n \n //类型\n //通过类型降序排序\n\t@Query(\"from Attends a where a.user.userId=?1 ORDER BY a.typeId DESC \")\n\tPage<Attends> findByUserOrderByTypeIdDesc(long userid,Pageable pa);\n\t\n\t//通过类型升序排序\n\t@Query(\"from Attends a where a.user.userId=?1 ORDER BY a.typeId ASC \")\n\t\tPage<Attends> findByUserOrderByTypeIdAsc(long userid,Pageable pa);\n\t\n\t//状态\n\t //通过状态降序排序\n\t\t@Query(\"from Attends a where a.user.userId=?1 ORDER BY a.statusId DESC \")\n\t\tPage<Attends> findByUserOrderByStatusIdDesc(long userid,Pageable pa);\n\t\t\n\t//通过状态升序排序\n\t @Query(\"from Attends a where a.user.userId=?1 ORDER BY a.statusId ASC \")\n\t\t\tPage<Attends> findByUserOrderByStatusIdAsc(long userid,Pageable pa);\n\t \n\t //时间\n\t \t\t//时间降序在开始的时候就已经默认了\n\t //通过时间升序排序\n\t \t @Query(\"from Attends a where a.user.userId=?1 ORDER BY a.attendsTime ASC \")\n\t \t\t\tPage<Attends> findByUserOrderByAttendsTimeAsc(long userid,Pageable pa);\n\t\n \n} " }, { "identifier": "AttendceService", "path": "src/main/java/cn/gson/oasys/model/dao/attendcedao/AttendceService.java", "snippet": "@Service\n@Transactional\npublic class AttendceService {\n\n\t@Autowired\n\tAttendceDao attendceDao;\n\n\t// 删除\n\tpublic Integer delete(long aid) {\n\t\treturn attendceDao.delete(aid);\n\t}\n\n\t// 更改考勤时间\n\tpublic Integer updatetime(Date date, String hourmin, Long statusIdlong, long attid) {\n\t\treturn attendceDao.updateatttime(date, hourmin, statusIdlong, attid);\n\t}\n\n\t// 更新备注\n\tpublic Integer updatereamrk(String attendsRemark, long attendsId) {\n\t\treturn attendceDao.updateremark(attendsRemark, attendsId);\n\t}\n\n\t//查找在这个时间段的每个用户的考勤\n//\tpublic Page<Attends> findoneweekatt(int page, String baseKey, Date start,Date end, List<Long> user) {\n//\t\tPageable pa =new PageRequest(page, 10);\n//\t\tif (!StringUtils.isEmpty(baseKey)) {\n//\t\t\t// 模糊查询\n//\t\t}else{\n//\t\t\treturn attendceDao.findoneweek(start, end, user, pa);\n//\t\t}\n//\t\treturn null;\n//\t\t\n//\t}\n\t\n\t// 分页\n\tpublic Page<Attends> paging(int page, String baseKey, List<Long> user, Object type, Object status, Object time) {\n\t\tPageable pa =new PageRequest(page, 10);\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 模糊查询\n\t\t\treturn attendceDao.findsomemohu(baseKey, user, pa);\n\t\t}if (!StringUtils.isEmpty(type)) {\n\t\t\tif(type.toString().equals(\"0\")){\n\t\t\t\t//降序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdDesc(user, pa);\n\t\t\t}else{System.out.println(\"22\");\n\t\t\t\t//升序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdAsc(user, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(status)) {\n\t\t\tif(status.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdDesc(user, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdAsc(user, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(time)) {\n\t\t\tif(time.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(user, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeAsc(user, pa);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(user, pa);\n\t\t}\n\n\n\t}\n\n\t// 单个用户分页\n\tpublic Page<Attends> singlepage(int page, String baseKey, long userid, Object type, Object status, Object time) {\n\t\tPageable pa = new PageRequest(page, 10);\n\t\t//0为降序 1为升序\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 查询\n\t\t\tSystem.out.println(baseKey);\n\t\t\tattendceDao.findonemohu(baseKey, userid, pa);\n\t\t}\n\t\tif (!StringUtils.isEmpty(type)) {\n\t\t\tif(type.toString().equals(\"0\")){\n\t\t\t\t//降序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdDesc(userid, pa);\n\t\t\t}else{\n\t\t\t\t//升序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdAsc(userid, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(status)) {\n\t\t\tif(status.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdDesc(userid, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdAsc(userid, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(time)) {\n\t\t\tif(time.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(userid, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeAsc(userid, pa);\n\t\t\t}\n\t\t} else {\n\t\t\t// 第几页 以及页里面数据的条数\n\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(userid, pa);\n\t\t}\n\n\t}\n}" }, { "identifier": "StatusDao", "path": "src/main/java/cn/gson/oasys/model/dao/system/StatusDao.java", "snippet": "@Repository\npublic interface StatusDao extends PagingAndSortingRepository<SystemStatusList, Long>{\n\t\n\t//根据模块名和名字查找到唯一对象\n\tSystemStatusList findByStatusModelAndStatusName(String statusModel,String statusName);\n\t\n\t//根据模块名查找到状态集合\n\tList<SystemStatusList> findByStatusModel(String statusModel);\n\t\n\tList<SystemStatusList> findByStatusNameLikeOrStatusModelLike(String name,String name2);\n\t\n\t\n\t\n\t@Query(\"select sl.statusName from SystemStatusList sl where sl.statusId=:id\")\n\tString findname(@Param(\"id\")Long id);\n\t\n\t@Query(\"select sl.statusColor from SystemStatusList sl where sl.statusId=:id\")\n\tString findcolor(@Param(\"id\")Long id);\n\t\n\n}" }, { "identifier": "TypeDao", "path": "src/main/java/cn/gson/oasys/model/dao/system/TypeDao.java", "snippet": "@Repository\npublic interface TypeDao extends PagingAndSortingRepository<SystemTypeList, Long>{\n\t\n\t//根据模块名和名称查找唯一对象\n\tSystemTypeList findByTypeModelAndTypeName(String typeModel,String typeName);\n\t\n\t//根据模块名查找到类型集合\n\tList<SystemTypeList> findByTypeModel(String typeModel);\n\t\n\tList<SystemTypeList> findByTypeNameLikeOrTypeModelLike(String name,String name2);\n\t\n\t\n\t\n\t@Query(\"select type.typeName from SystemTypeList type where type.typeId=:id\")\n\tString findname(@Param(\"id\")Long id);\n\t\n\t\n}" }, { "identifier": "UserDao", "path": "src/main/java/cn/gson/oasys/model/dao/user/UserDao.java", "snippet": "public interface UserDao extends JpaRepository<User, Long>{\n \n\tList<User> findByUserId(Long id);\n\t\n\tList<User> findByFatherId(Long parentid);\n\n\t@Query(\"select u from User u \")\n\tList<User> findAll();\n\n\t@Query(\"select u from User u \")\n\tPage<User> findAllPage(Pageable pa);\n\t\n\tPage<User> findByFatherId(Long parentid,Pageable pa);\n\t\n\t//名字模糊查找\n\t@Query(\"select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 \")\n\tPage<User> findbyFatherId(String name,Long parentid,Pageable pa);\n\n\t//名字模糊查找\n\t@Query(\"select u from User u where (u.userName like %?1% or u.realName like %?1%)\")\n\tPage<User> findAllUserByName(String name,Pageable pa);\n\t\n\t@Query(\"select u from User u where u.userName=:name\")\n\tUser findid(@Param(\"name\")String name);\n\t\n\t@Query(\"select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid\")\n\tLong findpkId(@Param(\"taskid\")Long taskid,@Param(\"userid\")Long userid);\n\t\n\t//根据名字找用户\n\tUser findByUserName(String title);\n\t\n\t//根据用户名模糊查找\n\t@Query(\"from User u where u.userName like %:name% or u.realName like %:name%\")\n\tPage<User> findbyUserNameLike(@Param(\"name\")String name,Pageable pa);\n\t//根据真实姓名模糊查找\n\tPage<User> findByrealNameLike(String title,Pageable pa);\n\t\n\t//根据姓名首拼模糊查找,并分页\n\tPage<User> findByPinyinLike(String pinyin,Pageable pa);\n\t\n\t//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页\n\t@Query(\"from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2\")\n\tPage<User> findSelectUsers(String baseKey,String pinyinm,Pageable pa);\n\t\n\t//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页\n\t@Query(\"from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2\")\n\tPage<User> findUsers(String baseKey,String baseKey2,Pageable pa);\n\t/**\n\t * 用户管理查询可用用户\n\t * @param isLock\n\t * @param pa\n\t * @return\n\t */\n\tPage<User> findByIsLock(Integer isLock,Pageable pa);\n\t\n\t\n\t@Query(\"from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%\")\n\tPage<User> findnamelike(String name,Pageable pa);\n\t\n\tList<User> findByDept(Dept dept);\n\t@Query(\"select u from User u where u.role.roleId=?1\")\n\tList<User> findrole(Long lid); \n\t\n\t/*通过(用户名或者电话号码)+密码查找用户*/\n\t@Query(\"from User u where (u.userName = ?1 or u.userTel = ?1) and u.password =?2\")\n\tUser findOneUser(String userName,String password);\n}" }, { "identifier": "UserService", "path": "src/main/java/cn/gson/oasys/model/dao/user/UserService.java", "snippet": "@Transactional\n@Service\npublic class UserService {\n\n\t@Autowired\n\tUserDao userDao;\n\t\n\t//找到该管理员下面的所有用户并且分页\n\tpublic Page<User> findmyemployuser(int page, String baseKey,long parentid) {\n\t\tPageable pa=new PageRequest(page, 10);\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 模糊查询\n\t\t\treturn userDao.findbyFatherId(baseKey, parentid, pa);\n\t\t}\n\t\telse{\n\t\t\treturn userDao.findByFatherId(parentid, pa);\n\t\t}\n\t\t\n\t}\n\n\t//找到所有用户并且分页\n\tpublic Page<User> findAllmyemployuser(int page, String baseKey) {\n\t\tPageable pa=new PageRequest(page, 10);\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 模糊查询\n\t\t\treturn userDao.findAllUserByName(baseKey, pa);\n\t\t}\n\t\telse{\n\t\t\treturn userDao.findAllPage(pa);\n\t\t}\n\n\t}\n}" }, { "identifier": "Attends", "path": "src/main/java/cn/gson/oasys/model/entity/attendce/Attends.java", "snippet": "@Entity\n@Table(name=\"aoa_attends_list\")\npublic class Attends {\n\n\t@Id\n\t@Column(name=\"attends_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long attendsId; \n\t\n\t@Column(name=\"type_id\")\n\tprivate Long typeId; //类型id\n\t\n\t@Column(name=\"status_id\")\n\tprivate Long statusId; //状态id\n\t\n\t@Column(name=\"attends_time\")\n\tprivate Date attendsTime; //考勤时间\n\t\n\t@Column(name=\"attend_hmtime\")\n\tprivate String attendHmtime; //考勤时分\n\t\n\t@Column(name=\"week_ofday\")\n\tprivate String weekOfday; //星期几\n\t\n\t@Column(name=\"attends_ip\")\n\tprivate String attendsIp; //登陆ip\n\t\n\t@Column(name=\"attends_remark\")\n\tprivate String attendsRemark; //考勤备注\n\t\n\t@Column(name=\"holiday_start\")//请假开始时间\n\tprivate Date holidayStart;\n\t\n\t@Column(name=\"holiday_days\")//请假开始时间\n\tprivate Double holidayDays;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"attends_user_id\")\n\tprivate User user;\n\t\n\t\n\t\n\tpublic String getAttendHmtime() {\n\t\treturn attendHmtime;\n\t}\n\n\tpublic void setAttendHmtime(String attendHmtime) {\n\t\tthis.attendHmtime = attendHmtime;\n\t}\n\n\tpublic String getWeekOfday() {\n\t\treturn weekOfday;\n\t}\n\n\tpublic void setWeekOfday(String weekOfday) {\n\t\tthis.weekOfday = weekOfday;\n\t}\n\n\tpublic Long getAttendsId() {\n\t\treturn attendsId;\n\t}\n\n\tpublic void setAttendsId(Long attendsId) {\n\t\tthis.attendsId = attendsId;\n\t}\n\n\tpublic Date getAttendsTime() {\n\t\treturn attendsTime;\n\t}\n\n\tpublic void setAttendsTime(Date attendsTime) {\n\t\tthis.attendsTime = attendsTime;\n\t}\n\n\tpublic String getAttendsIp() {\n\t\treturn attendsIp;\n\t}\n\n\tpublic void setAttendsIp(String attendsIp) {\n\t\tthis.attendsIp = attendsIp;\n\t}\n\n\tpublic String getAttendsRemark() {\n\t\treturn attendsRemark;\n\t}\n\n\tpublic void setAttendsRemark(String attendsRemark) {\n\t\tthis.attendsRemark = attendsRemark;\n\t}\n\n\t\n\t\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Long getTypeId() {\n\t\treturn typeId;\n\t}\n\n\tpublic void setTypeId(Long typeId) {\n\t\tthis.typeId = typeId;\n\t}\n\n\tpublic Long getStatusId() {\n\t\treturn statusId;\n\t}\n\n\tpublic void setStatusId(Long statusId) {\n\t\tthis.statusId = statusId;\n\t}\n\n\tpublic Double getHolidayDays() {\n\t\treturn holidayDays;\n\t}\n\n\tpublic void setHolidayDays(Double holidayDays) {\n\t\tthis.holidayDays = holidayDays;\n\t}\n\t\n\t\n\n\tpublic Date getHolidayStart() {\n\t\treturn holidayStart;\n\t}\n\n\tpublic void setHolidayStart(Date holidayStart) {\n\t\tthis.holidayStart = holidayStart;\n\t}\n\n\tpublic Attends() {\n\t\tsuper();\n\t\t// TODO Auto-generated constructor stub\n\t} \n\t\n\t\n\tpublic Attends(Long typeId, Long statusId, Date attendsTime, String attendsIp, String attendsRemark, User user) {\n\t\tsuper();\n\t\tthis.typeId = typeId;\n\t\tthis.statusId = statusId;\n\t\tthis.attendsTime = attendsTime;\n\t\tthis.attendsIp = attendsIp;\n\t\tthis.attendsRemark = attendsRemark;\n\t\tthis.user = user;\n\t}\n\t\n\tpublic Attends(Long typeId, Long statusId, Date attendsTime, String attendHmtime, String weekOfday,\n\t\t\tString attendsIp, User user) {\n\t\tsuper();\n\t\tthis.typeId = typeId;\n\t\tthis.statusId = statusId;\n\t\tthis.attendsTime = attendsTime;\n\t\tthis.attendHmtime = attendHmtime;\n\t\tthis.weekOfday = weekOfday;\n\t\tthis.attendsIp = attendsIp;\n\t\tthis.user = user;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Attends [attendsId=\" + attendsId + \", typeId=\" + typeId + \", statusId=\" + statusId + \", attendsTime=\"\n\t\t\t\t+ attendsTime + \", attendHmtime=\" + attendHmtime + \", weekOfday=\" + weekOfday + \", attendsIp=\"\n\t\t\t\t+ attendsIp + \", attendsRemark=\" + attendsRemark + \"]\";\n\t}\n\n\t\n\t\n\t\n}" }, { "identifier": "SystemStatusList", "path": "src/main/java/cn/gson/oasys/model/entity/system/SystemStatusList.java", "snippet": "@Entity\n@Table(name = \"aoa_status_list\")\npublic class SystemStatusList {\n\n\t@Id\n\t@Column(name = \"status_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long statusId; // 状态id\n\n\t@Column(name = \"status_name\")\n\t@NotEmpty(message=\"状态名称不能为空\")\n\tprivate String statusName; // 状态名称\n\n\t@Column(name = \"sort_value\")\n\tprivate Integer statusSortValue; // 状态排序值\n\n\t@Column(name = \"status_model\")\n\tprivate String statusModel; // 状态模块\n\n\t@Column(name = \"status_color\")\n\tprivate String statusColor; // 状态颜色\n\t\n\t@Column(name = \"sort_precent\")\n\tprivate String statusPrecent;//百分比\n\n\tpublic SystemStatusList() {\n\t}\n\n\tpublic Long getStatusId() {\n\t\treturn statusId;\n\t}\n\n\tpublic void setStatusId(Long statusId) {\n\t\tthis.statusId = statusId;\n\t}\n\n\tpublic String getStatusName() {\n\t\treturn statusName;\n\t}\n\n\tpublic void setStatusName(String statusName) {\n\t\tthis.statusName = statusName;\n\t}\n\n\tpublic Integer getStatusSortValue() {\n\t\treturn statusSortValue;\n\t}\n\n\tpublic void setStatusSortValue(Integer statusSortValue) {\n\t\tthis.statusSortValue = statusSortValue;\n\t}\n\n\tpublic String getStatusModel() {\n\t\treturn statusModel;\n\t}\n\n\tpublic void setStatusModel(String statusModel) {\n\t\tthis.statusModel = statusModel;\n\t}\n\n\tpublic String getStatusColor() {\n\t\treturn statusColor;\n\t}\n\n\tpublic void setStatusColor(String statusColor) {\n\t\tthis.statusColor = statusColor;\n\t}\n\t\n\t\n\n\tpublic String getStatusPrecent() {\n\t\treturn statusPrecent;\n\t}\n\n\tpublic void setStatusPrecent(String statusPrecent) {\n\t\tthis.statusPrecent = statusPrecent;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SystemStatusList [statusId=\" + statusId + \", statusName=\" + statusName + \", statusSortValue=\"\n\t\t\t\t+ statusSortValue + \", statusModel=\" + statusModel + \", statusColor=\" + statusColor + \", statusPrecent=\"\n\t\t\t\t+ statusPrecent + \"]\";\n\t}\n\n\t\n\n}" }, { "identifier": "SystemTypeList", "path": "src/main/java/cn/gson/oasys/model/entity/system/SystemTypeList.java", "snippet": "@Entity\n@Table(name=\"aoa_type_list\")\npublic class SystemTypeList {\n\t\n\t@Id\n\t@Column(name=\"type_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long typeId;\t\t\t//类型id\n\t\n\t@Column(name=\"type_name\")\n\t@NotEmpty(message=\"类型名称不能为空\")\n\tprivate String typeName;\t\t//类型名字\n\t\n\t@Column(name=\"sort_value\")\n\tprivate Integer typeSortValue;\t//排序值\n\t\n\t@Column(name=\"type_model\")\n\tprivate String typeModel;\t\t//所属模块\n\t\n\t@Column(name=\"type_color\")\n\tprivate String typeColor;\t\t//类型颜色\n\n\tpublic Long getTypeId() {\n\t\treturn typeId;\n\t}\n\n\tpublic void setTypeId(Long typeId) {\n\t\tthis.typeId = typeId;\n\t}\n\n\tpublic String getTypeName() {\n\t\treturn typeName;\n\t}\n\n\tpublic void setTypeName(String typeName) {\n\t\tthis.typeName = typeName;\n\t}\n\n\tpublic Integer getTypeSortValue() {\n\t\treturn typeSortValue;\n\t}\n\n\tpublic void setTypeSortValue(Integer typeSortValue) {\n\t\tthis.typeSortValue = typeSortValue;\n\t}\n\n\tpublic String getTypeModel() {\n\t\treturn typeModel;\n\t}\n\n\tpublic void setTypeModel(String typeModel) {\n\t\tthis.typeModel = typeModel;\n\t}\n\n\tpublic String getTypeColor() {\n\t\treturn typeColor;\n\t}\n\n\tpublic void setTypeColor(String typeColor) {\n\t\tthis.typeColor = typeColor;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SystemTypeList [typeId=\" + typeId + \", typeName=\" + typeName + \", typeSortValue=\" + typeSortValue\n\t\t\t\t+ \", typeModel=\" + typeModel + \", typeColor=\" + typeColor + \"]\";\n\t}\n\t\n\t\n}" }, { "identifier": "User", "path": "src/main/java/cn/gson/oasys/model/entity/user/User.java", "snippet": "@Entity\n@Table(name=\"aoa_user\")\npublic class User {\n\t\n\t@Id\n\t@Column(name=\"user_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long userId;\t\t//用户id\n\t\n\t@Column(name=\"user_name\")\n\t@NotEmpty(message=\"用户名不能为空\")\n\tprivate String userName;\t//登录用户名\n\t\n\t@Column(name=\"user_tel\")\n\t@NotEmpty(message=\"电话不能为空\")\n\tprivate String userTel;\t\t//用户电话\n\t\n\t@Column(name=\"real_name\")\n\t@NotEmpty(message=\"真实姓名不能为空\")\n\tprivate String realName; //真实姓名\n\t\n\tprivate String pinyin;\n\t\n\t@NotEmpty(message=\"邮箱不能为空\")\n\t@Pattern(regexp=\"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\\\.[a-zA-Z0-9_-]{2,3}){1,2})$\",message=\"请填写正确邮箱号\")\n\tprivate String eamil;\t\t//邮件\n\t\n\t@NotEmpty(message=\"地址不能为空\")\n\tprivate String address;\t\t//地址\n\t\n\t@Column(name=\"user_edu\")\n\t@NotEmpty(message=\"学历不能为空\")\n\tprivate String userEdu;\t\t//用户学历\n\t\n\t\n\tprivate Boolean superman=false;\n\t\n\t@Column(name=\"user_school\")\n\t@NotEmpty(message=\"毕业院校不能为空\")\n\tprivate String school;\t\t//学校\n\t\n\t@Column(name=\"user_idcard\")\n\t@Pattern(regexp=\"^(\\\\d{6})(19|20)(\\\\d{2})(1[0-2]|0[1-9])(0[1-9]|[1-2][0-9]|3[0-1])(\\\\d{3})(\\\\d|X|x)?$\",message=\"请填写正确身份证号\")\n\tprivate String idCard;\t\t//用户身份证\n\t\n\t@NotEmpty(message=\"卡号不能为空\")\n\t@Length(min=16, max=19,message=\"银行卡号长度必须在16到19之间!\")\n\tprivate String bank;\t\t//银行\n\t\n\tprivate String sex;\t\t\t//性别\n\t\n\t@Column(name=\"theme_skin\")\n\tprivate String themeSkin;\t//主题皮肤\n\t\n\tprivate Date birth;\t\t\t//生日\n\t\n\t@Column(name=\"user_sign\")\n\tprivate String userSign;\t//用户签名\n\t\n\tprivate String password;\t//用户密码\n\t\n\tprivate String salary;\t\t//用户薪水\n\t\n\t@Column(name=\"img_path\")\n\tprivate String imgPath;\t\t//用户头像路径\n\t\n\t@Column(name=\"hire_time\")\n\tprivate Date hireTime;\t\t//入职时间\n\t\n\t@Column(name=\"is_lock\")\n\tprivate Integer isLock=0;\t\t//该用户是否被禁用\n\t\n\t@Column(name=\"last_login_ip\")\n\tprivate String lastLoginIp;\t//用户最后登录ip;\n\t\n\t@Column(name=\"last_login_time\")\n\tprivate Date lastLoginTime;\t//最后登录时间\n\t\n\t@Column(name=\"modify_time\")\n\tprivate Date modifyTime;\t\t//最后修改时间\n\t\n\t@Column(name=\"modify_user_id\")\n\tprivate Long modifyUserId;\t//最后修改此用户的用户id\n\t\n\t@Column(name=\"father_id\")\n\tprivate Long fatherId;\t\t//上司id\n\t\n\tprivate Integer holiday; //请假天数\n\n\t@ManyToOne()\n\t@JoinColumn(name = \"position_id\")\n\tprivate Position position;\t//外键关联 职位表\n\t\n\t@ManyToOne()\n\t@JoinColumn(name = \"dept_id\")\n\tprivate Dept dept;\t\t\t//外键关联 部门表\n\t\n\t@ManyToOne()\n\t@JoinColumn(name = \"role_id\")\n\tprivate Role role;\t\t\t//外键关联 角色表\n\t\n\n\t@ManyToMany(mappedBy = \"users\")\n\tprivate List<ScheduleList> scheduleLists;\n\t\n\t@ManyToMany(mappedBy = \"users\")\n\tprivate List<Reply> replys;\n\t\n\t@ManyToMany(mappedBy = \"users\")\n\tprivate List<Discuss> discuss;\n\t\n\t@ManyToMany(mappedBy = \"userss\")\n\tprivate List<Note> note;\n\n\t@OneToMany(mappedBy=\"user\",cascade=CascadeType.ALL,fetch=FetchType.EAGER)\n\tprivate Set<Attends> aSet;\n\t\n\t\n\t\n\t\n\tpublic String getPinyin() {\n\t\treturn pinyin;\n\t}\n\n\tpublic void setPinyin(String pinyin) {\n\t\tthis.pinyin = pinyin;\n\t}\n\n\tpublic List<Discuss> getDiscuss() {\n\t\treturn discuss;\n\t}\n\n\tpublic void setDiscuss(List<Discuss> discuss) {\n\t\tthis.discuss = discuss;\n\t}\n\n\tpublic User() {}\t\t\n\n public Set<Attends> getaSet() {\n\t\treturn aSet;\n\t}\n\npublic void setaSet(Set<Attends> aSet) {\n\t\tthis.aSet = aSet;\n\t}\n\n\t\n\tpublic Boolean getSuperman() {\n\treturn superman;\n}\n\npublic void setSuperman(Boolean superman) {\n\tthis.superman = superman;\n}\n\n\tpublic Long getUserId() {\n\t\treturn userId;\n\t}\n\n\tpublic void setUserId(Long userId) {\n\t\tthis.userId = userId;\n\t}\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n\tpublic String getUserTel() {\n\t\treturn userTel;\n\t}\n\n\tpublic void setUserTel(String userTel) {\n\t\tthis.userTel = userTel;\n\t}\n\n\tpublic String getRealName() {\n\t\treturn realName;\n\t}\n\n\tpublic void setRealName(String realName) {\n\t\tthis.realName = realName;\n\t}\n\n\tpublic String getEamil() {\n\t\treturn eamil;\n\t}\n\n\tpublic void setEamil(String eamil) {\n\t\tthis.eamil = eamil;\n\t}\n\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n\n\tpublic String getUserEdu() {\n\t\treturn userEdu;\n\t}\n\n\tpublic void setUserEdu(String userEdu) {\n\t\tthis.userEdu = userEdu;\n\t}\n\n\tpublic String getSchool() {\n\t\treturn school;\n\t}\n\n\tpublic void setSchool(String school) {\n\t\tthis.school = school;\n\t}\n\n\tpublic String getIdCard() {\n\t\treturn idCard;\n\t}\n\n\tpublic void setIdCard(String idCard) {\n\t\tthis.idCard = idCard;\n\t}\n\n\tpublic String getBank() {\n\t\treturn bank;\n\t}\n\n\tpublic void setBank(String bank) {\n\t\tthis.bank = bank;\n\t}\n\n\tpublic String getSex() {\n\t\treturn sex;\n\t}\n\n\tpublic void setSex(String sex) {\n\t\tthis.sex = sex;\n\t}\n\n\tpublic String getThemeSkin() {\n\t\treturn themeSkin;\n\t}\n\n\tpublic void setThemeSkin(String themeSkin) {\n\t\tthis.themeSkin = themeSkin;\n\t}\n\n\tpublic Date getBirth() {\n\t\treturn birth;\n\t}\n\n\tpublic void setBirth(Date birth) {\n\t\tthis.birth = birth;\n\t}\n\n\tpublic String getUserSign() {\n\t\treturn userSign;\n\t}\n\n\tpublic void setUserSign(String userSign) {\n\t\tthis.userSign = userSign;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getSalary() {\n\t\treturn salary;\n\t}\n\n\tpublic void setSalary(String salary) {\n\t\tthis.salary = salary;\n\t}\n\n\tpublic String getImgPath() {\n\t\treturn imgPath;\n\t}\n\n\tpublic void setImgPath(String imgPath) {\n\t\tthis.imgPath = imgPath;\n\t}\n\n\tpublic Date getHireTime() {\n\t\treturn hireTime;\n\t}\n\n\tpublic void setHireTime(Date hireTime) {\n\t\tthis.hireTime = hireTime;\n\t}\n\n\tpublic Integer getIsLock() {\n\t\treturn isLock;\n\t}\n\n\tpublic void setIsLock(Integer isLock) {\n\t\tthis.isLock = isLock;\n\t}\n\n\tpublic String getLastLoginIp() {\n\t\treturn lastLoginIp;\n\t}\n\n\tpublic void setLastLoginIp(String lastLoginIp) {\n\t\tthis.lastLoginIp = lastLoginIp;\n\t}\n\n\tpublic Date getLastLoginTime() {\n\t\treturn lastLoginTime;\n\t}\n\n\tpublic void setLastLoginTime(Date lastLoginTime) {\n\t\tthis.lastLoginTime = lastLoginTime;\n\t}\n\n\tpublic Date getModifyTime() {\n\t\treturn modifyTime;\n\t}\n\n\tpublic void setModifyTime(Date modifyTime) {\n\t\tthis.modifyTime = modifyTime;\n\t}\n\n\tpublic Long getModifyUserId() {\n\t\treturn modifyUserId;\n\t}\n\n\tpublic void setModifyUserId(Long modifyUserId) {\n\t\tthis.modifyUserId = modifyUserId;\n\t}\n\n\tpublic Long getFatherId() {\n\t\treturn fatherId;\n\t}\n\n\tpublic void setFatherId(Long fatherId) {\n\t\tthis.fatherId = fatherId;\n\t}\n\n\tpublic Position getPosition() {\n\t\treturn position;\n\t}\n\n\tpublic void setPosition(Position position) {\n\t\tthis.position = position;\n\t}\n\n\n\tpublic Dept getDept() {\n\t\treturn dept;\n\t}\n\n\n\tpublic void setDept(Dept dept) {\n\t\tthis.dept = dept;\n\t}\n\n\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n\t\n\tpublic List<ScheduleList> getScheduleLists() {\n\t\treturn scheduleLists;\n\t}\n\n\n\tpublic void setScheduleLists(List<ScheduleList> scheduleLists) {\n\t\tthis.scheduleLists = scheduleLists;\n\t}\n\n\n\tpublic List<Reply> getReplys() {\n\t\treturn replys;\n\t}\n\n\n\tpublic void setReplys(List<Reply> replys) {\n\t\tthis.replys = replys;\n\t}\n\n\n\tpublic List<Note> getNote() {\n\t\treturn note;\n\t}\n\n\n\tpublic void setNote(List<Note> note) {\n\t\tthis.note = note;\n\t}\n\n\t\n\n\tpublic Integer getHoliday() {\n\t\treturn holiday;\n\t}\n\n\tpublic void setHoliday(Integer holiday) {\n\t\tthis.holiday = holiday;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [userId=\" + userId + \", userName=\" + userName + \", userTel=\" + userTel + \", realName=\" + realName\n\t\t\t\t+ \", eamil=\" + eamil + \", address=\" + address + \", userEdu=\" + userEdu + \", school=\" + school\n\t\t\t\t+ \", idCard=\" + idCard + \", bank=\" + bank + \", sex=\" + sex + \", themeSkin=\" + themeSkin + \", birth=\"\n\t\t\t\t+ birth + \", userSign=\" + userSign + \", password=\" + password + \", salary=\" + salary + \", imgPath=\"\n\t\t\t\t+ imgPath + \", hireTime=\" + hireTime + \", isLock=\" + isLock + \", lastLoginIp=\" + lastLoginIp\n\t\t\t\t+ \", lastLoginTime=\" + lastLoginTime + \", modifyTime=\" + modifyTime + \", modifyUserId=\" + modifyUserId\n\t\t\t\t+ \", fatherId=\" + fatherId + \", holiday=\" + holiday + \",superman=\" + superman + \",pinyin=\" + pinyin + \"]\";\n\t}\n\t\n\t\n\t\n\t\n}" } ]
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
10,654
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao; List<Attends> alist;
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao; List<Attends> alist;
List<User> uList;
10
2023-11-03 02:29:57+00:00
12k
ballerina-platform/module-ballerina-data-xmldata
native/src/main/java/io/ballerina/stdlib/data/xmldata/xml/XmlParser.java
[ { "identifier": "FromString", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/FromString.java", "snippet": "public class FromString {\n\n public static Object fromStringWithType(BString string, BTypedesc typed) {\n Type expType = typed.getDescribingType();\n\n try {\n return fromStringWithType(string, expType);\n } catch (NumberFormatException e) {\n return returnError(string.getValue(), expType.toString());\n }\n }\n\n public static Object fromStringWithTypeInternal(BString string, Type expType) {\n return fromStringWithType(string, expType);\n }\n\n private static Object fromStringWithType(BString string, Type expType) {\n String value = string.getValue();\n try {\n switch (expType.getTag()) {\n case TypeTags.INT_TAG:\n return stringToInt(value);\n case TypeTags.FLOAT_TAG:\n return stringToFloat(value);\n case TypeTags.DECIMAL_TAG:\n return stringToDecimal(value);\n case TypeTags.STRING_TAG:\n return string;\n case TypeTags.BOOLEAN_TAG:\n return stringToBoolean(value);\n case TypeTags.NULL_TAG:\n return stringToNull(value);\n case TypeTags.UNION_TAG:\n return stringToUnion(string, (UnionType) expType);\n case TypeTags.TYPE_REFERENCED_TYPE_TAG:\n return fromStringWithType(string, ((ReferenceType) expType).getReferredType());\n default:\n return returnError(value, expType.toString());\n }\n } catch (NumberFormatException e) {\n return returnError(value, expType.toString());\n }\n }\n\n private static Long stringToInt(String value) throws NumberFormatException {\n return Long.parseLong(value);\n }\n\n private static Double stringToFloat(String value) throws NumberFormatException {\n if (hasFloatOrDecimalLiteralSuffix(value)) {\n throw new NumberFormatException();\n }\n return Double.parseDouble(value);\n }\n\n private static BDecimal stringToDecimal(String value) throws NumberFormatException {\n return ValueCreator.createDecimalValue(value);\n }\n \n private static Object stringToBoolean(String value) throws NumberFormatException {\n if (\"true\".equalsIgnoreCase(value) || \"1\".equalsIgnoreCase(value)) {\n return true;\n }\n\n if (\"false\".equalsIgnoreCase(value) || \"0\".equalsIgnoreCase(value)) {\n return false;\n }\n return returnError(value, \"boolean\");\n }\n\n private static Object stringToNull(String value) throws NumberFormatException {\n if (\"null\".equalsIgnoreCase(value) || \"()\".equalsIgnoreCase(value)) {\n return null;\n }\n return returnError(value, \"()\");\n }\n\n private static Object stringToUnion(BString string, UnionType expType) throws NumberFormatException {\n List<Type> memberTypes = expType.getMemberTypes();\n memberTypes.sort(Comparator.comparingInt(t -> t.getTag()));\n boolean isStringExpType = false;\n for (Type memberType : memberTypes) {\n try {\n Object result = fromStringWithType(string, memberType);\n if (result instanceof BString) {\n isStringExpType = true;\n continue;\n } else if (result instanceof BError) {\n continue;\n }\n return result;\n } catch (Exception e) {\n // Skip\n }\n }\n \n if (isStringExpType) {\n return string;\n }\n return returnError(string.getValue(), expType.toString());\n }\n\n private static boolean hasFloatOrDecimalLiteralSuffix(String value) {\n int length = value.length();\n if (length == 0) {\n return false;\n }\n\n switch (value.charAt(length - 1)) {\n case 'F':\n case 'f':\n case 'D':\n case 'd':\n return true;\n default:\n return false;\n }\n }\n\n private static BError returnError(String string, String expType) {\n return DiagnosticLog.error(DiagnosticErrorCode.CANNOT_CONVERT_TO_EXPECTED_TYPE,\n PredefinedTypes.TYPE_STRING.getName(), string, expType);\n }\n}" }, { "identifier": "Constants", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/Constants.java", "snippet": "public class Constants {\n\n private Constants() {}\n\n public static final String UNDERSCORE = \"_\";\n public static final String COLON = \":\";\n public static final MapType JSON_MAP_TYPE = TypeCreator.createMapType(PredefinedTypes.TYPE_JSON);\n public static final ArrayType JSON_ARRAY_TYPE = TypeCreator.createArrayType(PredefinedTypes.TYPE_JSON);\n public static final String FIELD = \"$field$.\";\n public static final String NAMESPACE = \"Namespace\";\n public static final BString URI = StringUtils.fromString(\"uri\");\n public static final BString PREFIX = StringUtils.fromString(\"prefix\");\n public static final String ATTRIBUTE = \"Attribute\";\n public static final int DEFAULT_TYPE_FLAG = 2049;\n public static final String NAME = \"Name\";\n public static final BString VALUE = StringUtils.fromString(\"value\");\n public static final String CONTENT = \"#content\";\n public static final QualifiedName CONTENT_QNAME = new QualifiedName(\"\", CONTENT, \"\");\n public static final String FIELD_REGEX = \"\\\\$field\\\\$\\\\.\";\n public static final int NS_PREFIX_BEGIN_INDEX = BXmlItem.XMLNS_NS_URI_PREFIX.length();\n public static final String RECORD = \"record\";\n public static final String RECORD_OR_MAP = \"record or map\";\n public static final String ANON_TYPE = \"$anonType$\";\n}" }, { "identifier": "DataUtils", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DataUtils.java", "snippet": "public class DataUtils {\n private static final String ATTRIBUTE_PREFIX = \"attribute_\";\n private static final String VALUE = \"value\";\n\n @SuppressWarnings(\"unchecked\")\n public static QualifiedName validateAndGetXmlNameFromRecordAnnotation(RecordType recordType, String recordName,\n QualifiedName elementName) {\n BMap<BString, Object> annotations = recordType.getAnnotations();\n String localName = recordName;\n for (BString annotationsKey : annotations.getKeys()) {\n String key = annotationsKey.getValue();\n if (!key.contains(Constants.FIELD) && key.endsWith(Constants.NAME)) {\n String name = ((BMap<BString, Object>) annotations.get(annotationsKey)).get(Constants.VALUE).toString();\n String localPart = elementName.getLocalPart();\n if (!name.equals(localPart)) {\n throw DiagnosticLog.error(DiagnosticErrorCode.TYPE_NAME_MISMATCH_WITH_XML_ELEMENT, name, localPart);\n }\n localName = name;\n break;\n }\n }\n\n // Handle the namespace annotation.\n for (BString annotationsKey : annotations.getKeys()) {\n String key = annotationsKey.getValue();\n if (!key.contains(Constants.FIELD) && key.endsWith(Constants.NAMESPACE)) {\n Map<BString, Object> namespaceAnnotation =\n ((Map<BString, Object>) annotations.get(StringUtils.fromString(key)));\n BString uri = (BString) namespaceAnnotation.get(Constants.URI);\n BString prefix = (BString) namespaceAnnotation.get(Constants.PREFIX);\n return new QualifiedName(uri == null ? \"\" : uri.getValue(), localName,\n prefix == null ? \"\" : prefix.getValue());\n }\n }\n return new QualifiedName(QualifiedName.NS_ANNOT_NOT_DEFINED, localName, \"\");\n }\n\n public static void validateTypeNamespace(String prefix, String uri, RecordType recordType) {\n ArrayList<String> namespace = getNamespace(recordType);\n if (namespace.isEmpty() || prefix.equals(namespace.get(0)) && uri.equals(namespace.get(1))) {\n return;\n }\n throw DiagnosticLog.error(DiagnosticErrorCode.NAMESPACE_MISMATCH, recordType.getName());\n }\n\n @SuppressWarnings(\"unchecked\")\n private static ArrayList<String> getNamespace(RecordType recordType) {\n BMap<BString, Object> annotations = recordType.getAnnotations();\n ArrayList<String> namespace = new ArrayList<>();\n for (BString annotationsKey : annotations.getKeys()) {\n String key = annotationsKey.getValue();\n if (!key.contains(Constants.FIELD) && key.endsWith(Constants.NAMESPACE)) {\n BMap<BString, Object> namespaceAnnotation = (BMap<BString, Object>) annotations.get(annotationsKey);\n namespace.add(namespaceAnnotation.containsKey(Constants.PREFIX) ?\n ((BString) namespaceAnnotation.get(Constants.PREFIX)).getValue() : \"\");\n namespace.add(((BString) namespaceAnnotation.get(Constants.URI)).getValue());\n break;\n }\n }\n return namespace;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Map<QualifiedName, Field> getAllFieldsInRecordType(RecordType recordType,\n XmlAnalyzerData analyzerData) {\n BMap<BString, Object> annotations = recordType.getAnnotations();\n HashMap<String, QualifiedName> modifiedNames = new LinkedHashMap<>();\n for (BString annotationKey : annotations.getKeys()) {\n String keyStr = annotationKey.getValue();\n if (keyStr.contains(Constants.FIELD)) {\n // Capture namespace and name from the field annotation.\n String fieldName = keyStr.split(Constants.FIELD_REGEX)[1].replaceAll(\"\\\\\\\\\", \"\");\n Map<BString, Object> fieldAnnotation = (Map<BString, Object>) annotations.get(annotationKey);\n QualifiedName fieldQName = DataUtils.getFieldNameFromRecord(fieldAnnotation, fieldName);\n fieldQName.setLocalPart(getModifiedName(fieldAnnotation, fieldName));\n modifiedNames.put(fieldName, fieldQName);\n }\n }\n\n Map<QualifiedName, Field> fields = new HashMap<>();\n Map<String, Field> recordFields = recordType.getFields();\n for (String key : recordFields.keySet()) {\n QualifiedName modifiedQName = modifiedNames.getOrDefault(key,\n new QualifiedName(QualifiedName.NS_ANNOT_NOT_DEFINED, key, \"\"));\n if (fields.containsKey(modifiedQName)) {\n throw DiagnosticLog.error(DiagnosticErrorCode.DUPLICATE_FIELD, modifiedQName.getLocalPart());\n } else if (analyzerData.attributeHierarchy.peek().containsKey(modifiedQName)) {\n continue;\n }\n fields.put(modifiedQName, recordFields.get(key));\n }\n return fields;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Map<QualifiedName, Field> getAllAttributesInRecordType(RecordType recordType) {\n BMap<BString, Object> annotations = recordType.getAnnotations();\n Map<QualifiedName, Field> attributes = new HashMap<>();\n for (BString annotationKey : annotations.getKeys()) {\n String keyStr = annotationKey.getValue();\n if (keyStr.contains(Constants.FIELD) && DataUtils.isAttributeField(annotationKey, annotations)) {\n String attributeName = keyStr.split(Constants.FIELD_REGEX)[1].replaceAll(\"\\\\\\\\\", \"\");\n Map<BString, Object> fieldAnnotation = (Map<BString, Object>) annotations.get(annotationKey);\n QualifiedName fieldQName = getFieldNameFromRecord(fieldAnnotation, attributeName);\n fieldQName.setLocalPart(getModifiedName(fieldAnnotation, attributeName));\n attributes.put(fieldQName, recordType.getFields().get(attributeName));\n }\n }\n return attributes;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static QualifiedName getFieldNameFromRecord(Map<BString, Object> fieldAnnotation, String fieldName) {\n for (BString key : fieldAnnotation.keySet()) {\n if (key.getValue().endsWith(Constants.NAMESPACE)) {\n Map<BString, Object> namespaceAnnotation = ((Map<BString, Object>) fieldAnnotation.get(key));\n BString uri = (BString) namespaceAnnotation.get(Constants.URI);\n BString prefix = (BString) namespaceAnnotation.get(Constants.PREFIX);\n return new QualifiedName(uri == null ? \"\" : uri.getValue(), fieldName,\n prefix == null ? \"\" : prefix.getValue());\n }\n }\n return new QualifiedName(QualifiedName.NS_ANNOT_NOT_DEFINED, fieldName, \"\");\n }\n\n @SuppressWarnings(\"unchecked\")\n private static String getModifiedName(Map<BString, Object> fieldAnnotation, String attributeName) {\n for (BString key : fieldAnnotation.keySet()) {\n if (key.getValue().endsWith(Constants.NAME)) {\n return ((Map<BString, Object>) fieldAnnotation.get(key)).get(Constants.VALUE).toString();\n }\n }\n return attributeName;\n }\n\n public static BArray createNewAnydataList(Type type) {\n return ValueCreator.createArrayValue(getArrayTypeFromElementType(type));\n }\n\n public static QualifiedName getElementName(QName qName) {\n return new QualifiedName(qName.getNamespaceURI(), qName.getLocalPart(), qName.getPrefix());\n }\n\n public static Object convertStringToExpType(BString value, Type expType) {\n Object result;\n switch (expType.getTag()) {\n case TypeTags.ANYDATA_TAG, TypeTags.ANY_TAG, TypeTags.JSON_TAG ->\n result = FromString.fromStringWithTypeInternal(value, PredefinedTypes.TYPE_STRING);\n case TypeTags.ARRAY_TAG -> result = convertStringToExpType(value, ((ArrayType) expType).getElementType());\n default -> result = FromString.fromStringWithTypeInternal(value, expType);\n }\n\n if (result instanceof BError) {\n throw (BError) result;\n }\n return result;\n }\n\n public static void validateRequiredFields(BMap<BString, Object> currentMapValue, XmlAnalyzerData analyzerData) {\n Map<QualifiedName, Field> fields = analyzerData.fieldHierarchy.peek();\n for (QualifiedName key : fields.keySet()) {\n // Validate required array size\n Field field = fields.get(key);\n String fieldName = field.getFieldName();\n if (field.getFieldType().getTag() == TypeTags.ARRAY_TAG) {\n ArrayType arrayType = (ArrayType) field.getFieldType();\n if (arrayType.getSize() != -1\n && arrayType.getSize() != ((BArray) currentMapValue.get(\n StringUtils.fromString(fieldName))).getLength()) {\n throw DiagnosticLog.error(DiagnosticErrorCode.ARRAY_SIZE_MISMATCH);\n }\n }\n\n if (!SymbolFlags.isFlagOn(field.getFlags(), SymbolFlags.OPTIONAL)\n && !currentMapValue.containsKey(StringUtils.fromString(fieldName))) {\n throw DiagnosticLog.error(DiagnosticErrorCode.REQUIRED_FIELD_NOT_PRESENT, fieldName);\n }\n }\n\n Map<QualifiedName, Field> attributes = analyzerData.attributeHierarchy.peek();\n for (QualifiedName key : attributes.keySet()) {\n Field field = attributes.get(key);\n String fieldName = field.getFieldName();\n if (!SymbolFlags.isFlagOn(field.getFlags(), SymbolFlags.OPTIONAL)) {\n throw DiagnosticLog.error(DiagnosticErrorCode.REQUIRED_ATTRIBUTE_NOT_PRESENT, fieldName);\n }\n }\n }\n\n public static boolean isArrayValueAssignable(int typeTag) {\n return typeTag == TypeTags.ARRAY_TAG || typeTag == TypeTags.ANYDATA_TAG || typeTag == TypeTags.JSON_TAG;\n }\n\n public static boolean isStringValueAssignable(int typeTag) {\n return typeTag == TypeTags.STRING_TAG || typeTag == TypeTags.ANYDATA_TAG || typeTag == TypeTags.JSON_TAG;\n }\n\n public static ArrayType getValidArrayType(Type type) {\n return switch (type.getTag()) {\n case TypeTags.ARRAY_TAG -> (ArrayType) type;\n case TypeTags.ANYDATA_TAG -> PredefinedTypes.TYPE_ANYDATA_ARRAY;\n case TypeTags.JSON_TAG -> PredefinedTypes.TYPE_JSON_ARRAY;\n default -> null;\n };\n }\n\n public static ArrayType getArrayTypeFromElementType(Type type) {\n return switch (type.getTag()) {\n case TypeTags.ARRAY_TAG -> TypeCreator.createArrayType(((ArrayType) type).getElementType());\n case TypeTags.JSON_TAG -> PredefinedTypes.TYPE_JSON_ARRAY;\n case TypeTags.INT_TAG, TypeTags.FLOAT_TAG, TypeTags.STRING_TAG, TypeTags.BOOLEAN_TAG, TypeTags.BYTE_TAG,\n TypeTags.DECIMAL_TAG, TypeTags.RECORD_TYPE_TAG, TypeTags.MAP_TAG, TypeTags.OBJECT_TYPE_TAG,\n TypeTags.XML_TAG, TypeTags.NULL_TAG -> TypeCreator.createArrayType(type);\n case TypeTags.TYPE_REFERENCED_TYPE_TAG -> getArrayTypeFromElementType(TypeUtils.getReferredType(type));\n default -> PredefinedTypes.TYPE_ANYDATA_ARRAY;\n };\n }\n\n public static MapType getMapTypeFromConstraintType(Type constraintType) {\n return switch (constraintType.getTag()) {\n case TypeTags.MAP_TAG -> (MapType) constraintType;\n case TypeTags.INT_TAG, TypeTags.FLOAT_TAG, TypeTags.STRING_TAG, TypeTags.BOOLEAN_TAG, TypeTags.BYTE_TAG,\n TypeTags.DECIMAL_TAG, TypeTags.JSON_TAG, TypeTags.RECORD_TYPE_TAG, TypeTags.OBJECT_TYPE_TAG,\n TypeTags.XML_TAG, TypeTags.NULL_TAG -> TypeCreator.createMapType(constraintType);\n case TypeTags.ARRAY_TAG -> TypeCreator.createMapType(((ArrayType) constraintType).getElementType());\n case TypeTags.TYPE_REFERENCED_TYPE_TAG ->\n getMapTypeFromConstraintType(TypeUtils.getReferredType(constraintType));\n default -> TypeCreator.createMapType(PredefinedTypes.TYPE_ANYDATA);\n };\n }\n\n public static void updateExpectedTypeStacks(RecordType recordType, XmlAnalyzerData analyzerData) {\n analyzerData.attributeHierarchy.push(new HashMap<>(getAllAttributesInRecordType(recordType)));\n analyzerData.fieldHierarchy.push(new HashMap<>(getAllFieldsInRecordType(recordType, analyzerData)));\n analyzerData.restTypes.push(recordType.getRestFieldType());\n }\n\n public static void removeExpectedTypeStacks(XmlAnalyzerData analyzerData) {\n analyzerData.attributeHierarchy.pop();\n analyzerData.fieldHierarchy.pop();\n analyzerData.restTypes.pop();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Object getModifiedRecord(BMap<BString, Object> input, BTypedesc type) {\n Type describingType = type.getDescribingType();\n if (describingType.getTag() == TypeTags.MAP_TAG) {\n Type constraintType = TypeUtils.getReferredType(((MapType) describingType).getConstrainedType());\n switch (constraintType.getTag()) {\n case TypeTags.ARRAY_TAG -> {\n return processArrayValue(input, (ArrayType) constraintType);\n }\n case TypeTags.MAP_TAG -> {\n BMap<BString, Object> jsonMap =\n ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_XML));\n for (Map.Entry<BString, Object> entry : input.entrySet()) {\n jsonMap.put(entry.getKey(), entry.getValue());\n }\n return jsonMap;\n }\n case TypeTags.UNION_TAG -> {\n return DiagnosticLog.error(DiagnosticErrorCode.UNSUPPORTED_TYPE);\n }\n }\n }\n if (describingType.getTag() == TypeTags.RECORD_TYPE_TAG &&\n describingType.getFlags() != Constants.DEFAULT_TYPE_FLAG) {\n BArray jsonArray = ValueCreator.createArrayValue(PredefinedTypes.TYPE_JSON_ARRAY);\n BMap<BString, Object> recordField = addFields(input, type.getDescribingType());\n BMap<BString, Object> processedRecord = processParentAnnotation(type.getDescribingType(), recordField);\n BString rootTagName = processedRecord.getKeys()[0];\n jsonArray.append(processedRecord.get(rootTagName));\n jsonArray.append(rootTagName);\n return jsonArray;\n }\n return input;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static BMap<BString, Object> processArrayValue(BMap<BString, Object> input, ArrayType arrayType) {\n Type elementType = TypeUtils.getReferredType(arrayType.getElementType());\n switch (elementType.getTag()) {\n case TypeTags.RECORD_TYPE_TAG -> {\n BMap<BString, Object> jsonMap = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n for (Map.Entry<BString, Object> entry : input.entrySet()) {\n List<BMap<BString, Object>> records = new ArrayList<>();\n BArray arrayValue = (BArray) entry.getValue();\n for (int i = 0; i < arrayValue.getLength(); i++) {\n BMap<BString, Object> record = addFields(((BMap<BString, Object>) arrayValue.get(i)),\n elementType);\n BMap<BString, Object> parentRecord = processParentAnnotation(elementType, record);\n // Remove parent element\n records.add((BMap<BString, Object>) parentRecord.get(parentRecord.getKeys()[0]));\n }\n jsonMap.put(entry.getKey(), ValueCreator.createArrayValue(records.toArray(),\n TypeCreator.createArrayType(elementType)));\n }\n return jsonMap;\n }\n case TypeTags.XML_TAG -> {\n ArrayType xmlArrayType = TypeCreator.createArrayType(PredefinedTypes.TYPE_XML);\n BMap<BString, Object> jsonMap =\n ValueCreator.createMapValue(TypeCreator.createMapType(xmlArrayType));\n for (Map.Entry<BString, Object> entry : input.entrySet()) {\n BArray arrayValue = (BArray) entry.getValue();\n BArray xmlArrayValue = ValueCreator.createArrayValue(xmlArrayType);\n for (int i = 0; i < arrayValue.getLength(); i++) {\n xmlArrayValue.append(arrayValue.get(i));\n }\n jsonMap.put(entry.getKey(), xmlArrayValue);\n }\n return jsonMap;\n }\n default -> {\n return input;\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static BMap<BString, Object> addFields(BMap<BString, Object> input, Type type) {\n BMap<BString, Object> recordValue = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n Map<String, Field> fields = ((RecordType) type).getFields();\n BMap<BString, Object> annotations = ((RecordType) type).getAnnotations();\n for (Map.Entry<BString, Object> entry: input.entrySet()) {\n String key = entry.getKey().getValue();\n Object value = entry.getValue();\n if (fields.containsKey(key)) {\n Type fieldType = fields.get(key).getFieldType();\n fieldType = getTypeFromUnionType(fieldType, value);\n if (fieldType.getTag() == TypeTags.RECORD_TYPE_TAG) {\n processRecord(key, annotations, recordValue, value, fieldType);\n } else if (fieldType.getTag() == TypeTags.TYPE_REFERENCED_TYPE_TAG) {\n Type referredType = TypeUtils.getReferredType(fieldType);\n if (annotations.size() > 0) {\n key = getKeyNameFromAnnotation(annotations, key);\n }\n BMap<BString, Object> subRecordAnnotations = ((RecordType) referredType).getAnnotations();\n key = getElementName(subRecordAnnotations, key);\n BMap<BString, Object> annotationRecord = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n processSubRecordAnnotation(subRecordAnnotations, annotationRecord);\n BMap<BString, Object> subRecordValue = addFields(((BMap<BString, Object>) value), referredType);\n if (annotationRecord.size() > 0) {\n subRecordValue.put(annotationRecord.getKeys()[0],\n annotationRecord.get(annotationRecord.getKeys()[0]));\n }\n recordValue.put(StringUtils.fromString(key), subRecordValue);\n } else if (fieldType.getTag() == TypeTags.ARRAY_TAG) {\n processArray(fieldType, annotations, recordValue, entry);\n } else {\n addPrimitiveValue(addFieldNamespaceAnnotation(key, annotations, recordValue),\n annotations, recordValue, value);\n }\n } else {\n recordValue.put(StringUtils.fromString(key), value);\n }\n }\n return recordValue;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static QName addFieldNamespaceAnnotation(String key, BMap<BString, Object> annotations,\n BMap<BString, Object> recordValue) {\n BString annotationKey =\n StringUtils.fromString((Constants.FIELD + key).replace(Constants.COLON, \"\\\\:\"));\n boolean isAttributeField = isAttributeField(annotationKey, annotations);\n if (annotations.containsKey(annotationKey)) {\n BMap<BString, Object> annotationValue = (BMap<BString, Object>) annotations.get(annotationKey);\n for (BString fieldKey : annotationValue.getKeys()) {\n if (fieldKey.toString().endsWith(Constants.NAMESPACE)) {\n return processFieldNamespaceAnnotation(annotationValue, key, fieldKey, recordValue,\n isAttributeField);\n }\n }\n }\n return new QName(\"\", key, \"\");\n }\n\n @SuppressWarnings(\"unchecked\")\n public static boolean isAttributeField(BString annotationKey, BMap<BString, Object> annotations) {\n if (!annotations.containsKey(annotationKey)) {\n return false;\n }\n\n BMap<BString, Object> annotationValue = (BMap<BString, Object>) annotations.get(annotationKey);\n for (BString fieldKey : annotationValue.getKeys()) {\n if (fieldKey.toString().endsWith(Constants.ATTRIBUTE)) {\n return true;\n }\n }\n return false;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static BMap<BString, Object> getFieldNamespaceAndNameAnnotations(String key,\n BMap<BString, Object> parentAnnotations) {\n BMap<BString, Object> nsFieldAnnotation = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n BString annotationKey =\n StringUtils.fromString((Constants.FIELD + key).replace(Constants.COLON, \"\\\\:\"));\n if (!parentAnnotations.containsKey(annotationKey)) {\n return nsFieldAnnotation;\n }\n\n BMap<BString, Object> annotationValue = (BMap<BString, Object>) parentAnnotations.get(annotationKey);\n for (BString fieldKey : annotationValue.getKeys()) {\n String keyName = fieldKey.getValue();\n if (keyName.endsWith(Constants.NAMESPACE) || keyName.endsWith(Constants.NAME)) {\n nsFieldAnnotation.put(fieldKey, annotationValue.get(fieldKey));\n break;\n }\n }\n return nsFieldAnnotation;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void processRecord(String key, BMap<BString, Object> parentAnnotations,\n BMap<BString, Object> record, Object value, Type childType) {\n BMap<BString, Object> parentRecordAnnotations = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n BMap<BString, Object> annotation = ((RecordType) childType).getAnnotations();\n if (parentAnnotations.size() > 0) {\n annotation.merge(getFieldNamespaceAndNameAnnotations(key, parentAnnotations), true);\n processSubRecordAnnotation(parentAnnotations, parentRecordAnnotations);\n }\n BMap<BString, Object> subRecord = addFields(((BMap<BString, Object>) value), childType);\n if (annotation.size() > 0) {\n processSubRecordAnnotation(annotation, subRecord);\n }\n key = getElementName(annotation, key);\n record.put(StringUtils.fromString(key), subRecord);\n if (parentRecordAnnotations.size() > 0) {\n record.put(parentRecordAnnotations.getKeys()[0],\n parentRecordAnnotations.get(parentRecordAnnotations.getKeys()[0]));\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void addPrimitiveValue(QName qName, BMap<BString, Object> annotations,\n BMap<BString, Object> record, Object value) {\n BString localPart = StringUtils.fromString(qName.getLocalPart());\n BString key = qName.getPrefix().isBlank() ?\n localPart : StringUtils.fromString(qName.getPrefix() + \":\" + localPart);\n BString annotationKey =\n StringUtils.fromString((Constants.FIELD + localPart).replace(Constants.COLON, \"\\\\:\"));\n BMap<BString, Object> currentValue;\n if (record.containsKey(key)) {\n currentValue = (BMap<BString, Object>) record.get(key);\n key = StringUtils.fromString(Constants.CONTENT);\n } else {\n currentValue = record;\n }\n\n if (annotations.containsKey(annotationKey)) {\n BMap<BString, Object> annotationValue = (BMap<BString, Object>) annotations.get(annotationKey);\n currentValue.put(StringUtils.fromString(processFieldAnnotation(annotationValue, key.getValue())), value);\n } else {\n currentValue.put(key, value);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void processArray(Type childType, BMap<BString, Object> annotations,\n BMap<BString, Object> record, Map.Entry<BString, Object> entry) {\n Type elementType = TypeUtils.getReferredType(((ArrayType) childType).getElementType());\n BMap<BString, Object> annotationRecord = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n String keyName = entry.getKey().getValue();\n if (annotations.size() > 0) {\n keyName = getKeyNameFromAnnotation(annotations, keyName);\n processSubRecordAnnotation(annotations, annotationRecord);\n }\n BArray arrayValue = (BArray) entry.getValue();\n if (elementType.getTag() == TypeTags.RECORD_TYPE_TAG) {\n List<BMap<BString, Object>> records = new ArrayList<>();\n for (int i = 0; i < arrayValue.getLength(); i++) {\n BMap<BString, Object> subRecord = addFields(((BMap<BString, Object>) arrayValue.get(i)),\n elementType);\n subRecord = processParentAnnotation(elementType, subRecord);\n records.add((BMap<BString, Object>) subRecord.get(subRecord.getKeys()[0]));\n }\n record.put(\n StringUtils.fromString(getElementName(((RecordType) elementType).getAnnotations(), keyName)),\n ValueCreator.createArrayValue(records.toArray(),\n TypeCreator.createArrayType(Constants.JSON_ARRAY_TYPE)));\n } else {\n List<Object> records = new ArrayList<>();\n for (int i = 0; i < arrayValue.getLength(); i++) {\n records.add(arrayValue.get(i));\n }\n record.put(StringUtils.fromString(keyName), ValueCreator.createArrayValue(records.toArray(),\n TypeCreator.createArrayType(Constants.JSON_ARRAY_TYPE)));\n }\n if (annotationRecord.size() > 0) {\n record.put(annotationRecord.getKeys()[0],\n annotationRecord.get(annotationRecord.getKeys()[0]));\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static String getKeyNameFromAnnotation(BMap<BString, Object> annotations, String keyName) {\n BString annotationKey = StringUtils.fromString((Constants.FIELD + keyName).\n replace(Constants.COLON, \"\\\\:\"));\n if (annotations.containsKey(annotationKey)) {\n BMap<BString, Object> annotationValue = (BMap<BString, Object>) annotations.get(annotationKey);\n return processFieldAnnotation(annotationValue, keyName);\n }\n return keyName;\n }\n\n public static Type getTypeFromUnionType(Type childType, Object value) {\n if (childType instanceof UnionType bUnionType) {\n for (Type memberType : bUnionType.getMemberTypes()) {\n if (value.getClass().getName().toUpperCase(Locale.ROOT).contains(\n memberType.getName().toUpperCase(Locale.ROOT))) {\n childType = TypeUtils.getReferredType(memberType);\n }\n }\n }\n return childType;\n }\n\n private static BMap<BString, Object> processParentAnnotation(Type type, BMap<BString, Object> record) {\n BMap<BString, Object> parentRecord = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n BMap<BString, Object> namespaces = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n BMap<BString, Object> annotations = ((RecordType) type).getAnnotations();\n BString rootName = processAnnotation(annotations, type.getName(), namespaces);\n if (namespaces.size() > 0) {\n for (Map.Entry<BString, Object> namespace : namespaces.entrySet()) {\n record.put(namespace.getKey(), namespace.getValue());\n }\n }\n parentRecord.put(rootName, record);\n return parentRecord;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static String processFieldAnnotation(BMap<BString, Object> annotation, String key) {\n for (BString value : annotation.getKeys()) {\n String stringValue = value.getValue();\n if (stringValue.endsWith(Constants.NAME)) {\n BMap<BString, Object> names = (BMap<BString, Object>) annotation.get(value);\n String name = names.get(StringUtils.fromString(VALUE)).toString();\n if (key.contains(Constants.COLON)) {\n key = key.substring(0, key.indexOf(Constants.COLON) + 1) + name;\n } else if (key.contains(ATTRIBUTE_PREFIX)) {\n key = key.substring(0, key.indexOf(Constants.UNDERSCORE) + 1) + name;\n } else {\n key = name;\n }\n }\n if (stringValue.endsWith(Constants.ATTRIBUTE)) {\n key = ATTRIBUTE_PREFIX.concat(key);\n }\n }\n return key;\n }\n\n private static BString processAnnotation(BMap<BString, Object> annotation, String key,\n BMap<BString, Object> namespaces) {\n boolean hasNamespaceAnnotation = false;\n for (BString value : annotation.getKeys()) {\n if (!value.getValue().contains(Constants.FIELD)) {\n String stringValue = value.getValue();\n if (stringValue.endsWith(Constants.NAME)) {\n key = processNameAnnotation(annotation, key, value, hasNamespaceAnnotation);\n }\n if (stringValue.endsWith(Constants.NAMESPACE)) {\n hasNamespaceAnnotation = true;\n key = processNamespaceAnnotation(annotation, key, value, namespaces);\n }\n }\n }\n return StringUtils.fromString(key);\n }\n\n private static void processSubRecordAnnotation(BMap<BString, Object> annotation, BMap<BString, Object> subRecord) {\n BString[] keys = annotation.getKeys();\n for (BString value : keys) {\n if (value.getValue().endsWith(Constants.NAMESPACE)) {\n processNamespaceAnnotation(annotation, \"\", value, subRecord);\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static String getElementName(BMap<BString, Object> annotation, String key) {\n BString[] keys = annotation.getKeys();\n boolean hasNamespaceAnnotation = false;\n for (BString value : keys) {\n if (value.getValue().endsWith(Constants.NAMESPACE)) {\n hasNamespaceAnnotation = true;\n BMap<BString, Object> namespaceAnnotation = (BMap<BString, Object>) annotation.get(value);\n BString prefix = (BString) namespaceAnnotation.get(Constants.PREFIX);\n if (prefix != null) {\n key = prefix.getValue().concat(Constants.COLON).concat(key);\n }\n }\n if (value.getValue().endsWith(Constants.NAME)) {\n key = processNameAnnotation(annotation, key, value, hasNamespaceAnnotation);\n }\n }\n return key;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static String processNameAnnotation(BMap<BString, Object> annotation, String key, BString value,\n boolean hasNamespaceAnnotation) {\n String nameValue = ((BMap<BString, Object>) annotation.get(value)).\n get(StringUtils.fromString(VALUE)).toString();\n if (hasNamespaceAnnotation) {\n return key.substring(0, key.indexOf(Constants.COLON) + 1) + nameValue;\n } else {\n return nameValue;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static String processNamespaceAnnotation(BMap<BString, Object> annotation, String key, BString value,\n BMap<BString, Object> subRecord) {\n BMap<BString, Object> namespaceAnnotation = (BMap<BString, Object>) annotation.get(value);\n BString uri = (BString) namespaceAnnotation.get(Constants.URI);\n BString prefix = (BString) namespaceAnnotation.get(Constants.PREFIX);\n if (prefix == null) {\n subRecord.put(StringUtils.fromString(ATTRIBUTE_PREFIX + \"xmlns\"), uri);\n } else {\n subRecord.put(StringUtils.fromString(ATTRIBUTE_PREFIX + \"xmlns:\" + prefix), uri);\n key = prefix.getValue().concat(Constants.COLON).concat(key);\n }\n return key;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static QName processFieldNamespaceAnnotation(BMap<BString, Object> annotation, String key, BString value,\n BMap<BString, Object> subRecord, boolean isAttributeField) {\n BMap<BString, Object> namespaceAnnotation = (BMap<BString, Object>) annotation.get(value);\n BString uri = (BString) namespaceAnnotation.get(Constants.URI);\n BString prefix = (BString) namespaceAnnotation.get(Constants.PREFIX);\n QName qName = new QName(uri == null ? \"\" : uri.getValue(), key, prefix == null ? \"\" : prefix.getValue());\n if (isAttributeField) {\n addAttributeToRecord(prefix, uri, key, subRecord);\n } else {\n BMap<BString, Object> nextMapValue = ValueCreator.createMapValue(Constants.JSON_MAP_TYPE);\n key = addAttributeToRecord(prefix, uri, key, nextMapValue);\n subRecord.put(StringUtils.fromString(key), nextMapValue);\n }\n return qName;\n }\n\n private static String addAttributeToRecord(BString prefix, BString uri, String key,\n BMap<BString, Object> subRecord) {\n if (prefix == null) {\n subRecord.put(StringUtils.fromString(ATTRIBUTE_PREFIX + \"xmlns\"), uri);\n return key;\n }\n subRecord.put(StringUtils.fromString(ATTRIBUTE_PREFIX + \"xmlns:\" + prefix), uri);\n return prefix.getValue().concat(Constants.COLON).concat(key);\n }\n\n /**\n * Holds data required for the traversing.\n *\n * @since 0.1.0\n */\n public static class XmlAnalyzerData {\n public final Stack<Object> nodesStack = new Stack<>();\n public final Stack<Map<QualifiedName, Field>> fieldHierarchy = new Stack<>();\n public final Stack<Map<QualifiedName, Field>> attributeHierarchy = new Stack<>();\n public final Stack<Type> restTypes = new Stack<>();\n public RecordType rootRecord;\n public Field currentField;\n public QualifiedName rootElement;\n }\n}" }, { "identifier": "DiagnosticErrorCode", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticErrorCode.java", "snippet": "public enum DiagnosticErrorCode {\n\n INVALID_TYPE(\"BDE_0001\", \"invalid.type\"),\n XML_ROOT_MISSING(\"BDE_0002\", \"xml.root.missing\"),\n INVALID_REST_TYPE(\"BDE_0003\", \"invalid.rest.type\"),\n ARRAY_SIZE_MISMATCH(\"BDE_0004\", \"array.size.mismatch\"),\n REQUIRED_FIELD_NOT_PRESENT(\"BDE_0005\", \"required.field.not.present\"),\n REQUIRED_ATTRIBUTE_NOT_PRESENT(\"BDE_0006\", \"required.attribute.not.present\"),\n DUPLICATE_FIELD(\"BDE_0007\", \"duplicate.field\"),\n FOUND_ARRAY_FOR_NON_ARRAY_TYPE(\"BDE_0008\", \"found.array.for.non.array.type\"),\n EXPECTED_ANYDATA_OR_JSON(\"BDE_0009\", \"expected.anydata.or.json\"),\n NAMESPACE_MISMATCH(\"BDE_0010\", \"namespace.mismatch\"),\n TYPE_NAME_MISMATCH_WITH_XML_ELEMENT(\"BDE_0011\", \"type.name.mismatch.with.xml.element\"),\n CAN_NOT_READ_STREAM(\"BDE_0012\", \"error.cannot.read.stream\"),\n CANNOT_CONVERT_TO_EXPECTED_TYPE(\"BDE_0013\", \"cannot.convert.to.expected.type\"),\n UNSUPPORTED_TYPE(\"BDE_0014\", \"unsupported.type\"),\n STREAM_BROKEN(\"BDE_0015\", \"stream.broken\"),\n XML_PARSE_ERROR(\"BDE_0016\", \"xml.parse.error\");\n\n String diagnosticId;\n String messageKey;\n\n DiagnosticErrorCode(String diagnosticId, String messageKey) {\n this.diagnosticId = diagnosticId;\n this.messageKey = messageKey;\n }\n\n public String messageKey() {\n return messageKey;\n }\n}" }, { "identifier": "DiagnosticLog", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticLog.java", "snippet": "public class DiagnosticLog {\n private static final String ERROR_PREFIX = \"error\";\n private static final String ERROR = \"Error\";\n private static final ResourceBundle MESSAGES = ResourceBundle.getBundle(\"error\", Locale.getDefault());\n\n public static BError error(DiagnosticErrorCode code, Object... args) {\n String msg = formatMessage(code, args);\n return getXmlError(msg);\n }\n\n private static String formatMessage(DiagnosticErrorCode code, Object[] args) {\n String msgKey = MESSAGES.getString(ERROR_PREFIX + \".\" + code.messageKey());\n return MessageFormat.format(msgKey, args);\n }\n\n public static BError getXmlError(String message) {\n return ErrorCreator.createError(ModuleUtils.getModule(), ERROR, StringUtils.fromString(message),\n null, null);\n }\n}" } ]
import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.Field; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.RecordType; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import io.ballerina.stdlib.data.xmldata.FromString; import io.ballerina.stdlib.data.xmldata.utils.Constants; import io.ballerina.stdlib.data.xmldata.utils.DataUtils; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; import java.io.Reader; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Stack; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.DTD; import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.PROCESSING_INSTRUCTION; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
10,148
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. 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 io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml string to a ballerina record. * * @since 0.1.0 */ public class XmlParser { // XMLInputFactory2 private static final XMLInputFactory xmlInputFactory; static { xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } private XMLStreamReader xmlStreamReader; public static final String PARSE_ERROR = "failed to parse xml"; public static final String PARSE_ERROR_PREFIX = PARSE_ERROR + ": "; public XmlParser(Reader stringReader) { try { xmlStreamReader = xmlInputFactory.createXMLStreamReader(stringReader); } catch (XMLStreamException e) { handleXMLStreamException(e); } } public static Object parse(Reader reader, Type type) { try { XmlParserData xmlParserData = new XmlParserData(); XmlParser xmlParser = new XmlParser(reader); return xmlParser.parse(type, xmlParserData); } catch (BError e) { return e; } catch (Throwable e) {
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. 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 io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml string to a ballerina record. * * @since 0.1.0 */ public class XmlParser { // XMLInputFactory2 private static final XMLInputFactory xmlInputFactory; static { xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } private XMLStreamReader xmlStreamReader; public static final String PARSE_ERROR = "failed to parse xml"; public static final String PARSE_ERROR_PREFIX = PARSE_ERROR + ": "; public XmlParser(Reader stringReader) { try { xmlStreamReader = xmlInputFactory.createXMLStreamReader(stringReader); } catch (XMLStreamException e) { handleXMLStreamException(e); } } public static Object parse(Reader reader, Type type) { try { XmlParserData xmlParserData = new XmlParserData(); XmlParser xmlParser = new XmlParser(reader); return xmlParser.parse(type, xmlParserData); } catch (BError e) { return e; } catch (Throwable e) {
return DiagnosticLog.error(DiagnosticErrorCode.XML_PARSE_ERROR, e.getMessage());
3
2023-11-08 04:13:52+00:00
12k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleTankDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 30;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ANG_ACCEL = Math.toRadians(90);" }, { "identifier": "MAX_ANG_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ANG_VEL = Math.toRadians(90);" }, { "identifier": "MAX_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_VEL = 30;" }, { "identifier": "MOTOR_VELO_PID", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static PIDFCoefficients MOTOR_VELO_PID = new PIDFCoefficients(0, 0, 0,\n getMotorVelocityF(MAX_RPM / 60 * TICKS_PER_REV));" }, { "identifier": "RUN_USING_ENCODER", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static final boolean RUN_USING_ENCODER = false;" }, { "identifier": "TRACK_WIDTH", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double TRACK_WIDTH = 9.92126; // in" }, { "identifier": "encoderTicksToInches", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double encoderTicksToInches(double ticks) {\n return WHEEL_RADIUS * 2 * Math.PI * GEAR_RATIO * ticks / TICKS_PER_REV;\n}" }, { "identifier": "kA", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double kA = .00004;" }, { "identifier": "kStatic", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double kStatic = .066;" }, { "identifier": "kV", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double kV = .01120;" }, { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> sequenceList) {\n if (sequenceList.size() == 0) throw new EmptySequenceException();\n\n this.sequenceList = Collections.unmodifiableList(sequenceList);\n }\n\n public Pose2d start() {\n return sequenceList.get(0).getStartPose();\n }\n\n public Pose2d end() {\n return sequenceList.get(sequenceList.size() - 1).getEndPose();\n }\n\n public double duration() {\n double total = 0.0;\n\n for (SequenceSegment segment : sequenceList) {\n total += segment.getDuration();\n }\n\n return total;\n }\n\n public SequenceSegment get(int i) {\n return sequenceList.get(i);\n }\n\n public int size() {\n return sequenceList.size();\n }\n}" }, { "identifier": "TrajectorySequenceBuilder", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/trajectorysequence/TrajectorySequenceBuilder.java", "snippet": "public class TrajectorySequenceBuilder {\n private final double resolution = 0.25;\n\n private final TrajectoryVelocityConstraint baseVelConstraint;\n private final TrajectoryAccelerationConstraint baseAccelConstraint;\n\n private TrajectoryVelocityConstraint currentVelConstraint;\n private TrajectoryAccelerationConstraint currentAccelConstraint;\n\n private final double baseTurnConstraintMaxAngVel;\n private final double baseTurnConstraintMaxAngAccel;\n\n private double currentTurnConstraintMaxAngVel;\n private double currentTurnConstraintMaxAngAccel;\n\n private final List<SequenceSegment> sequenceSegments;\n\n private final List<TemporalMarker> temporalMarkers;\n private final List<DisplacementMarker> displacementMarkers;\n private final List<SpatialMarker> spatialMarkers;\n\n private Pose2d lastPose;\n\n private double tangentOffset;\n\n private boolean setAbsoluteTangent;\n private double absoluteTangent;\n\n private TrajectoryBuilder currentTrajectoryBuilder;\n\n private double currentDuration;\n private double currentDisplacement;\n\n private double lastDurationTraj;\n private double lastDisplacementTraj;\n\n public TrajectorySequenceBuilder(\n Pose2d startPose,\n Double startTangent,\n TrajectoryVelocityConstraint baseVelConstraint,\n TrajectoryAccelerationConstraint baseAccelConstraint,\n double baseTurnConstraintMaxAngVel,\n double baseTurnConstraintMaxAngAccel\n ) {\n this.baseVelConstraint = baseVelConstraint;\n this.baseAccelConstraint = baseAccelConstraint;\n\n this.currentVelConstraint = baseVelConstraint;\n this.currentAccelConstraint = baseAccelConstraint;\n\n this.baseTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.baseTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n sequenceSegments = new ArrayList<>();\n\n temporalMarkers = new ArrayList<>();\n displacementMarkers = new ArrayList<>();\n spatialMarkers = new ArrayList<>();\n\n lastPose = startPose;\n\n tangentOffset = 0.0;\n\n setAbsoluteTangent = (startTangent != null);\n absoluteTangent = startTangent != null ? startTangent : 0.0;\n\n currentTrajectoryBuilder = null;\n\n currentDuration = 0.0;\n currentDisplacement = 0.0;\n\n lastDurationTraj = 0.0;\n lastDisplacementTraj = 0.0;\n }\n\n public TrajectorySequenceBuilder(\n Pose2d startPose,\n TrajectoryVelocityConstraint baseVelConstraint,\n TrajectoryAccelerationConstraint baseAccelConstraint,\n double baseTurnConstraintMaxAngVel,\n double baseTurnConstraintMaxAngAccel\n ) {\n this(\n startPose, null,\n baseVelConstraint, baseAccelConstraint,\n baseTurnConstraintMaxAngVel, baseTurnConstraintMaxAngAccel\n );\n }\n\n public TrajectorySequenceBuilder lineTo(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineTo(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToConstantHeading(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToConstantHeading(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToLinearHeading(Pose2d endPose) {\n return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToLinearHeading(\n Pose2d endPose,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToSplineHeading(Pose2d endPose) {\n return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToSplineHeading(\n Pose2d endPose,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeTo(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeTo(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder forward(double distance) {\n return addPath(() -> currentTrajectoryBuilder.forward(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder forward(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.forward(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder back(double distance) {\n return addPath(() -> currentTrajectoryBuilder.back(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder back(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.back(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeLeft(double distance) {\n return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeLeft(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeRight(double distance) {\n return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeRight(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineTo(Vector2d endPosition, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineTo(\n Vector2d endPosition,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToConstantHeading(Vector2d endPosition, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToConstantHeading(\n Vector2d endPosition,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToLinearHeading(Pose2d endPose, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToLinearHeading(\n Pose2d endPose,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToSplineHeading(Pose2d endPose, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToSplineHeading(\n Pose2d endPose,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, velConstraint, accelConstraint));\n }\n\n private TrajectorySequenceBuilder addPath(AddPathCallback callback) {\n if (currentTrajectoryBuilder == null) newPath();\n\n try {\n callback.run();\n } catch (PathContinuityViolationException e) {\n newPath();\n callback.run();\n }\n\n Trajectory builtTraj = currentTrajectoryBuilder.build();\n\n double durationDifference = builtTraj.duration() - lastDurationTraj;\n double displacementDifference = builtTraj.getPath().length() - lastDisplacementTraj;\n\n lastPose = builtTraj.end();\n currentDuration += durationDifference;\n currentDisplacement += displacementDifference;\n\n lastDurationTraj = builtTraj.duration();\n lastDisplacementTraj = builtTraj.getPath().length();\n\n return this;\n }\n\n public TrajectorySequenceBuilder setTangent(double tangent) {\n setAbsoluteTangent = true;\n absoluteTangent = tangent;\n\n pushPath();\n\n return this;\n }\n\n private TrajectorySequenceBuilder setTangentOffset(double offset) {\n setAbsoluteTangent = false;\n\n this.tangentOffset = offset;\n this.pushPath();\n\n return this;\n }\n\n public TrajectorySequenceBuilder setReversed(boolean reversed) {\n return reversed ? this.setTangentOffset(Math.toRadians(180.0)) : this.setTangentOffset(0.0);\n }\n\n public TrajectorySequenceBuilder setConstraints(\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n this.currentVelConstraint = velConstraint;\n this.currentAccelConstraint = accelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetConstraints() {\n this.currentVelConstraint = this.baseVelConstraint;\n this.currentAccelConstraint = this.baseAccelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) {\n this.currentVelConstraint = velConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetVelConstraint() {\n this.currentVelConstraint = this.baseVelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) {\n this.currentAccelConstraint = accelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetAccelConstraint() {\n this.currentAccelConstraint = this.baseAccelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) {\n this.currentTurnConstraintMaxAngVel = maxAngVel;\n this.currentTurnConstraintMaxAngAccel = maxAngAccel;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetTurnConstraint() {\n this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n return this;\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) {\n return this.addTemporalMarker(currentDuration, callback);\n }\n\n public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) {\n return this.addTemporalMarker(currentDuration + offset, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) {\n return this.addTemporalMarker(0.0, time, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) {\n return this.addTemporalMarker(time -> scale * time + offset, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) {\n this.temporalMarkers.add(new TemporalMarker(time, callback));\n return this;\n }\n\n public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) {\n this.spatialMarkers.add(new SpatialMarker(point, callback));\n return this;\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) {\n return this.addDisplacementMarker(currentDisplacement, callback);\n }\n\n public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) {\n return this.addDisplacementMarker(currentDisplacement + offset, callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) {\n return this.addDisplacementMarker(0.0, displacement, callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) {\n return addDisplacementMarker((displacement -> scale * displacement + offset), callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) {\n displacementMarkers.add(new DisplacementMarker(displacement, callback));\n\n return this;\n }\n\n public TrajectorySequenceBuilder turn(double angle) {\n return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel);\n }\n\n public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) {\n pushPath();\n\n MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile(\n new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0),\n new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0),\n maxAngVel,\n maxAngAccel\n );\n\n sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList()));\n\n lastPose = new Pose2d(\n lastPose.getX(), lastPose.getY(),\n Angle.norm(lastPose.getHeading() + angle)\n );\n\n currentDuration += turnProfile.duration();\n\n return this;\n }\n\n public TrajectorySequenceBuilder waitSeconds(double seconds) {\n pushPath();\n sequenceSegments.add(new WaitSegment(lastPose, seconds, Collections.emptyList()));\n\n currentDuration += seconds;\n return this;\n }\n\n public TrajectorySequenceBuilder addTrajectory(Trajectory trajectory) {\n pushPath();\n\n sequenceSegments.add(new TrajectorySegment(trajectory));\n return this;\n }\n\n private void pushPath() {\n if (currentTrajectoryBuilder != null) {\n Trajectory builtTraj = currentTrajectoryBuilder.build();\n sequenceSegments.add(new TrajectorySegment(builtTraj));\n }\n\n currentTrajectoryBuilder = null;\n }\n\n private void newPath() {\n if (currentTrajectoryBuilder != null)\n pushPath();\n\n lastDurationTraj = 0.0;\n lastDisplacementTraj = 0.0;\n\n double tangent = setAbsoluteTangent ? absoluteTangent : Angle.norm(lastPose.getHeading() + tangentOffset);\n\n currentTrajectoryBuilder = new TrajectoryBuilder(lastPose, tangent, currentVelConstraint, currentAccelConstraint, resolution);\n }\n\n public TrajectorySequence build() {\n pushPath();\n\n List<TrajectoryMarker> globalMarkers = convertMarkersToGlobal(\n sequenceSegments,\n temporalMarkers, displacementMarkers, spatialMarkers\n );\n\n return new TrajectorySequence(projectGlobalMarkersToLocalSegments(globalMarkers, sequenceSegments));\n }\n\n private List<TrajectoryMarker> convertMarkersToGlobal(\n List<SequenceSegment> sequenceSegments,\n List<TemporalMarker> temporalMarkers,\n List<DisplacementMarker> displacementMarkers,\n List<SpatialMarker> spatialMarkers\n ) {\n ArrayList<TrajectoryMarker> trajectoryMarkers = new ArrayList<>();\n\n // Convert temporal markers\n for (TemporalMarker marker : temporalMarkers) {\n trajectoryMarkers.add(\n new TrajectoryMarker(marker.getProducer().produce(currentDuration), marker.getCallback())\n );\n }\n\n // Convert displacement markers\n for (DisplacementMarker marker : displacementMarkers) {\n double time = displacementToTime(\n sequenceSegments,\n marker.getProducer().produce(currentDisplacement)\n );\n\n trajectoryMarkers.add(\n new TrajectoryMarker(\n time,\n marker.getCallback()\n )\n );\n }\n\n // Convert spatial markers\n for (SpatialMarker marker : spatialMarkers) {\n trajectoryMarkers.add(\n new TrajectoryMarker(\n pointToTime(sequenceSegments, marker.getPoint()),\n marker.getCallback()\n )\n );\n }\n\n return trajectoryMarkers;\n }\n\n private List<SequenceSegment> projectGlobalMarkersToLocalSegments(List<TrajectoryMarker> markers, List<SequenceSegment> sequenceSegments) {\n if (sequenceSegments.isEmpty()) return Collections.emptyList();\n\n markers.sort(Comparator.comparingDouble(TrajectoryMarker::getTime));\n\n int segmentIndex = 0;\n double currentTime = 0;\n\n for (TrajectoryMarker marker : markers) {\n SequenceSegment segment = null;\n\n double markerTime = marker.getTime();\n double segmentOffsetTime = 0;\n\n while (segmentIndex < sequenceSegments.size()) {\n SequenceSegment seg = sequenceSegments.get(segmentIndex);\n\n if (currentTime + seg.getDuration() >= markerTime) {\n segment = seg;\n segmentOffsetTime = markerTime - currentTime;\n break;\n } else {\n currentTime += seg.getDuration();\n segmentIndex++;\n }\n }\n if (segmentIndex >= sequenceSegments.size()) {\n segment = sequenceSegments.get(sequenceSegments.size()-1);\n segmentOffsetTime = segment.getDuration();\n }\n\n SequenceSegment newSegment = null;\n\n if (segment instanceof WaitSegment) {\n WaitSegment thisSegment = (WaitSegment) segment;\n \n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new WaitSegment(thisSegment.getStartPose(), thisSegment.getDuration(), newMarkers);\n } else if (segment instanceof TurnSegment) {\n TurnSegment thisSegment = (TurnSegment) segment;\n \n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new TurnSegment(thisSegment.getStartPose(), thisSegment.getTotalRotation(), thisSegment.getMotionProfile(), newMarkers);\n } else if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getTrajectory().getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new TrajectorySegment(new Trajectory(thisSegment.getTrajectory().getPath(), thisSegment.getTrajectory().getProfile(), newMarkers));\n }\n\n sequenceSegments.set(segmentIndex, newSegment);\n }\n\n return sequenceSegments;\n }\n\n // Taken from Road Runner's TrajectoryGenerator.displacementToTime() since it's private\n // note: this assumes that the profile position is monotonic increasing\n private Double motionProfileDisplacementToTime(MotionProfile profile, double s) {\n double tLo = 0.0;\n double tHi = profile.duration();\n while (!(Math.abs(tLo - tHi) < 1e-6)) {\n double tMid = 0.5 * (tLo + tHi);\n if (profile.get(tMid).getX() > s) {\n tHi = tMid;\n } else {\n tLo = tMid;\n }\n }\n return 0.5 * (tLo + tHi);\n }\n\n private Double displacementToTime(List<SequenceSegment> sequenceSegments, double s) {\n double currentTime = 0.0;\n double currentDisplacement = 0.0;\n\n for (SequenceSegment segment : sequenceSegments) {\n if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n double segmentLength = thisSegment.getTrajectory().getPath().length();\n\n if (currentDisplacement + segmentLength > s) {\n double target = s - currentDisplacement;\n double timeInSegment = motionProfileDisplacementToTime(\n thisSegment.getTrajectory().getProfile(),\n target\n );\n\n return currentTime + timeInSegment;\n } else {\n currentDisplacement += segmentLength;\n currentTime += thisSegment.getTrajectory().duration();\n }\n } else {\n currentTime += segment.getDuration();\n }\n }\n\n return 0.0;\n }\n\n private Double pointToTime(List<SequenceSegment> sequenceSegments, Vector2d point) {\n class ComparingPoints {\n private final double distanceToPoint;\n private final double totalDisplacement;\n private final double thisPathDisplacement;\n\n public ComparingPoints(double distanceToPoint, double totalDisplacement, double thisPathDisplacement) {\n this.distanceToPoint = distanceToPoint;\n this.totalDisplacement = totalDisplacement;\n this.thisPathDisplacement = thisPathDisplacement;\n }\n }\n\n List<ComparingPoints> projectedPoints = new ArrayList<>();\n\n for (SequenceSegment segment : sequenceSegments) {\n if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n double displacement = thisSegment.getTrajectory().getPath().project(point, 0.25);\n Vector2d projectedPoint = thisSegment.getTrajectory().getPath().get(displacement).vec();\n double distanceToPoint = point.minus(projectedPoint).norm();\n\n double totalDisplacement = 0.0;\n\n for (ComparingPoints comparingPoint : projectedPoints) {\n totalDisplacement += comparingPoint.totalDisplacement;\n }\n\n totalDisplacement += displacement;\n\n projectedPoints.add(new ComparingPoints(distanceToPoint, displacement, totalDisplacement));\n }\n }\n\n ComparingPoints closestPoint = null;\n\n for (ComparingPoints comparingPoint : projectedPoints) {\n if (closestPoint == null) {\n closestPoint = comparingPoint;\n continue;\n }\n\n if (comparingPoint.distanceToPoint < closestPoint.distanceToPoint)\n closestPoint = comparingPoint;\n }\n\n return displacementToTime(sequenceSegments, closestPoint.thisPathDisplacement);\n }\n\n private interface AddPathCallback {\n void run();\n }\n}" }, { "identifier": "TrajectorySequenceRunner", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/trajectorysequence/TrajectorySequenceRunner.java", "snippet": "@Config\npublic class TrajectorySequenceRunner {\n public static String COLOR_INACTIVE_TRAJECTORY = \"#4caf507a\";\n public static String COLOR_INACTIVE_TURN = \"#7c4dff7a\";\n public static String COLOR_INACTIVE_WAIT = \"#dd2c007a\";\n\n public static String COLOR_ACTIVE_TRAJECTORY = \"#4CAF50\";\n public static String COLOR_ACTIVE_TURN = \"#7c4dff\";\n public static String COLOR_ACTIVE_WAIT = \"#dd2c00\";\n\n public static int POSE_HISTORY_LIMIT = 100;\n\n private final TrajectoryFollower follower;\n\n private final PIDFController turnController;\n\n private final NanoClock clock;\n\n private TrajectorySequence currentTrajectorySequence;\n private double currentSegmentStartTime;\n private int currentSegmentIndex;\n private int lastSegmentIndex;\n\n private Pose2d lastPoseError = new Pose2d();\n\n List<TrajectoryMarker> remainingMarkers = new ArrayList<>();\n\n private final FtcDashboard dashboard;\n private final LinkedList<Pose2d> poseHistory = new LinkedList<>();\n\n private VoltageSensor voltageSensor;\n\n private List<Integer> lastDriveEncPositions, lastDriveEncVels, lastTrackingEncPositions, lastTrackingEncVels;\n\n public TrajectorySequenceRunner(\n TrajectoryFollower follower, PIDCoefficients headingPIDCoefficients, VoltageSensor voltageSensor,\n List<Integer> lastDriveEncPositions, List<Integer> lastDriveEncVels, List<Integer> lastTrackingEncPositions, List<Integer> lastTrackingEncVels\n ) {\n this.follower = follower;\n\n turnController = new PIDFController(headingPIDCoefficients);\n turnController.setInputBounds(0, 2 * Math.PI);\n\n this.voltageSensor = voltageSensor;\n\n this.lastDriveEncPositions = lastDriveEncPositions;\n this.lastDriveEncVels = lastDriveEncVels;\n this.lastTrackingEncPositions = lastTrackingEncPositions;\n this.lastTrackingEncVels = lastTrackingEncVels;\n\n clock = NanoClock.system();\n\n dashboard = FtcDashboard.getInstance();\n dashboard.setTelemetryTransmissionInterval(25);\n }\n\n public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {\n currentTrajectorySequence = trajectorySequence;\n currentSegmentStartTime = clock.seconds();\n currentSegmentIndex = 0;\n lastSegmentIndex = -1;\n }\n\n public @Nullable\n DriveSignal update(Pose2d poseEstimate, Pose2d poseVelocity) {\n Pose2d targetPose = null;\n DriveSignal driveSignal = null;\n\n TelemetryPacket packet = new TelemetryPacket();\n Canvas fieldOverlay = packet.fieldOverlay();\n\n SequenceSegment currentSegment = null;\n\n if (currentTrajectorySequence != null) {\n if (currentSegmentIndex >= currentTrajectorySequence.size()) {\n for (TrajectoryMarker marker : remainingMarkers) {\n marker.getCallback().onMarkerReached();\n }\n\n remainingMarkers.clear();\n\n currentTrajectorySequence = null;\n }\n\n if (currentTrajectorySequence == null)\n return new DriveSignal();\n\n double now = clock.seconds();\n boolean isNewTransition = currentSegmentIndex != lastSegmentIndex;\n\n currentSegment = currentTrajectorySequence.get(currentSegmentIndex);\n\n if (isNewTransition) {\n currentSegmentStartTime = now;\n lastSegmentIndex = currentSegmentIndex;\n\n for (TrajectoryMarker marker : remainingMarkers) {\n marker.getCallback().onMarkerReached();\n }\n\n remainingMarkers.clear();\n\n remainingMarkers.addAll(currentSegment.getMarkers());\n Collections.sort(remainingMarkers, (t1, t2) -> Double.compare(t1.getTime(), t2.getTime()));\n }\n\n double deltaTime = now - currentSegmentStartTime;\n\n if (currentSegment instanceof TrajectorySegment) {\n Trajectory currentTrajectory = ((TrajectorySegment) currentSegment).getTrajectory();\n\n if (isNewTransition)\n follower.followTrajectory(currentTrajectory);\n\n if (!follower.isFollowing()) {\n currentSegmentIndex++;\n\n driveSignal = new DriveSignal();\n } else {\n driveSignal = follower.update(poseEstimate, poseVelocity);\n lastPoseError = follower.getLastError();\n }\n\n targetPose = currentTrajectory.get(deltaTime);\n } else if (currentSegment instanceof TurnSegment) {\n MotionState targetState = ((TurnSegment) currentSegment).getMotionProfile().get(deltaTime);\n\n turnController.setTargetPosition(targetState.getX());\n\n double correction = turnController.update(poseEstimate.getHeading());\n\n double targetOmega = targetState.getV();\n double targetAlpha = targetState.getA();\n\n lastPoseError = new Pose2d(0, 0, turnController.getLastError());\n\n Pose2d startPose = currentSegment.getStartPose();\n targetPose = startPose.copy(startPose.getX(), startPose.getY(), targetState.getX());\n\n driveSignal = new DriveSignal(\n new Pose2d(0, 0, targetOmega + correction),\n new Pose2d(0, 0, targetAlpha)\n );\n\n if (deltaTime >= currentSegment.getDuration()) {\n currentSegmentIndex++;\n driveSignal = new DriveSignal();\n }\n } else if (currentSegment instanceof WaitSegment) {\n lastPoseError = new Pose2d();\n\n targetPose = currentSegment.getStartPose();\n driveSignal = new DriveSignal();\n\n if (deltaTime >= currentSegment.getDuration()) {\n currentSegmentIndex++;\n }\n }\n\n while (remainingMarkers.size() > 0 && deltaTime > remainingMarkers.get(0).getTime()) {\n remainingMarkers.get(0).getCallback().onMarkerReached();\n remainingMarkers.remove(0);\n }\n }\n\n poseHistory.add(poseEstimate);\n\n if (POSE_HISTORY_LIMIT > -1 && poseHistory.size() > POSE_HISTORY_LIMIT) {\n poseHistory.removeFirst();\n }\n\n final double NOMINAL_VOLTAGE = 12.0;\n double voltage = voltageSensor.getVoltage();\n if (driveSignal != null && !DriveConstants.RUN_USING_ENCODER) {\n driveSignal = new DriveSignal(\n driveSignal.getVel().times(NOMINAL_VOLTAGE / voltage),\n driveSignal.getAccel().times(NOMINAL_VOLTAGE / voltage)\n );\n }\n\n if (targetPose != null) {\n// LogFiles.record(\n// targetPose, poseEstimate, voltage,\n// lastDriveEncPositions, lastDriveEncVels, lastTrackingEncPositions, lastTrackingEncVels\n// );\n }\n\n packet.put(\"x\", poseEstimate.getX());\n packet.put(\"y\", poseEstimate.getY());\n packet.put(\"heading (deg)\", Math.toDegrees(poseEstimate.getHeading()));\n\n packet.put(\"xError\", getLastPoseError().getX());\n packet.put(\"yError\", getLastPoseError().getY());\n packet.put(\"headingError (deg)\", Math.toDegrees(getLastPoseError().getHeading()));\n\n draw(fieldOverlay, currentTrajectorySequence, currentSegment, targetPose, poseEstimate);\n\n dashboard.sendTelemetryPacket(packet);\n\n return driveSignal;\n }\n\n private void draw(\n Canvas fieldOverlay,\n TrajectorySequence sequence, SequenceSegment currentSegment,\n Pose2d targetPose, Pose2d poseEstimate\n ) {\n if (sequence != null) {\n for (int i = 0; i < sequence.size(); i++) {\n SequenceSegment segment = sequence.get(i);\n\n if (segment instanceof TrajectorySegment) {\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_INACTIVE_TRAJECTORY);\n\n DashboardUtil.drawSampledPath(fieldOverlay, ((TrajectorySegment) segment).getTrajectory().getPath());\n } else if (segment instanceof TurnSegment) {\n Pose2d pose = segment.getStartPose();\n\n fieldOverlay.setFill(COLOR_INACTIVE_TURN);\n fieldOverlay.fillCircle(pose.getX(), pose.getY(), 2);\n } else if (segment instanceof WaitSegment) {\n Pose2d pose = segment.getStartPose();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_INACTIVE_WAIT);\n fieldOverlay.strokeCircle(pose.getX(), pose.getY(), 3);\n }\n }\n }\n\n if (currentSegment != null) {\n if (currentSegment instanceof TrajectorySegment) {\n Trajectory currentTrajectory = ((TrajectorySegment) currentSegment).getTrajectory();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_ACTIVE_TRAJECTORY);\n\n DashboardUtil.drawSampledPath(fieldOverlay, currentTrajectory.getPath());\n } else if (currentSegment instanceof TurnSegment) {\n Pose2d pose = currentSegment.getStartPose();\n\n fieldOverlay.setFill(COLOR_ACTIVE_TURN);\n fieldOverlay.fillCircle(pose.getX(), pose.getY(), 3);\n } else if (currentSegment instanceof WaitSegment) {\n Pose2d pose = currentSegment.getStartPose();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_ACTIVE_WAIT);\n fieldOverlay.strokeCircle(pose.getX(), pose.getY(), 3);\n }\n }\n\n if (targetPose != null) {\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(\"#4CAF50\");\n DashboardUtil.drawRobot(fieldOverlay, targetPose);\n }\n\n fieldOverlay.setStroke(\"#3F51B5\");\n DashboardUtil.drawPoseHistory(fieldOverlay, poseHistory);\n\n fieldOverlay.setStroke(\"#3F51B5\");\n DashboardUtil.drawRobot(fieldOverlay, poseEstimate);\n }\n\n public Pose2d getLastPoseError() {\n return lastPoseError;\n }\n\n public boolean isBusy() {\n return currentTrajectorySequence != null;\n }\n}" }, { "identifier": "LynxModuleUtil", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/util/LynxModuleUtil.java", "snippet": "public class LynxModuleUtil {\n\n private static final LynxFirmwareVersion MIN_VERSION = new LynxFirmwareVersion(1, 8, 2);\n\n /**\n * Parsed representation of a Lynx module firmware version.\n */\n public static class LynxFirmwareVersion implements Comparable<LynxFirmwareVersion> {\n public final int major;\n public final int minor;\n public final int eng;\n\n public LynxFirmwareVersion(int major, int minor, int eng) {\n this.major = major;\n this.minor = minor;\n this.eng = eng;\n }\n\n @Override\n public boolean equals(Object other) {\n if (other instanceof LynxFirmwareVersion) {\n LynxFirmwareVersion otherVersion = (LynxFirmwareVersion) other;\n return major == otherVersion.major && minor == otherVersion.minor &&\n eng == otherVersion.eng;\n } else {\n return false;\n }\n }\n\n @Override\n public int compareTo(LynxFirmwareVersion other) {\n int majorComp = Integer.compare(major, other.major);\n if (majorComp == 0) {\n int minorComp = Integer.compare(minor, other.minor);\n if (minorComp == 0) {\n return Integer.compare(eng, other.eng);\n } else {\n return minorComp;\n }\n } else {\n return majorComp;\n }\n }\n\n @Override\n public String toString() {\n return Misc.formatInvariant(\"%d.%d.%d\", major, minor, eng);\n }\n }\n\n /**\n * Retrieve and parse Lynx module firmware version.\n * @param module Lynx module\n * @return parsed firmware version\n */\n public static LynxFirmwareVersion getFirmwareVersion(LynxModule module) {\n String versionString = module.getNullableFirmwareVersionString();\n if (versionString == null) {\n return null;\n }\n\n String[] parts = versionString.split(\"[ :,]+\");\n try {\n // note: for now, we ignore the hardware entry\n return new LynxFirmwareVersion(\n Integer.parseInt(parts[3]),\n Integer.parseInt(parts[5]),\n Integer.parseInt(parts[7])\n );\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n /**\n * Exception indicating an outdated Lynx firmware version.\n */\n public static class LynxFirmwareVersionException extends RuntimeException {\n public LynxFirmwareVersionException(String detailMessage) {\n super(detailMessage);\n }\n }\n\n /**\n * Ensure all of the Lynx modules attached to the robot satisfy the minimum requirement.\n * @param hardwareMap hardware map containing Lynx modules\n */\n public static void ensureMinimumFirmwareVersion(HardwareMap hardwareMap) {\n Map<String, LynxFirmwareVersion> outdatedModules = new HashMap<>();\n for (LynxModule module : hardwareMap.getAll(LynxModule.class)) {\n LynxFirmwareVersion version = getFirmwareVersion(module);\n if (version == null || version.compareTo(MIN_VERSION) < 0) {\n for (String name : hardwareMap.getNamesOf(module)) {\n outdatedModules.put(name, version);\n }\n }\n }\n if (outdatedModules.size() > 0) {\n StringBuilder msgBuilder = new StringBuilder();\n msgBuilder.append(\"One or more of the attached Lynx modules has outdated firmware\\n\");\n msgBuilder.append(Misc.formatInvariant(\"Mandatory minimum firmware version for Road Runner: %s\\n\",\n MIN_VERSION.toString()));\n for (Map.Entry<String, LynxFirmwareVersion> entry : outdatedModules.entrySet()) {\n msgBuilder.append(Misc.formatInvariant(\n \"\\t%s: %s\\n\", entry.getKey(),\n entry.getValue() == null ? \"Unknown\" : entry.getValue().toString()));\n }\n throw new LynxFirmwareVersionException(msgBuilder.toString());\n }\n }\n}" } ]
import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.TankDrive; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.roadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,774
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner;
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner;
private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
6
2023-11-06 21:25:54+00:00
12k
celedev97/asa-server-manager
src/main/java/dev/cele/asa_sm/ui/components/ServerTab.java
[ { "identifier": "Const", "path": "src/main/java/dev/cele/asa_sm/Const.java", "snippet": "public final class Const {\n public final static String ASA_STEAM_GAME_NUMBER = \"2430930\";\n\n public final static Path DATA_DIR = Path.of(\"data\");\n public final static Path PROFILES_DIR = DATA_DIR.resolve(\"profiles\");\n public final static Path SERVERS_DIR = Path.of(\"servers\");\n\n\n public final static Path THEME_DIR = DATA_DIR.resolve(\"themes\");\n public final static Path MOD_CACHE_DIR = DATA_DIR.resolve(\"mod_cache\");\n\n public final static Path SETTINGS_FILE = DATA_DIR.resolve(\"settings.json\");\n\n public final static Path TEMP_DIR = SystemUtils.getJavaIoTmpDir().toPath().resolve(\"asa_sm\");\n}" }, { "identifier": "SpringApplicationContext", "path": "src/main/java/dev/cele/asa_sm/config/SpringApplicationContext.java", "snippet": "@Configuration\npublic class SpringApplicationContext implements ApplicationContextAware {\n private static ApplicationContext context;\n\n @Override\n public void setApplicationContext(ApplicationContext context) {\n SpringApplicationContext.context = context;\n }\n\n public static <T> T autoWire(Class<T> java) {\n return context.getBean(java);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T autoWire(String qualifier) {\n return (T) context.getBean(qualifier);\n }\n}" }, { "identifier": "AsaServerConfigDto", "path": "src/main/java/dev/cele/asa_sm/dto/AsaServerConfigDto.java", "snippet": "@Getter\n@Setter\n@FieldNameConstants\n@Slf4j\npublic class AsaServerConfigDto {\n\n //region stuff for management of profiles\n @JsonIgnore\n private Boolean justImported = false;\n private String customInstallPath = null;\n\n public Path getServerPath(){\n if(customInstallPath != null){\n return Path.of(customInstallPath);\n }else{\n return Const.SERVERS_DIR.resolve(guid);\n }\n }\n\n //endregion\n\n //region stuff for the unsaved variable\n @JsonIgnore\n private Boolean unsaved = false;\n public void setUnsaved(Boolean value){\n unsaved = value;\n unsavedChangeListeners.forEach(listener -> listener.accept(value));\n }\n\n @JsonIgnore\n private List<Consumer<Boolean>> unsavedChangeListeners = new ArrayList<>();\n @JsonIgnore\n public void addUnsavedChangeListener(Consumer<Boolean> listener){\n unsavedChangeListeners.add(listener);\n }\n @JsonIgnore\n public void removeUnsavedChangeListener(Consumer<Boolean> listener){\n unsavedChangeListeners.remove(listener);\n }\n //endregion\n\n //region Administration\n private String map = MapsEnum.THE_ISLAND.getMapName();\n private String guid = UUID.randomUUID().toString();\n\n private String profileName = \"Server\";\n private String serverName = \"\";\n\n private String serverPassword = \"\";\n private String serverAdminPassword = \"\";\n private String serverSpectatorPassword = \"\";\n\n private int serverPort = 7777;\n private int serverQueryPort = 27015;\n @ExtraCommandLineArgument(\"WinLiveMaxPlayers\") @IgnoreIfEqual(type = Integer.class, value = \"70\")\n private int serverMaxPlayers = 70;\n\n private Boolean rconEnabled = false;\n private int rconPort = 32330;\n private int rconServerLogBuffer = 600;\n\n @ExtraCommandLineArgument(\"mods\")\n private String modIds = \"\";\n\n @ExtraCommandLineArgument(\"MaxNumOfSaveBackups\") @IgnoreIfEqual(type = Integer.class, value = \"20\")\n private Integer maxBackupQuantity = 20;\n //endregion\n\n\n GameUserSettingsINI gameUserSettingsINI = new GameUserSettingsINI();\n\n\n\n @ExtraCommandLineArgument(value = \"NoBattlEye\", invertBoolean = true)\n private Boolean battlEye = false;\n\n @ExtraCommandLineArgument(\"EnableIdlePlayerKick\")\n private Boolean enableIdlePlayerKick = false;\n\n @ExtraCommandLineArgument(\"culture\")\n private String culture = null;\n\n @ExtraCommandLineArgument(value = \"insecure\")\n private Boolean vacDisabled = false;\n\n @ExtraCommandLineArgument(\"noantispeedhack\")\n private Boolean antiSpeedHackDisabled = false;\n\n @ExtraCommandLineArgument(\"speedhackbias\") @IgnoreIfEqual(type = Double.class, value = \"1.0\")\n private Double speedHackBias = 1.0;\n\n @ExtraCommandLineArgument(\"nocombineclientmoves\")\n private Boolean disablePlayerMovePhysicsOptimization = false;\n\n @ExtraCommandLineArgument(\"servergamelog\")\n private Boolean serverGameLog = false;\n\n @ExtraCommandLineArgument(\"NoHangDetection\")\n private Boolean disableHangDetection = false;\n\n @ExtraCommandLineArgument(\"nodinos\")\n private Boolean disableDinos = false;\n\n @ExtraCommandLineArgument(\"noundermeshchecking\")\n private Boolean noUnderMeshChecking = false;\n\n @ExtraCommandLineArgument(\"noundermeshkilling\")\n private Boolean noUnderMeshKilling = false;\n\n @ExtraCommandLineArgument(\"AllowSharedConnections\")\n private Boolean allowSharedConnections = false;\n\n @ExtraCommandLineArgument(\"SecureSendArKPayload\")\n private Boolean creatureUploadIssueProtection = false;\n\n @ExtraCommandLineArgument(\"UseSecureSpawnRules\")\n private Boolean secureItemDinoSpawnRules = false;\n\n @ExtraCommandLineArgument(\"UseItemDupeCheck\")\n private Boolean additionalDupeProtection = false;\n\n @ExtraCommandLineArgument(\"ForceRespawnDinos\")\n private Boolean forceRespawnDinos = false;\n\n @ExtraCommandLineArgument(\"StasisKeepControllers\")\n private Boolean stasisKeepControllers = false;\n\n @ExtraCommandLineArgument(\"structurememopts\")\n private Boolean structureMemoryOptimizations = false;\n\n @ExtraCommandLineArgument(\"UseStructureStasisGrid\")\n private Boolean useStructureStasisGrid = false;\n\n @ExtraCommandLineArgument(\"servergamelogincludetribelogs\")\n private Boolean serverGameLogIncludeTribeLogs = false;\n\n @ExtraCommandLineArgument(\"ServerRCONOutputTribeLogs\")\n private Boolean serverRCONOutputTribeLogs = false;\n\n @ExtraCommandLineArgument(\"AdminLogging\")\n private Boolean adminLogsToPublicChat = false;\n\n @ExtraCommandLineArgument(\"NotifyAdminCommandsInChat\")\n private Boolean adminLogsToAdminChat = false;\n\n\n private String additionalServerArgs = \"\";\n\n @JsonIgnore\n public String[] getCommand() {\n List<String> mainArgs = new ArrayList<>();\n\n mainArgs.add(map);\n mainArgs.add(\"listen\");\n\n //name and password\n if (!serverName.isEmpty()) mainArgs.add(\"SessionName=\" + serverName);\n\n if (!StringUtils.isEmpty(serverPassword)) mainArgs.add(\"ServerPassword=\" + serverPassword);\n if (!StringUtils.isEmpty(serverAdminPassword)) mainArgs.add(\"ServerAdminPassword=\" + serverAdminPassword);\n if (!StringUtils.isEmpty(serverSpectatorPassword)) mainArgs.add(\"SpectatorPassword=\" + serverSpectatorPassword);\n\n //networking\n if (serverPort != 0) mainArgs.add(\"Port=\" + serverPort);\n if (serverQueryPort != 0) mainArgs.add(\"QueryPort=\" + serverQueryPort);\n\n //TODO: move RCON config to the ini file?\n if (rconEnabled) {\n mainArgs.add(\"RCONEnabled=True\");\n mainArgs.add(\"RCONPort=\" + rconPort);\n mainArgs.add(\"RCONServerGameLogBuffer=\" + rconServerLogBuffer);\n }\n\n\n //extra separate args\n List<String> extraArgs = new ArrayList<>();\n\n var extraArgsFields = Arrays.stream(this.getClass().getDeclaredFields())\n .filter(it -> it.isAnnotationPresent(ExtraCommandLineArgument.class))\n .toList();\n\n for (var field : extraArgsFields) {\n var annotation = field.getAnnotation(ExtraCommandLineArgument.class);\n try {\n var argument = annotation.value().startsWith(\"-\") ? annotation.value() : \"-\" + annotation.value();\n var value = field.get(this);\n\n //check if there's an ignoreIf annotation\n var ignoreIf = field.getAnnotation(IgnoreIfEqual.class);\n if(ignoreIf != null){\n var ignoreIfValue = ignoreIf.value();\n var realValue = field.get(this);\n\n var ignore = false;\n\n ignore = Objects.equals(ignoreIfValue, realValue.toString());\n\n if(ignore) continue;\n }\n\n // if the field is null or empty, skip it\n if (value == null || value.toString().isEmpty()) continue;\n\n if(value instanceof Boolean){\n if(annotation.invertBoolean()) {\n value = !(Boolean) value;\n }\n if((Boolean) value){\n extraArgs.add(argument);\n }\n }else{\n extraArgs.add(argument + \"=\" + value.toString());\n }\n\n } catch (IllegalAccessException e) {\n log.error(\"Error while getting value of field: \" + field.getName(), e);\n }\n }\n\n List<String> finalCommand = new ArrayList<>();\n finalCommand.add(\n getServerPath()\n .resolve(\"ShooterGame/Binaries/Win64/ArkAscendedServer.exe\")\n .toAbsolutePath()\n .toString()\n );\n finalCommand.add(String.join(\"?\", mainArgs));\n finalCommand.addAll(extraArgs);\n\n return finalCommand.toArray(new String[0]);\n }\n\n}" }, { "identifier": "CommandRunnerService", "path": "src/main/java/dev/cele/asa_sm/services/CommandRunnerService.java", "snippet": "@Service\npublic class CommandRunnerService {\n\n private final SimpleLogger logToConsole = new SimpleLogger() {\n private final org.slf4j.Logger logger = LoggerFactory.getLogger(CommandRunnerService.class);\n\n @Override\n public void info(String message) {\n logger.info(message);\n }\n\n @Override\n public void error(String message) {\n logger.error(message);\n }\n };\n\n public ProcessOutputDto runCommand(String... commandAndArgs) {\n return runCommand(logToConsole, commandAndArgs);\n }\n\n public ProcessOutputDto runCommand(SimpleLogger log, String... commandAndArgs) {\n log.info(\"Running command: \" + String.join(\" \", commandAndArgs));\n\n ProcessOutputDto output = new ProcessOutputDto();\n\n ProcessBuilder pb = new ProcessBuilder().command(commandAndArgs);\n Process p = null;\n\n try {\n p = pb.start();\n\n Scanner infoStream = new Scanner(p.getInputStream());\n Scanner errorStream = new Scanner(p.getErrorStream());\n\n StringBuilder fullOutput = new StringBuilder();\n\n Thread threadInfo = new Thread(() -> {\n while (infoStream.hasNextLine()) {\n synchronized (fullOutput) {\n String line = infoStream.nextLine();\n fullOutput.append(line).append(\"\\n\");\n log.info(line);\n }\n }\n });\n\n Thread threadError = new Thread(() -> {\n while (errorStream.hasNextLine()) {\n synchronized (fullOutput) {\n String line = errorStream.nextLine();\n fullOutput.append(line).append(\"\\n\");\n log.error(line);\n }\n }\n });\n\n threadInfo.start();\n threadError.start();\n\n threadInfo.join();\n threadError.join();\n\n output.setExitCode(p.waitFor());\n output.setOutput(fullOutput.toString().trim());\n\n log.info(\"Command finished\");\n return output;\n } catch (InterruptedException e) {\n if (p != null) {\n p.destroy();\n }\n } catch (Exception e) {\n log.error(\"Error running command\", e);\n }\n output.setExitCode(-1);\n return output;\n }\n}" }, { "identifier": "IniSerializerService", "path": "src/main/java/dev/cele/asa_sm/services/IniSerializerService.java", "snippet": "@Service\n@Slf4j\npublic class IniSerializerService {\n\n @SneakyThrows\n public void readIniFile(Object iniDtoObject, File iniFile) {\n\n //use ini4j to read the ini file\n Ini ini = new Ini(iniFile);\n Map<String, Profile.Section> gameUserSettingsMap = ini.entrySet().stream()\n .collect(toMap(it -> it.getKey(), it -> it.getValue()));\n\n //read recognized sections from dto\n var iniDtoClass = iniDtoObject.getClass();\n var allFields = iniDtoClass.getDeclaredFields();\n var sections = Arrays.stream(allFields)\n .filter(field -> {;\n var hasAnnotation = field.isAnnotationPresent(IniSection.class);\n var classHasAnnotation = field.getType().isAnnotationPresent(IniSection.class);\n return hasAnnotation || classHasAnnotation;\n })\n .toList();\n\n //loop over sections\n for(Field sectionField: sections) {\n //finding section info/dto/class\n var sectionName = sectionField.getName();\n if(sectionField.isAnnotationPresent(IniSection.class) && !sectionField.getAnnotation(IniSection.class).value().isEmpty()){\n sectionName = sectionField.getAnnotation(IniSection.class).value();\n }\n if(sectionField.getType().isAnnotationPresent(IniSection.class) && !sectionField.getType().getAnnotation(IniSection.class).value().isEmpty()){\n sectionName = sectionField.getType().getAnnotation(IniSection.class).value();\n }\n\n log.debug(\"== READING SECTION \" + sectionName + \" ==\");\n\n if(!gameUserSettingsMap.containsKey(sectionName)){\n log.debug(sectionName + \"NOT FOUND!\");\n continue;\n }\n\n var sectionIniContent = gameUserSettingsMap.remove(sectionName);\n var sectionFieldClass = sectionField.getType();\n sectionField.setAccessible(true);\n var sectionFieldObject = sectionField.get(iniDtoObject);\n\n var validFields = Arrays.stream(sectionFieldClass.getDeclaredFields()).filter(\n field -> field.isAnnotationPresent(IniValue.class) && !field.isAnnotationPresent(IniExtraMap.class)\n ).toList();\n\n //reading fields inside the sectionField class\n var readFields = new ArrayList<String>();\n for(Field iniField: validFields){\n var fieldName = iniField.isAnnotationPresent(IniValue.class) ? iniField.getAnnotation(IniValue.class).value() : iniField.getName();\n readFields.add(fieldName);\n if(sectionIniContent.containsKey(fieldName)){\n log.info(\"rd: \" + fieldName);\n var fieldValueToSet = sectionIniContent.get(fieldName, iniField.getType());\n log.info(fieldName + \" <= \" + fieldValueToSet);\n iniField.setAccessible(true);\n iniField.set(sectionFieldObject, fieldValueToSet);\n }\n }\n\n //read extra fields from the section\n var extraFieldsFromIni = sectionIniContent.entrySet().stream()\n .filter(it -> !readFields.contains(it.getKey()))\n .collect(Collectors.toMap(it -> it.getKey(), it -> it.getValue()));\n\n var extraFieldsContainer = Arrays.stream(sectionFieldClass.getDeclaredFields())\n .filter(field -> field.isAnnotationPresent(IniExtraMap.class))\n .findFirst();\n\n if(!extraFieldsFromIni.isEmpty() && extraFieldsContainer.isPresent()){\n log.debug(\"Found extra fields container, injecting remaining fields there\");\n\n var extraFieldsContainerField = extraFieldsContainer.get();\n extraFieldsContainerField.setAccessible(true);\n var extraFieldsMap = (Map<String, String>) extraFieldsContainerField.get(sectionFieldObject);\n if(extraFieldsMap == null){\n extraFieldsMap = extraFieldsFromIni;\n }else{\n extraFieldsMap.putAll(extraFieldsFromIni);\n }\n extraFieldsContainerField.set(sectionFieldObject, extraFieldsMap);\n }\n }\n\n log.debug(\"== UNRECOGNIZED SECTIONS == \");\n for(var unrecognizedSection: gameUserSettingsMap.entrySet()){\n log.debug(unrecognizedSection.getKey());\n }\n var extraSectionsContainer = Arrays.stream(iniDtoClass.getDeclaredFields())\n .filter(field -> field.isAnnotationPresent(IniExtraMap.class))\n .findFirst();\n if(extraSectionsContainer.isPresent()){\n Map<String, Map<String, Object>> extraSections = gameUserSettingsMap.entrySet().stream().collect(\n toMap(\n it -> it.getKey(),\n it -> it.getValue().entrySet().stream().collect(toMap(it2 -> it2.getKey(), it2 -> it2.getValue()))\n )\n );\n\n log.debug(\"Found extra sections container, injecting remaining sections there\");\n var extraSectionsContainerField = extraSectionsContainer.get();\n extraSectionsContainerField.setAccessible(true);\n extraSectionsContainerField.set(iniDtoObject, extraSections);\n }\n\n }\n\n\n @SneakyThrows\n public void writeIniFile(Object iniDtoObject, File iniFile) {\n //check if all the folders of the files exist\n if(!iniFile.getParentFile().exists()){\n iniFile.getParentFile().mkdirs();\n }\n\n Ini ini = new Ini();\n\n //read recognized sections from dto\n var iniDtoClass = iniDtoObject.getClass();\n var allFields = iniDtoClass.getDeclaredFields();\n var sections = Arrays.stream(allFields)\n .filter(field -> {;\n var hasAnnotation = field.isAnnotationPresent(IniSection.class);\n var classHasAnnotation = field.getType().isAnnotationPresent(IniSection.class);\n return hasAnnotation || classHasAnnotation;\n })\n .toList();\n\n //loop over sections\n for(Field sectionField: sections) {\n //finding section info/dto/class\n var sectionName = sectionField.getName();\n if (sectionField.isAnnotationPresent(IniSection.class) && !sectionField.getAnnotation(IniSection.class).value().isEmpty()) {\n sectionName = sectionField.getAnnotation(IniSection.class).value();\n }\n if (sectionField.getType().isAnnotationPresent(IniSection.class) && !sectionField.getType().getAnnotation(IniSection.class).value().isEmpty()) {\n sectionName = sectionField.getType().getAnnotation(IniSection.class).value();\n }\n\n var sectionFieldClass = sectionField.getType();\n sectionField.setAccessible(true);\n var sectionFieldObject = sectionField.get(iniDtoObject);\n\n log.debug(\"Writing section \" + sectionName);\n\n var validFields = Arrays.stream(sectionFieldClass.getDeclaredFields()).filter(\n field -> field.isAnnotationPresent(IniValue.class) && !field.isAnnotationPresent(IniExtraMap.class)\n ).toList();\n\n //writing fields inside the sectionField class\n for (Field iniField : validFields) {\n var fieldName = iniField.isAnnotationPresent(IniValue.class) ? iniField.getAnnotation(IniValue.class).value() : iniField.getName();\n iniField.setAccessible(true);\n var fieldValue = iniField.get(sectionFieldObject);\n if (fieldValue != null) {\n log.debug(\"Setting field \" + fieldName + \" to \" + fieldValue);\n ini.put(sectionName, fieldName, fieldValue);\n }\n }\n\n //write extra fields\n var extraFieldsContainer = Arrays.stream(sectionFieldClass.getDeclaredFields())\n .filter(field -> field.isAnnotationPresent(IniExtraMap.class))\n .findFirst();\n\n if(extraFieldsContainer.isPresent()){\n log.debug(\"Found extra fields container, injecting remaining fields there\");\n\n var extraFieldsContainerField = extraFieldsContainer.get();\n extraFieldsContainerField.setAccessible(true);\n var extraFieldsMap = (Map<String, String>) extraFieldsContainerField.get(sectionFieldObject);\n if(extraFieldsMap != null){\n for(var extraField: extraFieldsMap.entrySet()){\n log.debug(\"Setting field \" + extraField.getKey() + \" to \" + extraField.getValue());\n ini.put(sectionName, extraField.getKey(), extraField.getValue());\n }\n }\n }\n\n }\n //write extra sections\n var extraSectionsContainer = Arrays.stream(iniDtoClass.getDeclaredFields())\n .filter(field -> field.isAnnotationPresent(IniExtraMap.class))\n .findFirst();\n if(extraSectionsContainer.isPresent()){\n var extraSectionsContainerField = extraSectionsContainer.get();\n extraSectionsContainerField.setAccessible(true);\n var extraSections = (Map<String, Map<String, Object>>) extraSectionsContainerField.get(iniDtoObject);\n if(extraSections != null){\n for(var extraSection: extraSections.entrySet()){\n log.debug(\"Writing extra section \" + extraSection.getKey());\n for(var extraSectionField: extraSection.getValue().entrySet()){\n log.debug(\"Setting field \" + extraSectionField.getKey() + \" to \" + extraSectionField.getValue());\n ini.put(extraSection.getKey(), extraSectionField.getKey(), extraSectionField.getValue());\n }\n }\n }\n }\n\n ini.store(iniFile);\n }\n\n}" }, { "identifier": "SteamCMDService", "path": "src/main/java/dev/cele/asa_sm/services/SteamCMDService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class SteamCMDService {\n private final Logger logger;\n private final CommandRunnerService commandRunnerService;\n\n private final String WINDOWS_URL = \"https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip\";\n private final Path STEAM_CMD_WIN_FOLDER = Path.of(\"steamcmd\");\n private final File STEAM_CMD_WIN_EXE_FILE = STEAM_CMD_WIN_FOLDER.resolve(\"steamcmd.exe\").toFile();\n\n\n public void checkSteamCMD() {\n logger.info(\"SteamCMDService initialized\");\n //checking for install...\n\n var exists = false;\n\n if(SystemUtils.IS_OS_WINDOWS) {\n exists = STEAM_CMD_WIN_EXE_FILE.exists();\n } else if(SystemUtils.IS_OS_LINUX) {\n var result = commandRunnerService.runCommand(\"which\", \"steamcmd\");\n exists = result.getExitCode() == 0 && result.getOutput().contains(\"steamcmd\");\n } else {\n logger.error(\"Unsupported OS\");\n throw new RuntimeException(\"Unsupported OS\");\n }\n\n if(exists) {\n logger.info(\"SteamCMD already installed\");\n } else {\n logger.info(\"SteamCMD not installed. Installing...\");\n install();\n }\n }\n\n //region SteamCMD Installation\n public void install() {\n if(SystemUtils.IS_OS_WINDOWS){\n windowsInstall();\n }else {\n logger.error(\"Unsupported OS\");\n throw new RuntimeException(\"Unsupported OS\");\n }\n }\n\n @SneakyThrows\n private void windowsInstall() {\n //get a temp dir\n Files.createDirectories(TEMP_DIR);\n\n //region download file from WINDOWS_URL to zipLocation\n logger.info(\"Downloading SteamCMD...\");\n InputStream input = new URL(WINDOWS_URL).openStream();\n var zipLocation = Files.createTempFile(TEMP_DIR, \"steamcmd\", \".zip\");\n\n //download file to temp dir\n var progressFrame = new ProgressFrame(null, \"Downloading SteamCMD\", \"Downloading SteamCMD...\", false);\n progressFrame.launch(pf -> {\n try {\n //download file from input to zipLocation with progress bar\n FileOutputStream output = new FileOutputStream(zipLocation.toFile());\n\n byte[] buffer = new byte[4096];\n int bytesRead;\n long totalBytesRead = 0;\n long fileSize = input.available();\n\n while ((bytesRead = input.read(buffer)) != -1) {\n output.write(buffer, 0, bytesRead);\n totalBytesRead += bytesRead;\n\n progressFrame.setProgress(\n (int) (totalBytesRead * 100 / fileSize)\n );\n logger.info(\"Downloaded \" + totalBytesRead + \" bytes out of \" + fileSize + \" bytes (\" + (totalBytesRead * 100 / fileSize) + \"%)\");\n\n progressFrame.repaint();\n }\n\n input.close();\n output.close();\n }catch (Exception e){\n throw new RuntimeException(e);\n }\n });\n logger.info(\"Download complete. Saved to \"+zipLocation);\n //endregion\n\n //region unzip file\n logger.info(\"Unzipping \"+zipLocation+\" to \"+STEAM_CMD_WIN_FOLDER);\n ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipLocation.toFile()));\n ZipEntry zipEntry;\n while ((zipEntry = zipInputStream.getNextEntry()) != null) {\n var newFile = STEAM_CMD_WIN_FOLDER.resolve(zipEntry.getName());\n\n if (zipEntry.isDirectory()) {\n Files.createDirectories(newFile);\n logger.info(\"Created directory \"+zipEntry.getName());\n } else {\n Files.createDirectories(newFile.getParent());\n\n // write file content\n Files.copy(zipInputStream, newFile, StandardCopyOption.REPLACE_EXISTING);\n logger.info(\"Unzipped \"+zipEntry.getName());\n }\n }\n //endregion\n\n\n if(STEAM_CMD_WIN_EXE_FILE.exists()){\n logger.info(\"SteamCMD installed successfully\");\n }else{\n logger.error(\"Error installing SteamCMD\");\n throw new RuntimeException(\"Error installing SteamCMD\");\n }\n }\n //endregion\n\n //region SteamCMD Commands\n\n @SneakyThrows\n public void runDownloadVerifyServer(Path installDir){\n var result = commandRunnerService.runCommand(downloadVerifyServerCommand(installDir));\n\n if(result.getExitCode() != 0) {\n logger.error(\"Error downloading server: \"+result.getExitCode());\n throw new RuntimeException(\"Error downloading server: \"+result.getExitCode());\n }\n\n logger.info(\"Server downloaded to \"+installDir);\n }\n\n @SneakyThrows\n public String[] downloadVerifyServerCommand(Path installDir){\n Files.createDirectories(installDir);\n var steamCMD = \"steamcmd\";\n if(SystemUtils.IS_OS_WINDOWS) {\n steamCMD = STEAM_CMD_WIN_EXE_FILE.getAbsolutePath();\n }\n\n // steamcmd +force_install_dir ..\\server\\guid +login anonymous +app_update 2430930 validate +quit\n return new String[]{\n steamCMD,\n \"+force_install_dir\", installDir.toAbsolutePath().toString(),\n \"+login\", \"anonymous\",\n \"+app_update\", ASA_STEAM_GAME_NUMBER, \"validate\",\n \"+quit\"\n };\n }\n\n //endregion\n\n}" }, { "identifier": "SliderWithText", "path": "src/main/java/dev/cele/asa_sm/ui/components/forms/SliderWithText.java", "snippet": "@Slf4j\npublic class SliderWithText extends JPanel {\n private final JSlider slider;\n private final NumberField numberField;\n\n @Getter\n private Number min = 0;\n @Getter\n private Number max = 100;\n @Getter\n private Number value = 0;\n @Getter\n private Number step = 1;\n\n public void setMin(Number min) {\n this.min = min;\n updateSlider();\n }\n\n public void setMax(Number max) {\n this.max = max;\n updateSlider();\n }\n\n public void setValue(Number value) {\n this.value = value;\n numberField.setNumber(value);\n updateSlider();\n }\n\n public void setStep(Number step) {\n this.step = step;\n if((double)step.intValue() != step.doubleValue()){\n numberField.setIsInteger(false);\n }\n updateSlider();\n }\n\n public void set(Number min, Number max, Number step){\n this.min = min;\n this.max = max;\n this.step = step;\n updateSlider();\n }\n\n public void set(Number min, Number max, Number step, Number value) {\n setValue(value);\n set(min, max, step);\n }\n\n\n private void updateSlider(){\n var stepMultiplier = 1 / step.doubleValue();\n\n slider.setMinimum((int)(stepMultiplier));\n slider.setMaximum((int)(max.doubleValue() * stepMultiplier));\n slider.setValue((int)(value.doubleValue() * stepMultiplier));\n\n if(stepMultiplier > 1){\n log.info(\"OR, min: {}, max: {}, step: {}\", min, max, step);\n log.info(\"ED, min: {}, max: {}, step: {}\", slider.getMinimum(), slider.getMaximum(), 1);\n }\n\n slider.setMajorTickSpacing(1);\n slider.setMinorTickSpacing(1);\n }\n\n\n public SliderWithText(){\n this(0, 100, 0);\n }\n\n public SliderWithText(int min, int max, int value) {\n slider = new JSlider(min, max, value);\n\n this.min = min;\n this.max = max;\n this.value = value;\n this.step = 1;\n\n updateSlider();\n\n numberField = new NumberField(value);\n\n setLayout(new BorderLayout());\n add(slider, BorderLayout.CENTER);\n add(numberField, BorderLayout.EAST);\n\n slider.addChangeListener(e -> {\n if(!Objects.equals(this.value, slider.getValue())){\n var realValue = slider.getValue() * step.doubleValue();\n log.info(\"Slider value: {}, real value: {}\", slider.getValue(), realValue);\n numberField.setNumber(realValue);\n }\n });\n\n numberField.addNumberListener(val -> {\n if(!Objects.equals(this.value, val)){\n this.value = val;\n slider.setValue((int)(val.doubleValue() * (1 / step.doubleValue())));\n }\n });\n\n }\n\n public void addChangeListener(Consumer<Number> listener) {\n numberField.addNumberListener(listener);\n }\n\n}" }, { "identifier": "ProcessDialog", "path": "src/main/java/dev/cele/asa_sm/ui/frames/ProcessDialog.java", "snippet": "public class ProcessDialog extends JDialog implements SimpleLogger {\n\n private final CommandRunnerService commandRunnerService = SpringApplicationContext.autoWire(CommandRunnerService.class);\n private final JTextPane textPane = new JTextPane();\n private final JLabel statusLabel = new JLabel(\"Idle\");\n private final JButton closeButton = new JButton(\"Close\");\n\n private final String[] commandAndArgs;\n private final Consumer<ProcessOutputDto> callback;\n\n Style red = textPane.addStyle(null, null);\n {\n StyleConstants.setForeground(red, Color.RED);\n }\n\n public ProcessDialog(JFrame parent, String title, String[] commandAndArgs) {\n this(parent, title, commandAndArgs, null);\n }\n\n public ProcessDialog(JFrame parent, String title, String[] commandAndArgs, Consumer<ProcessOutputDto> callback) {\n super(parent, title, true);\n\n this.commandAndArgs = commandAndArgs;\n this.callback = callback;\n\n setLayout(new BorderLayout());\n\n //textpane\n textPane.setEditable(false);\n textPane.setFont(\n UIManager.getFont( \"monospaced.font\" ).deriveFont( 14f )\n );\n textPane.setBackground(new Color(30,31,34,255));\n DefaultCaret caret = (DefaultCaret)textPane.getCaret();\n caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);\n\n //scroll and nowrap\n JPanel noWrapPanel = new JPanel( new BorderLayout() );\n noWrapPanel.add(textPane);\n JScrollPane scrollPane = new JScrollPane(noWrapPanel);\n scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);\n scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);\n add(scrollPane, BorderLayout.CENTER);\n\n //bottom panel\n JPanel statusPanel = new JPanel(new BorderLayout());\n statusPanel.add(new JLabel(\"Status:\"), BorderLayout.WEST);\n statusPanel.add(statusLabel, BorderLayout.CENTER);\n closeButton.setEnabled(false);\n closeButton.addActionListener(e -> {\n JDialog dialog = (JDialog) SwingUtilities.getRoot(ProcessDialog.this);\n dialog.dispose();\n });\n statusPanel.add(closeButton, BorderLayout.SOUTH);\n add(statusPanel, BorderLayout.SOUTH);\n\n //final setup\n setSize(1115, 630);\n setResizable(true);\n setLocationRelativeTo(null);\n setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);\n }\n\n boolean firstTimeVisible = true;\n @Override\n public void setVisible(boolean value){\n if(firstTimeVisible && value){\n firstTimeVisible = false;\n runCommand();\n }\n super.setVisible(value);\n }\n\n private void runCommand() {\n statusLabel.setText(\"Running...\");\n new Thread(() -> {\n var result = commandRunnerService.runCommand(this, commandAndArgs);\n closeButton.setEnabled(true);\n statusLabel.setText(\"Finished, code=\"+result.getExitCode()); // or \"Failed!\" depending on the result\n setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n\n if(callback != null) {\n callback.accept(result);\n }\n }).start();\n }\n\n @SneakyThrows\n @Override\n public void info(String message) {\n textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), message + \"\\n\", null);\n }\n\n @SneakyThrows\n @Override\n public void error(String message) {\n textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), message + \"\\n\", red);\n }\n\n}" }, { "identifier": "SimpleDocumentListener", "path": "src/main/java/dev/cele/asa_sm/ui/listeners/SimpleDocumentListener.java", "snippet": "public class SimpleDocumentListener implements DocumentListener {\n\n private Consumer<String> action;\n\n public SimpleDocumentListener(Consumer<String> action) {\n this.action = action;\n }\n\n @Override\n public void insertUpdate(DocumentEvent e) {\n try {\n action.accept(e.getDocument().getText(0, e.getDocument().getLength()));\n } catch (BadLocationException ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @Override\n public void removeUpdate(DocumentEvent e) {\n try {\n action.accept(e.getDocument().getText(0, e.getDocument().getLength()));\n } catch (BadLocationException ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @Override\n public void changedUpdate(DocumentEvent e) {\n try {\n action.accept(e.getDocument().getText(0, e.getDocument().getLength()));\n } catch (BadLocationException ex) {\n throw new RuntimeException(ex);\n }\n }\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.formdev.flatlaf.FlatClientProperties; import dev.cele.asa_sm.Const; import dev.cele.asa_sm.config.SpringApplicationContext; import dev.cele.asa_sm.dto.AsaServerConfigDto; import dev.cele.asa_sm.services.CommandRunnerService; import dev.cele.asa_sm.services.IniSerializerService; import dev.cele.asa_sm.services.SteamCMDService; import dev.cele.asa_sm.ui.components.forms.SliderWithText; import dev.cele.asa_sm.ui.components.server_tab_accordions.*; import dev.cele.asa_sm.ui.frames.ProcessDialog; import dev.cele.asa_sm.ui.listeners.SimpleDocumentListener; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import javax.swing.*; import javax.swing.text.JTextComponent; import java.awt.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.function.Consumer; import static java.util.stream.Collectors.toMap;
10,780
private void readAllIniFiles(){ var gameUserSettingsIniFile = configDto.getServerPath() .resolve("ShooterGame") .resolve("Saved") .resolve("Config") .resolve("WindowsServer") .resolve("GameUserSettings.ini") .toFile(); if(gameUserSettingsIniFile.exists()){ iniSerializerService.readIniFile(configDto.getGameUserSettingsINI(), gameUserSettingsIniFile); } //TODO: read Game.ini } private void writeAllIniFiles(){ var gameUserSettingsIniFile = configDto.getServerPath() .resolve("ShooterGame") .resolve("Saved") .resolve("Config") .resolve("WindowsServer") .resolve("GameUserSettings.ini") .toFile(); iniSerializerService.writeIniFile(configDto.getGameUserSettingsINI(), gameUserSettingsIniFile); } private boolean detectInstalled(){ //check if the server is installed if (Files.exists(configDto.getServerPath())) { topPanel.installVerifyButton.setText("Verify/Update"); topPanel.openInstallLocationButton.setEnabled(true); topPanel.installedLocationLabel.setText(configDto.getServerPath().toString()); topPanel.startButton.setEnabled(true); readVersionNumber(); return true; } else { topPanel.installVerifyButton.setText("Install"); topPanel.openInstallLocationButton.setEnabled(false); topPanel.installedLocationLabel.setText("Not installed yet"); topPanel.startButton.setEnabled(false); return false; } } private void readVersionNumber() { try { //read version from log file (ShooterGame\Saved\Logs\ShooterGame.log) var logFile = configDto.getServerPath() .resolve("ShooterGame") .resolve("Saved") .resolve("Logs") .resolve("ShooterGame.log") .toFile(); //read file line by line, not all at once, because the file can be huge var bufferedReader = new BufferedReader(new FileReader(logFile)); String line; var ARK_LOG_VERSION_DIVIDER = "ARK Version: "; while((line = bufferedReader.readLine()) != null){ if(line.contains(ARK_LOG_VERSION_DIVIDER)){ var versionParts = line.split(ARK_LOG_VERSION_DIVIDER); var version = "?"; if(versionParts.length == 2){ version = versionParts[1]; } log.info("Detected version: " + version); topPanel.installedVersionLabel.setText(version); break; } } bufferedReader.close(); }catch (Exception e){ log.error("Error reading version from log file", e); } } public void install(){ var wasInstalled = detectInstalled(); //if it's a new installation ask the user if they want to choose where to install the server or if they want to use the default location var defaultInstallDialogResult = JOptionPane.showConfirmDialog(this, "Do you want to choose where to install the server (if you press no the default install location will be used)?", "Choose installation location", JOptionPane.YES_NO_OPTION); if(defaultInstallDialogResult == JOptionPane.YES_OPTION){ //ask the user where to install the server var fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Choose where to install the server"); fileChooser.setApproveButtonText("Install"); fileChooser.setApproveButtonToolTipText("Install the server in the selected location"); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileHidingEnabled(false); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } @Override public String getDescription() { return "Directories"; } }); var result = fileChooser.showOpenDialog(this); if(result == JFileChooser.APPROVE_OPTION){ configDto.setCustomInstallPath(fileChooser.getSelectedFile().getAbsolutePath()); }else{ return; } }
package dev.cele.asa_sm.ui.components; public class ServerTab extends JPanel { //region Autowired stuff from spring private final SteamCMDService steamCMDService = SpringApplicationContext.autoWire(SteamCMDService.class); private final CommandRunnerService commandRunnerService = SpringApplicationContext.autoWire(CommandRunnerService.class); private final ObjectMapper objectMapper = SpringApplicationContext.autoWire(ObjectMapper.class); private final IniSerializerService iniSerializerService = SpringApplicationContext.autoWire(IniSerializerService.class); private Logger log = LoggerFactory.getLogger(ServerTab.class); private final Environment environment = SpringApplicationContext.autoWire(Environment.class); private final boolean isDev = Arrays.asList(environment.getActiveProfiles()).contains("dev"); //endregion //region UI components private final JPanel scrollPaneContent; private final TopPanel topPanel; //endregion private Thread serverThread = null; @Getter private AsaServerConfigDto configDto; public ServerTab(AsaServerConfigDto configDto) { this.configDto = configDto; //region setup UI components //region initial setup, var scrollPaneContent = JPanel() setLayout(new BorderLayout()); GridBagConstraints globalVerticalGBC = new GridBagConstraints(); globalVerticalGBC.fill = GridBagConstraints.HORIZONTAL; globalVerticalGBC.anchor = GridBagConstraints.BASELINE; globalVerticalGBC.gridwidth = GridBagConstraints.REMAINDER; globalVerticalGBC.weightx = 1.0; globalVerticalGBC.insets = new Insets(5, 5, 5, 0); //create a JScrollPane and a content panel scrollPaneContent = new JPanel(); scrollPaneContent.setLayout(new GridBagLayout()); JScrollPane scrollPane = new JScrollPane(scrollPaneContent); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); add(scrollPane, BorderLayout.CENTER); //endregion //top panel topPanel = new TopPanel(configDto); scrollPaneContent.add(topPanel.$$$getRootComponent$$$(), globalVerticalGBC); //create a group named "Administration" var administrationAccordion = new AdministrationAccordion(configDto); scrollPaneContent.add(administrationAccordion.$$$getRootComponent$$$(), globalVerticalGBC); //... other accordion groups ... if(isDev){ var rulesAccordion = new RulesAccordion(configDto); scrollPaneContent.add(rulesAccordion.$$$getRootComponent$$$(), globalVerticalGBC); } var chatAndNotificationsAccordion = new ChatAndNotificationsAccordion(configDto); scrollPaneContent.add(chatAndNotificationsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); var hudAndVisualsAccordion = new HUDAndVisuals(configDto); scrollPaneContent.add(hudAndVisualsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); if(isDev){ var playerSettingsAccordion = new PlayerSettingsAccordion(configDto); scrollPaneContent.add(playerSettingsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); } //create an empty filler panel that will fill the remaining space if there's any JPanel fillerPanel = new JPanel(); fillerPanel.setPreferredSize(new Dimension(0, 0)); scrollPaneContent.add(fillerPanel, gbcClone(globalVerticalGBC, gbc -> gbc.weighty = 1.0)); //endregion if(detectInstalled()){ //if the server is already installed read the ini files and populate the configDto, //the ini files have priority so if you create a profile for an already existing server //the interface will be populated with the values from your existing server readAllIniFiles(); if(configDto.getJustImported()){ //import extra settings from INI Files that are both on INI files and on the configDto configDto.setServerPassword(configDto.getGameUserSettingsINI().getServerSettings().getServerPassword()); configDto.setServerAdminPassword(configDto.getGameUserSettingsINI().getServerSettings().getServerAdminPassword()); configDto.setServerSpectatorPassword(configDto.getGameUserSettingsINI().getServerSettings().getSpectatorPassword()); configDto.setServerName(configDto.getGameUserSettingsINI().getSessionSettings().getSessionName()); configDto.setModIds(configDto.getGameUserSettingsINI().getServerSettings().getActiveMods()); configDto.setRconEnabled(configDto.getGameUserSettingsINI().getServerSettings().getRconEnabled()); configDto.setRconPort(configDto.getGameUserSettingsINI().getServerSettings().getRconPort()); configDto.setRconServerLogBuffer(configDto.getGameUserSettingsINI().getServerSettings().getRconServerGameLogBuffer()); } } configDto.addUnsavedChangeListener((unsaved) -> { //get tabbed pane and set title with a star if unsaved JTabbedPane tabbedPane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, this); if(tabbedPane != null){ int index = tabbedPane.indexOfComponent(this); if(index != -1){ tabbedPane.setTitleAt(index, configDto.getProfileName() + (unsaved ? " *" : "")); } } //set the save button outline to red if unsaved if(unsaved){ topPanel.saveButton.putClientProperty(FlatClientProperties.OUTLINE, FlatClientProperties.OUTLINE_ERROR); } else { topPanel.saveButton.putClientProperty(FlatClientProperties.OUTLINE, null); } }); SwingUtilities.invokeLater(() -> { setupListenersForUnsaved(this); setupAccordionsExpansion(); }); } void setupAccordionsExpansion(){ var accordions = new ArrayList<AccordionTopBar>(); //loop over all the children of the container for (Component component : scrollPaneContent.getComponents()) { //if the component is a container, has a borderlayout, and his top component is a AccordionTopBar if(component instanceof Container && ((Container) component).getLayout() instanceof BorderLayout ){ var topComponent = ((BorderLayout) ((Container) component).getLayout()).getLayoutComponent(BorderLayout.NORTH); if(topComponent instanceof AccordionTopBar){ accordions.add((AccordionTopBar) topComponent); } } } new Thread(() -> { try { Thread.sleep(1500); SwingUtilities.invokeLater(() -> { for (var accordion : accordions) { //TODO: use the text from the accordion to check if it's expanded or not and save it to a json or something? accordion.setExpanded(false); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } }).start(); } void setupListenersForUnsaved(Container container){ //loop over all the children of the container for (Component component : container.getComponents()) { //if the component is a container, call this function recursively if(component instanceof SliderWithText){ ((SliderWithText) component).addChangeListener(e -> configDto.setUnsaved(true)); } else if (component instanceof JTextComponent){ ((JTextComponent) component).getDocument().addDocumentListener(new SimpleDocumentListener(text -> configDto.setUnsaved(true))); } else if (component instanceof JCheckBox){ ((JCheckBox) component).addActionListener(e -> configDto.setUnsaved(true)); } else if (component instanceof JComboBox){ ((JComboBox<?>) component).addActionListener(e -> configDto.setUnsaved(true)); } else if (component instanceof JSpinner){ ((JSpinner) component).addChangeListener(e -> configDto.setUnsaved(true)); }else if(component instanceof Container){ setupListenersForUnsaved((Container) component); } } } private void readAllIniFiles(){ var gameUserSettingsIniFile = configDto.getServerPath() .resolve("ShooterGame") .resolve("Saved") .resolve("Config") .resolve("WindowsServer") .resolve("GameUserSettings.ini") .toFile(); if(gameUserSettingsIniFile.exists()){ iniSerializerService.readIniFile(configDto.getGameUserSettingsINI(), gameUserSettingsIniFile); } //TODO: read Game.ini } private void writeAllIniFiles(){ var gameUserSettingsIniFile = configDto.getServerPath() .resolve("ShooterGame") .resolve("Saved") .resolve("Config") .resolve("WindowsServer") .resolve("GameUserSettings.ini") .toFile(); iniSerializerService.writeIniFile(configDto.getGameUserSettingsINI(), gameUserSettingsIniFile); } private boolean detectInstalled(){ //check if the server is installed if (Files.exists(configDto.getServerPath())) { topPanel.installVerifyButton.setText("Verify/Update"); topPanel.openInstallLocationButton.setEnabled(true); topPanel.installedLocationLabel.setText(configDto.getServerPath().toString()); topPanel.startButton.setEnabled(true); readVersionNumber(); return true; } else { topPanel.installVerifyButton.setText("Install"); topPanel.openInstallLocationButton.setEnabled(false); topPanel.installedLocationLabel.setText("Not installed yet"); topPanel.startButton.setEnabled(false); return false; } } private void readVersionNumber() { try { //read version from log file (ShooterGame\Saved\Logs\ShooterGame.log) var logFile = configDto.getServerPath() .resolve("ShooterGame") .resolve("Saved") .resolve("Logs") .resolve("ShooterGame.log") .toFile(); //read file line by line, not all at once, because the file can be huge var bufferedReader = new BufferedReader(new FileReader(logFile)); String line; var ARK_LOG_VERSION_DIVIDER = "ARK Version: "; while((line = bufferedReader.readLine()) != null){ if(line.contains(ARK_LOG_VERSION_DIVIDER)){ var versionParts = line.split(ARK_LOG_VERSION_DIVIDER); var version = "?"; if(versionParts.length == 2){ version = versionParts[1]; } log.info("Detected version: " + version); topPanel.installedVersionLabel.setText(version); break; } } bufferedReader.close(); }catch (Exception e){ log.error("Error reading version from log file", e); } } public void install(){ var wasInstalled = detectInstalled(); //if it's a new installation ask the user if they want to choose where to install the server or if they want to use the default location var defaultInstallDialogResult = JOptionPane.showConfirmDialog(this, "Do you want to choose where to install the server (if you press no the default install location will be used)?", "Choose installation location", JOptionPane.YES_NO_OPTION); if(defaultInstallDialogResult == JOptionPane.YES_OPTION){ //ask the user where to install the server var fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Choose where to install the server"); fileChooser.setApproveButtonText("Install"); fileChooser.setApproveButtonToolTipText("Install the server in the selected location"); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileHidingEnabled(false); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } @Override public String getDescription() { return "Directories"; } }); var result = fileChooser.showOpenDialog(this); if(result == JFileChooser.APPROVE_OPTION){ configDto.setCustomInstallPath(fileChooser.getSelectedFile().getAbsolutePath()); }else{ return; } }
ProcessDialog processDialog = new ProcessDialog(
7
2023-11-07 19:36:49+00:00
12k
HexHive/Crystallizer
src/dynamic/SeriFuzz_nogg.java
[ { "identifier": "GadgetVertexSerializable", "path": "src/static/src/main/java/analysis/GadgetVertexSerializable.java", "snippet": "public class GadgetVertexSerializable implements Serializable {\n final GadgetMethodSerializable node;\n\n public GadgetVertexSerializable(GadgetMethodSerializable node) {\n this.node = node;\n }\n\n public String toString() {\n return node.keyString();\n }\n\n public String getType() {\n return node.getType();\n }\n\n public String getClsName() {\n return node.getClsName();\n }\n\n public String getMethodSignature() {\n return node.getMethodSignature();\n }\n\n public String getQualifiedName() {\n return node.getQualifiedName();\n }\n\n\n public int hashCode() {\n return toString().hashCode();\n }\n \n public boolean equals(Object o) {\n return (o instanceof GadgetVertexSerializable) && (toString().equals(o.toString()));\n }\n}" }, { "identifier": "GadgetMethodSerializable", "path": "src/static/src/main/java/analysis/GadgetMethodSerializable.java", "snippet": "public class GadgetMethodSerializable implements Serializable {\n\n final String clsName; \n final String methodSignature; \n\tfinal String qualifiedName; // The method name constructed to allow for comparison against what is output by method method in java \n final String type; // Type of gadget [Source/Sink/Chain]\n\n // We setup the unique key as <clsName: methodName(methodParameters)>\n public String keyString() {\n return this.methodSignature;\n }\n\n GadgetMethodSerializable(String clsName, String methodSignature, String type, String qualifiedName) {\n this.clsName = clsName;\n this.methodSignature = methodSignature;\n this.qualifiedName = qualifiedName;\n this.type = type;\n }\n\n String getMethodSignature() {\n return this.methodSignature;\n }\n\n String getClsName() {\n return this.clsName;\n }\n\n String getType() {\n return this.type;\n }\n\n String getQualifiedName() {\n return this.qualifiedName;\n }\n\n}" } ]
import com.code_intelligence.jazzer.api.FuzzedDataProvider; import com.code_intelligence.jazzer.autofuzz.*; import analysis.GadgetVertexSerializable; import analysis.GadgetMethodSerializable; import org.jgrapht.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; import org.jgrapht.alg.shortestpath.*; import java.io.*; import java.lang.reflect.Constructor; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator;
7,922
SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.UnmodifiableBag.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableBag.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.UnmodifiableBag.uniqueSet()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NullIsExceptionPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.<init>()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.containsAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableLinkedList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableLinkedList.hashCode()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableLinkedList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.isEmpty()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.CursorableLinkedList.iterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.CursorableLinkedList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.CursorableLinkedList.listIterator(int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableLinkedList.remove(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableLinkedList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableLinkedList.size()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.CursorableLinkedList.toArray()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.CursorableLinkedList.toArray(java.lang.Object[])"); SeriFuzz.sinkIDs.add("java.lang.String org.apache.commons.collections.CursorableLinkedList.toString()"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.CursorableLinkedList.subList(int,int)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.CursorableLinkedList$Listable org.apache.commons.collections.CursorableLinkedList.insertListable(org.apache.commons.collections.CursorableLinkedList$Listable,org.apache.commons.collections.CursorableLinkedList$Listable,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.removeListable(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.CursorableLinkedList$Listable org.apache.commons.collections.CursorableLinkedList.getListableAt(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.broadcastListableChanged(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.broadcastListableRemoved(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.broadcastListableInserted(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.TransformerClosure.execute(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.AnyPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.collection.UnmodifiableBoundedCollection.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableBoundedCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableBoundedCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.UnmodifiableBoundedCollection.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableBoundedCollection.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.LazyList.<init>(java.util.List,org.apache.commons.collections.Factory)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.LazyList.get(int)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.LazyList.subList(int,int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.<init>(java.util.SortedMap)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.getFast()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.setFast(boolean)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.get(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastTreeMap.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.containsKey(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.containsValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.FastTreeMap.comparator()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastTreeMap.hashCode()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.clone()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.FastTreeMap.entrySet()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.FastTreeMap.keySet()"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.FastTreeMap.values()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.ChainedTransformer.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.HashBag.<init>()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.HashBag.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.Bag org.apache.commons.collections.bag.TransformedBag.getBag()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.bag.TransformedBag.getCount(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.TransformedBag.uniqueSet()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.LazyMap.get(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.collection.UnmodifiableCollection.decorate(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.UnmodifiableCollection.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.collection.UnmodifiableCollection.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.UnmodifiableCollection.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableCollection.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.AbstractSerializableCollectionDecorator.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BoundedFifoBuffer.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BoundedFifoBuffer.isFull()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.buffer.BoundedFifoBuffer.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BoundedFifoBuffer.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.buffer.BoundedFifoBuffer.remove()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.increment(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.decrement(int)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.buffer.BoundedFifoBuffer.iterator()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.access$300(org.apache.commons.collections.buffer.BoundedFifoBuffer,int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.access$600(org.apache.commons.collections.buffer.BoundedFifoBuffer,int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NullIsTruePredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.ChainedClosure.execute(java.lang.Object)"); } else if (SeriFuzz.targetLibrary.equals("vaadin1")) { SeriFuzz.sinkIDs.add("java.lang.Object com.vaadin.data.util.NestedMethodProperty.getValue()"); } else if (SeriFuzz.targetLibrary.equals("aspectjweaver")) { SeriFuzz.sinkIDs.add("java.lang.String org.aspectj.weaver.tools.cache.SimpleCache$StoreableCachingMap.writeToPath(java.lang.String,byte[])"); } else if (SeriFuzz.targetLibrary.equals("synthetic_3")) { SeriFuzz.sinkIDs.add("void VulnObj_2.gadget_1()"); } else { LOGGER.info("Unknown target library passed, please put in a trigger gadget handling routine."); System.exit(1); } TrackStatistics.initProgressCounters(); } public static void fuzzerTestOneInput(FuzzedDataProvider data) { // GadgetDB.showVertices(); // GadgetDB.printAllPaths(); // System.exit(1); // Operating in the dynamic sink ID mode if (isSinkIDMode) { boolean didTest = DynamicSinkID.testPotentialSinks(data); LOGGER.debug("Test completed"); return; } // makeHookActive = false; sinkTriggered = false;
package com.example; // import clojure.*; // import org.apache.logging.log4j.Logger; public class SeriFuzz { // private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Logger LOGGER = Logger.getLogger(SeriFuzz.class); private static String logProperties = "/root/SeriFuzz/src/dynamic/log4j.properties"; // The targeted library defines how the payload is to be setup // public static String targetLibrary = "vaadin1"; public static String targetLibrary = "aspectjweaver"; // public static String targetLibrary = "commons_collections_itw"; // public static String targetLibrary = "commons_collections_5"; // public static String targetLibrary = "synthetic_3"; // This sinkID is used to identify is sink gadget is triggered public static List<String> sinkIDs = new ArrayList<String>(); // This flag identifies if we are running the fuzzer in the dynamic sink identification mode public static boolean isSinkIDMode = false; // This flag identifiers if we are running the fuzzer in the crash triage mode public static boolean isCrashTriageMode = false; // Specify the threshold time we put in to get new cov before we deem that the campaign has stalled public static long thresholdTime = 3600; // This flag defines if the hooks on sink gadgets acting as sanitizers // are to be activated. The reason we have this // flag is because we do incremental path validation and in that case its possible // for the hooked methods to be triggered during the incremental path validation which // would be a false positive // public static boolean makeHookActive; public static boolean sinkTriggered; public static void fuzzerInitialize(String[] args) { PropertyConfigurator.configure(logProperties); LogCrash.makeCrashDir(); LogCrash.initJDKCrashedPaths(); if (isSinkIDMode) { Meta.isSinkIDMode = true; LOGGER.debug("Reinitializing vulnerable sinks found"); LogCrash.reinitVulnerableSinks(); return; } if (isCrashTriageMode) { LOGGER.debug("Running the fuzzer in crash triage mode"); Meta.isCrashTriageMode = true; } TrackStatistics.sanityCheckSinks(); TrackStatistics.logInitTimeStamp(); LogCrash.initCrashID(); GadgetDB.tagSourcesAndSinks(); GadgetDB.findAllPaths(); //XXX: This piece of code can be removed if we figure out correctly hooking this method using jazzer //mehtod hooks if (SeriFuzz.targetLibrary.equals("commons_collections_5")) { SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.LazyMap.get(java.lang.Object)"); } else if (SeriFuzz.targetLibrary.equals("commons_collections_itw")) { // SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.transformKey(java.lang.Object)"); // SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.transformValue(java.lang.Object)"); // SeriFuzz.sinkIDs.add("java.util.Map org.apache.commons.collections.map.TransformedMap.transformMap(java.util.Map)"); // SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.checkSetValue(java.lang.Object)"); // SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.put(java.lang.Object,java.lang.Object)"); // SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.put(java.lang.Object,java.lang.Object)"); // SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.TransformedMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastArrayList.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.getFast()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastArrayList.setFast(boolean)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastArrayList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastArrayList.clear()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastArrayList.clone()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.containsAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastArrayList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastArrayList.hashCode()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastArrayList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.isEmpty()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.FastArrayList.iterator()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastArrayList.lastIndexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.FastArrayList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.FastArrayList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastArrayList.remove(int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastArrayList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastArrayList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastArrayList.size()"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.FastArrayList.subList(int,int)"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.FastArrayList.toArray()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.FastArrayList.toArray(java.lang.Object[])"); SeriFuzz.sinkIDs.add("java.lang.String org.apache.commons.collections.FastArrayList.toString()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.set.TransformedSet.decorate(java.util.Set,org.apache.commons.collections.Transformer)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.set.TransformedSet.<init>(java.util.Set,org.apache.commons.collections.Transformer)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.comparators.NullComparator.compare(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.comparators.NullComparator.hashCode()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.comparators.NullComparator.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.AllPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.PredicatedList.<init>(java.util.List,org.apache.commons.collections.Predicate)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.PredicatedList.getList()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.PredicatedList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.list.PredicatedList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.PredicatedList.remove(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.PredicatedList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.PredicatedList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.PredicatedList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.PredicatedList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.PredicatedList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.PredicatedList.subList(int,int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.PredicatedList.access$001(org.apache.commons.collections.list.PredicatedList,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.PredicatedList.access$101(org.apache.commons.collections.list.PredicatedList,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.comparators.ComparatorChain.checkChainIntegrity()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.comparators.ComparatorChain.compare(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.comparators.ComparatorChain.hashCode()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.comparators.ComparatorChain.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.SynchronizedBag$SynchronizedBagSet.<init>(org.apache.commons.collections.bag.SynchronizedBag,java.util.Set,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.SwitchClosure.execute(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.bag.UnmodifiableSortedBag.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableSortedBag.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableSortedBag.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.UnmodifiableSortedBag.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableSortedBag.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.UnmodifiableSortedBag.uniqueSet()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.SynchronizedCollection.<init>(java.util.Collection,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.SynchronizedCollection.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.containsAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.isEmpty()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.collection.SynchronizedCollection.iterator()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.collection.SynchronizedCollection.toArray()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.collection.SynchronizedCollection.toArray(java.lang.Object[])"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.collection.SynchronizedCollection.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.SynchronizedCollection.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.collection.SynchronizedCollection.hashCode()"); SeriFuzz.sinkIDs.add("java.lang.String org.apache.commons.collections.collection.SynchronizedCollection.toString()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BlockingBuffer.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BlockingBuffer.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.set.ListOrderedSet.clear()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.set.ListOrderedSet.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.set.ListOrderedSet.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.set.ListOrderedSet.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.set.ListOrderedSet.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.set.ListOrderedSet.toArray()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.set.ListOrderedSet.toArray(java.lang.Object[])"); SeriFuzz.sinkIDs.add("java.lang.String org.apache.commons.collections.set.ListOrderedSet.toString()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.TransformedPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.SynchronizedList.<init>(java.util.List,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.SynchronizedList.getList()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.SynchronizedList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SynchronizedList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.SynchronizedList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.list.SynchronizedList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.SynchronizedList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.SynchronizedList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.SynchronizedList.remove(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.SynchronizedList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.SynchronizedList.subList(int,int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.PredicatedCollection.<init>(java.util.Collection,org.apache.commons.collections.Predicate)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.PredicatedCollection.validate(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.PredicatedCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.PredicatedCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.PredicateTransformer.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.WhileClosure.execute(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.FactoryTransformer.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.buffer.UnmodifiableBuffer.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.UnmodifiableBuffer.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.UnmodifiableBuffer.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.buffer.UnmodifiableBuffer.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.UnmodifiableBuffer.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.CircularFifoBuffer.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.SingletonMap.getKey()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.SingletonMap.getValue()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.SingletonMap.setValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.SingletonMap.get(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.map.SingletonMap.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap.containsKey(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap.containsValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.SingletonMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.SingletonMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.SingletonMap.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.SingletonMap.clear()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.SingletonMap.entrySet()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.SingletonMap.keySet()"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.map.SingletonMap.values()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap.isEqualKey(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap.isEqualValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.map.SingletonMap.hashCode()"); SeriFuzz.sinkIDs.add("java.lang.String org.apache.commons.collections.map.SingletonMap.toString()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NullIsFalsePredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.PrototypeFactory$PrototypeSerializationFactory.<init>(java.io.Serializable)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.PrototypeFactory$PrototypeSerializationFactory.create()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.PrototypeFactory$PrototypeSerializationFactory.<init>(java.io.Serializable,org.apache.commons.collections.functors.PrototypeFactory$1)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.ClosureTransformer.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.TransformedCollection.<init>(java.util.Collection,org.apache.commons.collections.Transformer)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.collection.TransformedCollection.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.collection.TransformedCollection.transform(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.TransformedCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.TransformedCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.FixedSizeSortedMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.FixedSizeSortedMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.FixedSizeSortedMap.clear()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.FixedSizeSortedMap.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.FixedSizeSortedMap.entrySet()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.FixedSizeSortedMap.keySet()"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.map.FixedSizeSortedMap.values()"); SeriFuzz.sinkIDs.add("java.util.SortedMap org.apache.commons.collections.map.PredicatedSortedMap.getSortedMap()"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.map.PredicatedSortedMap.comparator()"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.list.AbstractLinkedList$Node org.apache.commons.collections.list.NodeCachingLinkedList.getNodeFromCache()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.NodeCachingLinkedList.isCacheFull()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.NodeCachingLinkedList.addNodeToCache(org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.list.AbstractLinkedList$Node org.apache.commons.collections.list.NodeCachingLinkedList.createNode(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.NodeCachingLinkedList.removeNode(org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.NodeCachingLinkedList.removeAllNodes()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableSubList.<init>(org.apache.commons.collections.CursorableLinkedList,int,int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableSubList.clear()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.CursorableSubList.iterator()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableSubList.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.isEmpty()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.CursorableSubList.toArray()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.CursorableSubList.toArray(java.lang.Object[])"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.containsAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableSubList.hashCode()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableSubList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableSubList.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableSubList.get(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableSubList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.CursorableSubList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableSubList.remove(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableSubList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.CursorableSubList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.CursorableSubList.subList(int,int)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.CursorableLinkedList$Listable org.apache.commons.collections.CursorableSubList.insertListable(org.apache.commons.collections.CursorableLinkedList$Listable,org.apache.commons.collections.CursorableLinkedList$Listable,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableSubList.removeListable(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableSubList.checkForComod()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.TransformerPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.Bag org.apache.commons.collections.bag.PredicatedBag.getBag()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.PredicatedBag.uniqueSet()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.bag.PredicatedBag.getCount(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.SetUniqueList.<init>(java.util.List,java.util.Set)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SetUniqueList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.SetUniqueList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SetUniqueList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SetUniqueList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.SetUniqueList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SetUniqueList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.SetUniqueList.remove(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.SetUniqueList.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SetUniqueList.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.SetUniqueList.containsAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.list.SetUniqueList.iterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.SetUniqueList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.SetUniqueList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.SetUniqueList.subList(int,int)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.set.UnmodifiableSet.decorate(java.util.Set)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.set.UnmodifiableSet.<init>(java.util.Set)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.set.UnmodifiableSet.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.set.UnmodifiableSet.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.set.UnmodifiableSet.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.set.UnmodifiableSet.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.set.UnmodifiableSet.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.Bag org.apache.commons.collections.bag.SynchronizedBag.getBag()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.SynchronizedBag.uniqueSet()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.bag.SynchronizedBag.getCount(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.IfClosure.execute(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.set.AbstractSerializableSetDecorator.<init>(java.util.Set)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.TransformedList.<init>(java.util.List,org.apache.commons.collections.Transformer)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.TransformedList.getList()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.TransformedList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.list.TransformedList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.TransformedList.remove(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.TransformedList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.TransformedList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.TransformedList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.TransformedList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.TransformedList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.TransformedList.subList(int,int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.TransformedList.access$001(org.apache.commons.collections.list.TransformedList,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.TransformedList.access$101(org.apache.commons.collections.list.TransformedList,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.SortedMap org.apache.commons.collections.map.LazySortedMap.getSortedMap()"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.map.LazySortedMap.comparator()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.UnboundedFifoBuffer.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.UnboundedFifoBuffer.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.UnboundedFifoBuffer.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.buffer.UnboundedFifoBuffer.remove()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.UnboundedFifoBuffer.increment(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.UnboundedFifoBuffer.decrement(int)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.buffer.UnboundedFifoBuffer.iterator()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.UnboundedFifoBuffer.access$000(org.apache.commons.collections.buffer.UnboundedFifoBuffer,int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.UnboundedFifoBuffer.access$100(org.apache.commons.collections.buffer.UnboundedFifoBuffer,int)"); SeriFuzz.sinkIDs.add("java.util.SortedMap org.apache.commons.collections.map.UnmodifiableSortedMap.decorate(java.util.SortedMap)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.UnmodifiableSortedMap.<init>(java.util.SortedMap)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.UnmodifiableSortedMap.clear()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.UnmodifiableSortedMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.UnmodifiableSortedMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.UnmodifiableSortedMap.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.UnmodifiableSortedMap.entrySet()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.UnmodifiableSortedMap.keySet()"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.map.UnmodifiableSortedMap.values()"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.map.UnmodifiableSortedMap.comparator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.AndPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.comparators.ReverseComparator.compare(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.comparators.ReverseComparator.hashCode()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.comparators.ReverseComparator.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.set.SynchronizedSet.<init>(java.util.Set,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.PredicatedMap.validate(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.PredicatedMap.checkSetValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.PredicatedMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.PredicatedMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.transformKey(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.transformValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Map org.apache.commons.collections.map.TransformedMap.transformMap(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.checkSetValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.TransformedMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.TransformedMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.util.SortedMap org.apache.commons.collections.map.TransformedSortedMap.getSortedMap()"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.map.TransformedSortedMap.comparator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NotPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.bidimap.DualTreeBidiMap.comparator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.OrPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.SwitchTransformer.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.list.CursorableLinkedList.iterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.CursorableLinkedList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.CursorableLinkedList.listIterator(int)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.list.CursorableLinkedList$Cursor org.apache.commons.collections.list.CursorableLinkedList.cursor(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.updateNode(org.apache.commons.collections.list.AbstractLinkedList$Node,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.addNode(org.apache.commons.collections.list.AbstractLinkedList$Node,org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.removeNode(org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.removeAllNodes()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.registerCursor(org.apache.commons.collections.list.CursorableLinkedList$Cursor)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.broadcastNodeChanged(org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.broadcastNodeRemoved(org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.CursorableLinkedList.broadcastNodeInserted(org.apache.commons.collections.list.AbstractLinkedList$Node)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.SingletonMap$SingletonValues.<init>(org.apache.commons.collections.map.SingletonMap)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.map.SingletonMap$SingletonValues.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap$SingletonValues.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.map.SingletonMap$SingletonValues.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.SingletonMap$SingletonValues.clear()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.map.SingletonMap$SingletonValues.iterator()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.UnmodifiableOrderedMap.clear()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.UnmodifiableOrderedMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.map.UnmodifiableOrderedMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.UnmodifiableOrderedMap.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.UnmodifiableOrderedMap.entrySet()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.map.UnmodifiableOrderedMap.keySet()"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.map.UnmodifiableOrderedMap.values()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.OnePredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.FixedSizeList.<init>(java.util.List)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.FixedSizeList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.FixedSizeList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.FixedSizeList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.FixedSizeList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.FixedSizeList.clear()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.FixedSizeList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.list.FixedSizeList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.list.FixedSizeList.iterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.FixedSizeList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.FixedSizeList.listIterator(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.FixedSizeList.remove(int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.FixedSizeList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.FixedSizeList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.FixedSizeList.subList(int,int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.AbstractSerializableListDecorator.<init>(java.util.List)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.UnmodifiableList.decorate(java.util.List)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.UnmodifiableList.<init>(java.util.List)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.list.UnmodifiableList.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.UnmodifiableList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.UnmodifiableList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.UnmodifiableList.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.UnmodifiableList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.UnmodifiableList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.list.UnmodifiableList.listIterator(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.UnmodifiableList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.list.UnmodifiableList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.UnmodifiableList.remove(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.UnmodifiableList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.UnmodifiableList.subList(int,int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NonePredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.ForClosure.execute(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.bag.UnmodifiableBag.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableBag.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableBag.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.UnmodifiableBag.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.bag.UnmodifiableBag.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.UnmodifiableBag.uniqueSet()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NullIsExceptionPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.<init>()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.add(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.addAll(int,java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.contains(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.containsAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableLinkedList.get(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableLinkedList.hashCode()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableLinkedList.indexOf(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.isEmpty()"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.CursorableLinkedList.iterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.CursorableLinkedList.listIterator()"); SeriFuzz.sinkIDs.add("java.util.ListIterator org.apache.commons.collections.CursorableLinkedList.listIterator(int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.CursorableLinkedList.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableLinkedList.remove(int)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.CursorableLinkedList.set(int,java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.CursorableLinkedList.size()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.CursorableLinkedList.toArray()"); SeriFuzz.sinkIDs.add("java.lang.Object[] org.apache.commons.collections.CursorableLinkedList.toArray(java.lang.Object[])"); SeriFuzz.sinkIDs.add("java.lang.String org.apache.commons.collections.CursorableLinkedList.toString()"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.CursorableLinkedList.subList(int,int)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.CursorableLinkedList$Listable org.apache.commons.collections.CursorableLinkedList.insertListable(org.apache.commons.collections.CursorableLinkedList$Listable,org.apache.commons.collections.CursorableLinkedList$Listable,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.removeListable(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.CursorableLinkedList$Listable org.apache.commons.collections.CursorableLinkedList.getListableAt(int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.broadcastListableChanged(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.broadcastListableRemoved(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.CursorableLinkedList.broadcastListableInserted(org.apache.commons.collections.CursorableLinkedList$Listable)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.TransformerClosure.execute(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.AnyPredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.collection.UnmodifiableBoundedCollection.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableBoundedCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableBoundedCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.UnmodifiableBoundedCollection.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableBoundedCollection.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.list.LazyList.<init>(java.util.List,org.apache.commons.collections.Factory)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.list.LazyList.get(int)"); SeriFuzz.sinkIDs.add("java.util.List org.apache.commons.collections.list.LazyList.subList(int,int)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.<init>(java.util.SortedMap)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.getFast()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.setFast(boolean)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.get(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastTreeMap.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.containsKey(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.containsValue(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Comparator org.apache.commons.collections.FastTreeMap.comparator()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.put(java.lang.Object,java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.putAll(java.util.Map)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.FastTreeMap.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.FastTreeMap.equals(java.lang.Object)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.FastTreeMap.hashCode()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.FastTreeMap.clone()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.FastTreeMap.entrySet()"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.FastTreeMap.keySet()"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.FastTreeMap.values()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.functors.ChainedTransformer.transform(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.HashBag.<init>()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.bag.HashBag.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("org.apache.commons.collections.Bag org.apache.commons.collections.bag.TransformedBag.getBag()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.bag.TransformedBag.getCount(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Set org.apache.commons.collections.bag.TransformedBag.uniqueSet()"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.map.LazyMap.get(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.util.Collection org.apache.commons.collections.collection.UnmodifiableCollection.decorate(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.UnmodifiableCollection.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.collection.UnmodifiableCollection.iterator()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableCollection.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableCollection.addAll(java.util.Collection)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.UnmodifiableCollection.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.collection.UnmodifiableCollection.remove(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.collection.AbstractSerializableCollectionDecorator.<init>(java.util.Collection)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.size()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BoundedFifoBuffer.isEmpty()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BoundedFifoBuffer.isFull()"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.buffer.BoundedFifoBuffer.clear()"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.buffer.BoundedFifoBuffer.add(java.lang.Object)"); SeriFuzz.sinkIDs.add("java.lang.Object org.apache.commons.collections.buffer.BoundedFifoBuffer.remove()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.increment(int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.decrement(int)"); SeriFuzz.sinkIDs.add("java.util.Iterator org.apache.commons.collections.buffer.BoundedFifoBuffer.iterator()"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.access$300(org.apache.commons.collections.buffer.BoundedFifoBuffer,int)"); SeriFuzz.sinkIDs.add("int org.apache.commons.collections.buffer.BoundedFifoBuffer.access$600(org.apache.commons.collections.buffer.BoundedFifoBuffer,int)"); SeriFuzz.sinkIDs.add("boolean org.apache.commons.collections.functors.NullIsTruePredicate.evaluate(java.lang.Object)"); SeriFuzz.sinkIDs.add("void org.apache.commons.collections.functors.ChainedClosure.execute(java.lang.Object)"); } else if (SeriFuzz.targetLibrary.equals("vaadin1")) { SeriFuzz.sinkIDs.add("java.lang.Object com.vaadin.data.util.NestedMethodProperty.getValue()"); } else if (SeriFuzz.targetLibrary.equals("aspectjweaver")) { SeriFuzz.sinkIDs.add("java.lang.String org.aspectj.weaver.tools.cache.SimpleCache$StoreableCachingMap.writeToPath(java.lang.String,byte[])"); } else if (SeriFuzz.targetLibrary.equals("synthetic_3")) { SeriFuzz.sinkIDs.add("void VulnObj_2.gadget_1()"); } else { LOGGER.info("Unknown target library passed, please put in a trigger gadget handling routine."); System.exit(1); } TrackStatistics.initProgressCounters(); } public static void fuzzerTestOneInput(FuzzedDataProvider data) { // GadgetDB.showVertices(); // GadgetDB.printAllPaths(); // System.exit(1); // Operating in the dynamic sink ID mode if (isSinkIDMode) { boolean didTest = DynamicSinkID.testPotentialSinks(data); LOGGER.debug("Test completed"); return; } // makeHookActive = false; sinkTriggered = false;
GraphPath<GadgetVertexSerializable, DefaultEdge> candidate = GadgetDB.pickPath();
0
2023-11-07 22:03:19+00:00
12k
1341191074/aibote4j
sdk-core/src/main/java/net/aibote/sdk/WinBot.java
[ { "identifier": "OCRResult", "path": "sdk-core/src/main/java/net/aibote/sdk/dto/OCRResult.java", "snippet": "public class OCRResult {\n public Point lt;\n public Point rt;\n public Point ld;\n public Point rd;\n public String word;\n public double rate;\n}" }, { "identifier": "Point", "path": "sdk-core/src/main/java/net/aibote/sdk/dto/Point.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\npublic class Point {\n\n /**\n * x。默认0\n */\n public int x;\n /**\n * y。默认0\n */\n public int y;\n}" }, { "identifier": "Mode", "path": "sdk-core/src/main/java/net/aibote/sdk/options/Mode.java", "snippet": "public enum Mode {\n\n /**\n * 前台执行\n */\n front(false),\n /**\n * 后台执行\n */\n backed(true);\n\n private boolean boolValue;\n\n Mode(boolean boolValue) {\n this.boolValue = boolValue;\n }\n\n public boolean boolValue() {\n return boolValue;\n }\n\n public String boolValueStr() {\n return Boolean.toString(boolValue);\n }\n}" }, { "identifier": "Region", "path": "sdk-core/src/main/java/net/aibote/sdk/options/Region.java", "snippet": "public class Region {\n /**\n * 左。默认0\n */\n public int left;\n /**\n * 上。默认0\n */\n public int top;\n /**\n * 右。默认0\n */\n public int right;\n /**\n * 下。默认0\n */\n public int bottom;\n}" }, { "identifier": "SubColor", "path": "sdk-core/src/main/java/net/aibote/sdk/options/SubColor.java", "snippet": "@AllArgsConstructor\npublic class SubColor {\n public int offsetX;\n public int offsetY;\n public String colorStr;\n}" }, { "identifier": "HttpClientUtils", "path": "sdk-common/src/main/java/net/aibote/utils/HttpClientUtils.java", "snippet": "@Slf4j\npublic class HttpClientUtils {\n\n private static CloseableHttpClient httpClient;\n\n /**\n * post请求 json参数\n *\n * @param url\n * @param bodyJsonParams\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPost(String url, String bodyJsonParams, Map<String, String> headers) throws Exception {\n HttpPost httpPost = new HttpPost(url);\n //httpPost.setProtocolVersion(new ProtocolVersion(\"HTTP\", 1, 0));\n httpPost.addHeader(\"Content-Type\", \"application/json\");\n httpPost.setEntity(new StringEntity(bodyJsonParams, StandardCharsets.UTF_8));\n\n addHeader(httpPost, headers);\n return execute(httpPost);\n }\n\n /**\n * post请求 json参数\n *\n * @param url\n * @param httpEntity\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPost(String url, HttpEntity httpEntity, Map<String, String> headers) throws Exception {\n HttpPost httpPost = new HttpPost(url);\n //httpPost.setProtocolVersion(new ProtocolVersion(\"HTTP\", 1, 1));\n //httpPost.addHeader(\"Content-Type\", \"application/json\");\n httpPost.setEntity(httpEntity);\n\n addHeader(httpPost, headers);\n return execute(httpPost);\n }\n\n /**\n * post k-v参数\n *\n * @param url\n * @param params\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPost(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {\n HttpPost httpPost = new HttpPost(url);\n //httpPost.setProtocolVersion(new ProtocolVersion(\"HTTP\", 1, 1));\n if (params != null && !params.keySet().isEmpty()) {\n httpPost.setEntity(getUrlEncodedFormEntity(params));\n }\n addHeader(httpPost, headers);\n return execute(httpPost);\n }\n\n /**\n * patch json参数\n *\n * @param url\n * @param bodyJsonParams\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPatch(String url, String bodyJsonParams, Map<String, String> headers) throws Exception {\n HttpPatch httpPatch = new HttpPatch(url);\n httpPatch.setEntity(new StringEntity(bodyJsonParams));\n addHeader(httpPatch, headers);\n return execute(httpPatch);\n }\n\n /**\n * patch k-v参数\n *\n * @param url\n * @param params\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPatch(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {\n HttpPatch httpPatch = new HttpPatch(url);\n if (params != null && !params.isEmpty()) {\n httpPatch.setEntity(getUrlEncodedFormEntity(params));\n }\n addHeader(httpPatch, headers);\n return execute(httpPatch);\n }\n\n /**\n * PUT JSON参数\n *\n * @param url\n * @param bodyJsonParams\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPut(String url, String bodyJsonParams, Map<String, String> headers) throws Exception {\n HttpPut httpPut = new HttpPut(url);\n httpPut.addHeader(\"Content-Type\", \"application/json\");\n httpPut.setEntity(new StringEntity(bodyJsonParams, StandardCharsets.UTF_8));\n\n addHeader(httpPut, headers);\n return execute(httpPut);\n }\n\n /**\n * put k-v参数\n *\n * @param url\n * @param params\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doPut(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {\n HttpPut httpPut = new HttpPut(url);\n if (params != null && params.keySet().isEmpty()) {\n httpPut.setEntity(getUrlEncodedFormEntity(params));\n }\n addHeader(httpPut, headers);\n return execute(httpPut);\n }\n\n /**\n * delete k-v参数\n *\n * @param url\n * @param params\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doDelete(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {\n\n StringBuilder paramsBuilder = new StringBuilder(url);\n if (params != null && !params.keySet().isEmpty()) {\n if (url.indexOf(\"?\") == -1) {\n paramsBuilder.append(\"?\");\n }\n String paramsStr = EntityUtils.toString(Objects.requireNonNull(getUrlEncodedFormEntity(params)));\n paramsBuilder.append(paramsStr);\n }\n\n HttpDelete httpDelete = new HttpDelete(paramsBuilder.toString());\n addHeader(httpDelete, headers);\n\n return execute(httpDelete);\n }\n\n /**\n * head请求\n *\n * @param url\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doHeader(String url, Map<String, String> headers) throws Exception {\n HttpHead httpHead = new HttpHead(url);\n addHeader(httpHead, headers);\n return execute(httpHead);\n\n }\n\n /**\n * get请求\n *\n * @param url\n * @param params\n * @param headers\n * @return\n * @throws IOException\n */\n public static String doGet(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {\n // 参数\n StringBuilder paramsBuilder = new StringBuilder(url);\n if (params != null && !params.keySet().isEmpty()) {\n if (url.indexOf(\"?\") == -1) {\n paramsBuilder.append(\"?\");\n }\n String paramsStr = EntityUtils.toString(getUrlEncodedFormEntity(params));\n paramsBuilder.append(paramsStr);\n }\n HttpGet httpGet = new HttpGet(paramsBuilder.toString());\n addHeader(httpGet, headers);\n return execute(httpGet);\n }\n\n /**\n * 执行请求并返回string值\n *\n * @param httpUriRequest\n * @return\n * @throws IOException\n */\n private static String execute(HttpUriRequest httpUriRequest) throws IOException, ParseException {\n if (null == httpClient) {\n synchronized (httpUriRequest) {\n httpClient = HttpClients.createDefault();\n log.info(\"加锁,创建httpClient\");\n }\n }\n CloseableHttpResponse response = httpClient.execute(httpUriRequest);\n String defaultCharset = \"UTF-8\";\n if (null != response.getEntity().getContentType()) {\n String charset = getCharSet(response.getEntity().getContentType());\n if (!StringUtils.isEmpty(charset)) {\n defaultCharset = charset;\n }\n }\n\n return EntityUtils.toString(response.getEntity(), defaultCharset);\n\n }\n\n /**\n * 添加请求头部\n *\n * @param httpUriRequest\n * @param headers\n */\n private static void addHeader(HttpUriRequest httpUriRequest, Map<String, String> headers) {\n if (httpUriRequest != null) {\n if (headers != null && !headers.keySet().isEmpty()) {\n Set<String> keySet = headers.keySet();\n for (String key : keySet) {\n String value = headers.get(key);\n httpUriRequest.addHeader(key, value);\n }\n }\n }\n }\n\n /**\n * 获取 UrlEncodedFormEntity 参数实体\n *\n * @param params\n * @return\n * @throws UnsupportedEncodingException\n */\n private static UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, Object> params) throws UnsupportedEncodingException {\n if (params != null && !params.keySet().isEmpty()) {\n List<NameValuePair> list = new ArrayList<>();\n Set<String> keySet = params.keySet();\n Iterator<String> iterator = keySet.iterator();\n while (iterator.hasNext()) {\n String key = iterator.next();\n log.info(\"key :\" + key);\n Object value = params.get(key);\n log.info(\"value:\" + value);\n if (value == null) {\n continue;\n }\n String valueStr = value.toString();\n list.add(new BasicNameValuePair(key, valueStr));\n }\n return new UrlEncodedFormEntity(list, Charset.defaultCharset());\n }\n return null;\n }\n\n /**\n * 根据HTTP 响应头部的content type抓取响应的字符集编码\n *\n * @param content\n * @return\n */\n private static String getCharSet(String content) {\n String regex = \".*charset=([^;]*).*\";\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(content);\n if (matcher.find()) return matcher.group(1);\n else return null;\n }\n\n}" }, { "identifier": "ImageBase64Converter", "path": "sdk-common/src/main/java/net/aibote/utils/ImageBase64Converter.java", "snippet": "public class ImageBase64Converter {\n /**\n * 本地文件(图片、excel等)转换成Base64字符串\n *\n * @param imgPath\n */\n public static String convertFileToBase64(String imgPath) {\n byte[] data = null;\n // 读取图片字节数组\n try {\n InputStream in = Files.newInputStream(Paths.get(imgPath));\n System.out.println(\"文件大小(字节)=\" + in.available());\n data = new byte[in.available()];\n in.read(data);\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n // 对字节数组进行Base64编码,得到Base64编码的字符串\n return Base64Utils.encodeBASE64(data);\n }\n\n /**\n * 将base64字符串,生成文件\n */\n public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {\n BufferedOutputStream bos = null;\n FileOutputStream fos = null;\n File file = null;\n try {\n File dir = new File(filePath);\n if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在\n dir.mkdirs();\n }\n\n byte[] bfile = Base64Utils.decodeBASE64(fileBase64String);\n\n file = new File(filePath + File.separator + fileName);\n fos = new FileOutputStream(file);\n bos = new BufferedOutputStream(fos);\n bos.write(bfile);\n return file;\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n } finally {\n if (bos != null) {\n try {\n bos.close();\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n if (fos != null) {\n try {\n fos.close();\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n }\n\n}" } ]
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import lombok.Data; import lombok.EqualsAndHashCode; import net.aibote.sdk.dto.OCRResult; import net.aibote.sdk.dto.Point; import net.aibote.sdk.options.Mode; import net.aibote.sdk.options.Region; import net.aibote.sdk.options.SubColor; import net.aibote.utils.HttpClientUtils; import net.aibote.utils.ImageBase64Converter; import org.apache.commons.lang3.StringUtils; import java.util.*;
7,599
* @param hwnd 窗口句柄 * @param frameRate 前后两张图相隔的时间,单位毫秒 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findAnimation(String hwnd, int frameRate, Region region, Mode mode) { return strDelayCmd("findAnimation", hwnd, Integer.toString(frameRate), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), mode.boolValueStr()); } /** * 查找指定色值的坐标点 * * @param hwnd 窗口句柄 * @param strMainColor 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 在指定区域内找色,默认全屏; * @param sim 相似度。0.0-1.0,sim默认为1 * @param mode 后台 true,前台 false。默认前台操作。 * @return String 成功返回 x|y 失败返回null */ public String findColor(String hwnd, String strMainColor, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.strDelayCmd("findColor", hwnd, strMainColor, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 比较指定坐标点的颜色值 * * @param hwnd 窗口句柄 * @param mainX 主颜色所在的X坐标 * @param mainY 主颜色所在的Y坐标 * @param mainColorStr 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 截图区域 默认全屏 * @param sim 相似度,0-1 的浮点数 * @param mode 操作模式,后台 true,前台 false, * @return boolean */ public boolean compareColor(String hwnd, int mainX, int mainY, String mainColorStr, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.boolDelayCmd("compareColor", hwnd, Integer.toString(mainX), Integer.toString(mainY), mainColorStr, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 提取视频帧 * * @param videoPath 视频路径 * @param saveFolder 提取的图片保存的文件夹目录 * @param jumpFrame 跳帧,默认为1 不跳帧 * @return boolean 成功返回true,失败返回false */ public boolean extractImageByVideo(String videoPath, String saveFolder, int jumpFrame) { return this.boolCmd("extractImageByVideo", videoPath, saveFolder, Integer.toString(jumpFrame)); } /** * 裁剪图片 * * @param imagePath 图片路径 * @param saveFolder 裁剪后保存的图片路径 * @param region 区域 * @return boolean 成功返回true,失败返回false */ public boolean cropImage(String imagePath, String saveFolder, Region region) { return this.boolCmd("cropImage", imagePath, saveFolder, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom)); } /** * 初始化ocr服务 * * @param ocrServerIp ocr服务器IP * @param ocrServerPort ocr服务器端口,固定端口9527。 注意,如果传入的值<=0 ,则都会当默认端口处理。 * @param useAngleModel 支持图像旋转。 默认false。仅内置ocr有效。内置OCR需要安装 * @param enableGPU 启动GPU 模式。默认false 。GPU模式需要电脑安装NVIDIA驱动,并且到群文件下载对应cuda版本 * @param enableTensorrt 启动加速,仅 enableGPU = true 时有效,默认false 。图片太大可能会导致GPU内存不足 * @return boolean 总是返回true */ public boolean initOcr(String ocrServerIp, int ocrServerPort, boolean useAngleModel, boolean enableGPU, boolean enableTensorrt) { //if (ocrServerPort <= 0) { ocrServerPort = 9527; //} return this.boolCmd("initOcr", ocrServerIp, Integer.toString(ocrServerPort), Boolean.toString(useAngleModel), Boolean.toString(enableGPU), Boolean.toString(enableTensorrt)); } /** * ocr识别 * * @param hwnd 窗口句柄 * @param region 区域 * @param thresholdType 二值化算法类型 * @param thresh 阈值 * @param maxval 最大值 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return String jsonstr */
package net.aibote.sdk; @EqualsAndHashCode(callSuper = true) @Data public abstract class WinBot extends Aibote { /** * 查找窗口句柄 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindow(String className, String windowName) { return strCmd("findWindow", className, windowName); } /** * 查找窗口句柄数组, 以 “|” 分割 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindows(String className, String windowName) { return strCmd("findWindows", className, windowName); } /** * 查找窗口句柄 * * @param curHwnd 当前窗口句柄 * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findSubWindow(String curHwnd, String className, String windowName) { return strCmd("findSubWindow", curHwnd, className, windowName); } /** * 查找父窗口句柄 * * @param curHwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String findParentWindow(String curHwnd) { return strCmd("findParentWindow", curHwnd); } /** * 查找桌面窗口句柄 * * @return 成功返回窗口句柄,失败返回null */ public String findDesktopWindow() { return strCmd("findDesktopWindow"); } /** * 获取窗口名称 * * @param hwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String getWindowName(String hwnd) { return strCmd("getWindowName", hwnd); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isShow 是否显示 * @return boolean 成功返回true,失败返回false */ public boolean showWindow(String hwnd, boolean isShow) { return boolCmd("showWindow", hwnd, String.valueOf(isShow)); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isTop 是否置顶 * @return boolean 成功返回true,失败返回false */ public boolean setWindowTop(String hwnd, boolean isTop) { return boolCmd("setWindowTop", hwnd, String.valueOf(isTop)); } /** * 获取窗口位置。 用“|”分割 * * @param hwnd 当前窗口句柄 * @return 0|0|0|0 */ public String getWindowPos(String hwnd) { return strCmd("getWindowPos", hwnd); } /** * 设置窗口位置 * * @param hwnd 当前窗口句柄 * @param left 左上角横坐标 * @param top 左上角纵坐标 * @param width width 窗口宽度 * @param height height 窗口高度 * @return boolean 成功返回true 失败返回 false */ public boolean setWindowPos(String hwnd, int left, int top, int width, int height) { return boolCmd("setWindowPos", hwnd, Integer.toString(left), Integer.toString(top), Integer.toString(width), Integer.toString(height)); } /** * 移动鼠标 <br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true */ public boolean moveMouse(String hwnd, int x, int y, Mode mode, String elementHwnd) { return boolCmd("moveMouse", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr(), elementHwnd); } /** * 移动鼠标(相对坐标) * * @param hwnd 窗口句柄 * @param x 相对横坐标 * @param y 相对纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean moveMouseRelative(String hwnd, int x, int y, Mode mode) { return boolCmd("moveMouseRelative", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr()); } /** * 滚动鼠标 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param dwData 鼠标滚动次数,负数下滚鼠标,正数上滚鼠标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean rollMouse(String hwnd, int x, int y, int dwData, Mode mode) { return boolCmd("rollMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(dwData), mode.boolValueStr()); } /** * 鼠标点击<br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mouseType 单击左键:1 单击右键:2 按下左键:3 弹起左键:4 按下右键:5 弹起右键:6 双击左键:7 双击右键:8 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true。 */ public boolean clickMouse(String hwnd, int x, int y, int mouseType, Mode mode, String elementHwnd) { return boolCmd("clickMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(mouseType), mode.boolValueStr(), elementHwnd); } /** * 输入文本 * * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeys(String txt) { return boolCmd("sendKeys", txt); } /** * 后台输入文本 * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeysByHwnd(String hwnd, String txt) { return boolCmd("sendKeysByHwnd", hwnd, txt); } /** * 输入虚拟键值(VK) * * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVk(int vk, int keyState) { return boolCmd("sendVk", Integer.toString(vk), Integer.toString(keyState)); } /** * 后台输入虚拟键值(VK) * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVkByHwnd(String hwnd, int vk, int keyState) { return boolCmd("sendVkByHwnd", hwnd, Integer.toString(vk), Integer.toString(keyState)); } /** * 截图保存。threshold默认保存原图。 * * @param hwnd 窗口句柄 * @param savePath 保存的位置 * @param region 区域 * @param thresholdType hresholdType算法类型。<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。 thresh和maxval同为255时灰度处理 * @param maxval 最大值。 thresh和maxval同为255时灰度处理 * @return boolean */ public boolean saveScreenshot(String hwnd, String savePath, Region region, int thresholdType, int thresh, int maxval) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } return boolCmd("saveScreenshot", hwnd, savePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval)); } /** * 获取指定坐标点的色值 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回#开头的颜色值,失败返回null */ public String getColor(String hwnd, int x, int y, boolean mode) { return strCmd("getColor", hwnd, Integer.toString(x), Integer.toString(y), Boolean.toString(mode)); } /** * @param hwndOrBigImagePath 窗口句柄或者图片路径 * @param smallImagePath 小图片路径,多张小图查找应当用"|"分开小图路径 * @param region 区域 * @param sim 图片相似度 0.0-1.0,sim默认0.95 * @param thresholdType thresholdType算法类型:<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param maxval 最大值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param multi 找图数量,默认为1 找单个图片坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。hwndOrBigImagePath为图片文件,此参数无效 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findImages(String hwndOrBigImagePath, String smallImagePath, Region region, float sim, int thresholdType, int thresh, int maxval, int multi, Mode mode) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } String strData = null; if (hwndOrBigImagePath.toString().indexOf(".") == -1) {//在窗口上找图 return strDelayCmd("findImage", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } else {//在文件上找图 return this.strDelayCmd("findImageByFile", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } } /** * 找动态图 * * @param hwnd 窗口句柄 * @param frameRate 前后两张图相隔的时间,单位毫秒 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findAnimation(String hwnd, int frameRate, Region region, Mode mode) { return strDelayCmd("findAnimation", hwnd, Integer.toString(frameRate), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), mode.boolValueStr()); } /** * 查找指定色值的坐标点 * * @param hwnd 窗口句柄 * @param strMainColor 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 在指定区域内找色,默认全屏; * @param sim 相似度。0.0-1.0,sim默认为1 * @param mode 后台 true,前台 false。默认前台操作。 * @return String 成功返回 x|y 失败返回null */ public String findColor(String hwnd, String strMainColor, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.strDelayCmd("findColor", hwnd, strMainColor, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 比较指定坐标点的颜色值 * * @param hwnd 窗口句柄 * @param mainX 主颜色所在的X坐标 * @param mainY 主颜色所在的Y坐标 * @param mainColorStr 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 截图区域 默认全屏 * @param sim 相似度,0-1 的浮点数 * @param mode 操作模式,后台 true,前台 false, * @return boolean */ public boolean compareColor(String hwnd, int mainX, int mainY, String mainColorStr, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.boolDelayCmd("compareColor", hwnd, Integer.toString(mainX), Integer.toString(mainY), mainColorStr, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 提取视频帧 * * @param videoPath 视频路径 * @param saveFolder 提取的图片保存的文件夹目录 * @param jumpFrame 跳帧,默认为1 不跳帧 * @return boolean 成功返回true,失败返回false */ public boolean extractImageByVideo(String videoPath, String saveFolder, int jumpFrame) { return this.boolCmd("extractImageByVideo", videoPath, saveFolder, Integer.toString(jumpFrame)); } /** * 裁剪图片 * * @param imagePath 图片路径 * @param saveFolder 裁剪后保存的图片路径 * @param region 区域 * @return boolean 成功返回true,失败返回false */ public boolean cropImage(String imagePath, String saveFolder, Region region) { return this.boolCmd("cropImage", imagePath, saveFolder, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom)); } /** * 初始化ocr服务 * * @param ocrServerIp ocr服务器IP * @param ocrServerPort ocr服务器端口,固定端口9527。 注意,如果传入的值<=0 ,则都会当默认端口处理。 * @param useAngleModel 支持图像旋转。 默认false。仅内置ocr有效。内置OCR需要安装 * @param enableGPU 启动GPU 模式。默认false 。GPU模式需要电脑安装NVIDIA驱动,并且到群文件下载对应cuda版本 * @param enableTensorrt 启动加速,仅 enableGPU = true 时有效,默认false 。图片太大可能会导致GPU内存不足 * @return boolean 总是返回true */ public boolean initOcr(String ocrServerIp, int ocrServerPort, boolean useAngleModel, boolean enableGPU, boolean enableTensorrt) { //if (ocrServerPort <= 0) { ocrServerPort = 9527; //} return this.boolCmd("initOcr", ocrServerIp, Integer.toString(ocrServerPort), Boolean.toString(useAngleModel), Boolean.toString(enableGPU), Boolean.toString(enableTensorrt)); } /** * ocr识别 * * @param hwnd 窗口句柄 * @param region 区域 * @param thresholdType 二值化算法类型 * @param thresh 阈值 * @param maxval 最大值 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return String jsonstr */
public List<OCRResult> ocrByHwnd(String hwnd, Region region, int thresholdType, int thresh, int maxval, Mode mode) {
0
2023-11-08 14:31:58+00:00
12k
SeanPesce/AWS-IoT-Recon
src/main/java/com/seanpesce/aws/iot/AwsIotRecon.java
[ { "identifier": "AwsIotConstants", "path": "src/main/java/com/seanpesce/aws/iot/AwsIotConstants.java", "snippet": "public class AwsIotConstants {\n\n public static final String PROJECT_TITLE = \"[AWS IoT Core Enumeration Tool by Sean Pesce]\";\n\n public static final String ACTION_MQTT_DUMP = \"mqtt-dump\";\n public static final String ACTION_MQTT_TOPIC_FIELD_HARVEST = \"mqtt-topic-field-harvest\";\n public static final String ACTION_IAM_CREDS = \"iam-credentials\";\n public static final String ACTION_MQTT_SCRIPT = \"mqtt-script\";\n public static final String ACTION_MQTT_DATA_EXFIL = \"mqtt-data-exfil\";\n public static final String ACTION_GET_SHADOW = \"get-device-shadow\";\n public static final String ACTION_LIST_NAMED_SHADOWS = \"list-named-shadows\";\n public static final String ACTION_GET_JOBS = \"get-jobs\";\n public static final String ACTION_LIST_RETAINED_MQTT_MESSAGES = \"list-retained-mqtt-messages\";\n public static final List<String> CLI_ACTIONS = Collections.unmodifiableList(Arrays.asList(new String[]{\n ACTION_MQTT_DUMP,\n ACTION_MQTT_TOPIC_FIELD_HARVEST,\n ACTION_IAM_CREDS, ACTION_MQTT_SCRIPT,\n ACTION_MQTT_DATA_EXFIL,\n ACTION_GET_SHADOW,\n ACTION_LIST_NAMED_SHADOWS,\n ACTION_GET_JOBS,\n ACTION_LIST_RETAINED_MQTT_MESSAGES\n }));\n public static final String CLI_AUTH_ARG = \"(Auth option) \";\n \n public static final short AWS_IOT_REST_API_PORT = 8443;\n public static final String MQTT_ALL_TOPICS = \"#\";\n public static final String MQTT_RESERVED_TOPIC_PREFIX = \"$aws\";\n public static final String MQTT_PING_TOPIC = \"mqtt_ping\";\n\n // Used by the test implementation in the initial \"device connection kit.\" These might be left\n // over from initial setup.\n // @TODO: Make some tests involving these topics/client IDs?\n public static final String[] SETUP_TEST_SDK_MQTT_TOPICS = {\n \"sdk/test/java\",\n \"sdk/test/python\",\n \"sdk/test/js\",\n };\n public static final String[] SETUP_TEST_SDK_CLIENT_IDS = {\n \"sdk-java\",\n \"basicPubSub\",\n \"sdk-nodejs-test\", // sdk-nodejs-*\n (\"sdk-nodejs-\"+System.currentTimeMillis()) // sdk-nodejs-*\n };\n\n\n // https://docs.aws.amazon.com/iot/latest/developerguide/reserved-topics.html\n public static final PatternWithNamedGroups[] RESERVED_TOPICS_REGEX = {\n PatternWithNamedGroups.compile(\"^\\\\$aws/device_location/(?<thingName>[^/]+)/get_position_estimate$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/device_location/(?<thingName>[^/]+)/get_position_estimate/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/device_location/(?<thingName>[^/]+)/get_position_estimate/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/certificates/registered/(?<caCertificateId>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/presence/connected/(?<clientId>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/presence/disconnected/(?<clientId>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/subscriptions/subscribed/(?<clientId>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/subscriptions/unsubscribed/(?<clientId>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thing/(?<thingName>[^/]+)/created$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thing/(?<thingName>[^/]+)/updated$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thing/(?<thingName>[^/]+)/deleted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroup/(?<thingGroupName>[^/]+)/created$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroup/(?<thingGroupName>[^/]+)/updated$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroup/(?<thingGroupName>[^/]+)/deleted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingType/(?<thingTypeName>[^/]+)/created$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingType/(?<thingTypeName>[^/]+)/updated$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingType/(?<thingTypeName>[^/]+)/deleted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingTypeAssociation/thing/(?<thingName>[^/]+)/(?<thingTypeName>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroupMembership/thingGroup/(?<thingGroupName>[^/]+)/thing/(?<thingName>[^/]+)/added$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroupMembership/thingGroup/(?<thingGroupName>[^/]+)/thing/(?<thingName>[^/]+)/removed$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroupHierarchy/thingGroup/(?<parentThingGroupName>[^/]+)/childThingGroup/(?<childThingGroupName>[^/]+)/added$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/events/thingGroupHierarchy/thingGroup/(?<parentThingGroupName>[^/]+)/childThingGroup/(?<childThingGroupName>[^/]+)/removed$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/provisioning-templates/(?<templateName>[^/]+)/provision/(?<payloadFormat>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/provisioning-templates/(?<templateName>[^/]+)/provision/(?<payloadFormat>[^/]+)/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/provisioning-templates/(?<templateName>[^/]+)/provision/(?<payloadFormat>[^/]+)/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/rules/(?<ruleName>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/sitewise/asset-models/(?<assetModelId>[^/]+)/assets/(?<assetId>[^/]+)/properties/(?<propertyId>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/defender/metrics/(?<payloadFormat>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/defender/metrics/(?<payloadFormat>[^/]+)/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/defender/metrics/(?<payloadFormat>[^/]+)/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/get$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/get/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/get/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/start-next$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/start-next/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/start-next/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/(?<jobId>[^/]+)/get$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/(?<jobId>[^/]+)/get/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/(?<jobId>[^/]+)/get/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/(?<jobId>[^/]+)/update$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/(?<jobId>[^/]+)/update/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/(?<jobId>[^/]+)/update/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/notify$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/jobs/notify-next$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/tunnels/notify$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/delete$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/delete/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/delete/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/get$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/get/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/get/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/update$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/update/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/update/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/update/delta$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/update/documents$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/delete$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/delete/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/delete/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/get$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/get/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/get/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/update$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/update/accepted$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/update/rejected$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/update/delta$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/shadow/name/(?<shadowName>[^/]+)/update/documents$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/streams/(?<streamId>[^/]+)/data/(?<payloadFormat>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/streams/(?<streamId>[^/]+)/get/(?<payloadFormat>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/streams/(?<streamId>[^/]+)/description/(?<payloadFormat>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/streams/(?<streamId>[^/]+)/describe/(?<payloadFormat>[^/]+)$\"),\n PatternWithNamedGroups.compile(\"^\\\\$aws/things/(?<thingName>[^/]+)/streams/(?<streamId>[^/]+)/rejected/(?<payloadFormat>[^/]+)$\")\n };\n\n}" }, { "identifier": "MtlsHttpClient", "path": "src/main/java/com/seanpesce/http/MtlsHttpClient.java", "snippet": "public class MtlsHttpClient {\n\n // public static final HostnameVerifier insecureHostnameVerifier = new HostnameVerifier() {\n // public boolean verify(String hostname, SSLSession sslSession) {\n // return true;\n // }\n // };\n\n\n // public static final TrustManager[] insecureTrustManager = {\n // new X509TrustManager() {\n // public X509Certificate[] getAcceptedIssuers() {\n // return new X509Certificate[0];\n // }\n\n // public void checkClientTrusted(\n // X509Certificate[] certificates, String authType) {\n // }\n\n // public void checkServerTrusted(\n // X509Certificate[] certificates, String authType) {\n // }\n // }\n // };\n\n\n\n // @TODO: Actually implement mTLS client in Java instead of using this work-around\n public static String mtlsHttpGet(String url, String clientCertPath, String clientPrivkeyPath, String caCertPath, boolean insecure) {\n final String[] curlCmdBase = new String[]{ \"curl\", \"-s\", \"--cert\", clientCertPath, \"--key\", clientPrivkeyPath, \"--cacert\", caCertPath };\n String[] curlCmd = null;\n if (insecure) {\n curlCmd = Arrays.copyOf(curlCmdBase, curlCmdBase.length + 2);\n curlCmd[curlCmd.length-2] = \"-k\";\n curlCmd[curlCmd.length-1] = url;\n } else {\n curlCmd = Arrays.copyOf(curlCmdBase, curlCmdBase.length + 1);\n curlCmd[curlCmd.length-1] = url;\n }\n\n System.err.println(\"[INFO] HTTP GET \" + url);\n\n Process subproc = null;\n BufferedReader stdout = null;\n BufferedReader stderr = null;\n String output = \"\";\n try {\n subproc = Runtime.getRuntime().exec(curlCmd);\n stdout = new BufferedReader(new InputStreamReader(subproc.getInputStream()));\n stderr = new BufferedReader(new InputStreamReader(subproc.getErrorStream()));\n\n String line = null;\n while ((line = stdout.readLine()) != null) {\n output += line;\n }\n line = null;\n while ((line = stderr.readLine()) != null) {\n output += line;\n }\n } catch (IOException ex) {\n return null;\n }\n\n return output;\n }\n\n}" }, { "identifier": "MqttScript", "path": "src/main/java/com/seanpesce/mqtt/MqttScript.java", "snippet": "public class MqttScript {\r\n\r\n\r\n public static class Instruction {\r\n\r\n protected String op = null;\r\n protected String topic = null;\r\n protected byte[] payload = null;\r\n\r\n public static final String OP_PUBLISH = \"PUB\";\r\n public static final String OP_SUBSCRIBE = \"SUB\";\r\n public static final String OP_UNSUBSCRIBE = \"UNSUB\";\r\n public static final String OP_SLEEP = \"SLEEP\";\r\n public static final List<String> SUPPORTED_OPERATIONS = Collections.unmodifiableList(Arrays.asList(new String[]{\r\n OP_PUBLISH,\r\n OP_SUBSCRIBE,\r\n OP_UNSUBSCRIBE,\r\n OP_SLEEP\r\n }));\r\n \r\n\r\n public Instruction(String op, String topic) {\r\n this(op, topic, null);\r\n }\r\n\r\n public Instruction(@NotNull String op, @NotNull String topic, byte[] payload) {\r\n String opUpper = op.toUpperCase();\r\n\r\n if (opUpper.equals(OP_SUBSCRIBE) || opUpper.equals(OP_UNSUBSCRIBE) || opUpper.equals(OP_SLEEP)) {\r\n if (payload != null && payload.length != 0) {\r\n throw new UnsupportedOperationException(opUpper + \" operation does not support payload data\");\r\n }\r\n this.payload = null;\r\n\r\n } else if (opUpper.equals(OP_PUBLISH)) {\r\n this.payload = payload;\r\n if (this.payload == null) {\r\n this.payload = new byte[0];\r\n }\r\n\r\n } else {\r\n throw new UnsupportedOperationException(op);\r\n }\r\n\r\n this.op = opUpper;\r\n\r\n if (opUpper.equals(OP_SLEEP)) {\r\n long sleepDelay = Long.parseLong(topic, 10);\r\n if (sleepDelay < 0) {\r\n sleepDelay = 0;\r\n }\r\n this.topic = \"\" + sleepDelay;\r\n } else {\r\n this.topic = topic;\r\n }\r\n }\r\n\r\n\r\n public String getOp() {\r\n return this.op;\r\n }\r\n\r\n public String getTopic() {\r\n return this.topic;\r\n }\r\n\r\n public byte[] getPayload() {\r\n return this.payload;\r\n }\r\n\r\n public long getDelay() {\r\n if (this.getOp().equals(OP_SLEEP)) {\r\n return Long.parseLong(this.topic, 10);\r\n }\r\n throw new UnsupportedOperationException(\"Sleep delay unsupported for \" + this.getOp());\r\n }\r\n\r\n public void setOp(@NotNull String op) {\r\n String opUpper = op.toUpperCase();\r\n if (SUPPORTED_OPERATIONS.contains(opUpper)) {\r\n this.op = opUpper;\r\n }\r\n throw new UnsupportedOperationException(op);\r\n }\r\n\r\n public void setTopic (@NotNull String topic) {\r\n if (this.getOp().equals(OP_SLEEP)) {\r\n long sleepDelay = Long.parseLong(topic, 10);\r\n if (sleepDelay < 0) {\r\n sleepDelay = 0;\r\n }\r\n this.topic = \"\" + sleepDelay;\r\n } else {\r\n this.topic = topic;\r\n }\r\n }\r\n\r\n public void setDelay(long delay) {\r\n if (this.getOp().equals(OP_SLEEP)) {\r\n if (delay < 0) {\r\n delay = 0;\r\n }\r\n this.topic = \"\" + delay;\r\n }\r\n throw new UnsupportedOperationException(\"Sleep delay unsupported for \" + this.getOp());\r\n }\r\n\r\n public void setPayload(byte[] payload) {\r\n this.payload = payload;\r\n }\r\n\r\n public String toString() {\r\n String strVal = this.getOp() + FIELD_SEP + this.getTopic();\r\n // Stringify payload for PUB instruction\r\n if (this.getOp().equals(OP_PUBLISH)) {\r\n strVal += FIELD_SEP;\r\n\r\n ArrayList<Byte> payload = new ArrayList<Byte>();\r\n for (byte b : this.getPayload()) {\r\n payload.add(b);\r\n }\r\n ArrayList<Byte> fieldSep = new ArrayList<Byte>();\r\n byte[] fieldSepBytes = FIELD_SEP.getBytes(CHARSET);\r\n for (byte b : fieldSepBytes) {\r\n fieldSep.add(b);\r\n }\r\n // Check if newline or field separator are in the payload, and if so,\r\n // hexlify it. Otherwise, insert the raw payload.\r\n if (payload.contains(Byte.valueOf((byte)0x0a)) || Collections.indexOfSubList(payload, fieldSep) != -1) {\r\n // Hexlify the payload\r\n strVal += PAYLOAD_TYPE_HEX;\r\n strVal += Util.bytesToHex(this.getPayload());\r\n } else {\r\n // Insert the payload raw\r\n strVal += new String(this.getPayload(), CHARSET);\r\n }\r\n }\r\n return strVal;\r\n }\r\n }\r\n \r\n\r\n // Special payload prefixes\r\n public static final String PAYLOAD_TYPE_FILE = \"file://\";\r\n public static final String PAYLOAD_TYPE_HEX = \"hex://\";\r\n\r\n // Instruction field delimiter\r\n public static String FIELD_SEP = \"\\t\";\r\n // Comment delimiter\r\n public static String COMMENT_DELIM = \"#\";\r\n\r\n public static Charset CHARSET = StandardCharsets.UTF_8;\r\n // Whether to remove leading/trailing whitespace from topic strings\r\n public static boolean TRIM_TOPICS = true;\r\n\r\n\r\n // Parse the specified file into a series of MQTT script instructions\r\n public static List<Instruction> parseFromFile(@NotNull String scriptFilePath) throws IOException {\r\n String scriptData = new String(Files.readAllBytes(Paths.get(scriptFilePath)), CHARSET);\r\n return parse(scriptData);\r\n }\r\n\r\n\r\n // Parse string data into a series of MQTT script instructions\r\n public static List<Instruction> parse(@NotNull String scriptData) throws IOException {\r\n ArrayList<Instruction> instructions = new ArrayList<Instruction>();\r\n String[] lines = scriptData.split(\"\\n\");\r\n\r\n for (int i = 0; i < lines.length; i++) {\r\n String line = lines[i];\r\n String lineTrimmed = line.trim();\r\n\r\n // Ignore empty lines, lines that only contain whitespace, and comments\r\n if (lineTrimmed.isBlank() || lineTrimmed.startsWith(COMMENT_DELIM)) {\r\n continue;\r\n }\r\n\r\n String[] instructionFields = line.split(FIELD_SEP);\r\n if (instructionFields.length < 2 || instructionFields.length > 3) {\r\n throw new IOException(\"Invalid number of MQTT instruction fields (\" + instructionFields.length + \") in line \" + i+1);\r\n }\r\n\r\n // Clean up fields\r\n String op = instructionFields[0].trim();\r\n String topic = instructionFields[1];\r\n if (TRIM_TOPICS) {\r\n topic = topic.trim();\r\n }\r\n\r\n // Parse payload\r\n byte[] payload = null;\r\n if (instructionFields.length > 2) {\r\n payload = parsePayload(instructionFields[2]);\r\n }\r\n\r\n instructions.add(new Instruction(op, topic, payload));\r\n }\r\n\r\n return instructions;\r\n }\r\n\r\n\r\n // Determines whether a payload is raw data, a path to a file to read,\r\n // or a hex representation of bytes, and returns the parsed payload.\r\n public static byte[] parsePayload(String payload) throws IOException {\r\n if (payload == null) {\r\n return null;\r\n\r\n } else if (payload.startsWith(PAYLOAD_TYPE_FILE)) {\r\n String filePath = payload.substring(PAYLOAD_TYPE_FILE.length());\r\n return Files.readAllBytes(Paths.get(filePath));\r\n\r\n } else if (payload.startsWith(PAYLOAD_TYPE_HEX)) {\r\n String hexStr = payload.substring(PAYLOAD_TYPE_HEX.length());\r\n return Util.hexToBytes(hexStr.trim());\r\n }\r\n\r\n return payload.getBytes(CHARSET);\r\n }\r\n}\r" }, { "identifier": "PatternWithNamedGroups", "path": "src/main/java/com/seanpesce/regex/PatternWithNamedGroups.java", "snippet": "public class PatternWithNamedGroups {\n\n final static public Pattern NAMED_GROUP_REGEX = Pattern.compile(\"\\\\(\\\\?<(.+?)>.*?\\\\)\");\n\n\n protected Pattern mPattern = null;\n protected ArrayList<String> mGroupNames = null;\n\n\n protected PatternWithNamedGroups(Pattern pattern) {\n this.mPattern = pattern;\n this.mGroupNames = new ArrayList<String>();\n if (this.mPattern != null) {\n Matcher matcher = NAMED_GROUP_REGEX.matcher(this.mPattern.pattern());\n while (matcher.find()) {\n for (int i = 1; i <= matcher.groupCount(); i++) {\n this.mGroupNames.add(matcher.group(i));\n }\n }\n }\n }\n\n\n public Pattern getPattern() {\n return this.mPattern;\n }\n\n public List<String> getGroupNames() {\n return this.mGroupNames;\n }\n\n\n public static PatternWithNamedGroups compile(String regex) {\n return new PatternWithNamedGroups(Pattern.compile(regex));\n }\n\n public static PatternWithNamedGroups compile(String regex, int flags) {\n return new PatternWithNamedGroups(Pattern.compile(regex, flags));\n }\n\n}" }, { "identifier": "Util", "path": "src/main/java/com/seanpesce/Util.java", "snippet": "public class Util {\n\n // Checks if the provided string resolves to a readable file. If so, the file is read and the\n // file data is returned. If not, the provided string is returned unmodified.\n public static String getTextFileDataFromOptionalPath(@NotNull String pathOrData) throws IOException {\n if (!new File(pathOrData).exists()) {\n return pathOrData;\n }\n return new String(Files.readAllBytes(Paths.get(pathOrData)), StandardCharsets.UTF_8);\n }\n\n\n // Causes the current thread to sleep for the specified number of milliseconds (or until interrupted)\n public static void sleep(long milliseconds) {\n try {\n Thread.sleep(milliseconds);\n } catch (InterruptedException ex) {\n System.err.println(\"[WARNING] Sleep operation was interrupted: \" + ex.getMessage());\n }\n }\n\n\n // Causes the current thread to sleep forever, or until interrupted (e.g., when the user presses Ctrl+C)\n public static void sleepForever() {\n final int delaySecs = 2;\n while (true) {\n sleep(delaySecs * 1000);\n }\n }\n\n\n // \"Unhexlify\"\n public static byte[] hexToBytes(@NotNull String hexStr) {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n\n for (int i = 0; i < hexStr.length(); ) {\n if (Character.isWhitespace(hexStr.charAt(i))) {\n i++;\n continue;\n }\n String octetStr = hexStr.substring(i, i + 2);\n byte b = (byte)Short.parseShort(octetStr, 16);\n output.write(b);\n i += octetStr.length();\n }\n \n return output.toByteArray();\n }\n\n\n // \"Hexlify\"\n public static String bytesToHex(@NotNull byte[] data) {\n final char[] hexAlphabet = \"0123456789ABCDEF\".toCharArray();\n char[] hexChars = new char[data.length * 2];\n for (int i = 0; i < data.length; i++) {\n int val = data[i] & 0xFF;\n hexChars[i * 2] = hexAlphabet[val >>> 4];\n hexChars[i * 2 + 1] = hexAlphabet[val & 0x0F];\n }\n return new String(hexChars);\n }\n \n}" } ]
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.security.cert.CertificateException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import com.seanpesce.aws.iot.AwsIotConstants; import com.seanpesce.http.MtlsHttpClient; import com.seanpesce.mqtt.MqttScript; import com.seanpesce.regex.PatternWithNamedGroups; import com.seanpesce.Util; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import software.amazon.awssdk.crt.auth.credentials.Credentials; import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder;
9,676
public static void testDataExfilChannel() throws InterruptedException, ExecutionException { final String timestamp = "" + System.currentTimeMillis(); ArrayList<String> topics = new ArrayList<String>(); if (topicSubcriptions.isEmpty()) { // By default, use the current epoch timestamp for a unique MQTT topic topics.add(timestamp); } else { topics.addAll(topicSubcriptions); } final Consumer<MqttMessage> dataExfilConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { final String payloadStr = new String(message.getPayload(), StandardCharsets.UTF_8).trim(); String msg = null; if (payloadStr.equals(timestamp)) { System.out.println("\n[Data exfiltration] Confirmed data exfiltration channel via topic: " + message.getTopic()); } else { System.err.println("[WARNING] Unknown data received via data exfiltration channel (topic: " + message.getTopic() + "): " + payloadStr); } } }; // Subscribe to the data exfiltration topic(s) for (final String topic : topics) { System.err.println("[INFO] Testing data exfiltration via arbitrary topics (using topic: \"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, dataExfilConsumer); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); // Publish data to the data exfiltration topic MqttMessage msg = new MqttMessage(topic, timestamp.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_LEAST_ONCE); CompletableFuture<Integer> publication = clientConnection.publish(msg); publication.get(); } // Sleep 3 seconds to see if we receive our payload try { Thread.sleep(3000); } catch (InterruptedException ex) { System.err.println("[WARNING] Data exfiltration sleep operation was interrupted: " + ex.getMessage()); } // Unsubscribe from the data exfiltration topic(s) for (final String topic : topics) { CompletableFuture<Integer> unsub = clientConnection.unsubscribe(topic); unsub.get(); } } // Attempts to obtain IAM credentials for the specified role using the client mTLS key pair from an IoT "Thing" (device) // // Note that the iot:CredentialProvider is a different host/endpoint than the base IoT endpoint; it should have the format: // ${random_id}.credentials.iot.${region}.amazonaws.com // // (The random_id will also be different from the one in the base IoT Core endpoint) public static List<Credentials> getIamCredentialsFromDeviceX509(String[] roleAliases, String thingName) { // See also: // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/de4e5f3be56c325975674d4e3c0a801392edad96/samples/X509CredentialsProviderConnect/src/main/java/x509credentialsproviderconnect/X509CredentialsProviderConnect.java#L99 // https://awslabs.github.io/aws-crt-java/software/amazon/awssdk/crt/auth/credentials/X509CredentialsProvider.html // https://aws.amazon.com/blogs/security/how-to-eliminate-the-need-for-hardcoded-aws-credentials-in-devices-by-using-the-aws-iot-credentials-provider/ final String endpoint = cmd.getOptionValue("H"); if (!endpoint.contains("credentials.iot")) { System.err.println("[WARNING] Endpoint \"" + endpoint + "\" might not be an AWS IoT credentials provider; are you sure you have the right hostname? (Expected format: \"${random_id}.credentials.iot.${region}.amazonaws.com\")"); } ArrayList<Credentials> discoveredCreds = new ArrayList<Credentials>(); for (String roleAlias : roleAliases) { // // mTLS HTTP client method: // String url = "https://" + endpoint + "/role-aliases/" + roleAlias + "/credentials"; // String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // // Need to add header "x-amzn-iot-thingname: " + thingName // System.out.println(data); // return null; Credentials credentials = null; X509CredentialsProvider.X509CredentialsProviderBuilder x509CredsBuilder = new X509CredentialsProvider.X509CredentialsProviderBuilder(); x509CredsBuilder = x509CredsBuilder.withTlsContext(tlsContext); x509CredsBuilder = x509CredsBuilder.withEndpoint​(endpoint); x509CredsBuilder = x509CredsBuilder.withRoleAlias(roleAlias); x509CredsBuilder = x509CredsBuilder.withThingName(thingName); X509CredentialsProvider credsProvider = x509CredsBuilder.build(); CompletableFuture<Credentials> credsFuture = credsProvider.getCredentials(); try { credentials = credsFuture.get(); String credsStr = "{\"credentials\":{\"accessKeyId\":\"" + new String(credentials.getAccessKeyId(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"secretAccessKey\":\"" + new String(credentials.getSecretAccessKey(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"sessionToken\":\"" + new String(credentials.getSessionToken(), StandardCharsets.UTF_8) + "\"}}"; System.out.println(credsStr); discoveredCreds.add(credentials); } catch (ExecutionException | InterruptedException ex) { System.err.println("[ERROR] Failed to obtain credentials from X509 (role=\"" + roleAlias + "\"; thingName=\"" + thingName + "\"): " + ex.getMessage()); } credsProvider.close(); } return discoveredCreds; } public static void getDeviceShadow(String thingName, String shadowName) { // https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-rest-api.html#API_GetThingShadow // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP request (mTLS required): // // GET /things/<thingName>/shadow?name=<shadowName> HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 // // Note: Shadow name is optional (null name = classic device shadow) String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/things/" + thingName + "/shadow" + (shadowName == null ? "" : "?name="+shadowName);
// Author: Sean Pesce // // References: // https://aws.github.io/aws-iot-device-sdk-java-v2/ // https://docs.aws.amazon.com/iot/latest/developerguide // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/ // https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization // // @TODO: // - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables) // - Use CountDownLatch(count) in subscription message handlers for improved reliability package com.seanpesce.aws.iot; // import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient; public class AwsIotRecon { // MQTT topics to subscribe to (if empty, defaults to "#" - all topics) public static ArrayList<String> topicSubcriptions = new ArrayList<String>(); // Regular expressions with named capture groups for harvesting fields from MQTT topics public static ArrayList<PatternWithNamedGroups> topicsRegex = new ArrayList<PatternWithNamedGroups>(Arrays.asList(AwsIotConstants.RESERVED_TOPICS_REGEX)); public static String jarName = AwsIotRecon.class.getSimpleName() + ".jar"; // Run-time resources public static CommandLine cmd = null; public static String clientId = null; public static MqttClientConnection clientConnection = null; public static Mqtt5Client mqtt5ClientConnection = null; public static ClientTlsContext tlsContext = null; // For assuming IAM roles public static final MqttClientConnectionEvents connectionCallbacks = new MqttClientConnectionEvents() { @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionInterrupted(int errorCode) { System.err.println("[WARNING] Connection interrupted: (" + errorCode + ") " + CRT.awsErrorName(errorCode) + ": " + CRT.awsErrorString(errorCode)); } @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionResumed(boolean sessionPresent) { System.err.println("[INFO] Connection resumed (" + (sessionPresent ? "existing" : "new") + " session)"); } }; public static final Consumer<MqttMessage> genericMqttMsgConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { String msg = "\n[MQTT Message] " + message.getTopic() + "\t" + new String(message.getPayload(), StandardCharsets.UTF_8); System.out.println(msg); } }; public static final Consumer<MqttMessage> topicFieldHarvester = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { Map<String, String> m = extractFieldsFromTopic(message.getTopic()); if (m != null) { String msg = "[MQTT Topic Field Harvester] " + message.getTopic() + "\t" + m; System.out.println(msg); } } }; public static void main(String[] args) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, org.apache.commons.cli.ParseException, InterruptedException, ExecutionException { cmd = parseCommandLineArguments(args); buildConnection(cmd); String action = cmd.getOptionValue("a"); if (action.equals(AwsIotConstants.ACTION_MQTT_DUMP)) { mqttConnect(); beginMqttDump(); } else if (action.equals(AwsIotConstants.ACTION_MQTT_TOPIC_FIELD_HARVEST)) { mqttConnect(); beginMqttTopicFieldHarvesting(); } else if (action.equals(AwsIotConstants.ACTION_IAM_CREDS)) { getIamCredentialsFromDeviceX509(cmd.hasOption("R") ? Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("R")).split("\n") : new String[] {"admin"}, cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId); } else if (action.equals(AwsIotConstants.ACTION_MQTT_SCRIPT)) { mqttConnect(); runMqttScript(cmd.getOptionValue("f")); } else if (action.equals(AwsIotConstants.ACTION_MQTT_DATA_EXFIL)) { mqttConnect(); testDataExfilChannel(); } else if (action.equals(AwsIotConstants.ACTION_GET_JOBS)) { mqttConnect(); getPendingJobs(); } else if (action.equals(AwsIotConstants.ACTION_GET_SHADOW)) { getDeviceShadow(cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId, cmd.hasOption("s") ? cmd.getOptionValue("s") : null); } else if (action.equals(AwsIotConstants.ACTION_LIST_NAMED_SHADOWS)) { getNamedShadows(cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId); } else if (action.equals(AwsIotConstants.ACTION_LIST_RETAINED_MQTT_MESSAGES)) { getRetainedMqttMessages(); } // System.exit(0); } public static CommandLine parseCommandLineArguments(String[] args) throws IOException { // Get JAR name for help output try { jarName = AwsIotRecon.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); jarName = jarName.substring(jarName.lastIndexOf(FileSystems.getDefault().getSeparator()) + 1); } catch (URISyntaxException ex) { // Do nothing } // Parse command-line arguments Options opts = new Options(); Option optHelp = new Option("h", "help", false, "Print usage and exit"); opts.addOption(optHelp); Option optAwsHost = Option.builder("H").longOpt("host").argName("host").hasArg(true).required(true).desc("(Required) AWS IoT instance hostname").type(String.class).build(); opts.addOption(optAwsHost); Option optOperation = Option.builder("a").longOpt("action").argName("action").hasArg(true).required(true).desc("(Required) The enumeration task to carry out. Options: " + AwsIotConstants.CLI_ACTIONS).type(String.class).build(); opts.addOption(optOperation); Option optMqttUser = Option.builder("u").longOpt("user").argName("username").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Username for connection").type(String.class).build(); opts.addOption(optMqttUser); Option optMqttPw = Option.builder("p").longOpt("pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Password for connection").type(String.class).build(); opts.addOption(optMqttPw); Option optMtlsCert = Option.builder("c").longOpt("mtls-cert").argName("cert").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Client mTLS certificate (file path or string data)").type(String.class).build(); opts.addOption(optMtlsCert); Option optMtlsPrivKey = Option.builder("k").longOpt("mtls-priv-key").argName("key").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Client mTLS private key (file path or string data)").type(String.class).build(); opts.addOption(optMtlsPrivKey); Option optMtlsKeystore = Option.builder("K").longOpt("mtls-keystore").argName("keystore").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Path to keystore file (PKCS12/P12 or Java Keystore/JKS) containing client mTLS key pair. If keystore alias and/or certificate password is specified, the keystore is assumed to be a JKS file. Otherwise, the keystore is assumed to be P12").type(String.class).build(); opts.addOption(optMtlsKeystore); Option optMtlsKeystorePw = Option.builder("q").longOpt("keystore-pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Password for mTLS keystore (JKS or P12). Required if a keystore is specified").type(String.class).build(); opts.addOption(optMtlsKeystorePw); Option optMtlsKeystoreAlias = Option.builder("N").longOpt("keystore-alias").argName("alias").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Alias for mTLS keystore (JKS)").type(String.class).build(); opts.addOption(optMtlsKeystoreAlias); Option optMtlsKeystoreCertPw = Option.builder("Q").longOpt("keystore-cert-pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Certificate password for mTLS keystore (JKS)").type(String.class).build(); opts.addOption(optMtlsKeystoreCertPw); Option optMtlsWindowsCertPath = Option.builder(null).longOpt("windows-cert-store").argName("path").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Path to mTLS certificate in a Windows certificate store").type(String.class).build(); opts.addOption(optMtlsWindowsCertPath); Option optCertificateAuthority = Option.builder("A").longOpt("cert-authority").argName("cert").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Certificate authority (CA) to use for verifying the server TLS certificate (file path or string data)").type(String.class).build(); opts.addOption(optCertificateAuthority); Option optUseMqtt5 = new Option("5", "mqtt5", false, "Use MQTT 5"); opts.addOption(optUseMqtt5); Option optClientId = Option.builder("C").longOpt("client-id").argName("ID").hasArg(true).required(false).desc("Client ID to use for connections. If no client ID is provided, a unique ID will be generated every time this program runs.").type(String.class).build(); opts.addOption(optClientId); Option optPortNum = Option.builder("P").longOpt("port").argName("port").hasArg(true).required(false).desc("AWS server port number (1-65535)").type(Number.class).build(); opts.addOption(optPortNum); Option optTopicRegex = Option.builder("X").longOpt("topic-regex").argName("regex").hasArg(true).required(false).desc("Regular expression(s) with named capture groups for harvesting metadata from MQTT topics. This argument can be a file path or regex string data. To provide multiple regexes, separate each expression with a newline character. For more information on Java regular expressions with named capture groups, see here: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#special").type(String.class).build(); opts.addOption(optTopicRegex); Option optNoVerifyTls = new Option("U", "unsafe-tls", false, "Disable TLS certificate validation when possible"); // @TODO: Disable TLS validation for MQTT too? opts.addOption(optNoVerifyTls); Option optRoleAlias = Option.builder("R").longOpt("role-alias").argName("role").hasArg(true).required(false).desc("IAM role alias to obtain credentials for. Accepts a single alias string, or a path to a file containing a list of aliases.").type(String.class).build(); opts.addOption(optRoleAlias); Option optSubToTopics = Option.builder("T").longOpt("topics").argName("topics").hasArg(true).required(false).desc("MQTT topics to subscribe to (file path or string data). To provide multiple topics, separate each topic with a newline character").type(String.class).build(); opts.addOption(optSubToTopics); Option optThingName = Option.builder("t").longOpt("thing-name").argName("name").hasArg(true).required(false).desc("Unique \"thingName\" (device ID). If this argument is not provided, client ID will be used").type(String.class).build(); opts.addOption(optThingName); Option optShadowName = Option.builder("s").longOpt("shadow-name").argName("name").hasArg(true).required(false).desc("Shadow name (required for fetching named shadows with " + AwsIotConstants.ACTION_GET_SHADOW + ")").type(String.class).build(); opts.addOption(optShadowName); Option optCustomAuthUser = Option.builder(null).longOpt("custom-auth-user").argName("user").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer username").type(String.class).build(); opts.addOption(optCustomAuthUser); Option optCustomAuthName = Option.builder(null).longOpt("custom-auth-name").argName("name").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer name").type(String.class).build(); opts.addOption(optCustomAuthName); Option optCustomAuthSig = Option.builder(null).longOpt("custom-auth-sig").argName("signature").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer signature").type(String.class).build(); opts.addOption(optCustomAuthSig); Option optCustomAuthPass = Option.builder(null).longOpt("custom-auth-pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer password").type(String.class).build(); opts.addOption(optCustomAuthPass); Option optCustomAuthTokKey = Option.builder(null).longOpt("custom-auth-tok-name").argName("name").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer token key name").type(String.class).build(); opts.addOption(optCustomAuthTokKey); Option optCustomAuthTokVal = Option.builder(null).longOpt("custom-auth-tok-val").argName("value").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer token value").type(String.class).build(); opts.addOption(optCustomAuthTokVal); Option optMqttScript = Option.builder("f").longOpt("script").argName("file").hasArg(true).required(false).desc("MQTT script file (required for " + AwsIotConstants.ACTION_MQTT_SCRIPT + " action)").type(String.class).build(); opts.addOption(optMqttScript); // Option optAwsRegion = Option.builder("r").longOpt("region").argName("region").hasArg(true).required(false).desc("AWS instance region (e.g., \"us-west-2\")").type(String.class).build(); // opts.addOption(optAwsRegion); // @TODO: Add support for these: // Connection options: // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withCustomAuthorizer(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) // See also: https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/CustomAuthorizerConnect/src/main/java/customauthorizerconnect/CustomAuthorizerConnect.java#L70 // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withHttpProxyOptions(software.amazon.awssdk.crt.http.HttpProxyOptions) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqtt5ClientBuilder.html // // Timeout options: // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withKeepAliveSecs(int) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withPingTimeoutMs(int) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withProtocolOperationTimeoutMs(int) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withReconnectTimeoutSecs(long,long) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withTimeoutMs(int) // // Websocket options: // Option optUseWebsocket = new Option("w", "websocket", false, "Use Websockets"); // opts.addOption(optUseWebsocket); // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWebsocketCredentialsProvider(software.amazon.awssdk.crt.auth.credentials.CredentialsProvider) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWebsocketSigningRegion(java.lang.String) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWebsocketProxyOptions(software.amazon.awssdk.crt.http.HttpProxyOptions) // // Other miscellaneous options: // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWill(software.amazon.awssdk.crt.mqtt.MqttMessage) CommandLine cmd = null; CommandLineParser cmdParser = new BasicParser(); final String usagePrefix = "java -jar " + jarName + " -H <host> -a <action> [options]";//+ "\n\n" + AwsIotConstants.PROJECT_TITLE + "\n\n"; HelpFormatter helpFmt = new HelpFormatter(); // Determine the width of the terminal environment String columnsEnv = System.getenv("COLUMNS"); // Not exported by default. @TODO: Do something better to determine console width? int terminalWidth = 120; if (columnsEnv != null) { try { terminalWidth = Integer.parseInt(columnsEnv); } catch (NumberFormatException ex) { // Do nothing here; use default width } } helpFmt.setWidth(terminalWidth); // Check if "help" argument was passed in if (Arrays.stream(args).anyMatch(arg -> arg.equals("--help") || arg.equals("-h"))) { helpFmt.printHelp(usagePrefix, "\n", opts, "\n\n"+AwsIotConstants.PROJECT_TITLE); System.exit(0); } try { cmd = cmdParser.parse(opts, args); // Check for valid action String action = cmd.getOptionValue("a"); if (!AwsIotConstants.CLI_ACTIONS.contains(action)) { throw new org.apache.commons.cli.ParseException("Invalid action: \"" + action + "\""); } } catch (org.apache.commons.cli.ParseException ex) { System.err.println("[ERROR] " + ex.getMessage() + "\n"); helpFmt.printHelp(usagePrefix, "\n", opts, "\n\n"+AwsIotConstants.PROJECT_TITLE); System.exit(154); } // Add any manually-specified topic subscriptions if (cmd.hasOption("T")) { String topicStr = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("T")); String[] topicStrs = topicStr.split("\n"); for (String t : topicStrs) { System.err.println("[INFO] Adding custom MQTT topic subscription: " + t); topicSubcriptions.add(t); } System.err.println("[INFO] Added " + topicStrs.length + " custom MQTT topic subscription" + (topicStrs.length == 1 ? "" : "s")); } // Add any manually-specified topic regexes if (cmd.hasOption("X")) { String topicRegexStr = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("X")); String[] topicRegexStrs = topicRegexStr.split("\n"); for (String r : topicRegexStrs) { System.err.println("[INFO] Adding custom MQTT topic regex: " + r); topicsRegex.add(PatternWithNamedGroups.compile(r)); } System.err.println("[INFO] Added " + topicRegexStrs.length + " custom MQTT topic regular expression" + (topicRegexStrs.length == 1 ? "" : "s")); } return cmd; } public static void buildConnection(CommandLine cmd) throws CertificateException, FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, org.apache.commons.cli.ParseException { // Determine how to initialize the connection builder AwsIotMqttConnectionBuilder connBuilder = null; TlsContextOptions tlsCtxOpts = null; String action = cmd.getOptionValue("a"); // Check for arguments required for specific actions if (action.equals(AwsIotConstants.ACTION_MQTT_DUMP)) { // Nothing required except auth data } else if (action.equals(AwsIotConstants.ACTION_MQTT_TOPIC_FIELD_HARVEST)) { // Nothing required except auth data } else if (action.equals(AwsIotConstants.ACTION_IAM_CREDS)) { if (!cmd.hasOption("R")) { throw new IllegalArgumentException("Operation " + action + " requires role(s) to be specified with \"-R\""); } } else if (action.equals(AwsIotConstants.ACTION_MQTT_SCRIPT)) { if (!cmd.hasOption("f")) { System.err.println("[ERROR] \"" + action + "\" action requires an MQTT script file (\"-f\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_MQTT_DATA_EXFIL)) { // Nothing required except auth data } else if (action.equals(AwsIotConstants.ACTION_GET_JOBS)) { if (!(cmd.hasOption("t") || cmd.hasOption("C"))) { System.err.println("[ERROR] \"" + action + "\" action requires thing name (\"-t\") or client ID (\"-C\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_GET_SHADOW)) { // @TODO: Improve implementation to support this action in more ways if (!(cmd.hasOption("c") && cmd.hasOption("k") && cmd.hasOption("A"))) { System.err.println("[ERROR] \"" + action + "\" action currently requires file paths for client certificate (\"-c\"), client private key (\"-k\"), and certificate authority (\"-A\")"); System.exit(3); } if (!(cmd.hasOption("t") || cmd.hasOption("C"))) { System.err.println("[ERROR] \"" + action + "\" action requires thing name (\"-t\") or client ID (\"-C\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_LIST_NAMED_SHADOWS)) { // @TODO: Improve implementation to support this action in more ways if (!(cmd.hasOption("c") && cmd.hasOption("k") && cmd.hasOption("A"))) { System.err.println("[ERROR] \"" + action + "\" action currently requires file paths for client certificate (\"-c\"), client private key (\"-k\"), and certificate authority (\"-A\")"); System.exit(3); } if (!(cmd.hasOption("t") || cmd.hasOption("C"))) { System.err.println("[ERROR] \"" + action + "\" action requires thing name (\"-t\") or client ID (\"-C\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_LIST_RETAINED_MQTT_MESSAGES)) { // @TODO: Improve implementation to support this action in more ways if (!(cmd.hasOption("c") && cmd.hasOption("k") && cmd.hasOption("A"))) { System.err.println("[ERROR] \"" + action + "\" action currently requires file paths for client certificate (\"-c\"), client private key (\"-k\"), and certificate authority (\"-A\")"); System.exit(3); } } // Determine authentication mechanism if (cmd.hasOption("c") && cmd.hasOption("k")) { // mTLS using specified client certificate and private key String cert = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("c")); String privKey = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("k")); connBuilder = AwsIotMqttConnectionBuilder.newMtlsBuilder(cert, privKey); tlsCtxOpts = TlsContextOptions.createWithMtls(cert, privKey); } else if (cmd.hasOption("K")) { // mTLS using keystore file String ksPath = cmd.getOptionValue("K"); if (!cmd.hasOption("q")) { System.err.println("[ERROR] Provide a keystore password with \"-q\""); System.exit(1); } String ksPw = cmd.getOptionValue("q"); if (cmd.hasOption("N") || cmd.hasOption("Q")) { // JKS keystore if (!cmd.hasOption("N")) { System.err.println("[ERROR] JKS keystore requires a keystore alias. Provide an alias with \"-A\""); System.exit(1); } else if (!cmd.hasOption("Q")) { System.err.println("[ERROR] JKS keystore requires a certificate password. Provide a password with \"-Q\""); System.exit(1); } KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(ksPath), ksPw.toCharArray()); String ksAlias = cmd.getOptionValue("N"); String certPw = cmd.getOptionValue("Q"); connBuilder = AwsIotMqttConnectionBuilder.newJavaKeystoreBuilder(ks, ksAlias, certPw); tlsCtxOpts = TlsContextOptions.createWithMtlsJavaKeystore​(ks, ksAlias, certPw); } else { // P12 keystore connBuilder = AwsIotMqttConnectionBuilder.newMtlsPkcs12Builder(ksPath, ksPw); tlsCtxOpts = TlsContextOptions.createWithMtlsPkcs12​(ksPath, ksPw); } } else if (cmd.hasOption("windows-cert-store")) { // mTLS using Windows certificate store String winStorePath = cmd.getOptionValue("W"); connBuilder = AwsIotMqttConnectionBuilder.newMtlsWindowsCertStorePathBuilder(winStorePath); tlsCtxOpts = TlsContextOptions.createWithMtlsWindowsCertStorePath​(winStorePath); } else if (cmd.hasOption("custom-auth-name") || cmd.hasOption("custom-auth-sig") || cmd.hasOption("custom-auth-tok-name") || cmd.hasOption("custom-auth-tok-val") || cmd.hasOption("custom-auth-user") || cmd.hasOption("custom-auth-pass")) { // Custom authentication connBuilder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); connBuilder = connBuilder.withCustomAuthorizer( cmd.getOptionValue("custom-auth-user"), cmd.getOptionValue("custom-auth-name"), cmd.getOptionValue("custom-auth-sig"), // @TODO: "It is strongly suggested to URL-encode this value; the SDK will not do so for you." cmd.getOptionValue("custom-auth-pass"), cmd.getOptionValue("custom-auth-tok-name"), // @TODO: "It is strongly suggested to URL-encode this value; the SDK will not do so for you." cmd.getOptionValue("custom-auth-tok-val") ); tlsCtxOpts = TlsContextOptions.createDefaultClient(); } else { System.err.println("[ERROR] Missing connection properties (must provide some combination of \"-c\", \"-k\", \"-K\", \"-q\", \"-A\", \"-Q\", \"--custom-auth-*\", etc.)"); System.exit(1); } if (cmd.hasOption("C")) { clientId = cmd.getOptionValue("C"); } else { // Generate a unique client ID clientId = "DEVICE_" + System.currentTimeMillis(); } System.err.println("[INFO] Using client ID: " + clientId); // Configure the connection connBuilder = connBuilder.withConnectionEventCallbacks(connectionCallbacks); connBuilder = connBuilder.withClientId(clientId); connBuilder = connBuilder.withEndpoint(cmd.getOptionValue("H")); if (cmd.hasOption("A")) { String certAuthority = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("A")); connBuilder = connBuilder.withCertificateAuthority(certAuthority); tlsCtxOpts = tlsCtxOpts.withCertificateAuthority(certAuthority); } if (cmd.hasOption("u")) { connBuilder = connBuilder.withUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { connBuilder = connBuilder.withPassword(cmd.getOptionValue("p")); } int portNum = -1; if (cmd.hasOption("P")) { portNum = ((Number)cmd.getParsedOptionValue("P")).intValue(); if (portNum < 1 || portNum > 65535) { System.err.println("[ERROR] Port number must be in the range 1-65535 (inclusive)"); System.exit(1); } connBuilder = connBuilder.withPort((short)portNum); } if (cmd.hasOption("U")) { tlsCtxOpts = tlsCtxOpts.withVerifyPeer​(false); } // if (cmd.hasOption("w")) { // connBuilder = connBuilder.withWebsockets(true); // } // Build tlsContext = new ClientTlsContext(tlsCtxOpts); if (cmd.hasOption("5")) { // @TODO throw new UnsupportedOperationException("MQTT5 connections not supported yet"); //mqtt5ClientConnection = connBuilder.toAwsIotMqtt5ClientBuilder().build(); } else { clientConnection = connBuilder.build(); } connBuilder.close(); } public static void mqttConnect() { System.err.println("[INFO] Connecting to " + cmd.getOptionValue("H")); if (mqtt5ClientConnection != null) { mqtt5ClientConnection.start(); } else { CompletableFuture<Boolean> isCleanConnFuture = clientConnection.connect(); try { Boolean isCleanSession = isCleanConnFuture.get(); // System.err.println("[INFO] Clean session? " + isCleanSession.toString()); } catch (ExecutionException | InterruptedException e) { System.err.println("[ERROR] Exception connecting: " + e.toString()); System.exit(2); } } } // Extracts known data fields from MQTT topic strings. Note that this method is NOT meant for extracting data from MQTT message payloads. public static Map<String, String> extractFieldsFromTopic(String topic) { if (topic.equals(AwsIotConstants.MQTT_PING_TOPIC)) { return null; } for (PatternWithNamedGroups p : topicsRegex) { Matcher matcher = p.getPattern().matcher(topic); boolean matchFound = matcher.find(); if (matchFound) { List<String> groupNames = p.getGroupNames(); if (groupNames.size() != matcher.groupCount()) { System.err.println("[WARNING] Mismatch between number of capture group names (" + groupNames.size() + ") and matched group count (" + matcher.groupCount() + ")"); continue; } HashMap<String, String> captures = new HashMap<String, String>(); for (int i = 1; i <= matcher.groupCount(); i++) { captures.put(groupNames.get(i-1), matcher.group(i)); } return captures; } } if (topic.startsWith(AwsIotConstants.MQTT_RESERVED_TOPIC_PREFIX)) { // All AWS-reserved MQTT topics should be matched... System.err.println("[WARNING] Failed to extract fields from reserved MQTT topic: " + topic); } return null; } // Returns the list of user-specified MQTT topics, or a wildcard topic representing all topics ("#") public static List<String> buildMqttTopicList() { ArrayList<String> topics = new ArrayList<String>(); if (topicSubcriptions.isEmpty()) { // Use wildcard to subscribe to all topics topics.add(AwsIotConstants.MQTT_ALL_TOPICS); } else { // Subscribe to user-specified topics only topics.addAll(topicSubcriptions); } return topics; } // Dump all MQTT messages received via subscribed MQTT topics. Runs forever (or until cancelled by the user with Ctrl+C) public static void beginMqttDump() throws InterruptedException, ExecutionException { final List<String> topics = buildMqttTopicList(); for (final String topic : topics) { System.err.println("[INFO] Subscribing to topic for MQTT dump (\"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, genericMqttMsgConsumer); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); } Util.sleepForever(); } // Extract known data fields from subscribed MQTT topics. Runs forever (or until cancelled by the user with Ctrl+C). // Note that this only extracts data from the topic itself, and ignores MQTT message payloads. public static void beginMqttTopicFieldHarvesting() throws InterruptedException, ExecutionException { final List<String> topics = buildMqttTopicList(); for (final String topic : topics) { System.err.println("[INFO] Subscribing to topic for topic field harvesting (\"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, topicFieldHarvester); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); } Util.sleepForever(); } // Test whether the AWS IoT service can be used for data exfiltration via arbitrary topics public static void testDataExfilChannel() throws InterruptedException, ExecutionException { final String timestamp = "" + System.currentTimeMillis(); ArrayList<String> topics = new ArrayList<String>(); if (topicSubcriptions.isEmpty()) { // By default, use the current epoch timestamp for a unique MQTT topic topics.add(timestamp); } else { topics.addAll(topicSubcriptions); } final Consumer<MqttMessage> dataExfilConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { final String payloadStr = new String(message.getPayload(), StandardCharsets.UTF_8).trim(); String msg = null; if (payloadStr.equals(timestamp)) { System.out.println("\n[Data exfiltration] Confirmed data exfiltration channel via topic: " + message.getTopic()); } else { System.err.println("[WARNING] Unknown data received via data exfiltration channel (topic: " + message.getTopic() + "): " + payloadStr); } } }; // Subscribe to the data exfiltration topic(s) for (final String topic : topics) { System.err.println("[INFO] Testing data exfiltration via arbitrary topics (using topic: \"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, dataExfilConsumer); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); // Publish data to the data exfiltration topic MqttMessage msg = new MqttMessage(topic, timestamp.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_LEAST_ONCE); CompletableFuture<Integer> publication = clientConnection.publish(msg); publication.get(); } // Sleep 3 seconds to see if we receive our payload try { Thread.sleep(3000); } catch (InterruptedException ex) { System.err.println("[WARNING] Data exfiltration sleep operation was interrupted: " + ex.getMessage()); } // Unsubscribe from the data exfiltration topic(s) for (final String topic : topics) { CompletableFuture<Integer> unsub = clientConnection.unsubscribe(topic); unsub.get(); } } // Attempts to obtain IAM credentials for the specified role using the client mTLS key pair from an IoT "Thing" (device) // // Note that the iot:CredentialProvider is a different host/endpoint than the base IoT endpoint; it should have the format: // ${random_id}.credentials.iot.${region}.amazonaws.com // // (The random_id will also be different from the one in the base IoT Core endpoint) public static List<Credentials> getIamCredentialsFromDeviceX509(String[] roleAliases, String thingName) { // See also: // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/de4e5f3be56c325975674d4e3c0a801392edad96/samples/X509CredentialsProviderConnect/src/main/java/x509credentialsproviderconnect/X509CredentialsProviderConnect.java#L99 // https://awslabs.github.io/aws-crt-java/software/amazon/awssdk/crt/auth/credentials/X509CredentialsProvider.html // https://aws.amazon.com/blogs/security/how-to-eliminate-the-need-for-hardcoded-aws-credentials-in-devices-by-using-the-aws-iot-credentials-provider/ final String endpoint = cmd.getOptionValue("H"); if (!endpoint.contains("credentials.iot")) { System.err.println("[WARNING] Endpoint \"" + endpoint + "\" might not be an AWS IoT credentials provider; are you sure you have the right hostname? (Expected format: \"${random_id}.credentials.iot.${region}.amazonaws.com\")"); } ArrayList<Credentials> discoveredCreds = new ArrayList<Credentials>(); for (String roleAlias : roleAliases) { // // mTLS HTTP client method: // String url = "https://" + endpoint + "/role-aliases/" + roleAlias + "/credentials"; // String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // // Need to add header "x-amzn-iot-thingname: " + thingName // System.out.println(data); // return null; Credentials credentials = null; X509CredentialsProvider.X509CredentialsProviderBuilder x509CredsBuilder = new X509CredentialsProvider.X509CredentialsProviderBuilder(); x509CredsBuilder = x509CredsBuilder.withTlsContext(tlsContext); x509CredsBuilder = x509CredsBuilder.withEndpoint​(endpoint); x509CredsBuilder = x509CredsBuilder.withRoleAlias(roleAlias); x509CredsBuilder = x509CredsBuilder.withThingName(thingName); X509CredentialsProvider credsProvider = x509CredsBuilder.build(); CompletableFuture<Credentials> credsFuture = credsProvider.getCredentials(); try { credentials = credsFuture.get(); String credsStr = "{\"credentials\":{\"accessKeyId\":\"" + new String(credentials.getAccessKeyId(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"secretAccessKey\":\"" + new String(credentials.getSecretAccessKey(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"sessionToken\":\"" + new String(credentials.getSessionToken(), StandardCharsets.UTF_8) + "\"}}"; System.out.println(credsStr); discoveredCreds.add(credentials); } catch (ExecutionException | InterruptedException ex) { System.err.println("[ERROR] Failed to obtain credentials from X509 (role=\"" + roleAlias + "\"; thingName=\"" + thingName + "\"): " + ex.getMessage()); } credsProvider.close(); } return discoveredCreds; } public static void getDeviceShadow(String thingName, String shadowName) { // https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-rest-api.html#API_GetThingShadow // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP request (mTLS required): // // GET /things/<thingName>/shadow?name=<shadowName> HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 // // Note: Shadow name is optional (null name = classic device shadow) String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/things/" + thingName + "/shadow" + (shadowName == null ? "" : "?name="+shadowName);
String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true);
1
2023-11-06 23:10:21+00:00
12k
baguchan/BetterWithAquatic
src/main/java/baguchan/better_with_aquatic/BetterWithAquatic.java
[ { "identifier": "ModBlocks", "path": "src/main/java/baguchan/better_with_aquatic/block/ModBlocks.java", "snippet": "public class ModBlocks {\n\n\n\tpublic static final Block sea_grass = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.0f)\n\t\t.setResistance(100F)\n\t\t.setLightOpacity(1)\n\t\t.setTextures(\"sea_grass.png\")\n\t\t.setTags(BlockTags.IS_WATER, BlockTags.PLACE_OVERWRITES, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new BlockWaterPlantStill(\"sea_grass\", IDUtils.getCurrBlockId(), Material.water).withLitInteriorSurface(true));\n\tpublic static final Block sea_grass_flow = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.0f)\n\t\t.setResistance(100F)\n\t\t.setLightOpacity(1)\n\t\t.setTextures(\"sea_grass.png\")\n\t\t.setBlockDrop(sea_grass)\n\t\t.setTags(BlockTags.IS_WATER, BlockTags.PLACE_OVERWRITES, BlockTags.SHEARS_DO_SILK_TOUCH, BlockTags.NOT_IN_CREATIVE_MENU)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new BlockWaterPlantFlow(\"sea_grass_flow\", IDUtils.getCurrBlockId(), Material.water));\n\n\tpublic static final Block coral_blue = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_blue.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_blue\", IDUtils.getCurrBlockId(), Material.vegetable));\n\tpublic static final Block coral_cyan = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_cyan.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_cyan\", IDUtils.getCurrBlockId(), Material.vegetable));\n\tpublic static final Block coral_green = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_green.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_green\", IDUtils.getCurrBlockId(), Material.vegetable));\n\tpublic static final Block coral_pink = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_pink.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_pink\", IDUtils.getCurrBlockId(), Material.vegetable));\n\n\tpublic static final Block coral_purple = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_purple.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_purple\", IDUtils.getCurrBlockId(), Material.vegetable));\n\tpublic static final Block coral_red = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_red.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_red\", IDUtils.getCurrBlockId(), Material.vegetable));\n\tpublic static final Block coral_yellow = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.65F)\n\t\t.setTextures(\"coral_yellow.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.SHEARS_DO_SILK_TOUCH)\n\t\t.setBlockSound(BlockSounds.GRASS)\n\t\t.build(new CoralBlock(\"coral_yellow\", IDUtils.getCurrBlockId(), Material.vegetable));\n\tpublic static final Block light_blub = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.5f)\n\t\t.setResistance(1.5F)\n\t\t.setLuminance(13)\n\t\t.setTextures(\"light_bulb.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_PICKAXE)\n\t\t.setBlockSound(BlockSounds.METAL)\n\t\t.build(new Block(\"light_bulb\", IDUtils.getCurrBlockId(), Material.metal));\n\n\n\n\tpublic static void createBlocks() {\n\n\t}\n\n\tstatic {\n\t\tItem.itemsList[sea_grass.id] = new ItemBlock(sea_grass);\n\t\tItem.itemsList[sea_grass_flow.id] = new ItemBlock(sea_grass_flow);\n\t\tItem.itemsList[coral_blue.id] = new ItemBlock(coral_blue);\n\t\tItem.itemsList[coral_cyan.id] = new ItemBlock(coral_cyan);\n\t\tItem.itemsList[coral_green.id] = new ItemBlock(coral_green);\n\t\tItem.itemsList[coral_pink.id] = new ItemBlock(coral_pink);\n\t\tItem.itemsList[coral_purple.id] = new ItemBlock(coral_purple);\n\t\tItem.itemsList[coral_red.id] = new ItemBlock(coral_red);\n\t\tItem.itemsList[coral_yellow.id] = new ItemBlock(coral_yellow);\n\t\tItem.itemsList[light_blub.id] = new ItemBlock(light_blub).withTags(ItemTags.renderFullbright);\n\t}\n}" }, { "identifier": "EntityAnglerFish", "path": "src/main/java/baguchan/better_with_aquatic/entity/EntityAnglerFish.java", "snippet": "public class EntityAnglerFish extends EntityBaseFish {\n\tpublic EntityAnglerFish(World world) {\n\t\tsuper(world);\n\t\tthis.setSize(0.5F, 0.45F);\n\t\tthis.setPos(this.x, this.y, this.z);\n\t\tthis.health = 5;\n\t\tthis.skinName = \"angler_fish\";\n\t}\n\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/angler_fish.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/angler_fish.png\";\n\t}\n\n\n\t@Override\n\tprotected float getBlockPathWeight(int x, int y, int z) {\n\t\treturn 0.5f - this.world.getLightBrightness(x, y, z);\n\t}\n\n\t@Override\n\tpublic boolean getCanSpawnHere() {\n\t\tint k;\n\t\tint j;\n\t\tint i = MathHelper.floor_double(this.x);\n\t\tif (this.world.getSavedLightValue(LightLayer.Block, i, j = MathHelper.floor_double(this.bb.minY), k = MathHelper.floor_double(this.z)) > 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.world.getSavedLightValue(LightLayer.Sky, i, j, k) > this.random.nextInt(32)) {\n\t\t\treturn false;\n\t\t}\n\t\tint blockLight = this.world.getBlockLightValue(i, j, k);\n\t\tif (this.world.getCurrentWeather() != null && this.world.getCurrentWeather().doMobsSpawnInDaylight) {\n\t\t\tblockLight /= 2;\n\t\t}\n\t\treturn blockLight <= 4 && super.getCanSpawnHere();\n\t}\n\n\t@Override\n\tprotected Entity findPlayerToAttack() {\n\t\tEntityPlayer entityplayer = this.world.getClosestPlayerToEntity(this, 16.0);\n\t\tif (entityplayer != null && this.canEntityBeSeen(entityplayer) && entityplayer.getGamemode().areMobsHostile()) {\n\t\t\treturn entityplayer;\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean hurt(Entity entity, int i, DamageType type) {\n\t\tif (super.hurt(entity, i, type)) {\n\t\t\tif (this.passenger == entity || this.vehicle == entity) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (entity != this) {\n\t\t\t\tthis.entityToAttack = entity;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void attackEntity(Entity entity, float distance) {\n\t\tif (this.attackTime <= 0 && distance < 1.5f && entity.bb.maxY > this.bb.minY && entity.bb.minY < this.bb.maxY) {\n\t\t\tthis.attackTime = 20;\n\t\t\tentity.hurt(this, 1, DamageType.COMBAT);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void dropFewItems() {\n\t\tthis.spawnAtLocation(new ItemStack(ModItems.small_bulb, 1, 0), 0.0f);\n\t}\n\n}" }, { "identifier": "EntityDrowned", "path": "src/main/java/baguchan/better_with_aquatic/entity/EntityDrowned.java", "snippet": "public class EntityDrowned extends EntityZombie implements IPathGetter, ISwiming {\n\tprivate Entity currentTarget;\n\tpublic boolean swimming;\n\tprivate float swimAmount;\n\tprivate float swimAmountO;\n\n\tpublic EntityDrowned(World world) {\n\t\tsuper(world);\n\t\tthis.setPathFinder(this, new BetterSwimWalkPathFinder(world));\n\t\tthis.setPathfindingMalus(this, BlockPath.WATER, 0.0F);\n\t\tthis.setPathfindingMalus(this, BlockPath.OPEN, -1.0F);\n\t\tthis.footSize = 1f;\n\t\tthis.skinName = \"drowned\";\n\t}\n\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/drowned.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/drowned.png\";\n\t}\n\n\n\t@Override\n\tpublic void tick() {\n\t\tsuper.tick();\n\t\tsetSwimming(this.isInWater());\n\t\tthis.updateSwimAmount();\n\t}\n\n\tprivate void updateSwimAmount() {\n\t\tthis.swimAmountO = this.swimAmount;\n\t\tif (this.isSwimming()) {\n\t\t\tthis.swimAmount = Math.min(1.0F, this.swimAmount + 0.09F);\n\t\t} else {\n\t\t\tthis.swimAmount = Math.max(0.0F, this.swimAmount - 0.09F);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void moveEntityWithHeading(float moveStrafing, float moveForward) {\n\t\tif (this.isInWater()) {\n\t\t\tthis.moveRelative(moveStrafing, moveForward, 0.2F);\n\t\t\tthis.move(this.xd, this.yd, this.zd);\n\t\t\tthis.xd *= 0.8;\n\t\t\tthis.yd *= 0.8;\n\t\t\tthis.zd *= 0.8;\n\t\t\tthis.prevLimbYaw = this.limbYaw;\n\t\t\tdouble d2 = this.x - this.xo;\n\t\t\tdouble d3 = this.z - this.zo;\n\t\t\tfloat f5 = MathHelper.sqrt_double(d2 * d2 + d3 * d3) * 4.0f;\n\t\t\tif (f5 > 1.0f) {\n\t\t\t\tf5 = 1.0f;\n\t\t\t}\n\t\t\tthis.limbYaw += (f5 - this.limbYaw) * 0.4f;\n\t\t\tthis.limbSwing += this.limbYaw;\n\t\t} else {\n\t\t\tsuper.moveEntityWithHeading(moveStrafing, moveForward);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void updatePlayerActionState() {\n\t\tif (this.isInWater()) {\n\t\t\tthis.hasAttacked = this.isMovementCeased();\n\t\t\tfloat sightRadius = 16.0f;\n\t\t\tif (this.entityToAttack == null) {\n\t\t\t\tthis.entityToAttack = this.findPlayerToAttack();\n\t\t\t\tif (this.entityToAttack != null) {\n\t\t\t\t\tthis.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius);\n\t\t\t\t}\n\t\t\t} else if (!this.entityToAttack.isAlive()) {\n\t\t\t\tthis.entityToAttack = null;\n\t\t\t} else {\n\t\t\t\tfloat distanceToEntity = this.entityToAttack.distanceTo(this);\n\t\t\t\tif (this.canEntityBeSeen(this.entityToAttack)) {\n\t\t\t\t\tthis.attackEntity(this.entityToAttack, distanceToEntity);\n\t\t\t\t} else {\n\t\t\t\t\tthis.attackBlockedEntity(this.entityToAttack, distanceToEntity);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(this.hasAttacked || this.entityToAttack == null || this.pathToEntity != null && this.random.nextInt(20) != 0)) {\n\t\t\t\tthis.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius);\n\t\t\t} else if (!this.hasAttacked && this.closestFireflyEntity == null && (this.pathToEntity == null && this.random.nextInt(80) == 0 || this.random.nextInt(80) == 0)) {\n\t\t\t\tthis.roamRandomPath();\n\t\t\t}\n\t\t\tthis.xRot = 0.0f;\n\t\t\tif (this.pathToEntity == null || this.random.nextInt(100) == 0) {\n\t\t\t\tthis.defaultPlayerActionState();\n\t\t\t\tthis.pathToEntity = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tVec3d coordsForNextPath = this.pathToEntity.getPos(this);\n\t\t\tdouble d = this.bbWidth * 2.0f;\n\t\t\tdouble d2 = this.bbHeight * 2.0f;\n\t\t\twhile (coordsForNextPath != null && coordsForNextPath.squareDistanceTo(this.x, this.y, this.z) < d * d + d2 * d2) {\n\t\t\t\tthis.pathToEntity.next();\n\t\t\t\tif (this.pathToEntity.isDone()) {\n\t\t\t\t\tthis.closestFireflyEntity = null;\n\t\t\t\t\tcoordsForNextPath = null;\n\t\t\t\t\tthis.pathToEntity = null;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcoordsForNextPath = this.pathToEntity.getPos(this);\n\t\t\t}\n\t\t\tthis.isJumping = false;\n\t\t\tif (coordsForNextPath != null) {\n\t\t\t\tfloat f3;\n\t\t\t\tdouble x1 = coordsForNextPath.xCoord - this.x;\n\t\t\t\tdouble z1 = coordsForNextPath.zCoord - this.z;\n\t\t\t\tdouble y1 = coordsForNextPath.yCoord - this.y;\n\t\t\t\tfloat f2 = (float) (Math.atan2(z1, x1) * 180.0 / 3.1415927410125732) - 90.0f;\n\t\t\t\tthis.moveForward = this.moveSpeed * 0.15F;\n\t\t\t\tfor (f3 = f2 - this.yRot; f3 < -180.0f; f3 += 360.0f) {\n\t\t\t\t}\n\t\t\t\twhile (f3 >= 180.0f) {\n\t\t\t\t\tf3 -= 360.0f;\n\t\t\t\t}\n\t\t\t\tif (f3 > 30.0f) {\n\t\t\t\t\tf3 = 30.0f;\n\t\t\t\t}\n\t\t\t\tif (f3 < -30.0f) {\n\t\t\t\t\tf3 = -30.0f;\n\t\t\t\t}\n\t\t\t\tthis.yRot += f3;\n\t\t\t\tif (this.hasAttacked && this.entityToAttack != null) {\n\t\t\t\t\tdouble d4 = this.entityToAttack.x - this.x;\n\t\t\t\t\tdouble d5 = this.entityToAttack.z - this.z;\n\t\t\t\t\tfloat f5 = this.yRot;\n\t\t\t\t\tthis.yRot = (float) (Math.atan2(d5, d4) * 180.0 / 3.1415927410125732) - 90.0f;\n\t\t\t\t\tfloat f4 = (f5 - this.yRot + 90.0f) * 3.141593f / 180.0f;\n\t\t\t\t\tthis.moveStrafing = -MathHelper.sin(f4) * this.moveForward * 1.0f;\n\t\t\t\t\tthis.moveForward = MathHelper.cos(f4) * this.moveForward * 1.0f;\n\t\t\t\t}\n\n\n\t\t\t\tdouble d3 = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1);\n\t\t\t\tthis.yd += MathHelper.clamp(y1 / d3, -0.5F, 0.5F) * 0.15F * this.moveSpeed;\n\t\t\t}\n\t\t\tif (this.entityToAttack != null) {\n\t\t\t\tthis.faceEntity(this.entityToAttack, 30.0f, 30.0f);\n\t\t\t}\n\t\t} else {\n\t\t\tsuper.updatePlayerActionState();\n\t\t\tthis.currentTarget = null;\n\t\t}\n\t}\n\n\tprotected void defaultPlayerActionState() {\n\t\t++this.entityAge;\n\t\tthis.tryToDespawn();\n\t\tthis.moveStrafing = 0.0f;\n\t\tthis.moveForward = 0.0f;\n\t\tfloat f = 8.0f;\n\t\tif (this.random.nextFloat() < 0.02f) {\n\t\t\tEntityPlayer entityplayer1 = this.world.getClosestPlayerToEntity(this, f);\n\t\t\tif (entityplayer1 != null) {\n\t\t\t\tthis.currentTarget = entityplayer1;\n\t\t\t\tthis.numTicksToChaseTarget = 10 + this.random.nextInt(20);\n\t\t\t} else {\n\t\t\t\tthis.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f;\n\t\t\t}\n\t\t}\n\t\tif (this.currentTarget != null) {\n\t\t\tthis.faceEntity(this.currentTarget, 10.0f, this.func_25026_x());\n\t\t\tif (this.numTicksToChaseTarget-- <= 0 || this.currentTarget.removed || this.currentTarget.distanceToSqr(this) > (double) (f * f)) {\n\t\t\t\tthis.currentTarget = null;\n\t\t\t}\n\t\t} else {\n\t\t\tif (this.random.nextFloat() < 0.05f) {\n\t\t\t\tthis.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f;\n\t\t\t}\n\t\t\tthis.yRot += this.randomYawVelocity;\n\t\t\tthis.xRot = this.defaultPitch;\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean canBreatheUnderwater() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void setSwimming(boolean swiming) {\n\t\tthis.swimming = swiming;\n\t}\n\n\t@Override\n\tpublic boolean isSwimming() {\n\t\treturn this.swimming;\n\t}\n\n\t@Override\n\tpublic float getSwimAmount(float p_20999_) {\n\t\treturn MathUtil.lerp(p_20999_, this.swimAmountO, this.swimAmount);\n\t}\n}" }, { "identifier": "EntityFish", "path": "src/main/java/baguchan/better_with_aquatic/entity/EntityFish.java", "snippet": "public class EntityFish extends EntityBaseFish {\n\tpublic EntityFish(World world) {\n\t\tsuper(world);\n\t\tthis.setSize(0.45F, 0.45F);\n\t\tthis.setPos(this.x, this.y, this.z);\n\n\t\tthis.skinName = \"fish\";\n\t}\n\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/fish.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/fish.png\";\n\t}\n\n\t@Override\n\tprotected void dropFewItems() {\n\t\tthis.spawnAtLocation(new ItemStack(Item.foodFishRaw, 1, 0), 0.0f);\n\t}\n\n}" }, { "identifier": "EntityFrog", "path": "src/main/java/baguchan/better_with_aquatic/entity/EntityFrog.java", "snippet": "public class EntityFrog extends EntityAnimal implements IPathGetter, ISwiming {\n\tprivate Entity currentTarget;\n\tpublic boolean swimming;\n\tprivate int frogJumpDelay = 0;\n\n\tpublic AnimationState jumpState = new AnimationState();\n\tpublic AnimationState attackState = new AnimationState();\n\n\tpublic EntityFrog(World world) {\n\t\tsuper(world);\n\t\tthis.setPathFinder(this, new BetterSwimWalkPathFinder(world));\n\t\tthis.setPathfindingMalus(this, BlockPath.WATER, 0.0F);\n\t\tthis.setPathfindingMalus(this, BlockPath.OPEN, -1.0F);\n\t\tthis.footSize = 1f;\n\t\tthis.skinName = \"frog\";\n\t\tthis.frogJumpDelay = 20;\n\n\t\tthis.scoreValue = 0;\n\t\tthis.health = 6;\n\t\tthis.heightOffset = 0.0F;\n\t\tthis.moveSpeed = 0.75F;\n\t\tthis.setSize(0.45F, 0.35F);\n\t\tthis.setPos(this.x, this.y, this.z);\n\t}\n\n\t@Override\n\tpublic String getLivingSound() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected String getHurtSound() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected String getDeathSound() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/frog.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/better_with_aquatic/entity/frog.png\";\n\t}\n\n\n\t@Override\n\tpublic void tick() {\n\t\tsuper.tick();\n\t\tsetSwimming(this.isInWater());\n\t}\n\n\t@Override\n\tpublic void moveEntityWithHeading(float moveStrafing, float moveForward) {\n\t\tif (this.isInWater()) {\n\t\t\tthis.moveRelative(moveStrafing, moveForward, 0.2F);\n\t\t\tthis.move(this.xd, this.yd, this.zd);\n\t\t\tthis.xd *= 0.8;\n\t\t\tthis.yd *= 0.8;\n\t\t\tthis.zd *= 0.8;\n\t\t\tthis.prevLimbYaw = this.limbYaw;\n\t\t\tdouble d2 = this.x - this.xo;\n\t\t\tdouble d3 = this.z - this.zo;\n\t\t\tfloat f5 = MathHelper.sqrt_double(d2 * d2 + d3 * d3) * 4.0f;\n\t\t\tif (f5 > 1.0f) {\n\t\t\t\tf5 = 1.0f;\n\t\t\t}\n\t\t\tthis.limbYaw += (f5 - this.limbYaw) * 0.4f;\n\t\t\tthis.limbSwing += this.limbYaw;\n\t\t} else {\n\t\t\tsuper.moveEntityWithHeading(moveStrafing, moveForward);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void updatePlayerActionState() {\n\t\tif (this.onGround) {\n\t\t\tthis.jumpState.stop();\n\t\t\tthis.moveForward = 0.0f;\n\t\t\tthis.moveStrafing = 0.0f;\n\t\t}\n\t\tif (this.onGround) {\n\n\t\t}\n\t\tif (this.isInWater()) {\n\t\t\tthis.hasAttacked = this.isMovementCeased();\n\t\t\tfloat sightRadius = 16.0f;\n\t\t\tif (this.entityToAttack == null) {\n\t\t\t\tthis.entityToAttack = this.findPlayerToAttack();\n\t\t\t\tif (this.entityToAttack != null) {\n\t\t\t\t\tthis.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius);\n\t\t\t\t}\n\t\t\t} else if (!this.entityToAttack.isAlive()) {\n\t\t\t\tthis.entityToAttack = null;\n\t\t\t} else {\n\t\t\t\tfloat distanceToEntity = this.entityToAttack.distanceTo(this);\n\t\t\t\tif (this.canEntityBeSeen(this.entityToAttack)) {\n\t\t\t\t\tthis.attackEntity(this.entityToAttack, distanceToEntity);\n\t\t\t\t} else {\n\t\t\t\t\tthis.attackBlockedEntity(this.entityToAttack, distanceToEntity);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(this.hasAttacked || this.entityToAttack == null || this.pathToEntity != null && this.random.nextInt(20) != 0)) {\n\t\t\t\tthis.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius);\n\t\t\t} else if (!this.hasAttacked && this.closestFireflyEntity == null && (this.pathToEntity == null && this.random.nextInt(80) == 0 || this.random.nextInt(80) == 0)) {\n\t\t\t\tthis.roamRandomPath();\n\t\t\t}\n\t\t\tthis.xRot = 0.0f;\n\t\t\tif (this.pathToEntity == null || this.random.nextInt(100) == 0) {\n\t\t\t\tthis.defaultPlayerActionState();\n\t\t\t\tthis.pathToEntity = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tVec3d coordsForNextPath = this.pathToEntity.getPos(this);\n\t\t\tdouble d = this.bbWidth * 2.0f;\n\t\t\tdouble d2 = this.bbHeight * 2.0f;\n\t\t\twhile (coordsForNextPath != null && coordsForNextPath.squareDistanceTo(this.x, this.y, this.z) < d * d + d2 * d2) {\n\t\t\t\tthis.pathToEntity.next();\n\t\t\t\tif (this.pathToEntity.isDone()) {\n\t\t\t\t\tthis.closestFireflyEntity = null;\n\t\t\t\t\tcoordsForNextPath = null;\n\t\t\t\t\tthis.pathToEntity = null;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcoordsForNextPath = this.pathToEntity.getPos(this);\n\t\t\t}\n\t\t\tthis.isJumping = false;\n\t\t\tif (coordsForNextPath != null) {\n\t\t\t\tfloat f3;\n\t\t\t\tdouble x1 = coordsForNextPath.xCoord - this.x;\n\t\t\t\tdouble z1 = coordsForNextPath.zCoord - this.z;\n\t\t\t\tdouble y1 = coordsForNextPath.yCoord - this.y;\n\t\t\t\tfloat f2 = (float) (Math.atan2(z1, x1) * 180.0 / 3.1415927410125732) - 90.0f;\n\t\t\t\tthis.moveForward = this.moveSpeed * 0.15F;\n\t\t\t\tfor (f3 = f2 - this.yRot; f3 < -180.0f; f3 += 360.0f) {\n\t\t\t\t}\n\t\t\t\twhile (f3 >= 180.0f) {\n\t\t\t\t\tf3 -= 360.0f;\n\t\t\t\t}\n\t\t\t\tif (f3 > 30.0f) {\n\t\t\t\t\tf3 = 30.0f;\n\t\t\t\t}\n\t\t\t\tif (f3 < -30.0f) {\n\t\t\t\t\tf3 = -30.0f;\n\t\t\t\t}\n\t\t\t\tthis.yRot += f3;\n\t\t\t\tif (this.hasAttacked && this.entityToAttack != null) {\n\t\t\t\t\tdouble d4 = this.entityToAttack.x - this.x;\n\t\t\t\t\tdouble d5 = this.entityToAttack.z - this.z;\n\t\t\t\t\tfloat f5 = this.yRot;\n\t\t\t\t\tthis.yRot = (float) (Math.atan2(d5, d4) * 180.0 / 3.1415927410125732) - 90.0f;\n\t\t\t\t\tfloat f4 = (f5 - this.yRot + 90.0f) * 3.141593f / 180.0f;\n\t\t\t\t\tthis.moveStrafing = -MathHelper.sin(f4) * this.moveForward * 1.0f;\n\t\t\t\t\tthis.moveForward = MathHelper.cos(f4) * this.moveForward * 1.0f;\n\t\t\t\t}\n\n\n\t\t\t\tdouble d3 = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1);\n\t\t\t\tthis.yd += MathHelper.clamp(y1 / d3, -0.5F, 0.5F) * 0.15F * this.moveSpeed;\n\t\t\t}\n\t\t\tif (this.entityToAttack != null) {\n\t\t\t\tthis.faceEntity(this.entityToAttack, 30.0f, 30.0f);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.hasAttacked = this.isMovementCeased();\n\t\t\tfloat sightRadius = 16.0f;\n\t\t\tif (this.entityToAttack == null) {\n\t\t\t\tthis.entityToAttack = this.findPlayerToAttack();\n\t\t\t\tif (this.entityToAttack != null) {\n\t\t\t\t\tthis.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius);\n\t\t\t\t}\n\t\t\t} else if (!this.entityToAttack.isAlive()) {\n\t\t\t\tthis.entityToAttack = null;\n\t\t\t} else {\n\t\t\t\tfloat distanceToEntity = this.entityToAttack.distanceTo(this);\n\t\t\t\tif (this.canEntityBeSeen(this.entityToAttack)) {\n\t\t\t\t\tthis.attackEntity(this.entityToAttack, distanceToEntity);\n\t\t\t\t} else {\n\t\t\t\t\tthis.attackBlockedEntity(this.entityToAttack, distanceToEntity);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(this.hasAttacked || this.entityToAttack == null || this.pathToEntity != null && this.random.nextInt(20) != 0)) {\n\t\t\t\tthis.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius);\n\t\t\t} else if (!this.hasAttacked && this.closestFireflyEntity == null && (this.pathToEntity == null && this.random.nextInt(80) == 0 || this.random.nextInt(80) == 0)) {\n\t\t\t\tthis.roamRandomPath();\n\t\t\t}\n\t\t\tint i = MathHelper.floor_double(this.bb.minY + 0.5);\n\t\t\tboolean inWater = this.isInWater();\n\t\t\tboolean inLava = this.isInLava();\n\t\t\tthis.xRot = 0.0f;\n\t\t\tif (this.pathToEntity == null || this.random.nextInt(100) == 0) {\n\t\t\t\tsuper.updatePlayerActionState();\n\t\t\t\tthis.pathToEntity = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tVec3d coordsForNextPath = this.pathToEntity.getPos(this);\n\t\t\tdouble d = this.bbWidth * 2.0f;\n\t\t\twhile (coordsForNextPath != null && coordsForNextPath.squareDistanceTo(this.x, coordsForNextPath.yCoord, this.z) < d * d) {\n\t\t\t\tthis.pathToEntity.next();\n\t\t\t\tif (this.pathToEntity.isDone()) {\n\t\t\t\t\tthis.closestFireflyEntity = null;\n\t\t\t\t\tcoordsForNextPath = null;\n\t\t\t\t\tthis.pathToEntity = null;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcoordsForNextPath = this.pathToEntity.getPos(this);\n\t\t\t}\n\t\t\tthis.isJumping = false;\n\t\t\tif (coordsForNextPath != null) {\n\t\t\t\tif (this.onGround && this.frogJumpDelay-- <= 0) {\n\t\t\t\t\tfloat f3;\n\t\t\t\t\tdouble x1 = coordsForNextPath.xCoord - this.x;\n\t\t\t\t\tdouble z1 = coordsForNextPath.zCoord - this.z;\n\t\t\t\t\tdouble y1 = coordsForNextPath.yCoord - (double) i;\n\t\t\t\t\tfloat f2 = (float) (Math.atan2(z1, x1) * 180.0 / 3.1415927410125732) - 90.0f;\n\t\t\t\t\tthis.moveForward = this.moveSpeed;\n\t\t\t\t\tfor (f3 = f2 - this.yRot; f3 < -180.0f; f3 += 360.0f) {\n\t\t\t\t\t}\n\t\t\t\t\twhile (f3 >= 180.0f) {\n\t\t\t\t\t\tf3 -= 360.0f;\n\t\t\t\t\t}\n\t\t\t\t\tif (f3 > 30.0f) {\n\t\t\t\t\t\tf3 = 30.0f;\n\t\t\t\t\t}\n\t\t\t\t\tif (f3 < -30.0f) {\n\t\t\t\t\t\tf3 = -30.0f;\n\t\t\t\t\t}\n\t\t\t\t\tthis.yRot += f3;\n\t\t\t\t\tif (this.hasAttacked && this.entityToAttack != null) {\n\t\t\t\t\t\tdouble d4 = x1 - this.x;\n\t\t\t\t\t\tdouble d5 = z1 - this.z;\n\t\t\t\t\t\tfloat f5 = this.yRot;\n\t\t\t\t\t\tthis.yRot = (float) (Math.atan2(d5, d4) * 180.0 / 3.1415927410125732) - 90.0f;\n\t\t\t\t\t\tfloat f4 = (f5 - this.yRot + 90.0f) * 3.141593f / 180.0f;\n\t\t\t\t\t\tthis.moveStrafing = -MathHelper.sin(f4) * this.moveForward * 1.0f;\n\t\t\t\t\t\tthis.moveForward = MathHelper.cos(f4) * this.moveForward * 1.0f;\n\t\t\t\t\t}\n\t\t\t\t\tthis.isJumping = true;\n\t\t\t\t\tthis.frogJumpDelay = this.random.nextInt(20) + 10;\n\t\t\t\t\tif (this.entityToAttack != null) {\n\t\t\t\t\t\tthis.frogJumpDelay /= (int) 2.5F;\n\t\t\t\t\t}\n\t\t\t\t\tthis.jumpState.start(this.tickCount);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.entityToAttack != null) {\n\t\t\t\tthis.faceEntity(this.entityToAttack, 30.0f, 30.0f);\n\t\t\t}\n\t\t\tif (this.horizontalCollision && !this.hasPath()) {\n\t\t\t\tthis.isJumping = true;\n\t\t\t}\n\t\t\tif (this.random.nextFloat() < 0.8f && (inWater || inLava)) {\n\t\t\t\tthis.isJumping = true;\n\t\t\t}\n\t\t\tthis.currentTarget = null;\n\t\t}\n\t}\n\n\tprotected void defaultPlayerActionState() {\n\t\t++this.entityAge;\n\t\tthis.tryToDespawn();\n\t\tthis.moveStrafing = 0.0f;\n\t\tthis.moveForward = 0.0f;\n\t\tfloat f = 8.0f;\n\t\tif (this.random.nextFloat() < 0.02f) {\n\t\t\tEntityPlayer entityplayer1 = this.world.getClosestPlayerToEntity(this, f);\n\t\t\tif (entityplayer1 != null) {\n\t\t\t\tthis.currentTarget = entityplayer1;\n\t\t\t\tthis.numTicksToChaseTarget = 10 + this.random.nextInt(20);\n\t\t\t} else {\n\t\t\t\tthis.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f;\n\t\t\t}\n\t\t}\n\t\tif (this.currentTarget != null) {\n\t\t\tthis.faceEntity(this.currentTarget, 10.0f, this.func_25026_x());\n\t\t\tif (this.numTicksToChaseTarget-- <= 0 || this.currentTarget.removed || this.currentTarget.distanceToSqr(this) > (double) (f * f)) {\n\t\t\t\tthis.currentTarget = null;\n\t\t\t}\n\t\t} else {\n\t\t\tif (this.random.nextFloat() < 0.05f) {\n\t\t\t\tthis.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f;\n\t\t\t}\n\t\t\tthis.yRot += this.randomYawVelocity;\n\t\t\tthis.xRot = this.defaultPitch;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void attackEntity(Entity entity, float distance) {\n\t\tif (this.attackTime <= 0 && distance < 2.0f && entity.bb.maxY > this.bb.minY && entity.bb.minY < this.bb.maxY) {\n\t\t\tthis.attackState.start(this.tickCount);\n\t\t\tthis.attackTime = 20;\n\t\t\tentity.hurt(this, 2, DamageType.COMBAT);\n\t\t}\n\t}\n\n\t@Override\n\tprotected Entity findPlayerToAttack() {\n\t\tList<Entity> entityplayer = this.world.getEntitiesWithinAABB(EntitySlime.class, this.bb.expand(8F, 8F, 8F));\n\t\tOptional<Entity> slime = entityplayer.stream().min(Comparator.comparingDouble(this::distanceToSqr));\n\n\t\tif (slime.isPresent() && this.canEntityBeSeen(slime.get())) {\n\t\t\treturn slime.get();\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean canBreatheUnderwater() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void setSwimming(boolean swiming) {\n\t\tthis.swimming = swiming;\n\t}\n\n\t@Override\n\tpublic boolean isSwimming() {\n\t\treturn this.swimming;\n\t}\n\n\t@Override\n\tpublic float getSwimAmount(float p_20999_) {\n\t\treturn 0F;\n\t}\n\n\t@Override\n\tprotected void causeFallDamage(float f) {\n\t\tint i = (int) Math.ceil(f - 4.0f);\n\t\tif (i > 0) {\n\t\t\tsuper.causeFallDamage(f);\n\t\t}\n\t}\n}" }, { "identifier": "ModItems", "path": "src/main/java/baguchan/better_with_aquatic/item/ModItems.java", "snippet": "public class ModItems {\n\tpublic static final Item small_bulb = ItemHelper.createItem(BetterWithAquatic.MOD_ID, new Item(\"small_bulb\", IDUtils.getCurrItemId()).withTags(ItemTags.renderFullbright), \"small_bulb\", \"small_bulb.png\");\n\n\n\tpublic static void onInitialize() {\n\t}\n}" }, { "identifier": "SwimPacket", "path": "src/main/java/baguchan/better_with_aquatic/packet/SwimPacket.java", "snippet": "public class SwimPacket extends Packet {\n\tpublic boolean swim;\n\n\tpublic SwimPacket() {\n\t}\n\n\tpublic SwimPacket(boolean swim) {\n\t\tthis.swim = swim;\n\t}\n\n\t@Override\n\tpublic void readPacketData(DataInputStream dataInputStream) throws IOException {\n\t\tthis.swim = dataInputStream.readBoolean();\n\t}\n\n\t@Override\n\tpublic void writePacketData(DataOutputStream dataOutputStream) throws IOException {\n\t\tdataOutputStream.writeBoolean(this.swim);\n\t}\n\n\t@Override\n\tpublic void processPacket(NetHandler netHandler) {\n\t\t((ISwimPacket) netHandler).betterWithAquatic$handleSwim(this);\n\t}\n\n\t@Override\n\tpublic int getPacketSize() {\n\t\treturn 1;\n\t}\n}" } ]
import baguchan.better_with_aquatic.block.ModBlocks; import baguchan.better_with_aquatic.entity.EntityAnglerFish; import baguchan.better_with_aquatic.entity.EntityDrowned; import baguchan.better_with_aquatic.entity.EntityFish; import baguchan.better_with_aquatic.entity.EntityFrog; import baguchan.better_with_aquatic.item.ModItems; import baguchan.better_with_aquatic.packet.SwimPacket; import net.fabricmc.api.ModInitializer; import net.minecraft.client.gui.guidebook.mobs.MobInfoRegistry; import net.minecraft.core.achievement.stat.StatList; import net.minecraft.core.achievement.stat.StatMob; import net.minecraft.core.block.Block; import net.minecraft.core.entity.EntityDispatcher; import net.minecraft.core.item.Item; import turniplabs.halplibe.helper.EntityHelper; import turniplabs.halplibe.helper.NetworkHelper; import turniplabs.halplibe.util.ConfigHandler; import turniplabs.halplibe.util.GameStartEntrypoint; import java.util.Properties;
9,487
package baguchan.better_with_aquatic; public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer { public static final String MOD_ID = "better_with_aquatic"; private static final boolean enable_drowned; private static final boolean enable_swim; public static ConfigHandler config; static { Properties prop = new Properties(); prop.setProperty("starting_block_id", "3200"); prop.setProperty("starting_item_id", "26000"); prop.setProperty("starting_entity_id", "600"); prop.setProperty("enable_swim", "true"); prop.setProperty("enable_drowned", "true"); config = new ConfigHandler(BetterWithAquatic.MOD_ID, prop); entityID = config.getInt("starting_entity_id"); enable_swim = config.getBoolean("enable_swim"); enable_drowned = config.getBoolean("enable_drowned"); config.updateConfig(); } public static int entityID; @Override public void onInitialize() { NetworkHelper.register(SwimPacket.class, true, false); } @Override public void beforeGameStart() { Block.lightBlock[Block.fluidWaterFlowing.id] = 1; Block.lightBlock[Block.fluidWaterStill.id] = 1; ModBlocks.createBlocks(); ModItems.onInitialize();
package baguchan.better_with_aquatic; public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer { public static final String MOD_ID = "better_with_aquatic"; private static final boolean enable_drowned; private static final boolean enable_swim; public static ConfigHandler config; static { Properties prop = new Properties(); prop.setProperty("starting_block_id", "3200"); prop.setProperty("starting_item_id", "26000"); prop.setProperty("starting_entity_id", "600"); prop.setProperty("enable_swim", "true"); prop.setProperty("enable_drowned", "true"); config = new ConfigHandler(BetterWithAquatic.MOD_ID, prop); entityID = config.getInt("starting_entity_id"); enable_swim = config.getBoolean("enable_swim"); enable_drowned = config.getBoolean("enable_drowned"); config.updateConfig(); } public static int entityID; @Override public void onInitialize() { NetworkHelper.register(SwimPacket.class, true, false); } @Override public void beforeGameStart() { Block.lightBlock[Block.fluidWaterFlowing.id] = 1; Block.lightBlock[Block.fluidWaterStill.id] = 1; ModBlocks.createBlocks(); ModItems.onInitialize();
EntityHelper.Core.createEntity(EntityFish.class, entityID, "Fish");
3
2023-11-08 23:02:14+00:00
12k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/db/kernel/CSellItem.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Command<CommandSender> command;\n private static Economy econ;\n private TrieManager trieManager;\n private static TimeUtil timeUtil;\n private PlaceholderHook placeholderHook;\n private static UniqueNameGenerator uniqueNameGenerator;\n private static YamlConfig dbCfg;\n private boolean loaded;\n private static Set<String> blackList = new HashSet<>();\n private static String serverId;\n\n @Override\n public void onLoad() {\n instance = this;\n }\n\n @Override\n public void onEnable() {\n message = new Message(getLogger());\n if (!loadDbCfg()) {\n message.error(\"failed to load dbCfg.yml!\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n registerAdapters();\n loadCfgFromDbCfg();\n Lang.load(this);\n cfg = new Config(this);\n timeUtil = new TimeUtil();\n trieManager = new TrieManager(this);\n TagUtil.loadAliases(this);\n UpdateManager.checkUpdate();\n RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);\n econ = rsp.getProvider();\n initCommand();\n new Metrics(this, 20300);\n placeholderHook = new PlaceholderHook();\n placeholderHook.register();\n blackList = new HashSet<>(cfg.getConfig().getList(\"black-list\", String.class, Collections.emptyList()));\n loadDb();\n new VersionChecker();\n }\n\n private void loadDb() {\n String dbType = dbCfg.getContext().getAsString(\"db-type\");\n if (\"mysql\".equals(dbType)) {\n new Thread(() -> {\n TimeCounter timeCounter = new TimeCounter();\n\n try {\n storage = new MysqlDb(cfg.getCategoryMap(), cfg.getSortingMap(),\n dbCfg.getContext().getAsString(\"mysql-settings.host\"),\n dbCfg.getContext().getAsString(\"mysql-settings.db-name\"),\n dbCfg.getContext().getAsString(\"mysql-settings.user\"),\n dbCfg.getContext().getAsString(\"mysql-settings.password\"),\n dbCfg.getContext().getAsInteger(\"mysql-settings.port\")\n );\n storage.load();\n loaded = true;\n } catch (IOException | SQLException e) {\n message.error(\"failed to load db!\", e);\n instance.getServer().getPluginManager().disablePlugin(instance);\n }\n message.logger(Lang.getMessage(\"successful_loading\"), storage.getSellItemsSize(), timeCounter.getTime());\n\n getCommand(\"bauc\").setTabCompleter(this::onTabComplete0);\n getCommand(\"bauc\").setExecutor(this::onCommand0);\n }).start();\n } else {\n if (!\"file\".equals(dbType)) {\n dbCfg.getContext().set(\"db-type\", \"file\");\n dbCfg.trySave();\n }\n new Thread(() -> {\n TimeCounter timeCounter = new TimeCounter();\n storage = new FileDataBase(cfg.getCategoryMap(), cfg.getSortingMap());\n try {\n storage.load();\n loaded = true;\n } catch (IOException e) {\n message.error(\"failed to load db!\", e);\n instance.getServer().getPluginManager().disablePlugin(instance);\n }\n message.logger(Lang.getMessage(\"successful_loading\"), storage.getSellItemsSize(), timeCounter.getTime());\n getCommand(\"bauc\").setTabCompleter(this::onTabComplete0);\n getCommand(\"bauc\").setExecutor(this::onCommand0);\n }).start();\n }\n }\n\n @Override\n public void onDisable() {\n if (!loaded) return;\n try {\n storage.save();\n storage.close();\n } catch (IOException e) {\n message.error(\"failed to save db\", e);\n }\n AdapterRegistry.unregisterPrimitiveAdapter(Sorting.SortingType.class);\n AdapterRegistry.unregisterPrimitiveAdapter(InventoryType.class);\n AdapterRegistry.unregisterAdapter(Sorting.class);\n AdapterRegistry.unregisterAdapter(Category.class);\n AdapterRegistry.unregisterAdapter(Requirements.class);\n AdapterRegistry.unregisterAdapter(CustomItemStack.class);\n AdapterRegistry.unregisterAdapter(Boost.class);\n AdapterRegistry.unregisterAdapter(IRequirement.class);\n placeholderHook.unregister();\n }\n\n private void registerAdapters() {\n AdapterRegistry.registerPrimitiveAdapter(Sorting.SortingType.class, new AdapterEnum<>(Sorting.SortingType.class));\n AdapterRegistry.registerPrimitiveAdapter(InventoryType.class, new AdapterEnum<>(InventoryType.class));\n AdapterRegistry.registerAdapter(Sorting.class, new AdapterSortingType());\n AdapterRegistry.registerAdapter(Category.class, new AdapterCategory());\n AdapterRegistry.registerAdapter(Requirements.class, new AdapterRequirements());\n AdapterRegistry.registerAdapter(CustomItemStack.class, new AdapterCustomItemStack());\n AdapterRegistry.registerAdapter(Boost.class, new AdapterBoost());\n AdapterRegistry.registerAdapter(IRequirement.class, new AdapterIRequirement());\n }\n\n private boolean loadDbCfg() {\n try {\n File file = new File(getDataFolder() + \"/dbCfg.yml\");\n if (!file.exists()) {\n saveResource(\"dbCfg.yml\", false);\n }\n dbCfg = new YamlConfig(file);\n return true;\n } catch (IOException | InvalidConfigurationException e) {\n message.error(e);\n }\n return false;\n }\n\n public void reloadDbCfg() {\n loadDbCfg();\n loadCfgFromDbCfg();\n }\n\n private void loadCfgFromDbCfg() {\n int seed = dbCfg.getContext().getAsInteger(\"name-generator.last-seed\");\n serverId = dbCfg.getContext().getAsString(\"server-id\");\n uniqueNameGenerator = new UniqueNameGenerator(seed);\n dbCfg.getContext().set(\"name-generator.last-seed\", seed + 1);\n dbCfg.trySave();\n }\n\n public static YamlConfig getDbCfg() {\n return dbCfg;\n }\n\n public static UniqueNameGenerator getUniqueNameGenerator() {\n return uniqueNameGenerator;\n }\n\n public static Message getMessage() {\n return message;\n }\n\n public static Plugin getInstance() {\n return instance;\n }\n\n public static Config getCfg() {\n return cfg;\n }\n\n public static FileDataBase getStorage() {\n return storage;\n }\n\n public static Economy getEcon() {\n return econ;\n }\n\n public static TimeUtil getTimeUtil() {\n return timeUtil;\n }\n\n public void reloadConfigs() {\n reloadDbCfg();\n Lang.load(this);\n cfg.reload(instance);\n timeUtil.reload();\n trieManager.reload(instance);\n TagUtil.loadAliases(instance);\n }\n\n private void initCommand() {\n command = new Command<CommandSender>(\"bauc\")\n .addSubCommand(new Command<CommandSender>(\"reload\")\n //<editor-fold desc=\"reload\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.reload\"))\n .executor((sender, args) -> {\n TimeCounter timeCounter = new TimeCounter();\n\n getCommand(\"bauc\").setTabCompleter(instance);\n getCommand(\"bauc\").setExecutor(instance);\n\n message.sendMsg(sender, \"&fUnloading db...\");\n try {\n storage.save();\n storage.close();\n } catch (IOException e) {\n message.error(\"failed to save db\", e);\n }\n message.sendMsg(sender, \"&fReloading other files...\");\n reloadConfigs();\n blackList = new HashSet<>(cfg.getConfig().getList(\"black-list\", String.class, Collections.emptyList()));\n message.sendMsg(sender, \"&fLoading db...\");\n loadDb();\n\n message.sendMsg(sender, Lang.getMessage(\"plugin_reload\"), timeCounter.getTime());\n })\n //</editor-fold>\n )\n .requires(new RequiresPermission<>(\"bauc.use\"))\n .addSubCommand(new Command<CommandSender>(\"admin\")\n .requires(new RequiresPermission<>(\"bauc.admin\"))\n .addSubCommand(new Command<CommandSender>(\"debug\")\n //<editor-fold desc=\"debug\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.admin.debug\"))\n .addSubCommand(new Command<CommandSender>(\"run\")\n .requires((s) -> s instanceof Player)\n .argument(new ArgumentInteger<>(\"count\"))\n .argument(new ArgumentStrings<>(\"command\"))\n .executor(((sender, args) -> {\n Player player = (Player) sender;\n ItemStack itemStack = player.getInventory().getItemInMainHand().clone();\n if (itemStack.getType().isAir()) {\n throw new CommandException(Lang.getMessage(\"item_in_hand_required\"));\n }\n int count = (int) args.getOrThrow(\"count\");\n String cmd = (String) args.getOrThrow(\"command\");\n TimeCounter timeCounter = new TimeCounter();\n for (int i = 0; i < count; i++) {\n player.performCommand(cmd);\n player.getInventory().setItemInMainHand(itemStack);\n }\n message.sendMsg(sender, \"&fThe '%s' command was executed %s times for %s ms.\", cmd, count, timeCounter.getTime());\n }))\n )\n\n .addSubCommand(new Command<CommandSender>(\"ping\")\n .requires(new RequiresPermission<>(\"bauc.admin.ping\"))\n .requires((sender -> storage instanceof MysqlDb))\n .argument(new ArgumentSetList<>(\"server\", () -> ((MysqlDb) storage).getPacketConnection().getServerList()))\n .executor(((sender, args) -> {\n new Thread(() -> {\n String server = (String) args.getOrDefault(\"server\", \"all\");\n PacketConnection connection = ((MysqlDb) storage).getPacketConnection();\n if (!connection.hasConnection()) {\n message.sendMsg(sender, \"&cHas no connection!\");\n return;\n }\n message.sendMsg(sender, \"&fInit...\");\n connection.pining();\n\n int servers = server.equals(\"all\") ? 1 : connection.getServerList().size();\n\n AtomicInteger response = new AtomicInteger();\n WaitNotifyCallBack<PlayInPingResponsePacket> callBack = new WaitNotifyCallBack<>() {\n @Override\n protected void back0(@Nullable PlayInPingResponsePacket packet) {\n if (packet.getTo().equals(serverId)) {\n message.sendMsg(sender, \"&aPing '%s' %s ms.\", packet.getFrom(), packet.getPing());\n response.getAndIncrement();\n }\n }\n };\n connection.registerCallBack(PacketType.PING_RESPONSE, callBack);\n int lost = 0;\n for (int i = 1; i <= 5; i++) {\n int last = response.get();\n message.sendMsg(sender, \"&7Start pinging server %s... trying %s\", server, i);\n PlayOutPingRequestPacket packet = new PlayOutPingRequestPacket(serverId, server);\n connection.saveSend(packet);\n\n for (int i1 = 0; i1 < servers; i1++) {\n try {\n callBack.wait_(2000);\n } catch (Exception e) {\n }\n }\n\n if (last - response.get() == 0) {\n message.sendMsg(sender, \"&cLost...\");\n lost++;\n }\n }\n connection.unregisterCallBack(PacketType.PING_RESPONSE, callBack);\n message.sendMsg(sender, \"&7finish. Lost %s\", lost);\n }).start();\n }))\n )\n .addSubCommand(new Command<CommandSender>(\"clear\")\n .requires(new RequiresPermission<>(\"bauc.admin.debug.clear\"))\n .requires(s -> !(storage instanceof MysqlDb))\n .executor(((sender, args) -> {\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n CallBack<Optional<ConfirmMenu.Result>> callBack = (res) -> {\n if (res.isPresent()) {\n if (res.get() == ConfirmMenu.Result.ACCEPT) {\n storage.clear();\n message.sendMsg(player, Lang.getMessage(\"auc-cleared\"));\n }\n }\n player.closeInventory();\n };\n ItemStack itemStack = new ItemStack(Material.JIGSAW);\n ItemMeta im = itemStack.getItemMeta();\n im.setDisplayName(message.messageBuilder(Lang.getMessage(\"auc-clear-confirm\")));\n itemStack.setItemMeta(im);\n ConfirmMenu menu = new ConfirmMenu(callBack, itemStack, player);\n menu.open();\n }))\n )\n .addSubCommand(new Command<CommandSender>(\"stress\")\n .requires(new RequiresPermission<>(\"bauc.admin.debug.stress\"))\n .argument(new ArgumentIntegerAllowedMatch<>(\"count\", List.of(\"[count]\")))\n .argument(new ArgumentIntegerAllowedMatch<>(\"repeat\", List.of(\"[repeat]\")))\n .argument(new ArgumentIntegerAllowedMatch<>(\"cd\", List.of(\"[cd]\")))\n .argument(new ArgumentIntegerAllowedMatch<>(\"limit\", List.of(\"[limit]\")))\n .executor((sender, args) -> {\n int count = (int) args.getOrDefault(\"count\", 1);\n int repeat = (int) args.getOrDefault(\"repeat\", 1);\n int cd = (int) args.getOrDefault(\"cd\", 1);\n int limit = (int) args.getOrDefault(\"limit\", Integer.MAX_VALUE);\n TimeCounter timeCounter = new TimeCounter();\n FakePlayer fakePlayer = new FakePlayer(storage, limit);\n new BukkitRunnable() {\n int x = 0;\n List<Long> list = new ArrayList<>();\n\n @Override\n public void run() {\n timeCounter.reset();\n x++;\n for (int i = 0; i < count; i++) {\n fakePlayer.randomAction();\n }\n long time = timeCounter.getTime();\n message.sendMsg(sender, \"Completed in %s ms. %s\", time, x);\n list.add(time);\n if (x >= repeat) {\n long l = 0;\n for (Long l1 : list) {\n l += l1;\n }\n l /= list.size();\n\n String s = String.format(\"Deals per second: %s. Average duration: %s ms. Total deals made: %s. Items on auction: %s.\",\n count * (20 / cd),\n l,\n count * repeat,\n storage.getSellItemsSize()\n );\n message.logger(s);\n message.sendMsg(sender, s);\n cancel();\n }\n }\n }.runTaskTimerAsynchronously(instance, 0, cd);\n })\n )\n //</editor-fold>\n )\n\n .addSubCommand(new Command<CommandSender>(\"addTag\")\n //<editor-fold desc=\"addTag\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.admin.addTag\"))\n .argument(new ArgumentString<>(\"key\", List.of(\"[tag key]\")))\n .argument(new ArgumentString<>(\"value\", List.of(\"[tag value]\")))\n .executor((sender, args) -> {\n String key = (String) args.getOrThrow(\"key\");\n String value = (String) args.getOrThrow(\"value\");\n\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n ItemStack itemStack = player.getInventory().getItemInMainHand();\n if (itemStack.getType().isAir()) {\n throw new CommandException(Lang.getMessage(\"item_in_hand_required\"));\n }\n ItemMeta im = itemStack.getItemMeta();\n im.getPersistentDataContainer().set(NamespacedKey.fromString(key), PersistentDataType.STRING, value);\n itemStack.setItemMeta(im);\n message.sendMsg(sender, \"&adone\");\n }\n )\n //</editor-fold>\n )\n .addSubCommand(new Command<CommandSender>(\"open\")\n //<editor-fold desc=\"open\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.admin.open\"))\n .argument(new ArgumentPlayer<>(\"player\"))\n .argument(new ArgumentSetList<>(\"category\", cfg.getCategoryMap().keySet().stream().map(NameKey::getName).toList()))\n .executor((sender, args) -> {\n Player player = (Player) args.getOrThrow(\"player\");\n String categoryS = (String) args.getOrThrow(\"category\");\n\n Category category = cfg.getCategoryMap().get(new NameKey(categoryS, true));\n\n if (category == null) {\n message.sendMsg(sender, \"unknown category %s\", categoryS);\n return;\n }\n\n User user = storage.getUserOrCreate(player);\n MainMenu menu = new MainMenu(user, player);\n\n int index = menu.getCategories().indexOf(category);\n\n if (index == -1) {\n message.sendMsg(sender, \"unknown category %s\", categoryS);\n menu.close();\n return;\n }\n menu.getCategories().current = index;\n menu.open();\n })\n //</editor-fold>\n )\n .addSubCommand(new Command<CommandSender>(\"parse\")\n //<editor-fold desc=\"parse\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.parse\"))\n .addSubCommand(new Command<CommandSender>(\"tags\")\n .requires(new RequiresPermission<>(\"bauc.parse.tags\"))\n .executor((sender, args) -> {\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n ItemStack itemStack = player.getInventory().getItemInMainHand();\n if (itemStack.getType().isAir()) {\n throw new CommandException(Lang.getMessage(\"item_in_hand_required\"));\n }\n message.sendMsg(sender, TagUtil.getTags(itemStack).toString());\n })\n //</editor-fold>\n )\n .addSubCommand(new Command<CommandSender>(\"nbt\")\n //<editor-fold desc=\"nbt\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.parse.nbt\"))\n .executor((sender, args) -> {\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n ItemStack itemStack = player.getInventory().getItemInMainHand();\n if (itemStack.getType().isAir()) {\n throw new CommandException(Lang.getMessage(\"item_in_hand_required\"));\n }\n message.sendMsg(sender, new String(Base64.getDecoder().decode(BLib.getApi().getItemStackSerialize().serialize(itemStack))));\n })\n //</editor-fold>\n )\n )\n .addSubCommand(new Command<CommandSender>(\"push\")\n //<editor-fold desc=\"push\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.admin.push\"))\n .argument(new ArgumentIntegerAllowedMatch<>(\"price\", List.of(Lang.getMessage(\"price_tag\"))))\n .argument(new ArgumentInteger<>(\"amount\", List.of(Lang.getMessage(\"quantity_tag\"))))\n .argument(new ArgumentString<>(\"time\", List.of(Lang.getMessage(\"sale_time_tag\"))))\n .executor((sender, args) -> {\n int amount = (int) args.getOrDefault(\"amount\", 1);\n int price = (int) args.getOrThrow(\"price\", Lang.getMessage(\"price_not_specified\"));\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n\n ItemStack itemStack = player.getInventory().getItemInMainHand();\n if (itemStack.getType().isAir()) {\n throw new CommandException(Lang.getMessage(\"cannot_trade_air\"));\n }\n TimeCounter timeCounter = new TimeCounter();\n Random random = new Random();\n User user = storage.getUserOrCreate(player);\n long time = NumberUtil.getTime(((String) args.getOrDefault(\"time\", \"2d\")));\n for (int i = 0; i < amount; i++) {\n CSellItem sellItem = new CSellItem(player, itemStack, price + random.nextInt(price / 2), time);\n SellItemEvent event = new SellItemEvent(user, sellItem);\n storage.validateAndAddItem(event);\n if (!event.isValid()) {\n message.sendMsg(player, String.valueOf(event.getReason()));\n break;\n }\n }\n message.sendMsg(player, Lang.getMessage(\"successful_listing\"), amount, timeCounter.getTime());\n }\n )\n //</editor-fold>\n )\n )\n .addSubCommand(new Command<CommandSender>(\"sell\")\n //<editor-fold desc=\"sell\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.sell\"))\n .argument(new ArgumentIntegerAllowedMatch<>(\"price\", List.of(Lang.getMessage(\"price_tag\")),\n cfg.getConfig().getAsInteger(\"offer-min-price\", 1),\n cfg.getConfig().getAsInteger(\"offer-max-price\", Integer.MAX_VALUE)\n ))\n .argument(new ArgumentFullOrCount(\"arg\"))\n .executor(((sender, args) -> {\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n int price = (int) args.getOrThrow(\"price\", Lang.getMessage(\"price_not_specified\"));\n\n String saleByThePieceS = String.valueOf(args.getOrDefault(\"arg\", \"full:false\"));\n\n boolean saleByThePiece = !(saleByThePieceS.equals(\"full\"));\n\n\n int amount = -1; //(int) args.getOrDefault(\"amount\", -1);\n if (!saleByThePieceS.startsWith(\"f\")) {\n try {\n amount = Integer.parseInt(saleByThePieceS);\n } catch (NumberFormatException e) {\n message.sendMsg(sender, \"&cУкажите число для продажи определённого количества предметов!\");\n return;\n }\n }\n\n ItemStack itemStack = player.getInventory().getItemInMainHand().clone();\n if (itemStack.getType().isAir()) {\n throw new CommandException(Lang.getMessage(\"cannot_trade_air\"));\n }\n\n int cashback = 0;\n if (amount != -1) {\n if (itemStack.getAmount() > amount) {\n cashback = itemStack.getAmount() - amount;\n itemStack.setAmount(amount);\n }\n }\n\n if (saleByThePiece) saleByThePiece = Main.getCfg().isAllowBuyCount();\n User user = storage.getUserOrCreate(player);\n CSellItem sellItem = new CSellItem(player, itemStack, price, cfg.getDefaultSellTime() + user.getExternalSellTime(), saleByThePiece);\n\n for (String tag : sellItem.getTags()) {\n if (blackList.contains(tag)) {\n message.sendMsg(player, sellItem.replace(Lang.getMessage(\"item-in-black-list\")));\n return;\n }\n }\n\n SellItemEvent event = new SellItemEvent(user, sellItem);\n storage.validateAndAddItem(event);\n if (event.isValid()) {\n player.getInventory().getItemInMainHand().setAmount(cashback);\n message.sendMsg(player, sellItem.replace(Lang.getMessage(\"successful_single_listing\")));\n } else {\n message.sendMsg(player, String.valueOf(event.getReason()));\n }\n }))\n //</editor-fold>\n )\n .addSubCommand(new Command<CommandSender>(\"search\")\n //<editor-fold desc=\"search\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.search\"))\n .argument(new ArgumentStrings<>(\"tags\"))\n .executor((sender, args) -> {\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n\n String[] rawtags = ((String) args.getOrThrow(\"tags\", Lang.getMessage(\"tags_required\"))).split(\" \");\n List<String> tags = new ArrayList<>();\n for (String rawtag : rawtags) {\n tags.addAll(trieManager.getTrie().getAllWithPrefix(rawtag));\n }\n Category custom = cfg.getSorting().getAs(\"special.search\", Category.class);\n custom.setTags(new HashSet<>(tags));\n\n User user = storage.getUserOrCreate(player);\n\n MainMenu menu = new MainMenu(user, player);\n menu.setCustomCategory(custom);\n menu.open();\n })\n //</editor-fold>\n )\n .addSubCommand(new Command<CommandSender>(\"view\")\n //<editor-fold desc=\"view\" defaultstate=\"collapsed\">\n .requires(new RequiresPermission<>(\"bauc.view\"))\n .argument(new ArgumentString<>(\"player\", () -> List.of(Bukkit.getOnlinePlayers().stream().map(Player::getName).toArray(String[]::new))))\n .executor(((sender, args) -> {\n if (!(sender instanceof Player senderP))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n\n String player = (String) args.get(\"player\");\n if (player == null) {\n message.sendMsg(sender, Lang.getMessage(\"player-not-selected\"));\n return;\n }\n UUID uuid;\n if (UUIDUtils.isUUID(player)) {\n uuid = UUID.fromString(player);\n } else {\n Player p = Bukkit.getPlayer(player);\n if (p != null) {\n uuid = p.getUniqueId();\n } else {\n uuid = UUID.nameUUIDFromBytes((\"OfflinePlayer:\" + player).getBytes(Charsets.UTF_8));\n }\n }\n if (!storage.hasUser(uuid)) {\n message.sendMsg(sender, Lang.getMessage(\"player-not-found\"));\n return;\n }\n User user = storage.getUserOrCreate(senderP);\n PlayerItemsView menu = new PlayerItemsView(user, senderP, uuid, player);\n menu.open();\n }))\n //</editor-fold>\n )\n .executor(((sender, args) -> {\n if (!(sender instanceof Player player))\n throw new CommandException(Lang.getMessage(\"must_be_player\"));\n User user = storage.getUserOrCreate(player);\n MainMenu menu = new MainMenu(user, player);\n menu.open();\n }))\n ;\n }\n\n\n private boolean onCommand0(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command cmd, @NotNull String label, @NotNull String[] args) {\n try {\n command.process(sender, args);\n return true;\n } catch (CommandException e) {\n message.sendMsg(sender, e.getLocalizedMessage());\n }\n return true;\n }\n\n @Nullable\n private List<String> onTabComplete0(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command cmd, @NotNull String alias, @NotNull String[] args) {\n if (args[0].equals(\"search\") && sender.hasPermission(\"bauc.search\")) {\n String last = args[args.length - 1];\n if (last.isEmpty()) return List.of(Lang.getMessage(\"start_entering_item_name\"));\n return trieManager.getTrie().getAllKeysWithPrefix(last);\n }\n return command.getTabCompleter(sender, args);\n }\n\n public static String getServerId() {\n return serverId;\n }\n}" }, { "identifier": "SellItem", "path": "BaucApi/src/main/java/org/by1337/bauction/auc/SellItem.java", "snippet": "public interface SellItem extends Placeholderable, SerializableToByteArray {\n\n /**\n * Get the item available for sale as an ItemStack.\n *\n * @return ItemStack representing the item for sale.\n */\n ItemStack getItemStack();\n\n /**\n * Get the item available for sale as Base64-encoded NBT tags.\n *\n * @return Base64-encoded NBT tags representing the item for sale.\n */\n String getItem();\n\n /**\n * Get the name of the seller.\n *\n * @return The name of the seller.\n */\n String getSellerName();\n\n /**\n * Get the UUID of the seller.\n *\n * @return The UUID of the seller.\n */\n UUID getSellerUuid();\n\n /**\n * Get the price of the item.\n *\n * @return The price of the item.\n */\n double getPrice();\n\n /**\n * Check if the item can be purchased in pieces.\n *\n * @return True if the item can be purchased in pieces, false otherwise.\n */\n boolean isSaleByThePiece();\n\n /**\n * Get the tags associated with the item.\n *\n * @return Set of tags associated with the item.\n */\n Set<String> getTags();\n\n /**\n * Get the date when the item was listed for sale.\n *\n * @return The date when the item was listed for sale.\n */\n long getTimeListedForSale();\n\n /**\n * Get the date after which the item will become an UnsoldItem.\n *\n * @return The date after which the item will become an UnsoldItem.\n */\n long getRemovalDate();\n\n /**\n * Get the UUID of the item.\n *\n * @return The UUID of the item.\n */\n UniqueName getUniqueName();\n\n /**\n * Get the material of the item.\n *\n * @return The material of the item.\n */\n Material getMaterial();\n\n /**\n * Get the quantity of the item.\n *\n * @return The quantity of the item.\n */\n int getAmount();\n\n /**\n * Get the price per unit of the item if it can be sold in pieces, otherwise, get the total price.\n *\n * @return The price per unit of the item if sold in pieces, otherwise, the total price.\n */\n double getPriceForOne();\n\n String getServer();\n\n String toSql(String table);\n}" }, { "identifier": "Lang", "path": "Core/src/main/java/org/by1337/bauction/lang/Lang.java", "snippet": "public class Lang {\n private static final HashMap<String, String> messages = new HashMap<>();\n\n public static void load(Plugin plugin) {\n messages.clear();\n\n YamlContext context;\n File file;\n file = new File(plugin.getDataFolder().getPath() + \"/message.yml\");\n if (!file.exists()) {\n plugin.saveResource(\"message.yml\", true);\n }\n context = new YamlContext(YamlConfiguration.loadConfiguration(file));\n\n messages.putAll(context.getMap(\"messages\", String.class));\n messages.putAll(context.getMap(\"items\", String.class));\n }\n\n public static String getMessage(String s) {\n String str = messages.get(s);\n if (str == null) return \"missing message '\" + s + \"' in message.yml!\";\n return str;\n }\n}" }, { "identifier": "SerializeUtils", "path": "Core/src/main/java/org/by1337/bauction/serialize/SerializeUtils.java", "snippet": "public class SerializeUtils {\n\n public static void writeCollectionToStream(DataOutputStream data, Collection<String> collection) throws IOException {\n data.writeInt(collection.size());\n for (String element : collection) {\n data.writeUTF(element);\n }\n }\n public static List<String> readCollectionFromStream(DataInputStream in) throws IOException {\n int size = in.readInt();\n List<String> result = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n result.add(in.readUTF());\n }\n return result;\n }\n\n public static <T extends SerializableToByteArray> void writeSerializableCollection(DataOutputStream data, Collection<T> collection) throws IOException {\n data.writeInt(collection.size());\n for (T element : collection) {\n byte[] arr = element.getBytes();\n data.writeInt(arr.length);\n data.write(arr);\n }\n }\n\n public static <T> List<T> readSerializableCollection(DataInputStream in, Deserializable<T> deserializable) throws IOException {\n int size = in.readInt();\n List<T> result = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n int chunk = in.readInt();\n result.add(\n deserializable.deserialize(in.readNBytes(chunk))\n );\n }\n return result;\n }\n\n public static void writeUUID(UUID uuid, DataOutputStream data) throws IOException {\n data.writeLong(uuid.getMostSignificantBits());\n data.writeLong(uuid.getLeastSignificantBits());\n }\n\n public static UUID readUUID(DataInputStream in) throws IOException {\n return new UUID(in.readLong(), in.readLong());\n }\n}" }, { "identifier": "CUniqueName", "path": "Core/src/main/java/org/by1337/bauction/util/CUniqueName.java", "snippet": "public class CUniqueName implements UniqueName {\n private final String key;\n private final int seed;\n private final long pos;\n\n public CUniqueName(String key, int seed, long pos) {\n this.key = key;\n this.seed = seed;\n this.pos = pos;\n }\n\n public CUniqueName(String key) {\n this.key = key;\n seed = -1;\n pos = -1;\n }\n\n public String getKey() {\n return key;\n }\n\n public int getSeed() {\n return seed;\n }\n\n public long getPos() {\n return pos;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof CUniqueName that)) return false;\n return key.equals(that.key);\n }\n\n @Override\n public int hashCode() {\n return key.hashCode();\n }\n\n public boolean canBeCompressToSeedAndPos() {\n return seed > 0 && pos > 0;\n }\n\n @Override\n public String toString() {\n return key + \":\" + seed + \":\" + pos;\n }\n\n public static CUniqueName fromString(String s) {\n String[] parts = s.split(\":\");\n if (parts.length == 3) {\n String key = parts[0];\n int seed = Integer.parseInt(parts[1]);\n long pos = Long.parseLong(parts[2]);\n return new CUniqueName(key, seed, pos);\n } else if (parts.length == 1) {\n return new CUniqueName(parts[0]);\n } else {\n throw new IllegalArgumentException(\"Invalid string format for CUniqueName: \" + s);\n }\n }\n\n @Override\n public byte[] getBytes() throws IOException {\n try (ByteArrayOutputStream out = new ByteArrayOutputStream();\n DataOutputStream data = new DataOutputStream(out)) {\n data.writeUTF(getKey());\n data.flush();\n return out.toByteArray();\n }\n }\n\n public static UniqueName fromBytes(byte[] arr) throws IOException {\n try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(arr))) {\n return new CUniqueName(\n in.readUTF()\n );\n }\n }\n\n}" }, { "identifier": "NumberUtil", "path": "Core/src/main/java/org/by1337/bauction/util/NumberUtil.java", "snippet": "public class NumberUtil {\n\n /**\n * Обрезает стоку\n * @param value 1272.3443284\n * @return 1272.34\n * При выводе числа игроку всегда это число должно проходить через этот метод\n * так как он не только обрезает строку, но и приводит её в нормальное состояние из 1.27232432234E9 в 1272324322.34\n */\n public static String format(double value){\n DecimalFormat df = new DecimalFormat(\"#.##\");\n return df.format(value);\n }\n\n /**\n * Обрезает строку по аналогии с NumberUtil.format только возвращает обрезанный double\n * @param value 1272.3443284\n * @return 1272.34\n */\n public static double trim(double value){\n return Double.parseDouble(format(value));\n }\n\n public static long getTime(String s){\n StringBuilder number = new StringBuilder();\n StringBuilder type = new StringBuilder();\n long out = 0;\n char[] arr = s.toCharArray();\n\n for (char c : arr){\n if (Character.isDigit(c)){\n if (!type.isEmpty() && !number.isEmpty()){\n out += getResult(Integer.parseInt(number.toString()), type.toString());\n number = new StringBuilder();\n type = new StringBuilder();\n }\n number.append(c);\n }else {\n type.append(c);\n }\n }\n if (!type.isEmpty() && !number.isEmpty()){\n out += getResult(Integer.parseInt(number.toString()), type.toString());\n }\n return out;\n }\n private static long getResult(int x, String s){\n return switch (s) {\n case \"s\" -> 1000L * x;\n case \"m\" -> 60000L * x;\n case \"h\" -> 3600000L * x;\n case \"d\" -> 86400000L * x;\n case \"w\" -> 604800000L * x;\n case \"mo\" -> 2629746000L * x;\n case \"y\" -> 31556908800L * x;\n default -> 0;\n };\n }\n\n public static boolean isDouble(String num) {\n Pattern pattern = Pattern.compile(\"(-?\\\\d+)([.])?(\\\\d+)?\");\n Matcher matcher = pattern.matcher(num);\n if (matcher.find()) {\n return matcher.group().equals(num);\n } else\n return false;\n }\n}" }, { "identifier": "TagUtil", "path": "Core/src/main/java/org/by1337/bauction/util/TagUtil.java", "snippet": "public class TagUtil {\n private static final Map<String, String> tagAliases = new HashMap<>();\n\n public static void loadAliases(Plugin plugin) {\n tagAliases.clear();\n\n YamlContext context;\n File file;\n file = new File(plugin.getDataFolder().getPath() + \"/tagUtil.yml\");\n if (!file.exists()) {\n plugin.saveResource(\"tagUtil.yml\", true);\n }\n context = new YamlContext(YamlConfiguration.loadConfiguration(file));\n\n for (String tag : context.getHandle().getConfigurationSection(\"tags\").getKeys(false)) {\n List<String> list = context.getList(\"tags.\" + tag, String.class);\n list.forEach(str -> tagAliases.put(str, tag));\n }\n\n }\n\n public static HashSet<String> getTags(@NotNull ItemStack itemStack) {\n List<String> list = new ArrayList<>();\n\n Material material = itemStack.getType();\n list.add(material.name());\n ItemMeta im = itemStack.getItemMeta();\n if (im.hasCustomModelData()){\n list.add(\"customModelData:\" + im.getCustomModelData());\n }\n itemStack.getEnchantments().forEach((e, i) -> {\n list.add(e.getKey().getKey());\n list.add(e.getKey().getKey() + \":\" + i);\n });\n list.addAll(getTags(material));\n\n if (im != null) {\n if (im instanceof PotionMeta potionMeta) {\n potionMeta.getCustomEffects().forEach(potionEffect -> {\n list.add(potionEffect.getType().getName());\n list.add(potionEffect.getType().getName() + \":\" + potionEffect.getAmplifier());\n });\n list.add(potionMeta.getBasePotionData().getType().name());\n if (potionMeta.getBasePotionData().isUpgraded()){\n list.add(potionMeta.getBasePotionData().getType().name() + \":1\");\n }\n }\n list.addAll(ParsePDCTagsMagager.parseTags(im.getPersistentDataContainer()));\n if (im instanceof EnchantmentStorageMeta enchantmentStorageMeta) {\n enchantmentStorageMeta.getStoredEnchants().keySet().forEach(e -> list.add(e.getKey().getKey()));\n }\n }\n\n for (String str : list.toArray(new String[0])) {\n String s = tagAliases.get(str);\n if (s != null) {\n list.add(s);\n }\n }\n\n list.replaceAll(String::toLowerCase);\n return new HashSet<>(list);\n }\n\n public static List<String> getTags(Material material) {\n List<String> list = new ArrayList<>();\n if (material.isFlammable()) list.add(Tags.IS_FLAMMABLE.getTag());\n if (material.isBurnable()) list.add(Tags.IS_BURNABLE.getTag());\n if (material.isFuel()) list.add(Tags.IS_FUEL.getTag());\n if (material.hasGravity()) list.add(Tags.HAS_GRAVITY.getTag());\n if (material.isSolid()) list.add(Tags.IS_SOLID.getTag());\n if (material.isRecord()) list.add(Tags.IS_RECORD.getTag());\n if (material.isEdible()) list.add(Tags.IS_EDIBLE.getTag());\n if (material.isBlock()) list.add(Tags.IS_BLOCK.getTag());\n return list;\n }\n\n public static boolean matchesCategory(Category category, SellItem sellItem) {\n if (category.tags().contains(\"any\")) return true;\n for (String s : sellItem.getTags()) {\n if (category.tags().contains(s))\n return true;\n }\n return false;\n }\n\n public enum Tags {\n IS_FLAMMABLE(\"is_flammable\"),\n IS_BURNABLE(\"is_burnable\"),\n IS_FUEL(\"is_fuel\"),\n HAS_GRAVITY(\"has_gravity\"),\n IS_SOLID(\"is_solid\"),\n IS_RECORD(\"is_record\"),\n IS_EDIBLE(\"is_edible\"),\n IS_BLOCK(\"is_block\"),\n IS_TOOL(\"is_tool\"),\n IS_ARMOR(\"is_armor\"),\n IS_WEAPON(\"is_weapon\"),\n IS_SPAWN_AGG(\"is_spawn_agg\");\n\n private final String tag;\n\n Tags(String tag) {\n this.tag = tag;\n }\n\n public String getTag() {\n return tag;\n }\n }\n\n}" }, { "identifier": "UniqueName", "path": "BaucApi/src/main/java/org/by1337/bauction/util/UniqueName.java", "snippet": "public interface UniqueName extends SerializableToByteArray {\n String getKey();\n\n int getSeed();\n\n long getPos();\n\n boolean canBeCompressToSeedAndPos();\n}" } ]
import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.by1337.api.BLib; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.serialize.SerializeUtils; import org.by1337.bauction.util.CUniqueName; import org.by1337.bauction.util.NumberUtil; import org.by1337.bauction.util.TagUtil; import org.by1337.bauction.util.UniqueName; import org.jetbrains.annotations.NotNull; import java.io.*; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*;
10,795
package org.by1337.bauction.db.kernel; public class CSellItem implements SellItem { final String item; final String sellerName; final UUID sellerUuid; final double price; final boolean saleByThePiece; final Set<String> tags; final long timeListedForSale; final long removalDate; final UniqueName uniqueName; final Material material; final int amount; final double priceForOne; final Set<String> sellFor; transient ItemStack itemStack; final String server; public static CSellItemBuilder builder() { return new CSellItemBuilder(); } @Override public String toSql(String table) { return String.format( "INSERT INTO %s (uuid, seller_uuid, item, seller_name, price, sale_by_the_piece, tags, time_listed_for_sale, removal_date, material, amount, price_for_one, sell_for, server)" + "VALUES('%s', '%s', '%s', '%s', %s, %s, '%s', %s, %s, '%s', %s, %s, '%s', '%s')", table, uniqueName.getKey(), sellerUuid, item, sellerName, price, saleByThePiece, listToString(tags), timeListedForSale, removalDate, material.name(), amount, priceForOne, listToString(sellFor), server ); } public static CSellItem fromResultSet(ResultSet resultSet) throws SQLException { return CSellItem.builder() .uniqueName(new CUniqueName(resultSet.getString("uuid"))) .sellerUuid(UUID.fromString(resultSet.getString("seller_uuid"))) .item(resultSet.getString("item")) .sellerName(resultSet.getString("seller_name")) .price(resultSet.getDouble("price")) .saleByThePiece(resultSet.getBoolean("sale_by_the_piece")) .tags(new HashSet<>(Arrays.asList(resultSet.getString("tags").split(",")))) .timeListedForSale(resultSet.getLong("time_listed_for_sale")) .removalDate(resultSet.getLong("removal_date")) .material(Material.valueOf(resultSet.getString("material"))) .amount(resultSet.getInt("amount")) .priceForOne(resultSet.getDouble("price_for_one")) .sellFor(new HashSet<>(Arrays.asList(resultSet.getString("sell_for").split(",")))) .server(resultSet.getString("server")) .build(); } private static String listToString(Collection<? extends CharSequence> collection) { return String.join(",", collection); } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne, Set<String> sellFor, ItemStack itemStack, String server) { this.server = server; this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; this.sellFor = sellFor; this.itemStack = itemStack; } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne, ItemStack itemStack) { this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; this.itemStack = itemStack; sellFor = new HashSet<>();
package org.by1337.bauction.db.kernel; public class CSellItem implements SellItem { final String item; final String sellerName; final UUID sellerUuid; final double price; final boolean saleByThePiece; final Set<String> tags; final long timeListedForSale; final long removalDate; final UniqueName uniqueName; final Material material; final int amount; final double priceForOne; final Set<String> sellFor; transient ItemStack itemStack; final String server; public static CSellItemBuilder builder() { return new CSellItemBuilder(); } @Override public String toSql(String table) { return String.format( "INSERT INTO %s (uuid, seller_uuid, item, seller_name, price, sale_by_the_piece, tags, time_listed_for_sale, removal_date, material, amount, price_for_one, sell_for, server)" + "VALUES('%s', '%s', '%s', '%s', %s, %s, '%s', %s, %s, '%s', %s, %s, '%s', '%s')", table, uniqueName.getKey(), sellerUuid, item, sellerName, price, saleByThePiece, listToString(tags), timeListedForSale, removalDate, material.name(), amount, priceForOne, listToString(sellFor), server ); } public static CSellItem fromResultSet(ResultSet resultSet) throws SQLException { return CSellItem.builder() .uniqueName(new CUniqueName(resultSet.getString("uuid"))) .sellerUuid(UUID.fromString(resultSet.getString("seller_uuid"))) .item(resultSet.getString("item")) .sellerName(resultSet.getString("seller_name")) .price(resultSet.getDouble("price")) .saleByThePiece(resultSet.getBoolean("sale_by_the_piece")) .tags(new HashSet<>(Arrays.asList(resultSet.getString("tags").split(",")))) .timeListedForSale(resultSet.getLong("time_listed_for_sale")) .removalDate(resultSet.getLong("removal_date")) .material(Material.valueOf(resultSet.getString("material"))) .amount(resultSet.getInt("amount")) .priceForOne(resultSet.getDouble("price_for_one")) .sellFor(new HashSet<>(Arrays.asList(resultSet.getString("sell_for").split(",")))) .server(resultSet.getString("server")) .build(); } private static String listToString(Collection<? extends CharSequence> collection) { return String.join(",", collection); } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne, Set<String> sellFor, ItemStack itemStack, String server) { this.server = server; this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; this.sellFor = sellFor; this.itemStack = itemStack; } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne, ItemStack itemStack) { this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; this.itemStack = itemStack; sellFor = new HashSet<>();
server = Main.getServerId();
0
2023-11-08 18:25:18+00:00
12k
Svydovets-Bobocode-Java-Ultimate-3-0/Bring
src/test/java/com/bobocode/svydovets/ioc/core/beanFactory/BeanFactoryImplTest.java
[ { "identifier": "MessageService", "path": "src/test/java/com/bobocode/svydovets/source/base/MessageService.java", "snippet": "@Component(\"messageService\")\npublic class MessageService {\n private String message;\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "identifier": "InjCandidate", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/foundCandidateByInterface/InjCandidate.java", "snippet": "public interface InjCandidate {\n\n}" }, { "identifier": "InjFirstCandidate", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/foundCandidateByInterface/InjFirstCandidate.java", "snippet": "@Component\npublic class InjFirstCandidate implements InjCandidate {\n}" }, { "identifier": "InjFirstPrototypeCandidate", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/foundCandidateByInterface/InjFirstPrototypeCandidate.java", "snippet": "@Component\n@Primary\n@Scope(ApplicationContext.SCOPE_PROTOTYPE)\npublic class InjFirstPrototypeCandidate implements InjPrototypeCandidate {\n}" }, { "identifier": "InjPrototypeCandidate", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/foundCandidateByInterface/InjPrototypeCandidate.java", "snippet": "public interface InjPrototypeCandidate {\n\n}" }, { "identifier": "PrototypeCandidate", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/foundCandidateByInterface/PrototypeCandidate.java", "snippet": "@Component\n@Scope(ApplicationContext.SCOPE_PROTOTYPE)\npublic class PrototypeCandidate {\n}" }, { "identifier": "FirstInjectionCandidate", "path": "src/test/java/com/bobocode/svydovets/source/autowire/constructor/FirstInjectionCandidate.java", "snippet": "@Component\npublic class FirstInjectionCandidate {\n public String getMessage() {\n return \"I was injected\";\n }\n}" }, { "identifier": "SecondInjectionCandidate", "path": "src/test/java/com/bobocode/svydovets/source/autowire/constructor/SecondInjectionCandidate.java", "snippet": "@Component\npublic class SecondInjectionCandidate {\n public String getMessage() {\n return \"I was injected\";\n }\n}" }, { "identifier": "ValidConstructorInjectionService", "path": "src/test/java/com/bobocode/svydovets/source/autowire/constructor/ValidConstructorInjectionService.java", "snippet": "@Component\npublic class ValidConstructorInjectionService {\n\n private final FirstInjectionCandidate firstInjectionCandidate;\n private final SecondInjectionCandidate secondInjectionCandidate;\n\n @Autowired\n public ValidConstructorInjectionService(FirstInjectionCandidate firstInjectionCandidate, SecondInjectionCandidate secondInjectionCandidate) {\n this.firstInjectionCandidate = firstInjectionCandidate;\n this.secondInjectionCandidate = secondInjectionCandidate;\n }\n\n public FirstInjectionCandidate getFirstInjectionCandidate() {\n return firstInjectionCandidate;\n }\n\n public SecondInjectionCandidate getSecondInjectionCandidate() {\n return secondInjectionCandidate;\n }\n}" }, { "identifier": "ConfigMethodBasedBeanAutowiring", "path": "src/test/java/com/bobocode/svydovets/source/autowire/ConfigMethodBasedBeanAutowiring.java", "snippet": "@Configuration\npublic class ConfigMethodBasedBeanAutowiring {\n\n @Bean\n public ValidConstructorInjectionService validConstructorInjectionService(\n FirstInjectionCandidate firstInjectionCandidate,\n SecondInjectionCandidate secondInjectionCandidate) {\n return new ValidConstructorInjectionService(firstInjectionCandidate, secondInjectionCandidate);\n }\n}" }, { "identifier": "InjPrototypeCandidateMoreOnePrimary", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/throwPrototypeCandidateByInterfaceMoreOnePrimary/InjPrototypeCandidateMoreOnePrimary.java", "snippet": "public interface InjPrototypeCandidateMoreOnePrimary {\n\n}" }, { "identifier": "InjPrototypeCandidateWithoutPrimary", "path": "src/test/java/com/bobocode/svydovets/source/beanFactoryTest/throwPrototypeCandidateByInterfaceWithoutPrimary/InjPrototypeCandidateWithoutPrimary.java", "snippet": "public interface InjPrototypeCandidateWithoutPrimary {\n\n}" }, { "identifier": "CircularDependencyConfig", "path": "src/test/java/com/bobocode/svydovets/source/circularDependency/CircularDependencyConfig.java", "snippet": "@Configuration\npublic class CircularDependencyConfig {\n\n @Bean\n public CommonService commonService(MessageService messageService) {\n return new CommonService();\n }\n\n @Bean\n public MessageService messageService(CommonService commonService) {\n return new MessageService();\n }\n}" }, { "identifier": "FirstCircularDependencyOwner", "path": "src/test/java/com/bobocode/svydovets/source/circularDependency/FirstCircularDependencyOwner.java", "snippet": "@Component\npublic class FirstCircularDependencyOwner implements FirstCircularDependency {\n private SecondCircularDependency secondCircularDependency;\n\n @Autowired\n public FirstCircularDependencyOwner(SecondCircularDependency secondCircularDependency) {\n this.secondCircularDependency = secondCircularDependency;\n }\n}" }, { "identifier": "SecondCircularDependencyOwner", "path": "src/test/java/com/bobocode/svydovets/source/circularDependency/SecondCircularDependencyOwner.java", "snippet": "@Component\npublic class SecondCircularDependencyOwner implements SecondCircularDependency {\n private FirstCircularDependency firstCircularDependency;\n\n @Autowired\n public SecondCircularDependencyOwner(FirstCircularDependency firstCircularDependency) {\n this.firstCircularDependency = firstCircularDependency;\n }\n}" }, { "identifier": "BeanCreationException", "path": "src/main/java/svydovets/core/exception/BeanCreationException.java", "snippet": "public class BeanCreationException extends RuntimeException {\n public BeanCreationException(String message) {\n super(message);\n }\n public BeanCreationException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "NoSuchBeanDefinitionException", "path": "src/main/java/svydovets/core/exception/NoSuchBeanDefinitionException.java", "snippet": "public class NoSuchBeanDefinitionException extends RuntimeException {\n\n public NoSuchBeanDefinitionException(String message) {\n super(message);\n }\n}" }, { "identifier": "BeanFactoryImpl", "path": "src/main/java/svydovets/core/context/beanFactory/BeanFactoryImpl.java", "snippet": "public class BeanFactoryImpl implements BeanFactory {\n private static final Logger log = LoggerFactory.getLogger(BeanFactoryImpl.class);\n\n public static final Set<String> SUPPORTED_SCOPES = new HashSet<>(Arrays.asList(\n ApplicationContext.SCOPE_SINGLETON,\n ApplicationContext.SCOPE_PROTOTYPE\n ));\n\n\n private final Map<String, Object> beanMap = new LinkedHashMap<>();\n\n private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();\n\n private final PackageScanner packageScanner = new PackageScanner();\n\n private final BeanDefinitionFactory beanDefinitionFactory = new BeanDefinitionFactory();\n\n private final CommandFactory commandFactory = new CommandFactory();\n\n public BeanFactoryImpl() {\n commandFactory.registryCommand(CommandFunctionName.FC_GET_BEAN, this::createBeanIfNotPresent);\n commandFactory.registryCommand(CommandFunctionName.FC_GET_BEANS_OF_TYPE, this::getBeansOfType);\n beanPostProcessors.add(new AutowiredAnnotationBeanPostProcessor(commandFactory));\n }\n\n /**\n * Scans the specified base package for classes annotated as beans and registers them in the bean map.\n *\n * @param basePackage The base package to scan for classes annotated as beans.\n */\n @Override\n public void registerBeans(String basePackage) {\n log.info(\"Scanning package: {}\", basePackage);\n Set<Class<?>> beanClasses = packageScanner.findAllBeanCandidatesByBasePackage(basePackage);\n log.info(\"Registering beans\");\n doRegisterBeans(beanClasses);\n }\n\n @Override\n public void registerBeans(Class<?>... classes) {\n Set<Class<?>> beanClasses = packageScanner.findAllBeanCandidatesByClassTypes(classes);\n doRegisterBeans(beanClasses);\n }\n\n @Override\n public void registerBean(String beanName, BeanDefinition beanDefinition) {\n log.trace(\"Call registerBean({}, {})\", beanName, beanDefinition);\n if (beanDefinition.getScope().equals(ApplicationContext.SCOPE_SINGLETON)\n && beanDefinition.getCreationStatus().equals(BeanDefinition.BeanCreationStatus.NOT_CREATED.name())) {\n saveBean(beanName, beanDefinition);\n }\n }\n\n @Override\n public <T> T getBean(Class<T> requiredType) {\n log.trace(\"Call getBean({})\", requiredType);\n\n if (!isSelectSingleBeansOfType(requiredType) || isSelectMoreOneBeanDefinitionsOfType(requiredType)) {\n return createBeanIfNotPresent(requiredType, true);\n }\n\n String beanName = resolveBeanName(requiredType);\n\n return getBean(beanName, requiredType);\n }\n\n @Override\n public <T> T getBean(String name, Class<T> requiredType) {\n log.trace(\"Call getBean({}, {})\", name, requiredType);\n Object bean = Optional.ofNullable(beanMap.get(name))\n .or(() -> checkAndCreatePrototypeBean(name, requiredType))\n .orElseThrow(() -> new NoSuchBeanDefinitionException(String\n .format(NO_BEAN_FOUND_OF_TYPE, requiredType.getName())));\n\n return requiredType.cast(bean);\n }\n\n @Override\n public <T> Map<String, T> getBeansOfType(Class<T> requiredType) {\n return beanMap.entrySet()\n .stream()\n .filter(entry -> requiredType.isAssignableFrom(entry.getValue().getClass()))\n .collect(Collectors.toMap(Map.Entry::getKey, entry -> requiredType.cast(entry.getValue())));\n }\n\n @Override\n public Map<String, Object> getBeans() {\n log.trace(\"Call getBeans()\");\n\n return beanMap;\n }\n\n public BeanDefinitionFactory beanDefinitionFactory() {\n return beanDefinitionFactory;\n }\n\n private void doRegisterBeans(Set<Class<?>> beanClasses) {\n log.trace(\"Call doRegisterBeans({})\", beanClasses);\n beanDefinitionFactory\n .registerBeanDefinitions(beanClasses)\n .forEach(this::registerBean);\n\n log.info(\"Beans post processing\");\n beanMap.forEach(this::initializeBeanAfterRegistering);\n }\n\n private Object postProcessBeforeInitialization(Object bean, String beanName) {\n var beanProcess = bean;\n for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {\n beanProcess = beanPostProcessor.postProcessBeforeInitialization(bean, beanName);\n }\n\n return beanProcess;\n }\n\n private Object postProcessAfterInitialization(Object bean, String beanName) {\n var beanProcess = bean;\n for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {\n beanProcess = beanPostProcessor.postProcessAfterInitialization(bean, beanName);\n }\n\n return beanProcess;\n }\n\n private Object initWithBeanPostProcessor(String beanName, Object bean) {\n bean = postProcessBeforeInitialization(bean, beanName);\n postConstructInitialization(bean);\n\n return postProcessAfterInitialization(bean, beanName);\n }\n\n private void postConstructInitialization(Object bean) throws NoUniquePostConstructException {\n Class<?> beanType = bean.getClass();\n Method[] declaredMethods = beanType.getDeclaredMethods();\n Predicate<Method> isAnnotatedMethod = method -> method.isAnnotationPresent(PostConstruct.class);\n\n List<Method> methodsAnnotatedWithPostConstruct = Arrays.stream(declaredMethods)\n .filter(isAnnotatedMethod)\n .toList();\n if (methodsAnnotatedWithPostConstruct.size() > 1) {\n log.error(ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT);\n\n throw new NoUniquePostConstructException(ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT);\n }\n\n methodsAnnotatedWithPostConstruct.stream()\n .findFirst()\n .ifPresent(method -> invokePostConstructMethod(bean, method));\n }\n\n private void invokePostConstructMethod(Object bean, Method method) {\n try {\n prepareMethod(method).invoke(bean);\n } catch (IllegalAccessException | InvocationTargetException exception) {\n log.error(ERROR_THE_METHOD_THAT_WAS_ANNOTATED_WITH_POST_CONSTRUCT);\n\n throw new InvalidInvokePostConstructMethodException(\n ERROR_THE_METHOD_THAT_WAS_ANNOTATED_WITH_POST_CONSTRUCT, exception);\n }\n }\n\n private Object createBean(BeanDefinition beanDefinition) {\n log.trace(\"Call createBean({})\", beanDefinition);\n\n beanDefinition.setCreationStatus(BeanDefinition.BeanCreationStatus.IN_PROGRESS);\n try {\n if (beanDefinition instanceof ComponentAnnotationBeanDefinition componentBeanDefinition) {\n return createComponent(componentBeanDefinition);\n } else {\n return createInnerBeanOfConfigClass((BeanAnnotationBeanDefinition) beanDefinition);\n }\n } catch (Exception exception) {\n String message = String.format(ERROR_CREATED_BEAN_OF_TYPE, beanDefinition.getBeanClass().getName());\n log.error(message);\n\n throw new BeanCreationException(message, exception);\n }\n }\n\n private Object createInnerBeanOfConfigClass(BeanAnnotationBeanDefinition beanDefinition)\n throws InvocationTargetException, IllegalAccessException {\n var configClassName = beanDefinition.getConfigClassName();\n var configClassBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName(configClassName);\n var configClass = beanMap.get(configClassBeanDefinition.getBeanName());\n if (configClass == null) {\n configClass = createBeanBasedOnItScope(configClassName, configClassBeanDefinition);\n }\n\n var initMethod = beanDefinition.getInitMethodOfBeanFromConfigClass();\n Object[] args = retrieveBeanInitMethodArguments(initMethod);\n\n return prepareMethod(initMethod).invoke(configClass, args);\n }\n\n private Object[] retrieveBeanInitMethodArguments(Method initMethod) {\n Parameter[] parameters = initMethod.getParameters();\n Object[] args = new Object[parameters.length];\n for (int i = 0; i < parameters.length; i++) {\n Parameter parameter = parameters[i];\n\n String beanName = resolveBeanName(parameter.getType());\n BeanDefinition beanDefinition = beanDefinitionFactory\n .getBeanDefinitionByBeanName(beanName);\n Object parameterDependency = beanMap.get(beanName);\n if (parameterDependency == null) {\n checkIfCircularDependencyExist(beanDefinition);\n parameterDependency = createBeanBasedOnItScope(beanName, beanDefinition);\n }\n args[i] = parameterDependency;\n }\n\n return args;\n }\n\n private Object createBeanBasedOnItScope(String beanName, BeanDefinition beanDefinition) {\n return ApplicationContext.SCOPE_SINGLETON.equals(beanDefinition.getScope())\n ? saveBean(beanName, beanDefinition)\n : createBean(beanDefinition);\n }\n\n private Object createComponent(ComponentAnnotationBeanDefinition beanDefinition)\n throws InvocationTargetException, InstantiationException, IllegalAccessException {\n log.trace(\"Call createComponent({})\", beanDefinition);\n\n Constructor<?> initializationConstructor = prepareConstructor(beanDefinition.getInitializationConstructor());\n Object[] autowireCandidates = retrieveAutowireCandidates(initializationConstructor);\n\n return initializationConstructor.newInstance(autowireCandidates);\n }\n\n private Object[] retrieveAutowireCandidates(Constructor<?> initializationConstructor) {\n log.trace(\"Call retrieveAutowireCandidates({})\", initializationConstructor);\n\n Class<?>[] autowireCandidateTypes = Arrays.stream(initializationConstructor.getParameters())\n .map(this::defineSpecificTypeFromParameter)\n .toArray(Class[]::new);\n\n Object[] autowireCandidates = new Object[autowireCandidateTypes.length];\n for (int i = 0; i < autowireCandidateTypes.length; i++) {\n Class<?> autowireCandidateType = autowireCandidateTypes[i];\n autowireCandidates[i] = createBeanIfNotPresent(autowireCandidateType);\n }\n\n return autowireCandidates;\n }\n\n private Class<?> defineSpecificTypeFromParameter(Parameter parameter) {\n if (parameter.isAnnotationPresent(Qualifier.class)) {\n var qualifier = parameter.getDeclaredAnnotation(Qualifier.class);\n\n String beanName = qualifier.value();\n\n BeanDefinition beanDefinition = Optional.ofNullable(beanDefinitionFactory.getBeanDefinitionByBeanName(beanName)).orElseThrow();\n\n checkIfCircularDependencyExist(beanDefinition);\n\n if(beanDefinition.getCreationStatus().equals(BeanDefinition.BeanCreationStatus.NOT_CREATED.name())) {\n createBeanBasedOnItScope(beanName, beanDefinition);\n }\n\n return beanDefinition.getBeanClass();\n }\n\n return parameter.getType();\n }\n\n\n private Object saveBean(String beanName, BeanDefinition beanDefinition) {\n log.trace(\"Call saveBean({}, {})\", beanName, beanDefinition);\n\n Object bean = createBean(beanDefinition);\n\n beanDefinition.setCreationStatus(BeanDefinition.BeanCreationStatus.CREATED);\n\n beanMap.put(beanName, bean);\n log.trace(\"Bean has been saved: {}\", bean);\n\n return bean;\n }\n\n private void initializeBeanAfterRegistering(String beanName, Object bean) {\n beanMap.put(beanName, initWithBeanPostProcessor(beanName, bean));\n }\n\n private <T> T createBeanIfNotPresent(Class<T> requiredType) {\n return createBeanIfNotPresent(requiredType, false);\n }\n\n private <T> T createBeanIfNotPresent(Class<T> requiredType, boolean onlyPrototype) {\n log.trace(\"Call createBeanIfNotPresent({}, {})\", requiredType, onlyPrototype);\n\n Map<String, T> beansOfType = getBeansOfType(requiredType);\n if (beansOfType.isEmpty()) {\n BeanDefinition beanDefinitionOfType = getBeanDefinitionOfType(requiredType, onlyPrototype);\n checkIfCircularDependencyExist(beanDefinitionOfType);\n\n String beanName = beanDefinitionOfType.getBeanName();\n Object bean = createBeanBasedOnItScope(beanName, beanDefinitionOfType);\n\n return requiredType.cast(bean);\n }\n\n if (beansOfType.size() > 1) {\n return definePrimarySpecificBean(requiredType, beansOfType);\n }\n\n return beansOfType.values().stream().findAny().orElseThrow();\n }\n\n private void checkIfCircularDependencyExist(BeanDefinition beanDefinition) {\n if (beanDefinition.getScope().equals(ApplicationContext.SCOPE_SINGLETON)\n && BeanDefinition.BeanCreationStatus.IN_PROGRESS.name().equals(beanDefinition.getCreationStatus())) {\n throw new UnresolvedCircularDependencyException(String\n .format(ErrorMessageConstants.CIRCULAR_DEPENDENCY_DETECTED, beanDefinition.getBeanClass().getName())\n );\n }\n }\n\n private BeanDefinition getBeanDefinitionOfType(Class<?> requiredType, boolean onlyPrototype) {\n log.trace(\"Call getBeanDefinitionsOfType({})\", requiredType);\n\n Map<String, BeanDefinition> beanDefinitions = onlyPrototype\n ? beanDefinitionFactory.getPrototypeBeanDefinitionsOfType(requiredType)\n : beanDefinitionFactory.getBeanDefinitionsOfType(requiredType);\n if (beanDefinitions.isEmpty()) {\n String message = String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, requiredType.getName());\n log.error(message);\n\n throw new NoSuchBeanDefinitionException(message);\n }\n\n if (beanDefinitions.size() == 1) {\n return beanDefinitions.values().stream().toList().get(0);\n }\n\n List<BeanDefinition> primaryBeanDefinitions = beanDefinitions.values()\n .stream()\n .filter(BeanDefinition::isPrimary)\n .toList();\n if (primaryBeanDefinitions.isEmpty()) {\n String message = String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, requiredType.getName());\n log.error(message);\n\n throw new NoSuchBeanDefinitionException(message);\n }\n\n if (primaryBeanDefinitions.size() > 1) {\n String message = String.format(\n ErrorMessageConstants.NO_UNIQUE_BEAN_DEFINITION_FOUND_OF_TYPE,\n requiredType.getName()\n );\n log.error(message);\n\n throw new NoUniqueBeanDefinitionException(message);\n }\n\n return primaryBeanDefinitions.get(0);\n }\n\n private boolean isSelectSingleBeansOfType(Class<?> requiredType) {\n log.trace(\"Call isSelectSingleBeansOfType({})\", requiredType);\n\n return beanMap.entrySet()\n .stream()\n .filter(entry -> requiredType.isAssignableFrom(entry.getValue().getClass()))\n .count() == 1;\n }\n\n private boolean isSelectMoreOneBeanDefinitionsOfType(Class<?> requiredType) {\n log.trace(\"Call isSelectMoreOneBeanDefinitionsOfType({})\", requiredType);\n\n return beanDefinitionFactory.getBeanDefinitionsOfType(requiredType).entrySet()\n .stream()\n .filter(entry -> requiredType.isAssignableFrom(entry.getValue().getBeanClass()))\n .count() > 1;\n }\n\n private <T> T definePrimarySpecificBean(Class<T> requiredType, Map<String, T> beansOfType) {\n log.trace(\"Call definePrimarySpecificBean({}, {})\", requiredType, beansOfType);\n List<T> beansOfRequiredType = beansOfType.values().stream()\n .filter(bean -> beanDefinitionFactory.isBeanPrimary(bean.getClass()))\n .toList();\n\n if (beansOfRequiredType.isEmpty()) {\n // We have no beans of required type with @Primary\n throw new NoUniqueBeanException(String.format(NO_UNIQUE_BEAN_FOUND_OF_TYPE, requiredType.getName()));\n }\n\n if (beansOfRequiredType.size() > 1) {\n // We have more than 1 @Primary beans of required type\n throw new NoUniqueBeanException(String.format(NO_UNIQUE_BEAN_FOUND_OF_TYPE, requiredType.getName()));\n }\n\n return beansOfRequiredType.stream().findAny().orElseThrow();\n }\n\n private <T> Optional<T> checkAndCreatePrototypeBean(String name, Class<T> requiredType) {\n BeanDefinition beanDefinition = Optional\n .ofNullable(beanDefinitionFactory.getBeanDefinitionByBeanName(name))\n .orElseThrow(() -> new NoSuchBeanDefinitionException(\n String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, requiredType.getName())));\n\n if (beanDefinition.getScope().equals(ApplicationContext.SCOPE_PROTOTYPE)) {\n return Optional.of(requiredType.cast(createBean(beanDefinition)));\n }\n\n return Optional.empty();\n }\n}" }, { "identifier": "NoUniqueBeanDefinitionException", "path": "src/main/java/svydovets/core/exception/NoUniqueBeanDefinitionException.java", "snippet": "public class NoUniqueBeanDefinitionException extends RuntimeException {\n\n public NoUniqueBeanDefinitionException(String message) {\n super(message);\n }\n}" }, { "identifier": "UnresolvedCircularDependencyException", "path": "src/main/java/svydovets/core/exception/UnresolvedCircularDependencyException.java", "snippet": "public class UnresolvedCircularDependencyException extends RuntimeException {\n\n public UnresolvedCircularDependencyException(String message) {\n super(message);\n }\n}" }, { "identifier": "CIRCULAR_DEPENDENCY_DETECTED", "path": "src/main/java/svydovets/util/ErrorMessageConstants.java", "snippet": "public static final String CIRCULAR_DEPENDENCY_DETECTED = \"Circular dependency has been detected for %s\";" }, { "identifier": "ERROR_CREATED_BEAN_OF_TYPE", "path": "src/main/java/svydovets/util/ErrorMessageConstants.java", "snippet": "public static final String ERROR_CREATED_BEAN_OF_TYPE = \"Error creating bean of type '%s'\";" }, { "identifier": "NO_BEAN_DEFINITION_FOUND_OF_TYPE", "path": "src/main/java/svydovets/util/ErrorMessageConstants.java", "snippet": "public static final String NO_BEAN_DEFINITION_FOUND_OF_TYPE = \"No bean definition found of type %s\";" }, { "identifier": "NO_UNIQUE_BEAN_DEFINITION_FOUND_OF_TYPE", "path": "src/main/java/svydovets/util/ErrorMessageConstants.java", "snippet": "public static final String NO_UNIQUE_BEAN_DEFINITION_FOUND_OF_TYPE = \"No unique bean definition found of type %s\";" } ]
import com.bobocode.svydovets.source.base.MessageService; import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjCandidate; import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjFirstCandidate; import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjFirstPrototypeCandidate; import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjPrototypeCandidate; import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.PrototypeCandidate; import com.bobocode.svydovets.source.autowire.constructor.FirstInjectionCandidate; import com.bobocode.svydovets.source.autowire.constructor.SecondInjectionCandidate; import com.bobocode.svydovets.source.autowire.constructor.ValidConstructorInjectionService; import com.bobocode.svydovets.source.autowire.ConfigMethodBasedBeanAutowiring; import com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceMoreOnePrimary.InjPrototypeCandidateMoreOnePrimary; import com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceWithoutPrimary.InjPrototypeCandidateWithoutPrimary; import com.bobocode.svydovets.source.circularDependency.CircularDependencyConfig; import com.bobocode.svydovets.source.circularDependency.FirstCircularDependencyOwner; import com.bobocode.svydovets.source.circularDependency.SecondCircularDependencyOwner; import org.assertj.core.api.AssertionsForClassTypes; import org.junit.jupiter.api.*; import svydovets.core.exception.BeanCreationException; import svydovets.core.exception.NoSuchBeanDefinitionException; import java.util.Map; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import svydovets.core.context.beanFactory.BeanFactoryImpl; import svydovets.core.exception.NoUniqueBeanDefinitionException; import svydovets.core.exception.UnresolvedCircularDependencyException; import java.util.Set; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static svydovets.util.ErrorMessageConstants.CIRCULAR_DEPENDENCY_DETECTED; import static svydovets.util.ErrorMessageConstants.ERROR_CREATED_BEAN_OF_TYPE; import static svydovets.util.ErrorMessageConstants.NO_BEAN_DEFINITION_FOUND_OF_TYPE; import static svydovets.util.ErrorMessageConstants.NO_UNIQUE_BEAN_DEFINITION_FOUND_OF_TYPE;
7,379
assertThat(firstInjectionCandidate).isNotNull(); assertThat(secondInjectionCandidate).isNotNull(); } @Test @Order(4) void shouldRegisterMethodArgumentBeansAndPassThemToMethodBasedBean() { registerBeanDefinitionsForConfigMethodBaseBeanAutowiring(); beanFactoryImpl.registerBeans(ConfigMethodBasedBeanAutowiring.class); ValidConstructorInjectionService injectionService = beanFactoryImpl.getBean(ValidConstructorInjectionService.class); FirstInjectionCandidate firstInjectionCandidate = beanFactoryImpl.getBean(FirstInjectionCandidate.class); SecondInjectionCandidate secondInjectionCandidate = beanFactoryImpl.getBean(SecondInjectionCandidate.class); assertThat(injectionService.getFirstInjectionCandidate()).isEqualTo(firstInjectionCandidate); assertThat(injectionService.getSecondInjectionCandidate()).isEqualTo(secondInjectionCandidate); } @Test @Order(5) void shouldThrowExceptionIfCircularDependencyDetectedInClassBasedBeans() { AssertionsForClassTypes.assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> beanFactoryImpl.registerBeans(FirstCircularDependencyOwner.class, SecondCircularDependencyOwner.class)); } @Test @Order(6) void shouldThrowExceptionIfCircularDependencyDetectedInMethodBasedBeans() { AssertionsForClassTypes.assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> beanFactoryImpl.registerBeans(CircularDependencyConfig.class)) .withMessage(ERROR_CREATED_BEAN_OF_TYPE, MessageService.class.getName()); } @Test @Order(7) void shouldGetAllRegistersBeansWithoutPrototype() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); Map<String, Object> beans = beanFactoryImpl.getBeans(); assertEquals(2, beans.size()); assertTrue(beans.containsKey("injFirstCandidate")); assertTrue(beans.containsKey("injSecondCandidate")); } @Test @Order(8) void shouldGetPrimaryCandidateByClasTypeForInterface() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); Map<String, Object> beans = beanFactoryImpl.getBeans(); var bean = beanFactoryImpl.getBean(InjCandidate.class); assertEquals(beans.get("injSecondCandidate"), bean); } @Test @Order(9) void shouldGetPrimaryCandidateByClasTypeAndNameForInterface() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); Map<String, Object> beans = beanFactoryImpl.getBeans(); var bean = beanFactoryImpl.getBean("injSecondCandidate", InjCandidate.class); assertEquals(beans.get("injSecondCandidate"), bean); } @Test @Order(10) void shouldGetPrototypeCandidateByClasType() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var bean1 = beanFactoryImpl.getBean(PrototypeCandidate.class); var bean2 = beanFactoryImpl.getBean(PrototypeCandidate.class); assertNotEquals(bean1, bean2); } @Test @Order(11) void shouldGetPrototypeCandidateByClasTypeAndName() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var bean1 = beanFactoryImpl.getBean("prototypeCandidate", PrototypeCandidate.class); var bean2 = beanFactoryImpl.getBean("prototypeCandidate", PrototypeCandidate.class); assertNotEquals(bean1, bean2); } @Test @Order(12) void shouldThrowNoSuchBeanDefinitionExceptionGetPrototypeCandidateByClasTypeAndName() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); String errorMessageFormat = "No bean definition found of type %s"; String errorMessage = String.format(errorMessageFormat, PrototypeCandidate.class.getName()); var exception = assertThrows(NoSuchBeanDefinitionException.class, () -> beanFactoryImpl.getBean("prototypeSecondCandidate", PrototypeCandidate.class)); assertEquals(errorMessage, exception.getMessage()); errorMessageFormat = "No bean definition found of type %s"; errorMessage = String.format(errorMessageFormat, InjFirstCandidate.class.getName()); exception = assertThrows(NoSuchBeanDefinitionException.class, () -> beanFactoryImpl.getBean("prototypeSecondCandidate", InjFirstCandidate.class)); assertEquals(errorMessage, exception.getMessage()); } @Test @Order(13) void shouldGetBeansOfTypeByRequiredType() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var expectedBeanMap = beanFactoryImpl.getBeans(); var actualBeanMap = beanFactoryImpl.getBeansOfType(InjCandidate.class); assertEquals(expectedBeanMap.size(), actualBeanMap.size()); assertEquals(expectedBeanMap.get("injFirstCandidate"), actualBeanMap.get("injFirstCandidate")); assertEquals(expectedBeanMap.get("injSecondCandidate"), actualBeanMap.get("injSecondCandidate")); } @Test @Order(14) void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var actualBean = beanFactoryImpl.getBean("injFirstPrototypeCandidate", InjFirstPrototypeCandidate.class); assertEquals(InjFirstPrototypeCandidate.class, actualBean.getClass()); } @Test @Order(15) void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName1() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
package com.bobocode.svydovets.ioc.core.beanFactory; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class BeanFactoryImplTest { private BeanFactoryImpl beanFactoryImpl; @BeforeEach void setUp() { this.beanFactoryImpl = new BeanFactoryImpl(); } @Test @Order(1) void shouldRegisterBeanWhenConfigClassIsPassed() { registerBeanDefinitionsForConfigMethodBaseBeanAutowiring(); beanFactoryImpl.registerBeans(ConfigMethodBasedBeanAutowiring.class); ConfigMethodBasedBeanAutowiring config = beanFactoryImpl.getBean(ConfigMethodBasedBeanAutowiring.class); assertThat(config).isNotNull(); } @Test @Order(2) void shouldRegisterMethodBasedBeanWhenConfigClassIsPassed() { registerBeanDefinitionsForConfigMethodBaseBeanAutowiring(); beanFactoryImpl.registerBeans(ConfigMethodBasedBeanAutowiring.class); ValidConstructorInjectionService injectionService = beanFactoryImpl.getBean(ValidConstructorInjectionService.class); assertThat(injectionService).isNotNull(); assertThat(injectionService.getFirstInjectionCandidate()).isNotNull(); assertThat(injectionService.getSecondInjectionCandidate()).isNotNull(); } @Test @Order(3) void shouldRegisterMethodArgumentBeansWhenConfigClassIsPassed() { registerBeanDefinitionsForConfigMethodBaseBeanAutowiring(); beanFactoryImpl.registerBeans(ConfigMethodBasedBeanAutowiring.class); FirstInjectionCandidate firstInjectionCandidate = beanFactoryImpl.getBean(FirstInjectionCandidate.class); SecondInjectionCandidate secondInjectionCandidate = beanFactoryImpl.getBean(SecondInjectionCandidate.class); assertThat(firstInjectionCandidate).isNotNull(); assertThat(secondInjectionCandidate).isNotNull(); } @Test @Order(4) void shouldRegisterMethodArgumentBeansAndPassThemToMethodBasedBean() { registerBeanDefinitionsForConfigMethodBaseBeanAutowiring(); beanFactoryImpl.registerBeans(ConfigMethodBasedBeanAutowiring.class); ValidConstructorInjectionService injectionService = beanFactoryImpl.getBean(ValidConstructorInjectionService.class); FirstInjectionCandidate firstInjectionCandidate = beanFactoryImpl.getBean(FirstInjectionCandidate.class); SecondInjectionCandidate secondInjectionCandidate = beanFactoryImpl.getBean(SecondInjectionCandidate.class); assertThat(injectionService.getFirstInjectionCandidate()).isEqualTo(firstInjectionCandidate); assertThat(injectionService.getSecondInjectionCandidate()).isEqualTo(secondInjectionCandidate); } @Test @Order(5) void shouldThrowExceptionIfCircularDependencyDetectedInClassBasedBeans() { AssertionsForClassTypes.assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> beanFactoryImpl.registerBeans(FirstCircularDependencyOwner.class, SecondCircularDependencyOwner.class)); } @Test @Order(6) void shouldThrowExceptionIfCircularDependencyDetectedInMethodBasedBeans() { AssertionsForClassTypes.assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> beanFactoryImpl.registerBeans(CircularDependencyConfig.class)) .withMessage(ERROR_CREATED_BEAN_OF_TYPE, MessageService.class.getName()); } @Test @Order(7) void shouldGetAllRegistersBeansWithoutPrototype() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); Map<String, Object> beans = beanFactoryImpl.getBeans(); assertEquals(2, beans.size()); assertTrue(beans.containsKey("injFirstCandidate")); assertTrue(beans.containsKey("injSecondCandidate")); } @Test @Order(8) void shouldGetPrimaryCandidateByClasTypeForInterface() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); Map<String, Object> beans = beanFactoryImpl.getBeans(); var bean = beanFactoryImpl.getBean(InjCandidate.class); assertEquals(beans.get("injSecondCandidate"), bean); } @Test @Order(9) void shouldGetPrimaryCandidateByClasTypeAndNameForInterface() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); Map<String, Object> beans = beanFactoryImpl.getBeans(); var bean = beanFactoryImpl.getBean("injSecondCandidate", InjCandidate.class); assertEquals(beans.get("injSecondCandidate"), bean); } @Test @Order(10) void shouldGetPrototypeCandidateByClasType() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var bean1 = beanFactoryImpl.getBean(PrototypeCandidate.class); var bean2 = beanFactoryImpl.getBean(PrototypeCandidate.class); assertNotEquals(bean1, bean2); } @Test @Order(11) void shouldGetPrototypeCandidateByClasTypeAndName() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var bean1 = beanFactoryImpl.getBean("prototypeCandidate", PrototypeCandidate.class); var bean2 = beanFactoryImpl.getBean("prototypeCandidate", PrototypeCandidate.class); assertNotEquals(bean1, bean2); } @Test @Order(12) void shouldThrowNoSuchBeanDefinitionExceptionGetPrototypeCandidateByClasTypeAndName() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); String errorMessageFormat = "No bean definition found of type %s"; String errorMessage = String.format(errorMessageFormat, PrototypeCandidate.class.getName()); var exception = assertThrows(NoSuchBeanDefinitionException.class, () -> beanFactoryImpl.getBean("prototypeSecondCandidate", PrototypeCandidate.class)); assertEquals(errorMessage, exception.getMessage()); errorMessageFormat = "No bean definition found of type %s"; errorMessage = String.format(errorMessageFormat, InjFirstCandidate.class.getName()); exception = assertThrows(NoSuchBeanDefinitionException.class, () -> beanFactoryImpl.getBean("prototypeSecondCandidate", InjFirstCandidate.class)); assertEquals(errorMessage, exception.getMessage()); } @Test @Order(13) void shouldGetBeansOfTypeByRequiredType() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var expectedBeanMap = beanFactoryImpl.getBeans(); var actualBeanMap = beanFactoryImpl.getBeansOfType(InjCandidate.class); assertEquals(expectedBeanMap.size(), actualBeanMap.size()); assertEquals(expectedBeanMap.get("injFirstCandidate"), actualBeanMap.get("injFirstCandidate")); assertEquals(expectedBeanMap.get("injSecondCandidate"), actualBeanMap.get("injSecondCandidate")); } @Test @Order(14) void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface"); var actualBean = beanFactoryImpl.getBean("injFirstPrototypeCandidate", InjFirstPrototypeCandidate.class); assertEquals(InjFirstPrototypeCandidate.class, actualBean.getClass()); } @Test @Order(15) void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName1() { beanFactoryImpl.registerBeans("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
assertEquals(InjFirstPrototypeCandidate.class, beanFactoryImpl.getBean(InjPrototypeCandidate.class).getClass());
4
2023-11-07 06:36:50+00:00
12k
oneqxz/RiseLoader
src/main/java/me/oneqxz/riseloader/fxml/controllers/impl/viewpage/ScriptsController.java
[ { "identifier": "FadeIn", "path": "src/main/java/animatefx/animation/FadeIn.java", "snippet": "public class FadeIn extends AnimationFX {\n\n /**\n * Create a new FadeIn animation\n *\n * @param node the node to affect\n */\n public FadeIn(Node node) {\n super(node);\n }\n\n public FadeIn() {\n }\n\n @Override\n protected AnimationFX resetNode() {\n getNode().setOpacity(1);\n return this;\n }\n\n @Override\n protected void initTimeline() {\n setTimeline(new Timeline(\n new KeyFrame(Duration.millis(0),\n new KeyValue(getNode().opacityProperty(), 0, AnimateFXInterpolator.EASE)\n ),\n new KeyFrame(Duration.millis(1000),\n new KeyValue(getNode().opacityProperty(), 1, AnimateFXInterpolator.EASE)\n )\n\n ));\n }\n}" }, { "identifier": "FadeOut", "path": "src/main/java/animatefx/animation/FadeOut.java", "snippet": "public class FadeOut extends AnimationFX {\n /**\n * Create a new FadeOut animation\n * @param node the node to affect\n */\n public FadeOut(Node node) {\n super(node);\n }\n\n public FadeOut() {\n }\n\n @Override\n protected AnimationFX resetNode() {\n getNode().setOpacity(1);\n return this;\n }\n\n @Override\n protected void initTimeline() {\n setTimeline(new Timeline(\n new KeyFrame(Duration.millis(0),\n new KeyValue(getNode().opacityProperty(), 1, AnimateFXInterpolator.EASE)\n ),\n new KeyFrame(Duration.millis(1000),\n new KeyValue(getNode().opacityProperty(), 0, AnimateFXInterpolator.EASE)\n )\n ));\n }\n}" }, { "identifier": "RiseUI", "path": "src/main/java/me/oneqxz/riseloader/RiseUI.java", "snippet": "public class RiseUI extends Application {\n\n private static final Logger log = LogManager.getLogger(\"RiseLoader\");\n public static final Version version = new Version(\"1.0.8\");\n public static final String serverIp = \"http://riseloader.0x22.xyz\";\n public static final SimpleObjectProperty<Image> backgroundImage = new SimpleObjectProperty<Image>();\n\n @Override\n public void start(Stage stage) throws IOException {\n loadBackgroundImage();\n if(!Elua.getElua().isEluaAccepted())\n {\n new EluaAccept(() -> {try{load(stage);}catch (Exception e){e.printStackTrace();System.exit(0);}}).show();\n }\n else\n {\n load(stage);\n }\n }\n\n private void load(Stage stage) throws IOException\n {\n Loading loading = new Loading();\n Stage loadingStage = loading.show(true);\n\n loading.setStageText(\"Detecting os\");\n if(OSUtils.getOS() == OSUtils.OS.UNDEFINED)\n {\n log.info(\"Cannot detect OS!\");\n loadingStage.close();\n new ErrorBox().show(new IllegalStateException(\"Can't detect OS! \" + OSUtils.getOS().name()));\n }\n else\n {\n log.info(\"Detected OS: \" + OSUtils.getOS().name());\n }\n\n loading.setStageText(\"Initializing DiscordRPC\");\n DiscordRichPresence.getInstance();\n loading.setStageText(\"DiscordRPC ready\");\n\n Thread thread = new Thread(() ->\n {\n loading.setStageTextLater(\"Fetching scripts\");\n PublicInstance.getInstance();\n\n loading.setStageTextLater(\"Parsing settings\");\n Settings.getSettings();\n\n loading.setStageTextLater(\"Fetching rise files\");\n log.info(\"Getting Rise information...\");\n Response resp = null;\n try {\n resp = Requests.get(serverIp + \"/loader\");\n } catch (IOException e) {\n e.printStackTrace();\n\n Platform.runLater(() -> {\n loadingStage.close();\n new ErrorBox().show(e);\n });\n\n return;\n }\n if(resp.getStatusCode() == 200)\n {\n try {\n loading.setStageTextLater(\"Parsing rise files\");\n log.info(resp.getStatusCode() + \", writing info\");\n JSONObject json = resp.getJSON();\n\n JSONObject files = json.getJSONObject(\"files\");\n JSONObject client = json.getJSONObject(\"client\");\n\n if(version.needToUpdate(client.getString(\"loader_version\")))\n {\n loading.setStageTextLater(\"Updating...\");\n log.info(\"New version detected! Updating...\");\n try {\n Platform.runLater(() ->\n {\n Loading.close(loadingStage);\n try {\n new Updater().show();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n return;\n }\n catch (Exception e)\n {\n new ErrorBox().show(e);\n loadingStage.close();\n e.printStackTrace();\n }\n }\n\n JSONObject versions = client.getJSONObject(\"versions\");\n\n PublicBeta publicBeta = new PublicBeta(versions.getJSONObject(\"beta\").getString(\"version\"), versions.getJSONObject(\"beta\").getLong(\"lastUpdated\"));\n loading.setStageTextLater(\"Parsed Public beta version\");\n Release release = new Release(versions.getJSONObject(\"release\").getString(\"version\"), versions.getJSONObject(\"release\").getLong(\"lastUpdated\"));\n loading.setStageTextLater(\"Parsed Release version\");\n\n RiseInfo.createNew(\n files.getJSONObject(\"natives\"),\n files.getJSONObject(\"java\"),\n files.getJSONObject(\"rise\"),\n new ClientInfo(publicBeta, release, client.getString(\"release_changelog\"), client.getString(\"loader_version\")),\n client.getString(\"discord_invite\"),\n () -> {return client.getJSONObject(\"startup\").getString(\"normal\");},\n () -> {return client.getJSONObject(\"startup\").getString(\"optimized\");}\n );\n\n loading.setStageTextLater(\"Finalizing...\");\n Platform.runLater(() ->\n {\n try {\n Loading.close(loadingStage);\n MainScene.createScene(stage);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n }\n catch (Exception e)\n {\n Platform.runLater(() -> {\n loadingStage.close();\n new ErrorBox().show(e);\n });\n }\n }\n else\n {\n Platform.runLater(() -> {\n loadingStage.close();\n new ErrorBox().show(new RuntimeException(\"/loader returned invalid status code\"));\n });\n }\n });\n thread.start();\n }\n\n private static void loadBackgroundImage()\n {\n String customImage = Settings.getSettings().getString(\"personalization.background\", null);\n Image image = null;\n\n if(customImage == null || !new File(OSUtils.getRiseFolder().toFile(), \".config\\\\\" + customImage).exists() || new Image(\"file:///\" + new File(OSUtils.getRiseFolder().toFile(), \".config\\\\\" + customImage)).isError())\n image = new Image(\"/background.jpg\");\n else\n image = new Image(\"file:///\" + new File(OSUtils.getRiseFolder().toFile(), \".config\\\\\" + customImage));\n\n backgroundImage.setValue(image);\n\n }\n\n public static void main(String[] args) {\n Runtime.getRuntime().addShutdownHook(new Thread(() ->\n {\n if(DiscordRichPresence.isRegistered())\n DiscordRichPresence.getInstance().shutdown();\n }));\n launch();\n }\n}" }, { "identifier": "FX", "path": "src/main/java/me/oneqxz/riseloader/fxml/FX.java", "snippet": "public class FX {\n\n private static double xOffset = 0;\n private static double yOffset = 0;\n\n private static final Logger logger = LogManager.getLogger(\"FXUtils\");\n\n public static void showScene(String title, String resource, Stage primaryStage, Controller controller) throws IOException {\n showScene(title, resource, primaryStage, controller, null);\n }\n public static void showScene(String title, String resource, Stage primaryStage) throws IOException {\n showScene(title, resource, primaryStage, null, null);\n }\n\n public static void showScene(String title, String resource, Stage primaryStage, Controller controller, Consumer<Parent> runnable) throws IOException {\n Scene scene = createNewScene(resource, controller, primaryStage);\n showScene(scene, title, primaryStage, runnable);\n }\n\n public static void showScene(Scene scene, String title, Stage primaryStage, Consumer<Parent> runnable) throws IOException {\n primaryStage.setScene(scene);\n primaryStage.initStyle(StageStyle.TRANSPARENT);\n\n primaryStage.setTitle(title);\n primaryStage.setResizable(false);\n\n primaryStage.getIcons().add(new javafx.scene.image.Image(\"/logo.png\"));\n\n primaryStage.show();\n\n if(runnable != null)\n runnable.accept(scene.getRoot());\n }\n\n public static Scene createNewScene(String resource, Controller controller, Stage stage) throws IOException {\n Scene scene = new Scene(createNewParent(resource, controller, stage));\n scene.setFill(Color.TRANSPARENT);\n new FadeIn(scene.getRoot()).play();\n\n logger.info(\"JavaFX scene will created with name \" + resource);\n return scene;\n }\n\n public static Parent createNewParent(String resource, Controller controller, Stage stage) throws IOException {\n FXMLLoader loader = new FXMLLoader(FX.class.getResource(\"/fxml/\" + resource));\n if(controller != null)\n loader.setController(controller);\n\n Parent root = loader.load();\n\n logger.debug(\"JavaFX parent will created with name \" + resource);\n\n if(controller != null)\n controller.init(root, stage);\n\n return root;\n }\n\n public static void setTimeout(Runnable runnable, Duration duration) {\n Timeline timeline = new Timeline(new KeyFrame(duration, event -> {\n runnable.run();\n }));\n timeline.play();\n }\n\n public static void setDraggable(Scene scene, String paneId)\n {\n Node root = scene.getRoot().lookup(\"#\" + paneId);\n\n root.setOnMousePressed((event) ->\n {\n xOffset = event.getSceneX();\n yOffset = event.getSceneY();\n });\n root.setOnMouseReleased((event) ->\n {\n xOffset = 0;\n yOffset = 0;\n });\n root.setOnMouseDragged((event) ->\n {\n Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();\n stage.setX(event.getScreenX() - xOffset);\n stage.setY(event.getScreenY() - yOffset);\n });\n }\n\n public static void setMinimizeAndClose(Stage stage, String minimiseID, String closeID)\n {\n setMinimizeAndClose(stage, minimiseID, closeID, false);\n }\n\n public static void setMinimizeAndClose(Stage stage, String minimiseID, String closeID, boolean closeProgram)\n {\n setMinimizeAndClose(stage, minimiseID, closeID, null, closeProgram, false);\n }\n\n public static void setMinimizeAndClose(Stage stage, String minimiseID, String closeID, Runnable onClose, boolean closeProgram, boolean hideScene)\n {\n Node min = stage.getScene().getRoot().lookup(\"#\" + minimiseID);\n Node close = stage.getScene().getRoot().lookup(\"#\" + closeID);\n\n min.setOnMouseClicked((event) -> stage.setIconified(true));\n close.setOnMouseClicked((event) ->\n {\n if(hideScene)\n stage.hide();\n else stage.close();\n\n if(onClose != null)\n onClose.run();\n\n if(closeProgram)\n {\n logger.info(\"Goodbye!\");\n System.exit(0);\n }\n });\n }\n}" }, { "identifier": "ErrorBox", "path": "src/main/java/me/oneqxz/riseloader/fxml/components/impl/ErrorBox.java", "snippet": "public class ErrorBox extends Component {\n @Override\n public Stage show(Object... args) {\n try {\n Stage stage = new Stage();\n FX.showScene(\"RiseLoader error\", \"error.fxml\", stage, new ErrorBoxController((Throwable) args[0]));\n FX.setMinimizeAndClose(stage, \"minimizeBtn\", \"closeBtn\", args.length == 1 || (boolean) args[1]);\n FX.setDraggable(stage.getScene(), \"riseLogo\");\n stage.setIconified(false);\n return stage;\n }\n catch (Exception e)\n {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "Controller", "path": "src/main/java/me/oneqxz/riseloader/fxml/controllers/Controller.java", "snippet": "public abstract class Controller {\n\n protected Parent root;\n protected Stage stage;\n\n public void init(Parent root, Stage stage)\n {\n this.root = root;\n this.stage = stage;\n this.init();\n }\n\n protected abstract void init();\n\n protected void onlyNumbers(TextInputControl text)\n {\n text.textProperty().addListener((observable, oldValue, newValue) -> {\n if (!newValue.matches(\"\\\\d*\")) {\n text.setText(newValue.replaceAll(\"[^\\\\d]\", \"\"));\n }\n });\n }\n\n protected void rangedInput(TextInputControl text, int min, int max)\n {\n text.textProperty().addListener((observable, oldValue, newValue) -> {\n try\n {\n if(newValue.isEmpty())\n {\n return;\n }\n\n int i = Integer.parseInt(newValue);\n if(i < min)\n text.setText(String.valueOf(min));\n else if(i > max)\n text.setText(String.valueOf(max));\n }\n catch (Exception e)\n {\n\n }\n });\n }\n\n protected void callPatternMath(TextInputControl text, String regex, CallRangeMath runnable)\n {\n text.textProperty().addListener((observable, oldValue, newValue) -> {\n runnable.call(Pattern.compile(regex).matcher(newValue).matches());\n });\n }\n\n public interface CallRangeMath {\n void call(boolean isMath);\n }\n}" }, { "identifier": "DiscordRichPresence", "path": "src/main/java/me/oneqxz/riseloader/fxml/rpc/DiscordRichPresence.java", "snippet": "public class DiscordRichPresence {\n\n private static DiscordRichPresence instance;\n private String state;\n\n private DiscordRichPresence()\n {\n updateState(\"Initialization\");\n DiscordRPC.discordInitialize(\"1173162604055773184\", null, true);\n\n net.arikia.dev.drpc.DiscordRichPresence drpc = new net.arikia.dev.drpc.DiscordRichPresence.Builder(\"RiseLoader v\" + RiseUI.version.getVersion())\n .setBigImage(\"logo\", \"RiseLoader v\" + RiseUI.version.getVersion())\n .setStartTimestamps((System.currentTimeMillis() / 1000L))\n .build();\n\n new Thread(() ->\n {\n for(;;)\n {\n drpc.details = state;\n updatePresence(\n drpc\n );\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }).start();\n }\n\n private void updatePresence(net.arikia.dev.drpc.DiscordRichPresence drpc)\n {\n DiscordRPC.discordUpdatePresence(drpc);\n }\n\n public void updateState(String state)\n {\n this.state = state;\n }\n\n public void shutdown()\n {\n DiscordRPC.discordShutdown();\n DiscordRPC.discordClearPresence();\n instance = null;\n }\n\n public static DiscordRichPresence getInstance()\n {\n return instance == null ? instance = new DiscordRichPresence() : instance;\n }\n\n public static boolean isRegistered()\n {\n return instance != null;\n }\n}" }, { "identifier": "MainScene", "path": "src/main/java/me/oneqxz/riseloader/fxml/scenes/MainScene.java", "snippet": "public class MainScene {\n\n private static Scene scene;\n private static Stage stage;\n\n public static void createScene(Stage primaryStage) throws IOException {\n FX.showScene(\"Rise Loader v\" + RiseUI.version.getVersion(), \"main.fxml\", primaryStage, new MainController());\n\n stage = primaryStage;\n scene = primaryStage.getScene();\n\n FX.setDraggable(scene, \"topBar\");\n FX.setMinimizeAndClose(stage, \"hideButton\", \"closeButton\", true);\n setCurrenViewPage(Page.HOME);\n }\n\n public static Stage getStage() {\n return stage;\n }\n\n private static Node homeNode, settingsNode, scriptsNode;\n private static Page currentViewPage;\n\n public static void setCurrenViewPage(Page page)\n {\n if(currentViewPage == page)\n return;\n\n currentViewPage = page;\n\n Button home = ((Button) scene.getRoot().lookup(\"#btnHome\"));\n Button settings = ((Button) scene.getRoot().lookup(\"#btnSettings\"));\n Button scrips = ((Button) scene.getRoot().lookup(\"#btnScripts\"));\n\n Pane pageContent = ((Pane) scene.getRoot().lookup(\"#pageContent\"));\n VBox navVBOX = (VBox) scene.getRoot().lookup(\"#navVBOX\");\n\n home.getStyleClass().remove(\"navButtonActive\");\n settings.getStyleClass().remove(\"navButtonActive\");\n scrips.getStyleClass().remove(\"navButtonActive\");\n\n Node pageParent = null;\n try\n {\n switch (page) {\n case HOME ->\n {\n DiscordRichPresence.getInstance().updateState(\"In Home page\");\n home.getStyleClass().add(\"navButtonActive\");\n pageParent = homeNode == null ? homeNode = FX.createNewParent(\"pages/home.fxml\", new HomeController(), null) : homeNode;\n }\n case SETTINGS ->\n {\n DiscordRichPresence.getInstance().updateState(\"In Settings page\");\n settings.getStyleClass().add(\"navButtonActive\");\n pageParent = settingsNode == null ? settingsNode = FX.createNewParent(\"pages/settings.fxml\", new SettingsController(), null) : settingsNode;\n }\n case SCRIPTS ->\n {\n DiscordRichPresence.getInstance().updateState(\"In Scripts page\");\n scrips.getStyleClass().add(\"navButtonActive\");\n pageParent = scriptsNode == null ? scriptsNode = FX.createNewParent(\"pages/scripts.fxml\", new ScriptsController(), null) : scriptsNode;\n }\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n\n if(!pageContent.getChildren().isEmpty())\n {\n Node last = pageContent.getChildren().get(0);\n pageContent.getChildren().add(pageParent);\n new CFadeInLeft(pageParent).setSpeed(2).play();\n\n pageContent.setMouseTransparent(true);\n navVBOX.setMouseTransparent(true);\n\n new CFadeOutRight(last).setSpeed(3).setOnFinished(s ->\n {\n pageContent.setMouseTransparent(false);\n navVBOX.setMouseTransparent(false);\n pageContent.getChildren().remove(last);\n }).play();\n }\n else\n {\n pageContent.getChildren().add(pageParent);\n new CFadeInLeft(pageParent).setSpeed(3).play();\n }\n\n System.gc();\n }\n\n public static void addChildren(Node n)\n {\n Platform.runLater(() -> ((Pane) scene.getRoot()).getChildren().add(n));\n }\n\n public static void removeChildren(Node n)\n {\n Platform.runLater(() -> ((Pane) scene.getRoot()).getChildren().remove(n));\n }\n\n public static void hideSelf()\n {\n Platform.runLater(() -> stage.hide());\n }\n\n public static void showSelf()\n {\n Platform.runLater(() -> stage.show());\n }\n\n public static void closeSelf()\n {\n Platform.runLater(() -> stage.close());\n }\n\n public static void setBackground(Rectangle rectangle)\n {\n RiseUI.backgroundImage.addListener((observable, oldValue, newValue) ->\n {\n Image bg = RiseUI.backgroundImage.get();\n rectangle.setFill(new ImagePattern(bg));\n });\n\n Image bg = RiseUI.backgroundImage.get();\n\n rectangle.setFill(new ImagePattern(bg));\n }\n\n public static enum Page {\n HOME, SETTINGS, SCRIPTS;\n }\n}" }, { "identifier": "PublicInstance", "path": "src/main/java/me/oneqxz/riseloader/rise/pub/PublicInstance.java", "snippet": "public class PublicInstance {\n\n private static PublicInstance instance;\n private static final Logger log = LogManager.getLogger(\"PublicInstance\");\n\n private IPublic scripts;\n\n private PublicInstance()\n {\n log.info(\"Getting public scripts...\");\n this.scripts = new Scripts().updateData();\n\n log.info(\"All done! scripts: \" + this.scripts.getData().length);\n }\n\n public static PublicInstance getInstance()\n {\n return instance == null ? instance = new PublicInstance() : instance;\n }\n\n\n public IPublic getScripts() {\n return scripts;\n }\n}" }, { "identifier": "IPublic", "path": "src/main/java/me/oneqxz/riseloader/rise/pub/interfaces/IPublic.java", "snippet": "public interface IPublic {\n\n @NotNull IPublicData[] getData();\n IPublic updateData();\n\n}" }, { "identifier": "IPublicData", "path": "src/main/java/me/oneqxz/riseloader/rise/pub/interfaces/IPublicData.java", "snippet": "public interface IPublicData {\n\n @NotNull String getDescription();\n @NotNull IFileData getFileData();\n @NotNull String getName();\n\n @NotNull String getServers();\n @Nullable String getPreviewURL();\n @Nullable String getVideoURL();\n\n}" }, { "identifier": "Settings", "path": "src/main/java/me/oneqxz/riseloader/settings/Settings.java", "snippet": "public class Settings {\n\n protected static Settings currentConfig;\n protected static final File configFile = new File(OSUtils.getRiseFolder().toFile(), \"settings.yml\");\n\n private final YamlConfiguration yamlConfig = new YamlConfiguration();\n\n private Settings() throws IOException {\n if(!configFile.exists())\n configFile.createNewFile();\n\n try {\n yamlConfig.load(configFile);\n } catch (IOException | InvalidConfigurationException e) {\n e.printStackTrace();\n System.exit(0);\n }\n\n setDefault(\"preferences.memory\", 2048);\n\n setDefault(\"preferences.resolution.fullscreen\", false);\n setDefault(\"preferences.resolution.width\", 854);\n setDefault(\"preferences.resolution.height\", 480);\n\n setDefault(\"rise.version\", \"release\");\n\n setDefault(\"others.javaoptimize\", true);\n\n setDefault(\"rise.scripts.enabled\", Arrays.stream(new String[]{\"QuickPlay\", \"ItemUI\", \"NoJumpDelay\", \"BowTrajectories\"}).toList());\n setDefault(\"personalization.background\", null);\n saveConfig();\n }\n\n public static Settings getSettings()\n {\n if (currentConfig == null)\n {\n try{\n currentConfig = new Settings();\n }\n catch (Exception e)\n {\n e.printStackTrace();\n System.exit(0);\n }\n }\n\n return currentConfig;\n }\n\n\n private void setDefault(String path, Object value)\n {\n if(!yamlConfig.isSet(path))\n yamlConfig.set(path, value);\n }\n\n private void saveConfig()\n {\n try {\n yamlConfig.save(configFile);\n } catch (IOException e) {\n e.printStackTrace();\n System.exit(0);\n }\n }\n\n public Object set(String path, Object value)\n {\n yamlConfig.set(path, value);\n saveConfig();\n return value;\n }\n\n\n public boolean isBoolean(String s) {\n return yamlConfig.isBoolean(s);\n }\n\n\n public boolean getBoolean(String s) {\n return yamlConfig.getBoolean(s);\n }\n\n\n public boolean getBoolean(String s, boolean b) {\n return yamlConfig.getBoolean(s, b);\n }\n\n\n public boolean isByte(String s) {\n return yamlConfig.isByte(s);\n }\n\n\n public byte getByte(String s) {\n return yamlConfig.getByte(s);\n }\n\n\n public byte getByte(String s, byte b) {\n return yamlConfig.getByte(s, b);\n }\n\n\n public boolean isShort(String s) {\n return yamlConfig.isShort(s);\n }\n\n\n public short getShort(String s) {\n return yamlConfig.getShort(s);\n }\n\n\n public short getShort(String s, short i) {\n return yamlConfig.getShort(s, i);\n }\n\n\n public boolean isInt(String s) {\n return yamlConfig.isInt(s);\n }\n\n\n public int getInt(String s) {\n return yamlConfig.getInt(s);\n }\n\n\n public int getInt(String s, int i) {\n return yamlConfig.getInt(s, i);\n }\n\n\n public boolean isLong(String s) {\n return yamlConfig.isLong(s);\n }\n\n\n public long getLong(String s) {\n return yamlConfig.getLong(s);\n }\n\n public long getLong(String s, long l) {\n return yamlConfig.getLong(s, l);\n }\n\n\n public boolean isFloat(String s) {\n return yamlConfig.isFloat(s);\n }\n\n\n public float getFloat(String s) {\n return yamlConfig.getFloat(s);\n }\n\n\n public float getFloat(String s, float v) {\n return yamlConfig.getFloat(s, v);\n }\n\n\n public boolean isDouble(String s) {\n return yamlConfig.isDouble(s);\n }\n\n\n public double getDouble(String s) {\n return yamlConfig.getDouble(s);\n }\n\n\n public double getDouble(String s, double v) {\n return yamlConfig.getDouble(s, v);\n }\n\n\n public boolean isChar(String s) {\n return yamlConfig.isChar(s);\n }\n\n\n public char getChar(String s) {\n return yamlConfig.getChar(s);\n }\n\n\n public char getChar(String s, char c) {\n return yamlConfig.getChar(s, c);\n }\n\n\n public boolean isString(String s) {\n return yamlConfig.isString(s);\n }\n\n\n public String getString(String s) {\n return yamlConfig.getString(s);\n }\n\n\n public String getString(String s, String s1) {\n return yamlConfig.getString(s, s1);\n }\n\n\n public boolean isList(String s) {\n return yamlConfig.isList(s);\n }\n\n\n public List<?> getList(String s) {\n return yamlConfig.getList(s);\n }\n\n\n public List<?> getList(String s, List<?> list) {\n return yamlConfig.getList(s, list);\n }\n\n\n public boolean isConfigurationSection(String s) {\n return yamlConfig.isConfigurationSection(s);\n }\n\n\n public ConfigurationSection getConfigurationSection(String s) {\n return yamlConfig.getConfigurationSection(s);\n }\n\n\n public <T> T getObject(String s, Class<T> aClass) {\n return yamlConfig.getObject(s, aClass);\n }\n\n\n public <T> T getObject(String s, Class<T> aClass, T t) {\n return yamlConfig.getObject(s, aClass, t);\n }\n\n\n public <T extends ConfigurationSerializable> T getSerializable(String s, Class<T> aClass) {\n return yamlConfig.getSerializable(s, aClass);\n }\n\n\n public <T extends ConfigurationSerializable> T getSerializable(String s, Class<T> aClass, T t) {\n return yamlConfig.getSerializable(s, aClass, t);\n }\n\n\n public List<Boolean> getBooleanList(String s) {\n return yamlConfig.getBooleanList(s);\n }\n\n\n public List<Byte> getByteList(String s) {\n return yamlConfig.getByteList(s);\n }\n\n\n public List<Short> getShortList(String s) {\n return yamlConfig.getShortList(s);\n }\n\n\n public List<Integer> getIntList(String s) {\n return yamlConfig.getIntList(s);\n }\n\n\n public List<Long> getLongList(String s) {\n return yamlConfig.getLongList(s);\n }\n\n\n public List<Float> getFloatList(String s) {\n return yamlConfig.getFloatList(s);\n }\n\n\n public List<Double> getDoubleList(String s) {\n return yamlConfig.getDoubleList(s);\n }\n\n\n public List<Character> getCharList(String s) {\n return yamlConfig.getCharList(s);\n }\n\n\n public List<String> getStringList(String s) {\n return yamlConfig.getStringList(s);\n }\n\n\n public List<Map<?, ?>> getMapList(String s) {\n return yamlConfig.getMapList(s);\n }\n\n\n public Set<String> getKeys(boolean b) {\n return yamlConfig.getKeys(b);\n }\n\n\n public Map<String, Object> getValues(boolean b) {\n return yamlConfig.getValues(b);\n }\n\n\n public String getCurrentPath() {\n return yamlConfig.getCurrentPath();\n }\n\n\n public String getName() {\n return yamlConfig.getName();\n }\n\n\n public Configuration getRoot() {\n return yamlConfig.getRoot();\n }\n\n\n public ConfigurationSection getParent() {\n return yamlConfig.getParent();\n }\n\n\n public ConfigurationSection getDefaultSection() {\n return yamlConfig.getDefaultSection();\n }\n\n\n public void addDefault(String s, Object o) {\n yamlConfig.addDefault(s, o);\n }\n\n public boolean isSet(String path)\n {\n return yamlConfig.isSet(path);\n }\n}" }, { "identifier": "OSUtils", "path": "src/main/java/me/oneqxz/riseloader/utils/OSUtils.java", "snippet": "public class OSUtils {\n\n public static OS getOS()\n {\n String os = System.getProperty(\"os.name\").toLowerCase();\n if(os.contains(\"win\"))\n return OS.WINDOWS;\n else if(os.contains(\"mac\"))\n return OS.MACOS;\n else if(os.contains(\"nix\") || os.contains(\"nux\") || os.indexOf(\"aix\") > 0)\n return OS.LINUX;\n else\n return OS.UNDEFINED;\n }\n\n public static Path getRiseFolder()\n {\n return Path.of(System.getProperty(\"user.home\"), \".rise\");\n }\n\n public static String getFileExtension(Path path) {\n String fileName = path.getFileName().toString();\n int index = fileName.lastIndexOf('.');\n if (index > 0 && index < fileName.length() - 1) {\n return fileName.substring(index);\n }\n return \"\";\n }\n\n public enum OS {\n WINDOWS,\n LINUX,\n MACOS,\n UNDEFINED\n }\n}" }, { "identifier": "Requests", "path": "src/main/java/me/oneqxz/riseloader/utils/requests/Requests.java", "snippet": "public class Requests {\n\n public static Response get(String serverUrl) throws IOException {\n URL url = new URL(serverUrl);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n setHeaders(connection);\n\n int responseCode = connection.getResponseCode();\n\n InputStream inputStream = connection.getInputStream();\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int bytesRead;\n\n while ((bytesRead = inputStream.read(buffer)) != -1) {\n byteArrayOutputStream.write(buffer, 0, bytesRead);\n }\n\n byte[] content = byteArrayOutputStream.toByteArray();\n\n inputStream.close();\n byteArrayOutputStream.close();\n connection.disconnect();\n\n return new Response(content, responseCode);\n }\n\n\n public static void setHeaders(HttpURLConnection connection)\n {\n connection.setRequestProperty(\"rise-0x22\", \"0x22/8cycbi9360M54qUu5cMZYRNjvpw69pYBVaSFDKQbfEfRyHoukC3nqUu5\");\n connection.setRequestProperty(\"User-Agent\", \"0x22/\" + RiseUI.version.getVersion());\n }\n\n}" }, { "identifier": "Response", "path": "src/main/java/me/oneqxz/riseloader/utils/requests/Response.java", "snippet": "public class Response {\n\n private byte[] resp;\n private int statusCode;\n\n public int getStatusCode() {\n return statusCode;\n }\n\n public Response(byte[] resp, int statusCode) {\n this.resp = resp;\n this.statusCode = statusCode;\n }\n\n public byte[] getBytes() {\n return resp;\n }\n\n public String getString()\n {\n return new String(resp);\n }\n\n public JSONObject getJSON()\n {\n return new JSONObject(getString());\n }\n}" } ]
import animatefx.animation.FadeIn; import animatefx.animation.FadeOut; import javafx.application.Platform; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import me.oneqxz.riseloader.RiseUI; import me.oneqxz.riseloader.fxml.FX; import me.oneqxz.riseloader.fxml.components.impl.ErrorBox; import me.oneqxz.riseloader.fxml.controllers.Controller; import me.oneqxz.riseloader.fxml.rpc.DiscordRichPresence; import me.oneqxz.riseloader.fxml.scenes.MainScene; import me.oneqxz.riseloader.rise.pub.PublicInstance; import me.oneqxz.riseloader.rise.pub.interfaces.IPublic; import me.oneqxz.riseloader.rise.pub.interfaces.IPublicData; import me.oneqxz.riseloader.settings.Settings; import me.oneqxz.riseloader.utils.OSUtils; import me.oneqxz.riseloader.utils.requests.Requests; import me.oneqxz.riseloader.utils.requests.Response; import java.awt.*; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.util.List;
8,652
package me.oneqxz.riseloader.fxml.controllers.impl.viewpage; public class ScriptsController extends Controller { protected Button reloadScripts; protected TextField searchScripts; protected Pane loadingScripts, paneCurrentScript, paneSelectCurrentScript; protected Pane scriptsPane; protected ScrollPane scriptsScrollPane; protected VBox scriptsBOX; protected SimpleObjectProperty<CurrentScriptController> currentSelectedScript = new SimpleObjectProperty<>(); @Override protected void init() { reloadScripts = (Button) root.lookup("#reloadScripts"); searchScripts = (TextField) root.lookup("#searchScripts"); loadingScripts = (Pane) root.lookup("#loadingScripts"); scriptsPane = (Pane) root.lookup("#scriptsPane"); scriptsScrollPane = (ScrollPane) root.lookup("#scriptsScrollPane"); paneCurrentScript = (Pane) root.lookup("#paneCurrentScript"); paneSelectCurrentScript = (Pane) root.lookup("#paneSelectCurrentScript"); scriptsBOX = (VBox) scriptsScrollPane.getContent(); reloadScripts.setOnMouseClicked((e) -> { activateLoadingScripts(); new Thread(() -> { PublicInstance.getInstance().getScripts().updateData(); Platform.runLater(this::updateScripts); }).start(); }); currentSelectedScript.addListener((o, oldValue, newValue) -> { if(newValue != null) { paneCurrentScript.getChildren().clear(); paneCurrentScript.getChildren().add(newValue.getRoot()); paneCurrentScript.setVisible(true); paneSelectCurrentScript.setVisible(false); } else { paneCurrentScript.getChildren().clear(); paneCurrentScript.setVisible(false); paneSelectCurrentScript.setVisible(true); } }); updateScripts(); } private void updateScripts() { activateLoadingScripts(); for(IPublicData scriptData : PublicInstance.getInstance().getScripts().getData()) { try { Parent script = FX.createNewParent("pages/child/script.fxml", new ScriptController(this, scriptData), null); scriptsBOX.getChildren().add(script); } catch (IOException e) { e.printStackTrace();
package me.oneqxz.riseloader.fxml.controllers.impl.viewpage; public class ScriptsController extends Controller { protected Button reloadScripts; protected TextField searchScripts; protected Pane loadingScripts, paneCurrentScript, paneSelectCurrentScript; protected Pane scriptsPane; protected ScrollPane scriptsScrollPane; protected VBox scriptsBOX; protected SimpleObjectProperty<CurrentScriptController> currentSelectedScript = new SimpleObjectProperty<>(); @Override protected void init() { reloadScripts = (Button) root.lookup("#reloadScripts"); searchScripts = (TextField) root.lookup("#searchScripts"); loadingScripts = (Pane) root.lookup("#loadingScripts"); scriptsPane = (Pane) root.lookup("#scriptsPane"); scriptsScrollPane = (ScrollPane) root.lookup("#scriptsScrollPane"); paneCurrentScript = (Pane) root.lookup("#paneCurrentScript"); paneSelectCurrentScript = (Pane) root.lookup("#paneSelectCurrentScript"); scriptsBOX = (VBox) scriptsScrollPane.getContent(); reloadScripts.setOnMouseClicked((e) -> { activateLoadingScripts(); new Thread(() -> { PublicInstance.getInstance().getScripts().updateData(); Platform.runLater(this::updateScripts); }).start(); }); currentSelectedScript.addListener((o, oldValue, newValue) -> { if(newValue != null) { paneCurrentScript.getChildren().clear(); paneCurrentScript.getChildren().add(newValue.getRoot()); paneCurrentScript.setVisible(true); paneSelectCurrentScript.setVisible(false); } else { paneCurrentScript.getChildren().clear(); paneCurrentScript.setVisible(false); paneSelectCurrentScript.setVisible(true); } }); updateScripts(); } private void updateScripts() { activateLoadingScripts(); for(IPublicData scriptData : PublicInstance.getInstance().getScripts().getData()) { try { Parent script = FX.createNewParent("pages/child/script.fxml", new ScriptController(this, scriptData), null); scriptsBOX.getChildren().add(script); } catch (IOException e) { e.printStackTrace();
new ErrorBox().show(e.getMessage());
4
2023-11-01 01:40:52+00:00
12k
YufiriaMazenta/CrypticLib
common/src/main/java/crypticlib/BukkitPlugin.java
[ { "identifier": "AnnotationProcessor", "path": "common/src/main/java/crypticlib/annotation/AnnotationProcessor.java", "snippet": "public enum AnnotationProcessor {\n\n INSTANCE;\n\n private final Map<Class<?>, Object> singletonObjectMap;\n private final Map<Class<? extends Annotation>, BiConsumer<Annotation, Class<?>>> classAnnotationProcessorMap;\n private final Map<Class<? extends Annotation>, ProcessPriority> annotationProcessorPriorityMap;\n\n AnnotationProcessor() {\n singletonObjectMap = new ConcurrentHashMap<>();\n classAnnotationProcessorMap = new ConcurrentHashMap<>();\n annotationProcessorPriorityMap = new ConcurrentHashMap<>();\n }\n\n @Deprecated\n public void scanJar(File file) {\n try {\n scanJar(new JarFile(file));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void scanJar(JarFile jarFile) {\n Enumeration<JarEntry> entries = jarFile.entries();\n ClassLoader classLoader = getClass().getClassLoader();\n Map<ProcessPriority, List<Runnable>> processTaskCache = new HashMap<>();\n while (entries.hasMoreElements()) {\n try {\n JarEntry entry = entries.nextElement();\n if (!entry.getName().endsWith(\".class\")) {\n continue;\n }\n String className = entry.getName()\n .replace('/', '.')\n .substring(0, entry.getName().length() - 6);\n Class<?> clazz = classLoader.loadClass(className);\n\n //处理类级别的注解\n for (Class<? extends Annotation> annotationClass : classAnnotationProcessorMap.keySet()) {\n if (!clazz.isAnnotationPresent(annotationClass))\n continue;\n ProcessPriority priority = annotationProcessorPriorityMap.get(annotationClass);\n Annotation annotation = clazz.getAnnotation(annotationClass);\n Runnable processTask = () -> classAnnotationProcessorMap.get(annotationClass).accept(annotation, clazz);\n if (processTaskCache.containsKey(priority)) {\n processTaskCache.get(priority).add(processTask);\n } else {\n List<Runnable> runnableList = new ArrayList<>();\n runnableList.add(processTask);\n processTaskCache.put(priority, runnableList);\n }\n }\n } catch (ClassNotFoundException | NoClassDefFoundError ignored) {\n } catch (Throwable throwable) {\n throw new RuntimeException(throwable);\n }\n }\n\n for (ProcessPriority priority : ProcessPriority.values()) {\n List<Runnable> tasks = processTaskCache.get(priority);\n if (tasks == null)\n continue;\n for (Runnable task : tasks) {\n task.run();\n }\n }\n\n try {\n jarFile.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * 注册一个类注解处理器\n * @param annotationClass 注册的注解类\n * @param annotationProcessor 注解的处理器\n * @param priority 处理器的优先级,从LOWEST往HIGHEST依次执行\n */\n public AnnotationProcessor regClassAnnotationProcessor(\n @NotNull Class<? extends Annotation> annotationClass,\n @NotNull BiConsumer<Annotation, Class<?>> annotationProcessor,\n @NotNull ProcessPriority priority\n ) {\n classAnnotationProcessorMap.put(annotationClass, annotationProcessor);\n annotationProcessorPriorityMap.put(annotationClass, priority);\n return this;\n }\n\n /**\n * 注册一个类注解处理器,优先级为NORMAL\n * @param annotationClass 注册的注解类\n * @param annotationProcessor 注解的处理器\n */\n public AnnotationProcessor regClassAnnotationProcessor(\n @NotNull Class<? extends Annotation> annotationClass,\n @NotNull BiConsumer<Annotation, Class<?>> annotationProcessor\n ) {\n return regClassAnnotationProcessor(annotationClass, annotationProcessor, ProcessPriority.NORMAL);\n }\n\n /**\n * 获取某类对应的实例,如果某类已经在注解处理器注册实例,则获取已经注册的实例\n * @param clazz 需要获取实例的类\n * @return 类对应的实例\n * @param <T> 类的类型\n */\n public <T> T getClassInstance(Class<T> clazz) {\n if (singletonObjectMap.containsKey(clazz)) {\n return (T) singletonObjectMap.get(clazz);\n } else {\n T t;\n if (clazz.isEnum()) {\n t = clazz.getEnumConstants()[0];\n } else {\n t = ReflectUtil.newDeclaredInstance(clazz);\n }\n singletonObjectMap.put(clazz, t);\n return t;\n }\n }\n\n public enum ProcessPriority {\n LOWEST, LOW, NORMAL, HIGH, HIGHEST\n }\n\n}" }, { "identifier": "LangConfigContainer", "path": "common/src/main/java/crypticlib/chat/LangConfigContainer.java", "snippet": "public class LangConfigContainer {\n\n private final Class<?> containerClass;\n private final Map<String, ConfigWrapper> langConfigWrapperMap;\n private final String langFileFolder;\n private final Plugin plugin;\n private final String defLang;\n\n public LangConfigContainer(@NotNull Plugin plugin, @NotNull Class<?> containerClass, String langFileFolder, String defLang) {\n this.plugin = plugin;\n this.langConfigWrapperMap = new ConcurrentHashMap<>();\n this.langFileFolder = langFileFolder;\n this.containerClass = containerClass;\n this.defLang = defLang;\n saveDefLangFiles();\n }\n\n private void saveDefLangFiles() {\n for (Locale locale : Locale.getAvailableLocales()) {\n String lang = LocaleUtil.localToLang(locale);\n String langFileName = langFileFolder + \"/\" + lang + \".yml\";\n if (plugin.getResource(langFileName) == null)\n continue;\n File file = new File(plugin.getDataFolder(), langFileName);\n if (!file.exists())\n plugin.saveResource(langFileName, false);\n }\n }\n\n public Class<?> containerClass() {\n return containerClass;\n }\n\n public Map<String, ConfigWrapper> langConfigWrapperMap() {\n return langConfigWrapperMap;\n }\n\n public String langFileFolder() {\n return langFileFolder;\n }\n\n public void reload() {\n loadLangFiles();\n langConfigWrapperMap.forEach((lang, configWrapper) -> configWrapper.reloadConfig());\n for (Field field : containerClass.getDeclaredFields()) {\n if (!Modifier.isStatic(field.getModifiers()))\n continue;\n Object object = ReflectUtil.getDeclaredFieldObj(field, null);\n if (!(object instanceof LangConfigEntry))\n continue;\n LangConfigEntry<?> langConfigEntry = (LangConfigEntry<?>) object;\n if (!langConfigEntry.defLang().equals(defLang)) {\n langConfigEntry.setDefLang(defLang);\n }\n langConfigEntry.load(this);\n }\n }\n\n protected void loadLangFiles() {\n langConfigWrapperMap.clear();\n File folder = new File(plugin.getDataFolder(), langFileFolder);\n //如果语言文件夹为空,防止出现NullPointerException,需要生成默认语言文件\n List<File> yamlFiles = FileUtil.allYamlFiles(folder);\n if (yamlFiles.isEmpty()) {\n saveDefLangFiles();\n yamlFiles = FileUtil.allYamlFiles(folder);\n }\n\n for (File langFile : yamlFiles) {\n String fileName = langFile.getName();\n String lang = fileName.substring(0, fileName.lastIndexOf(\".\"));\n langConfigWrapperMap.put(lang, new ConfigWrapper(langFile));\n }\n updateLangFiles();\n }\n\n private void updateLangFiles() {\n langConfigWrapperMap.forEach(\n (lang, configWrapper) -> {\n YamlConfiguration defLangConfig = getDefLangConfig(lang);\n if (defLangConfig == null)\n return;\n for (String key : defLangConfig.getKeys(true)) {\n if (configWrapper.contains(key))\n continue;\n configWrapper.set(key, defLangConfig.get(key));\n }\n configWrapper.saveConfig();\n }\n );\n }\n\n public boolean containsLang(String lang) {\n return langConfigWrapperMap.containsKey(lang);\n }\n\n public @Nullable ConfigWrapper getLangConfigWrapper(String lang) {\n return langConfigWrapperMap.get(lang);\n }\n\n public @NotNull ConfigWrapper createNewLang(String lang) {\n String fileName = lang + \".yml\";\n ConfigWrapper langConfigWrapper = new ConfigWrapper(plugin, langFileFolder + \"/\" + fileName);\n langConfigWrapperMap.put(lang, langConfigWrapper);\n return langConfigWrapper;\n }\n\n public Plugin plugin() {\n return plugin;\n }\n\n\n public YamlConfiguration getDefLangConfig(String lang) {\n String langFileName = langFileFolder + \"/\" + lang + \".yml\";\n try(InputStream langFileInputStream = plugin.getResource(langFileName)) {\n if (langFileInputStream == null)\n return null;\n return YamlConfiguration.loadConfiguration(new InputStreamReader(langFileInputStream, Charsets.UTF_8));\n } catch (IOException e) {\n return null;\n }\n }\n\n\n}" }, { "identifier": "MessageSender", "path": "common/src/main/java/crypticlib/chat/MessageSender.java", "snippet": "@SuppressWarnings(\"deprecation\")\npublic class MessageSender {\n\n /**\n * 发送语言文本给一个对象,此文本会处理颜色代码与papi变量\n * @param receiver 发送到的对象\n * @param msg 发送的语言\n */\n public static void sendMsg(@NotNull CommandSender receiver, StringLangConfigEntry msg) {\n sendMsg(receiver, msg, new HashMap<>());\n }\n\n /**\n * 发送文本给一个对象,此文本会处理颜色代码和papi变量\n *\n * @param receiver 发送到的对象\n * @param msg 发送的消息\n */\n public static void sendMsg(@NotNull CommandSender receiver, String msg) {\n sendMsg(receiver, msg, new HashMap<>());\n }\n\n /**\n * 发送语言文本给一个对象,此文本会处理颜色代码与papi变量\n * @param receiver 发送到的对象\n * @param msg 发送的语言\n * @param replaceMap 需要替换的文本\n */\n public static void sendMsg(@NotNull CommandSender receiver, StringLangConfigEntry msg, Map<String, String> replaceMap) {\n if (receiver instanceof Player) {\n sendMsg(receiver, msg.value((Player) receiver), replaceMap);\n } else {\n sendMsg(receiver, msg.value(), replaceMap);\n }\n }\n\n /**\n * 发送文本给一个对象,此文本会处理颜色代码和papi变量,并根据replaceMap的内容替换源文本\n *\n * @param receiver 发送到的对象\n * @param msg 发送的消息\n * @param replaceMap 需要替换的文本\n */\n public static void sendMsg(@NotNull CommandSender receiver, String msg, @NotNull Map<String, String> replaceMap) {\n if (msg == null)\n return;\n for (String formatStr : replaceMap.keySet()) {\n msg = msg.replace(formatStr, replaceMap.get(formatStr));\n }\n if (receiver instanceof Player)\n msg = TextProcessor.placeholder((Player) receiver, msg);\n sendMsg(receiver, TextProcessor.toComponent(TextProcessor.color(msg)));\n }\n\n /**\n * 发送多个Bungee聊天组件给接收者\n *\n * @param receiver 接收者\n * @param baseComponents bungee聊天组件\n */\n public static void sendMsg(@NotNull CommandSender receiver, @NotNull BaseComponent... baseComponents) {\n sendMsg(receiver, new TextComponent(baseComponents));\n }\n\n /**\n * 发送Bungee聊天组件给接收者\n *\n * @param receiver 接收者\n * @param baseComponent bungee聊天组件\n */\n public static void sendMsg(@NotNull CommandSender receiver, @NotNull BaseComponent baseComponent) {\n receiver.spigot().sendMessage(baseComponent);\n }\n\n public static void sendTitle(Player player, String title, StringLangConfigEntry subTitle, int fadeIn, int stay, int fadeOut) {\n sendTitle(player, title, subTitle.value(player), fadeIn, stay, fadeOut);\n }\n\n public static void sendTitle(Player player, StringLangConfigEntry title, String subTitle, int fadeIn, int stay, int fadeOut) {\n sendTitle(player, title.value(player), subTitle, fadeIn, stay, fadeOut);\n }\n\n public static void sendTitle(Player player, StringLangConfigEntry title, StringLangConfigEntry subTitle, int fadeIn, int stay, int fadeOut) {;\n sendTitle(player, title.value(player), subTitle.value(player), fadeIn, stay, fadeOut);\n }\n\n /**\n * 给玩家发送Title\n *\n * @param player 发送的玩家\n * @param title 发送的Title\n * @param subTitle 发送的Subtitle\n * @param fadeIn Title的淡入时间\n * @param stay Title的停留时间\n * @param fadeOut Title的淡出时间\n */\n public static void sendTitle(Player player, String title, String subTitle, int fadeIn, int stay, int fadeOut) {\n if (player == null)\n return;\n if (title == null) {\n title = \"\";\n }\n if (subTitle == null) {\n subTitle = \"\";\n }\n title = TextProcessor.color(TextProcessor.placeholder(player, title));\n subTitle = TextProcessor.color(TextProcessor.placeholder(player, subTitle));\n player.sendTitle(title, subTitle, fadeIn, stay, fadeOut);\n }\n\n public static void sendTitle(Player player, String title, StringLangConfigEntry subTitle) {\n sendTitle(player, title, subTitle.value(player));\n }\n\n public static void sendTitle(Player player, StringLangConfigEntry title, String subTitle) {\n sendTitle(player, title.value(player), subTitle);\n }\n\n public static void sendTitle(Player player, StringLangConfigEntry title, StringLangConfigEntry subTitle) {\n sendTitle(player, title.value(player), subTitle.value(player));\n }\n\n /**\n * 给玩家发送Title\n *\n * @param player 发送的玩家\n * @param title 发送的Title\n * @param subTitle 发送的Subtitle\n */\n public static void sendTitle(Player player, String title, String subTitle) {\n sendTitle(player, title, subTitle, 10, 70, 20);\n }\n\n /**\n * 给玩家发送Action Bar\n *\n * @param player 发送的玩家\n * @param component 发送的ActionBar聊天组件\n */\n public static void sendActionBar(Player player, BaseComponent component) {\n if (player == null)\n return;\n player.spigot().sendMessage(ChatMessageType.ACTION_BAR, component);\n }\n\n public static void sendActionBar(Player player, BaseComponent... components) {\n sendActionBar(player, new TextComponent(components));\n }\n\n public static void sendActionBar(Player player, StringLangConfigEntry text) {\n sendActionBar(player, text.value(player));\n }\n\n /**\n * 给玩家发送Action Bar消息\n *\n * @param player 发送的玩家\n * @param text 发送的ActionBar文本\n */\n public static void sendActionBar(Player player, String text) {\n text = TextProcessor.color(TextProcessor.placeholder(player, text));\n sendActionBar(player, TextProcessor.toComponent(text));\n }\n\n public static void broadcast(StringLangConfigEntry msg) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendMsg(player, msg);\n }\n info(msg);\n }\n\n /**\n * 为所有玩家发送一条消息,这条消息会处理颜色代码和PlaceholderAPI变量\n *\n * @param msg 发送的消息\n */\n public static void broadcast(String msg) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendMsg(player, msg);\n }\n info(msg);\n }\n\n public static void broadcastActionBar(StringLangConfigEntry msg) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendActionBar(player, msg);\n }\n }\n\n /**\n * 给所有玩家发送一条ActionBar位置的消息\n *\n * @param msg 发送的消息\n */\n public static void broadcastActionbar(String msg) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendActionBar(player, msg);\n }\n }\n\n public static void broadcastTitle(String title, StringLangConfigEntry subtitle, int fadeIn, int stay, int fadeOut) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle, fadeIn, stay, fadeOut);\n }\n }\n\n public static void broadcastTitle(StringLangConfigEntry title, String subtitle, int fadeIn, int stay, int fadeOut) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle, fadeIn, stay, fadeOut);\n }\n }\n\n public static void broadcastTitle(StringLangConfigEntry title, StringLangConfigEntry subtitle, int fadeIn, int stay, int fadeOut) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle, fadeIn, stay, fadeOut);\n }\n }\n\n /**\n * 给所有玩家发送一条title\n *\n * @param title 发送的title文本\n * @param subtitle 发送的subtitle文本\n * @param fadeIn 淡入时间\n * @param stay 停留时间\n * @param fadeOut 淡出时间\n */\n public static void broadcastTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle, fadeIn, stay, fadeOut);\n }\n }\n\n public static void broadcastTitle(String title, StringLangConfigEntry subtitle) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle);\n }\n }\n\n public static void broadcastTitle(StringLangConfigEntry title, String subtitle) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle);\n }\n }\n\n public static void broadcastTitle(StringLangConfigEntry title, StringLangConfigEntry subtitle) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle);\n }\n }\n\n /**\n * 给所有玩家发送一条title\n *\n * @param title 发送的title文本\n * @param subtitle 发送的subtitle文本\n */\n public static void broadcastTitle(String title, String subtitle) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n sendTitle(player, title, subtitle);\n }\n }\n\n public static void info(StringLangConfigEntry msg) {\n sendMsg(Bukkit.getConsoleSender(), msg);\n }\n\n /**\n * 给控制台发送一条文本,此文本会处理颜色代码\n *\n * @param msg 发送的文本\n */\n public static void info(String msg) {\n sendMsg(Bukkit.getConsoleSender(), msg);\n }\n\n public static void info(StringLangConfigEntry msg, Map<String, String> replaceMap) {\n info(msg.value(), replaceMap);\n }\n\n /**\n * 给控制台发送一条文本,此文本会处理颜色代码,并根据replaceMap的内容替换源文本\n *\n * @param msg 发送的文本\n * @param replaceMap 需要替换的文本\n */\n public static void info(String msg, Map<String, String> replaceMap) {\n sendMsg(Bukkit.getConsoleSender(), msg, replaceMap);\n }\n\n}" }, { "identifier": "CommandInfo", "path": "common/src/main/java/crypticlib/command/CommandInfo.java", "snippet": "public class CommandInfo {\n\n @NotNull\n private String name;\n @Nullable\n private String permission;\n private PermDef permDef = PermDef.OP;\n @NotNull\n private String[] aliases;\n @NotNull\n private String description;\n @NotNull\n private String usage;\n\n public CommandInfo(@NotNull BukkitCommand commandAnnotation) {\n this(\n commandAnnotation.name(),\n commandAnnotation.permission() == null || commandAnnotation.permission().isEmpty() ? null : commandAnnotation.permission(),\n commandAnnotation.aliases(),\n commandAnnotation.description(),\n commandAnnotation.usage()\n );\n this.permDef = commandAnnotation.permDef();\n }\n\n public CommandInfo(@NotNull String name) {\n this(name, (String) null);\n }\n\n public CommandInfo(@NotNull String name, @Nullable String permission) {\n this(name, permission, new String[0]);\n }\n\n public CommandInfo(@NotNull String name, @NotNull String[] aliases) {\n this(name, null, aliases);\n }\n\n public CommandInfo(@NotNull String name, @Nullable String permission, @NotNull String[] aliases) {\n this(name, permission, aliases, \"\");\n }\n\n public CommandInfo(@NotNull String name, @Nullable String permission, @NotNull String[] aliases, @NotNull String description) {\n this(name, permission, aliases, description, \"\");\n }\n\n public CommandInfo(@NotNull String name, @Nullable String permission, @NotNull String[] aliases, @NotNull String description, @NotNull String usage) {\n this.name = name;\n this.permission = permission;\n this.aliases = aliases;\n this.description = description;\n this.usage = usage;\n }\n\n @NotNull\n public String name() {\n return name;\n }\n\n public CommandInfo setName(@NotNull String name) {\n this.name = name;\n return this;\n }\n\n @Nullable\n public String permission() {\n return permission;\n }\n\n public CommandInfo setPermission(@Nullable String permission) {\n this.permission = permission;\n return this;\n }\n\n @NotNull\n public String[] aliases() {\n return aliases;\n }\n\n public CommandInfo setAliases(@NotNull String[] aliases) {\n this.aliases = aliases;\n return this;\n }\n\n @NotNull\n public String description() {\n return description;\n }\n\n public CommandInfo setDescription(@NotNull String description) {\n this.description = description;\n return this;\n }\n\n @NotNull\n public String usage() {\n return usage;\n }\n\n public CommandInfo setUsage(@NotNull String usage) {\n this.usage = usage;\n return this;\n }\n\n public PermDef permDef() {\n return permDef;\n }\n\n public CommandInfo setPermDef(PermDef permDef) {\n this.permDef = permDef;\n return this;\n }\n\n}" }, { "identifier": "CommandManager", "path": "common/src/main/java/crypticlib/command/CommandManager.java", "snippet": "public enum CommandManager {\n\n INSTANCE;\n\n private final CommandMap serverCommandMap;\n private final Constructor<?> pluginCommandConstructor;\n private final List<Command> registeredCommands;\n\n CommandManager() {\n Method getCommandMapMethod = ReflectUtil.getMethod(Bukkit.getServer().getClass(), \"getCommandMap\");\n serverCommandMap = (CommandMap) ReflectUtil.invokeMethod(getCommandMapMethod, Bukkit.getServer());\n pluginCommandConstructor = ReflectUtil.getDeclaredConstructor(PluginCommand.class, String.class, Plugin.class);\n registeredCommands = new CopyOnWriteArrayList<>();\n }\n\n public static SubcmdExecutor subcommand(@NotNull String name) {\n return new SubcmdExecutor(name);\n }\n\n public CommandManager register(@NotNull Plugin plugin, @NotNull CommandInfo commandInfo, @NotNull TabExecutor commandExecutor) {\n PluginCommand pluginCommand = (PluginCommand) ReflectUtil.invokeDeclaredConstructor(pluginCommandConstructor, commandInfo.name(), plugin);\n pluginCommand.setAliases(Arrays.asList(commandInfo.aliases()));\n pluginCommand.setDescription(commandInfo.description());\n pluginCommand.setPermission(commandInfo.permission());\n pluginCommand.setUsage(commandInfo.usage());\n pluginCommand.setExecutor(commandExecutor);\n pluginCommand.setTabCompleter(commandExecutor);\n serverCommandMap.register(plugin.getName(), pluginCommand);\n registeredCommands.add(pluginCommand);\n CrypticLib.permissionManager().regPerm(commandInfo.permission(), commandInfo.permDef());\n return this;\n }\n\n public CommandManager unregisterAll() {\n for (Command registeredCommand : registeredCommands) {\n registeredCommand.unregister(serverCommandMap);\n }\n registeredCommands.clear();\n return this;\n }\n\n}" }, { "identifier": "ConfigContainer", "path": "common/src/main/java/crypticlib/config/ConfigContainer.java", "snippet": "public class ConfigContainer {\n\n private final Class<?> containerClass;\n private final ConfigWrapper configWrapper;\n\n public ConfigContainer(@NotNull Class<?> containerClass, @NotNull ConfigWrapper configWrapper) {\n this.containerClass = containerClass;\n this.configWrapper = configWrapper;\n }\n\n @NotNull\n public Class<?> containerClass() {\n return containerClass;\n }\n\n @NotNull\n public ConfigWrapper configWrapper() {\n return configWrapper;\n }\n\n public void reload() {\n configWrapper.reloadConfig();\n for (Field field : containerClass.getDeclaredFields()) {\n if (!Modifier.isStatic(field.getModifiers()))\n continue;\n Object configEntry = ReflectUtil.getDeclaredFieldObj(field, null);\n if (configEntry instanceof ConfigEntry) {\n ((ConfigEntry<?>) configEntry).load(configWrapper.config());\n }\n }\n configWrapper.saveConfig();\n }\n\n}" }, { "identifier": "ConfigWrapper", "path": "common/src/main/java/crypticlib/config/ConfigWrapper.java", "snippet": "public class ConfigWrapper {\n private final File configFile;\n private final String path;\n private final Plugin plugin;\n private YamlConfiguration config;\n\n /**\n * 从指定插件中释放并创建一个配置文件\n *\n * @param plugin 创建配置文件的插件\n * @param path 相对插件文件夹的路径\n */\n public ConfigWrapper(@NotNull Plugin plugin, @NotNull String path) {\n this.path = path;\n File dataFolder = plugin.getDataFolder();\n configFile = new File(dataFolder, path);\n this.plugin = plugin;\n createDefaultConfig();\n }\n\n /**\n * 从指定的File对象中创建一个配置文件\n *\n * @param file 创建的配置文件\n */\n public ConfigWrapper(@NotNull File file) {\n this.configFile = file;\n this.path = file.getPath();\n if (!configFile.exists()) {\n FileUtil.createNewFile(file);\n }\n this.config = YamlConfiguration.loadConfiguration(file);\n this.plugin = null;\n }\n\n public void createDefaultConfig() {\n if (!configFile.exists()) {\n try {\n plugin.saveResource(path, false);\n } catch (NullPointerException | IllegalArgumentException e) {\n FileUtil.createNewFile(configFile);\n }\n }\n reloadConfig();\n }\n\n /**\n * 获取配置文件实例\n *\n * @return 配置文件实例\n */\n @NotNull\n public YamlConfiguration config() {\n if (config == null) {\n reloadConfig();\n }\n return config;\n }\n\n public boolean contains(String key) {\n return config.contains(key);\n }\n\n /**\n * 设置配置文件指定路径的值\n *\n * @param key 配置的路径\n * @param object 值\n */\n public void set(@NotNull String key, @Nullable Object object) {\n config.set(key, object);\n }\n\n /**\n * 重载配置文件\n */\n public void reloadConfig() {\n config = YamlConfiguration.loadConfiguration(configFile);\n }\n\n /**\n * 保存配置文件\n */\n public synchronized void saveConfig() {\n try {\n config().save(configFile);\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n\n /**\n * 返回配置文件相对于插件文件夹的路径\n *\n * @return 配置文件的路径\n */\n @NotNull\n public String filePath() {\n return path;\n }\n\n @NotNull\n public File configFile() {\n return configFile;\n }\n\n @Nullable\n public Plugin plugin() {\n return plugin;\n }\n\n}" }, { "identifier": "PermissionManager", "path": "common/src/main/java/crypticlib/perm/PermissionManager.java", "snippet": "public enum PermissionManager {\n\n INSTANCE;\n\n public PermissionManager regPerm(String permission, @NotNull PermDef permDef) {\n if (permission == null || permission.isEmpty())\n return this;\n Permission permissionObj = Bukkit.getPluginManager().getPermission(permission);\n PermissionDefault permissionDefault = PermissionDefault.valueOf(permDef.name().toUpperCase());\n if (permissionObj != null) {\n permissionObj.setDefault(permissionDefault);\n } else {\n permissionObj = new Permission(permission);\n permissionObj.setDefault(permissionDefault);\n Bukkit.getPluginManager().addPermission(permissionObj);\n }\n return this;\n }\n\n}" } ]
import crypticlib.annotation.AnnotationProcessor; import crypticlib.chat.LangConfigContainer; import crypticlib.chat.LangConfigHandler; import crypticlib.chat.MessageSender; import crypticlib.command.BukkitCommand; import crypticlib.command.CommandInfo; import crypticlib.command.CommandManager; import crypticlib.config.ConfigContainer; import crypticlib.config.ConfigHandler; import crypticlib.config.ConfigWrapper; import crypticlib.listener.BukkitListener; import crypticlib.perm.PermissionManager; import org.bukkit.Bukkit; import org.bukkit.command.TabExecutor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.Listener; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
7,574
package crypticlib; public abstract class BukkitPlugin extends JavaPlugin { protected final Map<String, ConfigContainer> configContainerMap = new ConcurrentHashMap<>(); protected final Map<String, LangConfigContainer> langConfigContainerMap = new ConcurrentHashMap<>(); private final String defaultConfigFileName = "config.yml"; private Integer lowestSupportVersion = 11200; private Integer highestSupportVersion = 12004; protected BukkitPlugin() { super(); } @Override public final void onLoad() { AnnotationProcessor annotationProcessor = AnnotationProcessor.INSTANCE; annotationProcessor .regClassAnnotationProcessor( BukkitListener.class, (annotation, clazz) -> { boolean reg = true; try { clazz.getDeclaredMethods(); } catch (NoClassDefFoundError ignored) { reg = false; } if (!reg) return; Listener listener = (Listener) annotationProcessor.getClassInstance(clazz); Bukkit.getPluginManager().registerEvents(listener, this); }) .regClassAnnotationProcessor( BukkitCommand.class, (annotation, clazz) -> { TabExecutor tabExecutor = (TabExecutor) annotationProcessor.getClassInstance(clazz); BukkitCommand bukkitCommand = (BukkitCommand) annotation;
package crypticlib; public abstract class BukkitPlugin extends JavaPlugin { protected final Map<String, ConfigContainer> configContainerMap = new ConcurrentHashMap<>(); protected final Map<String, LangConfigContainer> langConfigContainerMap = new ConcurrentHashMap<>(); private final String defaultConfigFileName = "config.yml"; private Integer lowestSupportVersion = 11200; private Integer highestSupportVersion = 12004; protected BukkitPlugin() { super(); } @Override public final void onLoad() { AnnotationProcessor annotationProcessor = AnnotationProcessor.INSTANCE; annotationProcessor .regClassAnnotationProcessor( BukkitListener.class, (annotation, clazz) -> { boolean reg = true; try { clazz.getDeclaredMethods(); } catch (NoClassDefFoundError ignored) { reg = false; } if (!reg) return; Listener listener = (Listener) annotationProcessor.getClassInstance(clazz); Bukkit.getPluginManager().registerEvents(listener, this); }) .regClassAnnotationProcessor( BukkitCommand.class, (annotation, clazz) -> { TabExecutor tabExecutor = (TabExecutor) annotationProcessor.getClassInstance(clazz); BukkitCommand bukkitCommand = (BukkitCommand) annotation;
CrypticLib.commandManager().register(this, new CommandInfo(bukkitCommand), tabExecutor);
3
2023-11-07 12:39:20+00:00
12k
Traben-0/resource_explorer
common/src/main/java/traben/resource_explorer/REConfig.java
[ { "identifier": "REExplorer", "path": "common/src/main/java/traben/resource_explorer/explorer/REExplorer.java", "snippet": "public class REExplorer {\n public static final Identifier ICON_FILE_BUILT = new Identifier(\"resource_explorer:textures/file_built.png\");\n public static final Identifier ICON_FOLDER_BUILT = new Identifier(\"resource_explorer:textures/folder_built.png\");\n public static final Identifier ICON_FOLDER = new Identifier(\"resource_explorer:textures/folder.png\");\n public static final Identifier ICON_FOLDER_OPEN = new Identifier(\"resource_explorer:textures/folder_open.png\");\n public static final Identifier ICON_FOLDER_BACK = new Identifier(\"resource_explorer:textures/folder_back.png\");\n public static final Identifier ICON_FILE_PNG = new Identifier(\"resource_explorer:textures/file_png.png\");\n public static final Identifier ICON_FILE_TEXT = new Identifier(\"resource_explorer:textures/file_text.png\");\n public static final Identifier ICON_FILE_PROPERTY = new Identifier(\"resource_explorer:textures/file_property.png\");\n public static final Identifier ICON_FILE_OGG = new Identifier(\"resource_explorer:textures/file_ogg.png\");\n public static final Identifier ICON_FILE_UNKNOWN = new Identifier(\"resource_explorer:textures/file_unknown.png\");\n public static final Identifier ICON_FOLDER_MOJANG = new Identifier(\"resource_explorer:textures/folder_mojang.png\");\n public static final Identifier ICON_FOLDER_OPTIFINE = new Identifier(\"resource_explorer:textures/folder_optifine.png\");\n public static final Identifier ICON_FOLDER_ETF = new Identifier(\"resource_explorer:textures/folder_etf.png\");\n public static final Identifier ICON_FOLDER_EMF = new Identifier(\"resource_explorer:textures/folder_emf.png\");\n public static final Identifier ICON_FOLDER_CORNER = new Identifier(\"resource_explorer:textures/folder_corner.png\");\n public static final Identifier ICON_FILE_BLANK = new Identifier(\"resource_explorer:textures/file_blank.png\");\n public static final Identifier ICON_FILE_JSON = new Identifier(\"resource_explorer:textures/file_json.png\");\n public static final Identifier ICON_FOLDER_UP = new Identifier(\"resource_explorer:textures/folder_up.png\");\n public static final Identifier ICON_FOLDER_UP_SELECTED = new Identifier(\"resource_explorer:textures/folder_up_selected.png\");\n public static final Identifier ICON_FILE_ZIP = new Identifier(\"resource_explorer:textures/file_zip.png\");\n public static final Identifier ICON_FILE_JEM = new Identifier(\"resource_explorer:textures/file_jem.png\");\n public static final Identifier ICON_HAS_META = new Identifier(\"resource_explorer:textures/has_meta.png\");\n public static final Identifier ICON_FOLDER_FABRIC = new Identifier(\"resource_explorer:textures/folder_fabric.png\");\n public static final Identifier ICON_FOLDER_PNG = new Identifier(\"resource_explorer:textures/folder_png.png\");\n public static final Identifier ICON_FOLDER_OGG = new Identifier(\"resource_explorer:textures/folder_ogg.png\");\n public static final Identifier ICON_MOD = new Identifier(\"resource_explorer:textures/icon.png\");\n\n\n public static LinkedList<REResourceEntry> getResourceFolderRoot() {\n try {\n\n ObjectLinkedOpenHashSet<REResourceFile> allFilesList = new ObjectLinkedOpenHashSet<>();\n\n\n boolean print = REConfig.getInstance().logFullFileTree;\n\n if (print) {\n ResourceExplorerClient.log(\"/START/\");\n ResourceExplorerClient.log(\"/START/READ/\");\n }\n\n //perform vanilla search with placeholder string that will trigger a blanket resource search\n try {\n Map<Identifier, Resource> resourceMap = MinecraftClient.getInstance().getResourceManager().findResources(\"resource_explorer$search\", (id) -> true);\n resourceMap.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));\n\n } catch (Exception ignored) {\n //the method I use to explore all resources will cause an exception once at the end of the resource list as I need to search for blank file names\n }\n\n //fabric mod resources allow direct blank searches so catch those too\n Map<Identifier, Resource> resourceMap2 = MinecraftClient.getInstance().getResourceManager().findResources(\"\", (id) -> true);\n resourceMap2.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));\n\n //search for generated texture assets\n Map<Identifier, AbstractTexture> textures = ((TextureManagerAccessor) MinecraftClient.getInstance().getTextureManager()).getTextures();\n textures.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));\n\n\n if (print) {\n ResourceExplorerClient.log(\"/END/READ/\");\n ResourceExplorerClient.log(\"/START/FOLDER_SORT/\");\n }\n Set<String> namespaces = MinecraftClient.getInstance().getResourceManager().getAllNamespaces();\n\n LinkedList<REResourceEntry> namesSpaceFoldersRoot = new LinkedList<>();\n Map<String, REResourceFolder> namespaceFolderMap = new HashMap<>();\n\n LinkedList<REResourceFolder> fabricApiFolders = new LinkedList<>();\n\n REResourceFolder minecraftFolder = new REResourceFolder(\"minecraft\");\n namespaceFolderMap.put(\"minecraft\", minecraftFolder);\n namespaces.remove(\"minecraft\");\n\n for (String nameSpace :\n namespaces) {\n REResourceFolder namespaceFolder = new REResourceFolder(nameSpace);\n\n if (\"fabric\".equals(nameSpace) || nameSpace.matches(\"(fabric-.*|renderer-registries)(renderer|api|-v\\\\d).*\")) {\n fabricApiFolders.add(namespaceFolder);\n } else {\n namesSpaceFoldersRoot.addLast(namespaceFolder);\n }\n namespaceFolderMap.put(nameSpace, namespaceFolder);\n\n }\n //fabric api all in 1\n if (!fabricApiFolders.isEmpty()) {\n REResourceFolder fabricApiFolder = new REResourceFolder(\"fabric-api\");\n fabricApiFolder.contentIcon = new Identifier(\"fabricloader\", \"icon.png\");\n fabricApiFolders.forEach(fabricApiFolder::addSubFolder);\n namesSpaceFoldersRoot.addFirst(fabricApiFolder);\n }\n //get filter\n REConfig.REFileFilter filter = REConfig.getInstance().filterMode;\n\n //minecraft at the top\n if (filter != REConfig.REFileFilter.ONLY_FROM_PACKS_NO_GENERATED)\n namesSpaceFoldersRoot.addFirst(minecraftFolder);\n\n //here allFilesAndFoldersRoot is only empty namespace directories\n\n REStats statistics = new REStats();\n\n //iterate over all files and give them folder structure\n for (REResourceFile resourceFile :\n allFilesList) {\n if (filter.allows(resourceFile)) {\n String namespace = resourceFile.identifier.getNamespace();\n REResourceFolder namespaceFolder = namespaceFolderMap.get(namespace);\n if (namespaceFolder == null) {\n namespaceFolder = new REResourceFolder(namespace);\n namespaceFolderMap.put(namespace, namespaceFolder);\n namesSpaceFoldersRoot.addLast(namespaceFolder);\n }\n namespaceFolder.addResourceFile(resourceFile, statistics);\n statistics.addEntryStatistic(resourceFile, true);\n } else {\n statistics.addEntryStatistic(resourceFile, false);\n }\n }\n\n if (print) {\n namesSpaceFoldersRoot.forEach(System.out::println);\n ResourceExplorerClient.log(\"/END/FOLDER_SORT/\");\n ResourceExplorerClient.log(\"/END/\");\n }\n\n REExplorerScreen.currentStats = statistics;\n\n return namesSpaceFoldersRoot;\n } catch (Exception e) {\n LinkedList<REResourceEntry> fail = new LinkedList<>();\n fail.add(REResourceFile.FAILED_FILE);\n return fail;\n }\n }\n\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n static boolean outputResourceToPackInternal(REResourceFile reResourceFile) {\n //only save existing file resources\n if (reResourceFile.resource == null)\n return false;\n\n Path resourcePackFolder = MinecraftClient.getInstance().getResourcePackDir();\n File thisPackFolder = new File(resourcePackFolder.toFile(), \"resource_explorer/\");\n\n if (validateOutputResourcePack(thisPackFolder)) {\n if (thisPackFolder.exists()) {\n File assets = new File(thisPackFolder, \"assets\");\n if (!assets.exists()) {\n assets.mkdir();\n }\n File namespace = new File(assets, reResourceFile.identifier.getNamespace());\n if (!namespace.exists()) {\n namespace.mkdir();\n }\n String[] pathList = reResourceFile.identifier.getPath().split(\"/\");\n String file = pathList[pathList.length - 1];\n String directories = reResourceFile.identifier.getPath().replace(file, \"\");\n File directoryFolder = new File(namespace, directories);\n if (!directoryFolder.exists()) {\n directoryFolder.mkdirs();\n }\n if (directoryFolder.exists()) {\n\n File outputFile = new File(directoryFolder, file);\n try {\n byte[] buffer = reResourceFile.resource.getInputStream().readAllBytes();\n OutputStream outStream = new FileOutputStream(outputFile);\n outStream.write(buffer);\n IOUtils.closeQuietly(outStream);\n return true;\n } catch (IOException e) {\n e.printStackTrace();\n ResourceExplorerClient.log(\" Exporting resource file failed for: \" + reResourceFile.identifier);\n }\n }\n }\n }\n return false;\n }\n\n\n private static boolean validateOutputResourcePack(File packFolder) {\n if (!packFolder.exists()) {\n if (packFolder.mkdir()) {\n return validateOutputResourcePackMeta(packFolder);\n }\n } else {\n return validateOutputResourcePackMeta(packFolder);\n }\n return false;\n }\n\n private static boolean validateOutputResourcePackMeta(File packFolder) {\n File thisMetaFile = new File(packFolder, \"pack.mcmeta\");\n if (thisMetaFile.exists()) {\n return true;\n }\n String mcmeta = \"\"\"\n {\n \\t\"pack\": {\n \\t\\t\"pack_format\": 15,\n \\t\\t\"supported_formats\":[0,99],\n \\t\\t\"description\": \"Output file for the Resource Explorer mod\"\n \\t}\n }\"\"\";\n try {\n FileWriter fileWriter = new FileWriter(thisMetaFile);\n fileWriter.write(mcmeta);\n fileWriter.close();\n ResourceExplorerClient.log(\" output resource-pack created.\");\n } catch (IOException e) {\n ResourceExplorerClient.log(\" output resource-pack not created.\");\n }\n File thisIconFile = new File(packFolder, \"pack.png\");\n Optional<Resource> image = MinecraftClient.getInstance().getResourceManager().getResource(ICON_FOLDER_BUILT);\n if (image.isPresent()) {\n try {\n InputStream stream = image.get().getInputStream();\n NativeImage.read(stream).writeTo(thisIconFile);\n ResourceExplorerClient.log(\" output resource-pack icon created.\");\n } catch (IOException e) {\n ResourceExplorerClient.log(\" output resource-pack icon not created.\");\n }\n }\n return thisMetaFile.exists();\n }\n\n static class REExportContext {\n\n\n final Set<REResourceFile.FileType> types = new HashSet<>();\n int vanillaCount = 0;\n int packCount = 0;\n int moddedCount = 0;\n int totalAttempted = 0;\n\n\n REExportContext() {\n }\n\n public void sendLargeFolderWarning() {\n ToastManager toastManager = MinecraftClient.getInstance().getToastManager();\n toastManager.clear();\n SystemToast.show(toastManager, SystemToast.Type.PERIODIC_NOTIFICATION,\n Text.translatable(\"resource_explorer.export_start.1\"), Text.translatable(\"resource_explorer.export_start.2\"));\n\n }\n\n public int getTotalExported() {\n return vanillaCount + packCount + moddedCount;\n }\n\n public int getTotalAttempted() {\n return totalAttempted;\n }\n\n public void tried(REResourceFile file, boolean exported) {\n if (file.resource != null) {\n totalAttempted++;\n if (exported) {\n types.add(file.fileType);\n String packName = file.resource.getResourcePackName();\n if (\"fabric\".equals(packName) || \"mod_resources\".equals(packName)) {\n moddedCount++;\n } else if (\"vanilla\".equals(packName) &&\n (\"minecraft\".equals(file.identifier.getNamespace()) || \"realms\".equals(file.identifier.getNamespace()))) {\n vanillaCount++;\n } else {\n //mod a mod default resource or vanilla\n packCount++;\n }\n }\n }\n }\n\n public void showExportToast() {\n ToastManager toastManager = MinecraftClient.getInstance().getToastManager();\n toastManager.clear();\n boolean partially = getTotalAttempted() != getTotalExported() && totalAttempted != 1 && getTotalExported() != 0;\n Text title = partially ?\n Text.of(Text.translatable(\"resource_explorer.export_warn.partial\").getString()\n .replace(\"#\", String.valueOf(getTotalExported())).replace(\"$\", String.valueOf(getTotalAttempted()))) :\n Text.of(getTotalAttempted() == getTotalExported() ?\n Text.translatable(ResourceExplorerClient.MOD_ID + \".export_warn\").getString()\n .replace(\"#\", String.valueOf(getTotalExported())) :\n Text.translatable(ResourceExplorerClient.MOD_ID + \".export_warn.fail\").getString()\n .replace(\"#\", String.valueOf(getTotalExported())));\n\n SystemToast.show(toastManager, SystemToast.Type.PERIODIC_NOTIFICATION, title, getMessage());\n }\n\n private Text getMessage() {\n if (getTotalExported() == 0) {\n return Text.translatable(\"resource_explorer.export_warn.none\");\n }\n if (getTotalAttempted() == 1) {\n return Text.translatable(\n packCount > 0 ?\n \"resource_explorer.export_warn.pack\" :\n moddedCount > 0 ?\n \"resource_explorer.export_warn.mod\" :\n \"resource_explorer.export_warn.vanilla\"\n );\n } else {\n return Text.translatable(\"resource_explorer.export_warn.all\");\n }\n }\n\n }\n}" }, { "identifier": "REExplorerScreen", "path": "common/src/main/java/traben/resource_explorer/explorer/REExplorerScreen.java", "snippet": "public class REExplorerScreen extends Screen {\n\n @Nullable\n static public REResourceSingleDisplayWidget currentDisplay = null;\n\n @Nullable\n static public REStats currentStats = null;\n public final Screen vanillaParent;\n @Nullable\n public final REExplorerScreen reParent;\n public final LinkedList<REResourceEntry> entriesInThisDirectory;\n final String cumulativePath;\n private REResourceListWidget fileList;\n private REConfig.REFileFilter filterChoice = REConfig.getInstance().filterMode;\n\n public REExplorerScreen(Screen vanillaParent) {\n super(Text.translatable(MOD_ID + \".title\"));\n this.cumulativePath = \"assets/\";\n this.entriesInThisDirectory = REExplorer.getResourceFolderRoot();\n this.vanillaParent = vanillaParent;\n this.reParent = null;\n }\n\n public REExplorerScreen(Screen vanillaParent, @NotNull REExplorerScreen reParent, LinkedList<REResourceEntry> entries, String cumulativePath) {\n super(Text.translatable(MOD_ID + \".title\"));\n this.cumulativePath = cumulativePath;\n this.entriesInThisDirectory = entries;\n this.vanillaParent = vanillaParent;\n this.reParent = reParent;\n }\n\n protected void init() {\n if (currentDisplay == null) currentDisplay = new REResourceSingleDisplayWidget(client, 200, this.height);\n\n this.fileList = new REResourceListWidget(this.client, this, 200, this.height);\n this.fileList.setLeftPos(this.width / 2 - 4 - 200);\n this.addSelectableChild(this.fileList);\n\n currentDisplay.setDimensions(width / 2 + 4, 200, this.height);\n this.addSelectableChild(currentDisplay);\n\n this.addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE,\n (button) -> this.close()).dimensions(this.width / 2 + 4, this.height - 48, 150, 20).build());\n\n Tooltip warn = Tooltip.of(Text.translatable(MOD_ID + \".explorer.apply_warn\"));\n\n ButtonWidget apply = this.addDrawableChild(ButtonWidget.builder(Text.translatable(MOD_ID + \".explorer.apply\"), (button) -> {\n this.close();\n REConfig.getInstance().filterMode = filterChoice;\n REConfig.saveConfig();\n }).dimensions(this.width / 2 - 4 - 46, this.height - 48, 46, 20).tooltip(warn).build());\n apply.active = false;\n\n this.addDrawableChild(ButtonWidget.builder(Text.translatable(REConfig.getInstance().filterMode.getKey()), (button) -> {\n filterChoice = filterChoice.next();\n button.setMessage(Text.translatable(filterChoice.getKey()));\n apply.active = filterChoice != REConfig.getInstance().filterMode;\n }).dimensions(this.width / 2 - 4 - 200, this.height - 48, 150, 20).tooltip(warn).build());\n\n this.addDrawableChild(ButtonWidget.builder(Text.translatable(MOD_ID + \".explorer.settings\"), (button) -> {\n this.close();\n MinecraftClient.getInstance().setScreen(new REConfig.REConfigScreen(null));\n }).dimensions(this.width / 2 - 4 - 200, this.height - 24, 150, 20).build());\n\n this.addDrawableChild(ButtonWidget.builder(Text.translatable(MOD_ID + \".explorer.stats\"), (button) -> {\n if (currentStats != null) MinecraftClient.getInstance().setScreen(currentStats.getAsScreen(this));\n }).dimensions(this.width / 2 - 4 - 46, this.height - 24, 46, 20).build());\n }\n\n public void render(DrawContext context, int mouseX, int mouseY, float delta) {\n super.render(context, mouseX, mouseY, delta);\n\n this.fileList.render(context, mouseX, mouseY, delta);\n if (currentDisplay != null)\n currentDisplay.render(context, mouseX, mouseY, delta);\n\n context.drawCenteredTextWithShadow(this.textRenderer, this.title, this.width / 2, 8, 16777215);\n context.drawCenteredTextWithShadow(this.textRenderer, Text.of(cumulativePath), this.width / 2, 20, Colors.GRAY);\n }\n\n public void renderBackground(DrawContext context, int mouseX, int mouseY, float delta) {\n this.renderBackgroundTexture(context);\n }\n\n @Override\n public void close() {\n this.fileList.close();\n super.close();\n\n entriesInThisDirectory.clear();\n\n if (currentDisplay != null)\n currentDisplay.close();\n currentDisplay = null;\n currentStats = null;\n\n //reading resources this way has some... affects to the resource system\n //thus a resource reload is required\n MinecraftClient.getInstance().reloadResources();\n if (vanillaParent instanceof REConfig.REConfigScreen configScreen) {\n configScreen.tempConfig.filterMode = REConfig.getInstance().filterMode;\n configScreen.reset();\n }\n MinecraftClient.getInstance().setScreen(vanillaParent);\n }\n\n\n}" }, { "identifier": "REResourceFile", "path": "common/src/main/java/traben/resource_explorer/explorer/REResourceFile.java", "snippet": "public class REResourceFile extends REResourceEntry {\n\n public static final REResourceFile FAILED_FILE = new REResourceFile();\n public final Identifier identifier;\n @Nullable\n public final Resource resource;\n public final FileType fileType;\n public final LinkedList<String> folderStructureList;\n final AbstractTexture abstractTexture;\n private final String displayName;\n private final OrderedText displayText;\n public MultilineText readTextByLineBreaks = null;\n public int height = 1;\n public int width = 1;\n boolean imageDone = false;\n Boolean hasMetaData = null;\n\n private REResourceFile() {\n //failed file\n this.identifier = new Identifier(\"search_failed:fail\");\n this.resource = null;\n this.abstractTexture = null;\n this.fileType = FileType.OTHER;\n displayName = \"search_failed\";\n folderStructureList = new LinkedList<>();\n this.displayText = Text.of(\"search_failed\").asOrderedText();\n }\n\n\n public REResourceFile(Identifier identifier, AbstractTexture texture) {\n this.identifier = identifier;\n this.resource = null;\n this.abstractTexture = texture;\n\n //try to capture some sizes\n if (abstractTexture instanceof SpriteAtlasTexture atlasTexture) {\n width = ((SpriteAtlasTextureAccessor) atlasTexture).getWidth();\n height = ((SpriteAtlasTextureAccessor) atlasTexture).getHeight();\n } else if (abstractTexture instanceof NativeImageBackedTexture nativeImageBackedTexture) {\n NativeImage image = nativeImageBackedTexture.getImage();\n if (image != null) {\n width = image.getWidth();\n height = image.getHeight();\n }\n }\n\n\n this.fileType = FileType.getType(this.identifier);\n\n //split out folder hierarchy\n String[] splitDirectories = this.identifier.getPath().split(\"/\");\n LinkedList<String> directories = new LinkedList<>(List.of(splitDirectories));\n\n //final entry is display file name\n displayName = directories.getLast();\n directories.removeLast();\n\n //remainder is folder hierarchy, which can be empty\n folderStructureList = directories;\n\n this.displayText = trimmedTextToWidth(displayName).asOrderedText();\n }\n\n public REResourceFile(Identifier identifier, @Nullable Resource resource) {\n this.identifier = identifier;\n this.resource = resource;\n this.abstractTexture = null;\n this.fileType = FileType.getType(this.identifier);\n\n //split out folder hierarchy\n String[] splitDirectories = this.identifier.getPath().split(\"/\");\n LinkedList<String> directories = new LinkedList<>(List.of(splitDirectories));\n\n //final entry is display file name\n displayName = directories.getLast();\n directories.removeLast();\n\n //remainder is folder hierarchy, which can be empty\n folderStructureList = directories;\n\n this.displayText = trimmedTextToWidth(displayName).asOrderedText();\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 REResourceFile that = (REResourceFile) o;\n return identifier.equals(that.identifier);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(identifier);\n }\n\n @Override\n boolean canExport() {\n return resource != null;\n }\n\n @Override\n public String toString() {\n return toString(0);\n }\n\n @Override\n public String toString(int indent) {\n\n return \" \".repeat(Math.max(0, indent)) + \"\\\\ \" +\n displayName + \"\\n\";\n }\n\n @Override\n public String getDisplayName() {\n return displayName;\n }\n\n @Override\n OrderedText getDisplayText() {\n return displayText;\n }\n\n @Override\n List<Text> getExtraText(boolean smallMode) {\n ArrayList<Text> lines = new ArrayList<>();\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.type\") + \": \" + fileType.toString() +\n (hasMetaData ? \" + \" + translated(\"resource_explorer.detail.metadata\") : \"\")));\n if (resource != null) {\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.pack\") + \": \" + resource.getResourcePackName().replace(\"file/\", \"\")));\n } else {\n lines.add(trimmedTextToWidth(\"§8§o \" + translated(\"resource_explorer.detail.built_msg\")));\n }\n if (smallMode) return lines;\n switch (fileType) {\n case PNG -> {\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.height\") + \": \" + height));\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.width\") + \": \" + width));\n if (hasMetaData && height > width && height % width == 0) {\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.frame_count\") + \": \" + (height / width)));\n }\n }\n case TXT, PROPERTIES, JSON -> {\n if (readTextByLineBreaks != null) {\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.lines\") + \": \" + height));\n lines.add(trimmedTextToWidth(\" \" + translated(\"resource_explorer.detail.character_count\") + \": \" + width));\n }\n }\n default -> {\n }//lines.add(trimmedTextToWidth(\" //todo \"));//todo\n }\n return lines;\n }\n\n MultilineText getTextLines() {\n if (!fileType.isRawTextType())\n return MultilineText.EMPTY;\n if (readTextByLineBreaks == null) {\n if (resource != null) {\n try {\n InputStream in = resource.getInputStream();\n try {\n ArrayList<Text> text = new ArrayList<>();\n String readString = new String(in.readAllBytes(), StandardCharsets.UTF_8);\n in.close();\n\n //make tabs smaller\n String reducedTabs = readString.replaceAll(\"(\\t| {4})\", \" \");\n\n\n String[] splitByLines = reducedTabs.split(\"\\n\");\n\n width = readString.length();\n height = splitByLines.length;\n\n //trim lines to width now\n for (int i = 0; i < splitByLines.length; i++) {\n splitByLines[i] = trimmedStringToWidth(splitByLines[i], 178);\n }\n int lineCount = 0;\n for (String line :\n splitByLines) {\n lineCount++;\n if (lineCount > 512) {//todo set limit in config\n text.add(Text.of(\"§l§4-- TEXT LONGER THAN \" + 512 + \" LINES --\"));\n text.add(Text.of(\"§r§o \" + (height - lineCount) + \" lines skipped.\"));\n text.add(Text.of(\"§l§4-- END --\"));\n break;\n }\n text.add(Text.of(line));\n }\n readTextByLineBreaks = MultilineText.createFromTexts(MinecraftClient.getInstance().textRenderer, text);\n\n } catch (Exception e) {\n //resource.close();\n in.close();\n readTextByLineBreaks = MultilineText.EMPTY;\n }\n } catch (Exception ignored) {\n readTextByLineBreaks = MultilineText.EMPTY;\n }\n } else {\n readTextByLineBreaks = MultilineText.create(MinecraftClient.getInstance().textRenderer, Text.of(\" ERROR: no file info could be read\"));\n }\n }\n return readTextByLineBreaks;\n }\n\n public void exportToOutputPack(REExplorer.REExportContext context) {\n boolean exported = outputResourceToPackInternal(this);\n context.tried(this, exported);\n }\n\n @Override\n public Identifier getIcon(boolean hovered) {\n\n\n if (fileType == FileType.PNG && hovered) {\n if (imageDone || resource == null)\n return identifier;\n\n imageDone = true;\n\n NativeImage img;\n try {\n InputStream in = resource.getInputStream();\n try {\n img = NativeImage.read(in);\n in.close();\n NativeImageBackedTexture imageBackedTexture = new NativeImageBackedTexture(img);\n MinecraftClient.getInstance().getTextureManager().registerTexture(identifier, imageBackedTexture);\n width = img.getWidth();\n height = img.getHeight();\n return identifier;\n } catch (Exception e) {\n //resource.close();\n in.close();\n }\n } catch (Exception ignored) {\n }\n }\n return resource == null ? REExplorer.ICON_FILE_BUILT : fileType.getDefaultIcon();\n }\n\n public REResourceFileDisplayWrapper wrapEntryAsDetailed() {\n return new REResourceFileDisplayWrapper(this);\n }\n\n @Override\n @Nullable Identifier getIcon2OrNull(boolean hovered) {\n if (hasMetaData == null) {\n if (resource != null) {\n try {\n ResourceMetadata meta = resource.getMetadata();\n hasMetaData = meta != null && meta != ResourceMetadata.NONE;\n } catch (IOException e) {\n hasMetaData = false;\n }\n } else {\n hasMetaData = false;\n }\n }\n return hasMetaData ? REExplorer.ICON_HAS_META : null;\n }\n\n\n @Override\n public boolean mouseClickExplorer() {\n if (REExplorerScreen.currentDisplay != null) {\n REExplorerScreen.currentDisplay.setSelectedFile(this.wrapEntryAsDetailed());\n }\n return true;\n }\n\n public enum FileType {\n PNG(REExplorer.ICON_FILE_PNG),\n TXT(REExplorer.ICON_FILE_TEXT),\n JSON(REExplorer.ICON_FILE_JSON),\n PROPERTIES(REExplorer.ICON_FILE_PROPERTY),\n OGG(REExplorer.ICON_FILE_OGG),\n ZIP(REExplorer.ICON_FILE_ZIP),\n JEM(REExplorer.ICON_FILE_JEM),\n JPM(REExplorer.ICON_FILE_JEM),\n OTHER(REExplorer.ICON_FILE_UNKNOWN),\n BLANK(REExplorer.ICON_FILE_BLANK);\n\n private final Identifier defaultIcon;\n\n FileType(Identifier defaultIcon) {\n this.defaultIcon = defaultIcon;\n }\n\n public static FileType getType(Identifier identifier) {\n String path = identifier.getPath();\n if (path.endsWith(\".png\")) {\n return PNG;\n }\n if (path.endsWith(\".json\") || path.endsWith(\".json5\")) {\n return JSON;\n }\n if (path.endsWith(\".properties\") || path.endsWith(\".toml\")) {\n return PROPERTIES;\n }\n if (path.endsWith(\".jem\")) {\n return JEM;\n }\n if (path.endsWith(\".jpm\")) {\n return JPM;\n }\n if (path.endsWith(\".txt\")) {\n return TXT;\n }\n if (path.endsWith(\".ogg\") || path.endsWith(\".mp3\")) {\n return OGG;\n }\n if (path.endsWith(\".zip\")) {\n return ZIP;\n }\n return OTHER;\n }\n\n public Identifier getDefaultIcon() {\n return defaultIcon;\n }\n\n @Override\n public String toString() {\n return switch (this) {\n case PNG -> \"texture\";\n case TXT -> \"text\";\n case PROPERTIES -> \"properties\";\n case OGG -> \"sound\";\n case ZIP -> \"zip folder\";\n case JEM -> \"CEM model\";\n case JPM -> \"CEM model part\";\n case OTHER -> \"unknown\";\n case BLANK -> \"\";\n case JSON -> \"json\";\n };\n }\n\n public boolean isRawTextType() {\n return switch (this) {\n case TXT, JSON, JPM, JEM, PROPERTIES -> true;\n default -> false;\n };\n }\n }\n}" }, { "identifier": "MOD_ID", "path": "common/src/main/java/traben/resource_explorer/ResourceExplorerClient.java", "snippet": "public static final String MOD_ID = \"resource_explorer\";" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.ButtonTextures; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.tooltip.Tooltip; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.TexturedButtonWidget; import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import traben.resource_explorer.explorer.REExplorer; import traben.resource_explorer.explorer.REExplorerScreen; import traben.resource_explorer.explorer.REResourceFile; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Objects; import java.util.function.Predicate; import static traben.resource_explorer.ResourceExplorerClient.MOD_ID;
8,706
if (config.exists()) { try { FileReader fileReader = new FileReader(config); instance = gson.fromJson(fileReader, REConfig.class); fileReader.close(); saveConfig(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be loaded, using defaults"); } } else { instance = new REConfig(); saveConfig(); } if (instance == null) { instance = new REConfig(); saveConfig(); } } catch (Exception e) { instance = new REConfig(); } } public static void saveConfig() { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (!config.getParentFile().exists()) { //noinspection ResultOfMethodCallIgnored config.getParentFile().mkdirs(); } try { FileWriter fileWriter = new FileWriter(config); fileWriter.write(gson.toJson(instance)); fileWriter.close(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be saved"); } } public REConfig copy() { REConfig newConfig = new REConfig(); newConfig.showResourcePackButton = showResourcePackButton; newConfig.filterMode = filterMode; newConfig.logFullFileTree = logFullFileTree; newConfig.addCauseToReloadFailureToast = addCauseToReloadFailureToast; return newConfig; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; REConfig reConfig = (REConfig) o; return showResourcePackButton == reConfig.showResourcePackButton && logFullFileTree == reConfig.logFullFileTree && filterMode == reConfig.filterMode && addCauseToReloadFailureToast == reConfig.addCauseToReloadFailureToast; } @Override public int hashCode() { return Objects.hash(showResourcePackButton, logFullFileTree, filterMode, addCauseToReloadFailureToast); } public enum REFileFilter { ALL_RESOURCES(MOD_ID + ".filter.0", (fileEntry) -> true), ALL_RESOURCES_NO_GENERATED(MOD_ID + ".filter.1", (fileEntry) -> fileEntry.resource != null), ONLY_FROM_PACKS_NO_GENERATED(MOD_ID + ".filter.2", (fileEntry) -> fileEntry.resource != null && !"vanilla".equals(fileEntry.resource.getResourcePackName())), ONLY_TEXTURES(MOD_ID + ".filter.3", (fileEntry) -> fileEntry.fileType == REResourceFile.FileType.PNG), ONLY_TEXTURE_NO_GENERATED(MOD_ID + ".filter.4", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType == REResourceFile.FileType.PNG), ONLY_TEXTURE_FROM_PACKS_NO_GENERATED(MOD_ID + ".filter.5", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType == REResourceFile.FileType.PNG && !"vanilla".equals(fileEntry.resource.getResourcePackName())), SOUNDS_ONLY(MOD_ID + ".filter.6", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType == REResourceFile.FileType.OGG), TEXT_ONLY(MOD_ID + ".filter.7", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType.isRawTextType()); private final String key; private final Predicate<REResourceFile> test; REFileFilter(String key, Predicate<REResourceFile> test) { this.key = key; this.test = test; } public String getKey() { return key; } public boolean allows(REResourceFile fileEntry) { return test.test(fileEntry); } public REFileFilter next() { return switch (this) { case ALL_RESOURCES -> ALL_RESOURCES_NO_GENERATED; case ALL_RESOURCES_NO_GENERATED -> ONLY_FROM_PACKS_NO_GENERATED; case ONLY_FROM_PACKS_NO_GENERATED -> ONLY_TEXTURES; case ONLY_TEXTURES -> ONLY_TEXTURE_NO_GENERATED; case ONLY_TEXTURE_NO_GENERATED -> ONLY_TEXTURE_FROM_PACKS_NO_GENERATED; case ONLY_TEXTURE_FROM_PACKS_NO_GENERATED -> SOUNDS_ONLY; case SOUNDS_ONLY -> TEXT_ONLY; case TEXT_ONLY -> ALL_RESOURCES; }; } } public static class REConfigScreen extends Screen { private final Screen parent; public REConfig tempConfig; public REConfigScreen(Screen parent) { super(Text.translatable(MOD_ID + ".settings.title"));
package traben.resource_explorer; public class REConfig { private static REConfig instance; public boolean showResourcePackButton = true; public boolean logFullFileTree = false; public boolean addCauseToReloadFailureToast = true; public REFileFilter filterMode = REFileFilter.ALL_RESOURCES; private REConfig() { } public static REConfig getInstance() { if (instance == null) { loadConfig(); } return instance; } public static void setInstance(REConfig newInstance) { instance = newInstance; saveConfig(); } public static void loadConfig() { try { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (config.exists()) { try { FileReader fileReader = new FileReader(config); instance = gson.fromJson(fileReader, REConfig.class); fileReader.close(); saveConfig(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be loaded, using defaults"); } } else { instance = new REConfig(); saveConfig(); } if (instance == null) { instance = new REConfig(); saveConfig(); } } catch (Exception e) { instance = new REConfig(); } } public static void saveConfig() { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (!config.getParentFile().exists()) { //noinspection ResultOfMethodCallIgnored config.getParentFile().mkdirs(); } try { FileWriter fileWriter = new FileWriter(config); fileWriter.write(gson.toJson(instance)); fileWriter.close(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be saved"); } } public REConfig copy() { REConfig newConfig = new REConfig(); newConfig.showResourcePackButton = showResourcePackButton; newConfig.filterMode = filterMode; newConfig.logFullFileTree = logFullFileTree; newConfig.addCauseToReloadFailureToast = addCauseToReloadFailureToast; return newConfig; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; REConfig reConfig = (REConfig) o; return showResourcePackButton == reConfig.showResourcePackButton && logFullFileTree == reConfig.logFullFileTree && filterMode == reConfig.filterMode && addCauseToReloadFailureToast == reConfig.addCauseToReloadFailureToast; } @Override public int hashCode() { return Objects.hash(showResourcePackButton, logFullFileTree, filterMode, addCauseToReloadFailureToast); } public enum REFileFilter { ALL_RESOURCES(MOD_ID + ".filter.0", (fileEntry) -> true), ALL_RESOURCES_NO_GENERATED(MOD_ID + ".filter.1", (fileEntry) -> fileEntry.resource != null), ONLY_FROM_PACKS_NO_GENERATED(MOD_ID + ".filter.2", (fileEntry) -> fileEntry.resource != null && !"vanilla".equals(fileEntry.resource.getResourcePackName())), ONLY_TEXTURES(MOD_ID + ".filter.3", (fileEntry) -> fileEntry.fileType == REResourceFile.FileType.PNG), ONLY_TEXTURE_NO_GENERATED(MOD_ID + ".filter.4", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType == REResourceFile.FileType.PNG), ONLY_TEXTURE_FROM_PACKS_NO_GENERATED(MOD_ID + ".filter.5", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType == REResourceFile.FileType.PNG && !"vanilla".equals(fileEntry.resource.getResourcePackName())), SOUNDS_ONLY(MOD_ID + ".filter.6", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType == REResourceFile.FileType.OGG), TEXT_ONLY(MOD_ID + ".filter.7", (fileEntry) -> fileEntry.resource != null && fileEntry.fileType.isRawTextType()); private final String key; private final Predicate<REResourceFile> test; REFileFilter(String key, Predicate<REResourceFile> test) { this.key = key; this.test = test; } public String getKey() { return key; } public boolean allows(REResourceFile fileEntry) { return test.test(fileEntry); } public REFileFilter next() { return switch (this) { case ALL_RESOURCES -> ALL_RESOURCES_NO_GENERATED; case ALL_RESOURCES_NO_GENERATED -> ONLY_FROM_PACKS_NO_GENERATED; case ONLY_FROM_PACKS_NO_GENERATED -> ONLY_TEXTURES; case ONLY_TEXTURES -> ONLY_TEXTURE_NO_GENERATED; case ONLY_TEXTURE_NO_GENERATED -> ONLY_TEXTURE_FROM_PACKS_NO_GENERATED; case ONLY_TEXTURE_FROM_PACKS_NO_GENERATED -> SOUNDS_ONLY; case SOUNDS_ONLY -> TEXT_ONLY; case TEXT_ONLY -> ALL_RESOURCES; }; } } public static class REConfigScreen extends Screen { private final Screen parent; public REConfig tempConfig; public REConfigScreen(Screen parent) { super(Text.translatable(MOD_ID + ".settings.title"));
if (parent instanceof REExplorerScreen) {
1
2023-11-05 17:35:39+00:00
12k
txline0420/nacos-dm
config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceProperties.java
[ { "identifier": "Preconditions", "path": "common/src/main/java/com/alibaba/nacos/common/utils/Preconditions.java", "snippet": "public class Preconditions {\n\n private Preconditions() {\n }\n\n /**\n * check precondition.\n * @param expression a boolean expression\n * @param errorMessage the exception message to use if the check fails\n * @throws IllegalArgumentException if {@code expression} is false\n */\n public static void checkArgument(boolean expression, Object errorMessage) {\n if (Objects.isNull(errorMessage)) {\n throw new IllegalArgumentException(\"errorMessage cannot be null.\");\n }\n if (!expression) {\n throw new IllegalArgumentException(String.valueOf(errorMessage));\n }\n }\n \n /**\n * check precondition.\n * @param expression a boolean expression\n * @param errorMessageTemplate the exception message template to use if the check fails\n * @param errorMessageArgs the arguments to be substituted into the message template.\n * @throws IllegalArgumentException if {@code expression} is false\n */\n public static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {\n if (Objects.isNull(errorMessageArgs) || Objects.isNull(errorMessageTemplate)) {\n throw new IllegalArgumentException(\"errorMessageTemplate or errorMessage cannot be null.\");\n }\n if (!expression) {\n throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs));\n }\n }\n}" }, { "identifier": "StringUtils", "path": "common/src/main/java/com/alibaba/nacos/common/utils/StringUtils.java", "snippet": "public class StringUtils {\n\n private StringUtils() {\n }\n \n public static final String DOT = \".\";\n \n private static final int INDEX_NOT_FOUND = -1;\n \n public static final String COMMA = \",\";\n \n public static final String EMPTY = \"\";\n \n public static final String LF = \"\\n\";\n \n private static final String[] EMPTY_STRING_ARRAY = {};\n \n private static final String TOP_PATH = \"..\";\n \n private static final String FOLDER_SEPARATOR = \"/\";\n \n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n \n /**\n * <p>Create a string with encoding format as utf8.</p>\n *\n * @param bytes the bytes that make up the string\n * @return created string\n */\n public static String newStringForUtf8(byte[] bytes) {\n return new String(bytes, StandardCharsets.UTF_8);\n }\n \n /**\n * <p>Checks if a string is empty (\"\"), null and whitespace only.</p>\n *\n * @param cs the string to check\n * @return {@code true} if the string is empty and null and whitespace\n */\n public static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(cs.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n \n /**\n * <p>Checks if a string is not empty (\"\"), not null and not whitespace only.</p>\n *\n * @param str the string to check, may be null\n * @return {@code true} if the string is not empty and not null and not whitespace\n */\n public static boolean isNotBlank(String str) {\n return !isBlank(str);\n }\n \n /**\n * <p>Checks if a str is not empty (\"\") or not null.</p>\n *\n * @param str the str to check, may be null\n * @return {@code true} if the str is not empty or not null\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n \n /**\n * <p>Checks if a str is empty (\"\") or null.</p>\n *\n * @param str the str to check, may be null\n * @return {@code true} if the str is empty or null\n */\n public static boolean isEmpty(String str) {\n return str == null || str.length() == 0;\n }\n \n /**\n * <p>Returns either the passed in CharSequence, or if the CharSequence is\n * empty or {@code null}, the value of {@code defaultStr}.</p>\n *\n * @param str the CharSequence to check, may be null\n * @param defaultStr the default CharSequence to return if the input is empty (\"\") or {@code null}, may be null\n * @return the passed in CharSequence, or the default\n */\n public static String defaultIfEmpty(String str, String defaultStr) {\n return isEmpty(str) ? defaultStr : str;\n }\n \n /**\n * <p>Compares two CharSequences, returning {@code true} if they represent\n * equal sequences of characters.</p>\n *\n * @param str1 the first string, may be {@code null}\n * @param str2 the second string, may be {@code null}\n * @return {@code true} if the string are equal (case-sensitive), or both {@code null}\n * @see Object#equals(Object)\n */\n public static boolean equals(String str1, String str2) {\n return str1 == null ? str2 == null : str1.equals(str2);\n }\n \n /**\n * <p>Removes control characters (char &lt;= 32) from both\n * ends of this String, handling {@code null} by returning {@code null}.</p>\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed string, {@code null} if null String input\n */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n \n /**\n * Substring between two index.\n *\n * @param str string\n * @param open start index to sub\n * @param close end index to sub\n * @return substring\n */\n public static String substringBetween(String str, String open, String close) {\n if (str == null || open == null || close == null) {\n return null;\n }\n int start = str.indexOf(open);\n if (start != INDEX_NOT_FOUND) {\n int end = str.indexOf(close, start + open.length());\n if (end != INDEX_NOT_FOUND) {\n return str.substring(start + open.length(), end);\n }\n }\n return null;\n }\n \n /**\n * <p>Joins the elements of the provided array into a single String\n * containing the provided list of elements.</p>\n *\n * @param collection the Collection of values to join together, may be null\n * @param separator the separator string to use\n * @return the joined String, {@code null} if null array input\n */\n public static String join(Collection collection, String separator) {\n if (collection == null) {\n return null;\n }\n \n StringBuilder stringBuilder = new StringBuilder();\n Object[] objects = collection.toArray();\n \n for (int i = 0; i < collection.size(); i++) {\n if (objects[i] != null) {\n stringBuilder.append(objects[i]);\n if (i != collection.size() - 1 && separator != null) {\n stringBuilder.append(separator);\n }\n }\n }\n \n return stringBuilder.toString();\n }\n \n public static String escapeJavaScript(String str) {\n return escapeJavaStyleString(str, true, true);\n }\n \n private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) {\n if (str == null) {\n return null;\n }\n try {\n StringWriter writer = new StringWriter(str.length() * 2);\n escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash);\n return writer.toString();\n } catch (IOException ioe) {\n // this should never ever happen while writing to a StringWriter\n return null;\n }\n }\n \n private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote,\n boolean escapeForwardSlash) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (str == null) {\n return;\n }\n int sz;\n sz = str.length();\n for (int i = 0; i < sz; i++) {\n char ch = str.charAt(i);\n \n // handle unicode\n if (ch > 0xfff) {\n out.write(\"\\\\u\" + hex(ch));\n } else if (ch > 0xff) {\n out.write(\"\\\\u0\" + hex(ch));\n } else if (ch > 0x7f) {\n out.write(\"\\\\u00\" + hex(ch));\n } else if (ch < 32) {\n switch (ch) {\n case '\\b':\n out.write('\\\\');\n out.write('b');\n break;\n case '\\n':\n out.write('\\\\');\n out.write('n');\n break;\n case '\\t':\n out.write('\\\\');\n out.write('t');\n break;\n case '\\f':\n out.write('\\\\');\n out.write('f');\n break;\n case '\\r':\n out.write('\\\\');\n out.write('r');\n break;\n default:\n if (ch > 0xf) {\n out.write(\"\\\\u00\" + hex(ch));\n } else {\n out.write(\"\\\\u000\" + hex(ch));\n }\n break;\n }\n } else {\n switch (ch) {\n case '\\'':\n if (escapeSingleQuote) {\n out.write('\\\\');\n }\n out.write('\\'');\n break;\n case '\"':\n out.write('\\\\');\n out.write('\"');\n break;\n case '\\\\':\n out.write('\\\\');\n out.write('\\\\');\n break;\n case '/':\n if (escapeForwardSlash) {\n out.write('\\\\');\n }\n out.write('/');\n break;\n default:\n out.write(ch);\n break;\n }\n }\n }\n }\n \n private static String hex(char ch) {\n return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);\n }\n \n /**\n * Checks if CharSequence contains a search CharSequence irrespective of case, handling {@code null}.\n * Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}.\n *\n * <p>A {@code null} CharSequence will return {@code false}.</p>\n *\n * @param str the CharSequence to check, may be null\n * @param searchStr the CharSequence to find, may be null\n * @return true if the CharSequence contains the search CharSequence irrespective of case or false if not or {@code\n * null} string input\n */\n public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n String str1 = str.toString().toLowerCase();\n String str2 = searchStr.toString().toLowerCase();\n return str1.contains(str2);\n }\n \n /**\n * Checks if CharSequence contains a search CharSequence.\n *\n * @param str the CharSequence to check, may be null\n * @param searchStr the CharSequence to find, may be null\n * @return true if the CharSequence contains the search CharSequence\n */\n public static boolean contains(final CharSequence str, final CharSequence searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return str.toString().contains(searchStr);\n }\n \n /**\n * <p>Checks if none of the CharSequences are blank (\"\") or null and whitespace only..</p>\n *\n * @param css the CharSequences to check, may be null or empty\n * @return {@code true} if none of the CharSequences are blank or null or whitespace only\n */\n public static boolean isNoneBlank(final CharSequence... css) {\n return !isAnyBlank(css);\n }\n \n /**\n * <p>Checks if any one of the CharSequences are blank (\"\") or null and not whitespace only..</p>\n *\n * @param css the CharSequences to check, may be null or empty\n * @return {@code true} if any of the CharSequences are blank or null or whitespace only\n */\n public static boolean isAnyBlank(final CharSequence... css) {\n if (ArrayUtils.isEmpty(css)) {\n return true;\n }\n for (final CharSequence cs : css) {\n if (isBlank(cs)) {\n return true;\n }\n }\n return false;\n }\n \n /**\n * <p>Check if a CharSequence starts with a specified prefix.</p>\n *\n * <p>{@code null}s are handled without exceptions. Two {@code null}\n * references are considered to be equal. The comparison is case sensitive.</p>\n *\n * @param str the CharSequence to check, may be null\n * @param prefix the prefix to find, may be null\n * @return {@code true} if the CharSequence starts with the prefix, case sensitive, or both {@code null}\n * @see java.lang.String#startsWith(String)\n */\n public static boolean startsWith(final CharSequence str, final CharSequence prefix) {\n return startsWith(str, prefix, false);\n }\n \n /**\n * <p>Check if a CharSequence starts with a specified prefix (optionally case insensitive).</p>\n *\n * @param str the CharSequence to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase indicates whether the compare should ignore case (case insensitive) or not.\n * @return {@code true} if the CharSequence starts with the prefix or both {@code null}\n * @see java.lang.String#startsWith(String)\n */\n private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n if (ignoreCase) {\n String lowerCaseStr = str.toString().toLowerCase();\n String lowerCasePrefix = str.toString().toLowerCase();\n return lowerCaseStr.startsWith(lowerCasePrefix);\n } else {\n return str.toString().startsWith(prefix.toString());\n }\n }\n \n /**\n * <p>Case insensitive check if a CharSequence starts with a specified prefix.</p>\n *\n * <p>{@code null}s are handled without exceptions. Two {@code null}\n * references are considered to be equal. The comparison is case insensitive.</p>\n *\n * @param str the CharSequence to check, may be null\n * @param prefix the prefix to find, may be null\n * @return {@code true} if the CharSequence starts with the prefix, case insensitive, or both {@code null}\n * @see java.lang.String#startsWith(String)\n */\n public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) {\n return startsWith(str, prefix, true);\n }\n \n /**\n * <p>Deletes all whitespaces from a String as defined by\n * {@link Character#isWhitespace(char)}.</p>\n *\n * @param str the String to delete whitespace from, may be null\n * @return the String without whitespaces, <code>null</code> if null String input\n */\n public static String deleteWhitespace(String str) {\n if (isEmpty(str)) {\n return str;\n }\n int sz = str.length();\n char[] chs = new char[sz];\n int count = 0;\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n chs[count++] = str.charAt(i);\n }\n }\n if (count == sz) {\n return str;\n }\n return new String(chs, 0, count);\n }\n \n /**\n * <p>Compares two CharSequences, returning {@code true} if they represent\n * equal sequences of characters, ignoring case.</p>\n *\n * @param str1 the first string, may be null\n * @param str2 the second string, may be null\n * @return {@code true} if the string are equal, case insensitive, or both {@code null}\n */\n public static boolean equalsIgnoreCase(String str1, String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n \n /**\n * Splits the provided text into an array with a maximum length, separators specified. If separatorChars is empty,\n * divide by blank.\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings\n */\n @SuppressWarnings(\"checkstyle:WhitespaceAround\")\n public static String[] split(final String str, String separatorChars) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return new String[0];\n }\n if (separatorChars == null) {\n separatorChars = \" +\";\n }\n return str.split(separatorChars);\n }\n \n private static String[] tokenizeLocaleSource(String localeSource) {\n return tokenizeToStringArray(localeSource, \"_ \", false, false);\n }\n \n /**\n * Tokenize the given {@code String} into a {@code String} array via a {@link StringTokenizer}.\n *\n * <p>The given {@code delimiters} string can consist of any number of\n * delimiter characters. Each of those characters can be used to separate tokens. A delimiter is always a single\n * character;\n *\n * @param str the {@code String} to tokenize (potentially {@code null} or empty)\n * @param delimiters the delimiter characters, assembled as a {@code String} (each of the characters is\n * individually considered as a delimiter)\n * @param trimTokens trim the tokens via {@link String#trim()}\n * @param ignoreEmptyTokens omit empty tokens from the result array (only applies to tokens that are empty after\n * trimming; StringTokenizer will not consider subsequent delimiters as token in the first\n * place).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see String#trim()\n */\n public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,\n boolean ignoreEmptyTokens) {\n \n if (str == null) {\n return EMPTY_STRING_ARRAY;\n }\n \n StringTokenizer st = new StringTokenizer(str, delimiters);\n List<String> tokens = new ArrayList<>();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n \n /**\n * Copy the given {@link Collection} into a {@code String} array.\n *\n * <p>The {@code Collection} must contain {@code String} elements only.\n *\n * @param collection the {@code Collection} to copy (potentially {@code null} or empty)\n * @return the resulting {@code String} array\n */\n public static String[] toStringArray(Collection<String> collection) {\n return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY);\n }\n \n /**\n * Check whether the given {@code String} contains actual <em>text</em>.\n *\n * <p>More specifically, this method returns {@code true} if the\n * {@code String} is not {@code null}, its length is greater than 0, and it contains at least one non-whitespace\n * character.\n *\n * @param str the {@code String} to check (may be {@code null})\n * @return {@code true} if the {@code String} is not {@code null}, its length is greater than 0, and it does not\n * contain whitespace only\n * @see Character#isWhitespace\n */\n public static boolean hasText(String str) {\n return (str != null && !str.isEmpty() && containsText(str));\n }\n \n private static boolean containsText(CharSequence str) {\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n \n /**\n * Normalize the path by suppressing sequences like \"path/..\" and inner simple dots.\n *\n * <p>The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n *\n * <p><strong>NOTE</strong> that {@code cleanPath} should not be depended\n * upon in a security context. Other mechanisms should be used to prevent path-traversal issues.\n *\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (!hasLength(path)) {\n return path;\n }\n \n String normalizedPath = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n String pathToUse = normalizedPath;\n \n // Shortcut if there is no work to do\n if (pathToUse.indexOf(DOT) == -1) {\n return pathToUse;\n }\n \n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(':');\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n if (prefix.contains(FOLDER_SEPARATOR)) {\n prefix = \"\";\n } else {\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n \n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n // we never require more elements than pathArray and in the common case the same number\n Deque<String> pathElements = new ArrayDeque<>(pathArray.length);\n int tops = 0;\n \n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (DOT.equals(element)) {\n // Points to current directory - drop it.\n } else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n } else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n } else {\n // Normal path element found.\n pathElements.addFirst(element);\n }\n }\n }\n \n // All path elements stayed the same - shortcut\n if (pathArray.length == pathElements.size()) {\n return normalizedPath;\n }\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.addFirst(TOP_PATH);\n }\n // If nothing else left, at least explicitly point to current path.\n if (pathElements.size() == 1 && pathElements.getLast().isEmpty() && !prefix.endsWith(FOLDER_SEPARATOR)) {\n pathElements.addFirst(DOT);\n }\n \n final String joined = collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n // avoid string concatenation with empty prefix\n return prefix.isEmpty() ? joined : prefix + joined;\n }\n \n /**\n * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV).\n *\n * <p>Useful for {@code toString()} implementations.\n *\n * @param coll the {@code Collection} to convert (potentially {@code null} or empty)\n * @param delim the delimiter to use (typically a \",\")\n * @return the delimited {@code String}\n */\n public static String collectionToDelimitedString(Collection<?> coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n \n /**\n * Convert a {@link Collection} to a delimited {@code String} (e.g. CSV).\n *\n * <p>Useful for {@code toString()} implementations.\n *\n * @param coll the {@code Collection} to convert (potentially {@code null} or empty)\n * @param delim the delimiter to use (typically a \",\")\n * @param prefix the {@code String} to start each element with\n * @param suffix the {@code String} to end each element with\n * @return the delimited {@code String}\n */\n public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {\n \n if (CollectionUtils.isEmpty(coll)) {\n return \"\";\n }\n \n int totalLength = coll.size() * (prefix.length() + suffix.length()) + (coll.size() - 1) * delim.length();\n for (Object element : coll) {\n totalLength += String.valueOf(element).length();\n }\n \n StringBuilder sb = new StringBuilder(totalLength);\n Iterator<?> it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n \n /**\n * Check that the given {@code String} is neither {@code null} nor of length 0.\n *\n * <p>Note: this method returns {@code true} for a {@code String} that\n * purely consists of whitespace.\n *\n * @param str the {@code String} to check (may be {@code null})\n * @return {@code true} if the {@code String} is not {@code null} and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(String str) {\n return (str != null && !str.isEmpty());\n }\n \n /**\n * Take a {@code String} that is a delimited list and convert it into a {@code String} array.\n *\n * <p>A single {@code delimiter} may consist of more than one character,\n * but it will still be considered as a single delimiter string, rather than as bunch of potential delimiter\n * characters, in contrast to {@link #tokenizeToStringArray}.\n *\n * @param str the input {@code String} (potentially {@code null} or empty)\n * @param delimiter the delimiter between elements (this is a single delimiter, rather than a bunch individual\n * delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n \n /**\n * Take a {@code String} that is a delimited list and convert it into a {@code String} array.\n *\n * <p>A single {@code delimiter} may consist of more than one character,\n * but it will still be considered as a single delimiter string, rather than as bunch of potential delimiter\n * characters, in contrast to {@link #tokenizeToStringArray}.\n *\n * @param str the input {@code String} (potentially {@code null} or empty)\n * @param delimiter the delimiter between elements (this is a single delimiter, rather than a bunch individual\n * delimiter characters)\n * @param charsToDelete a set of characters to delete; useful for deleting unwanted line breaks: e.g. \"\\r\\n\\f\" will\n * delete all new lines and line feeds in a {@code String}\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n \n if (str == null) {\n return EMPTY_STRING_ARRAY;\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n \n List<String> result = new ArrayList<>();\n if (delimiter.isEmpty()) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n } else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n \n /**\n * Delete any character in a given {@code String}.\n *\n * @param inString the original {@code String}\n * @param charsToDelete a set of characters to delete. E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting {@code String}\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n \n int lastCharIndex = 0;\n char[] result = new char[inString.length()];\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n result[lastCharIndex++] = c;\n }\n }\n if (lastCharIndex == inString.length()) {\n return inString;\n }\n return new String(result, 0, lastCharIndex);\n }\n \n /**\n * Replace all occurrences of a substring within a string with another string.\n *\n * @param inString {@code String} to examine\n * @param oldPattern {@code String} to replace\n * @param newPattern {@code String} to insert\n * @return a {@code String} with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n int index = inString.indexOf(oldPattern);\n if (index == -1) {\n // no occurrence -> can return input as-is\n return inString;\n }\n \n int capacity = inString.length();\n if (newPattern.length() > oldPattern.length()) {\n capacity += 16;\n }\n StringBuilder sb = new StringBuilder(capacity);\n \n int pos = 0;\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString, pos, index);\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n \n // append any characters to the right of a match\n sb.append(inString, pos, inString.length());\n return sb.toString();\n }\n \n /**\n * Apply the given relative path to the given Java resource path, assuming standard Java folder separation (i.e. \"/\"\n * separators).\n *\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n } else {\n return relativePath;\n }\n }\n \n /**\n * Extract the filename from the given Java resource path, e.g. {@code \"mypath/myfile.txt\" &rarr; \"myfile.txt\"}.\n *\n * @param path the file path (may be {@code null})\n * @return the extracted filename, or {@code null} if none\n */\n \n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n \n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n \n /**\n * Capitalize a {@code String}, changing the first letter to upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n *\n * @param str the {@code String} to capitalize\n * @return the capitalized {@code String}\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n \n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (!hasLength(str)) {\n return str;\n }\n \n char baseChar = str.charAt(0);\n char updatedChar;\n if (capitalize) {\n updatedChar = Character.toUpperCase(baseChar);\n } else {\n updatedChar = Character.toLowerCase(baseChar);\n }\n if (baseChar == updatedChar) {\n return str;\n }\n \n char[] chars = str.toCharArray();\n chars[0] = updatedChar;\n return new String(chars);\n }\n}" }, { "identifier": "getOrDefault", "path": "common/src/main/java/com/alibaba/nacos/common/utils/CollectionUtils.java", "snippet": "public static <T> T getOrDefault(Object obj, int index, T defaultValue) {\n try {\n return (T) get(obj, index);\n } catch (IndexOutOfBoundsException e) {\n return defaultValue;\n }\n}" } ]
import com.alibaba.nacos.common.utils.Preconditions; import com.alibaba.nacos.common.utils.StringUtils; import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.collections.CollectionUtils; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.Environment; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static com.alibaba.nacos.common.utils.CollectionUtils.getOrDefault;
9,002
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.alibaba.nacos.config.server.service.datasource; /** * Properties of external DataSource. * * @author Nacos */ public class ExternalDataSourceProperties { private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String TEST_QUERY = "SELECT 1"; private Integer num; private List<String> url = new ArrayList<>(); private List<String> user = new ArrayList<>(); private List<String> password = new ArrayList<>(); public void setNum(Integer num) { this.num = num; } public void setUrl(List<String> url) { this.url = url; } public void setUser(List<String> user) { this.user = user; } public void setPassword(List<String> password) { this.password = password; } private String jdbcDriverName; public String getJdbcDriverName() { return jdbcDriverName; } public void setJdbcDriverName(String jdbcDriverName) { this.jdbcDriverName = jdbcDriverName; } /** * Build serveral HikariDataSource. * * @param environment {@link Environment} * @param callback Callback function when constructing data source * @return List of {@link HikariDataSource} */ List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) { List<HikariDataSource> dataSources = new ArrayList<>(); Binder.get(environment).bind("db", Bindable.ofInstance(this)); Preconditions.checkArgument(Objects.nonNull(num), "db.num is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(user), "db.user or db.user.[index] is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(password), "db.password or db.password.[index] is null"); for (int index = 0; index < num; index++) { int currentSize = index + 1; Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index); DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.alibaba.nacos.config.server.service.datasource; /** * Properties of external DataSource. * * @author Nacos */ public class ExternalDataSourceProperties { private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String TEST_QUERY = "SELECT 1"; private Integer num; private List<String> url = new ArrayList<>(); private List<String> user = new ArrayList<>(); private List<String> password = new ArrayList<>(); public void setNum(Integer num) { this.num = num; } public void setUrl(List<String> url) { this.url = url; } public void setUser(List<String> user) { this.user = user; } public void setPassword(List<String> password) { this.password = password; } private String jdbcDriverName; public String getJdbcDriverName() { return jdbcDriverName; } public void setJdbcDriverName(String jdbcDriverName) { this.jdbcDriverName = jdbcDriverName; } /** * Build serveral HikariDataSource. * * @param environment {@link Environment} * @param callback Callback function when constructing data source * @return List of {@link HikariDataSource} */ List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) { List<HikariDataSource> dataSources = new ArrayList<>(); Binder.get(environment).bind("db", Bindable.ofInstance(this)); Preconditions.checkArgument(Objects.nonNull(num), "db.num is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(user), "db.user or db.user.[index] is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(password), "db.password or db.password.[index] is null"); for (int index = 0; index < num; index++) { int currentSize = index + 1; Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index); DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
if (StringUtils.isEmpty(poolProperties.getDataSource().getDriverClassName())) {
1
2023-11-02 01:34:09+00:00
12k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \n\t\t@Override\n\t\tpublic Date convert(String source) {\n\t\t\tpatterns.add(\"yyyy-MM-dd HH:mm:ss\");\n\t\t\tpatterns.add(\"yyyy-MM-dd HH:mm\");\n\t\t\t patterns.add(\"yyyy-MM-dd\");\n\t\t\t patterns.add(\"HH:mm\");\n\t\t\t patterns.add(\"yyyy-MM\");\n\t\t\tDate date=null;\n\t\t\tfor (String p : patterns) {\n\t\t\t\ttry {\n\t\t\t\t\tsdf.applyPattern(p);\n\t\t\t\t\tdate=sdf.parse(source);\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (ParseException e) {}\n\t\t\t}\n\t\t\tif(date==null){\n\t\t\t\tthrow new IllegalArgumentException(\"日期格式错误![\" + source + \"]\");\n\t\t\t}\n\t\t\treturn date;\n\t\t}\n\n\t\tpublic void setPatterns(List<String> patterns) {\n\t\t\tthis.patterns = patterns;\n\t\t}\n\n}" }, { "identifier": "AttendceDao", "path": "src/main/java/cn/gson/oasys/model/dao/attendcedao/AttendceDao.java", "snippet": "@Repository\npublic interface AttendceDao extends JpaRepository<Attends, Long>{\n\t\t@Query(\"update Attends a set a.attendsTime=?1 ,a.attendHmtime=?2 ,a.statusId=?3 where a.attendsId=?4 \")\n\t@Modifying(clearAutomatically=true)\n\tInteger updateatttime(Date date,String hourmin,Long statusIdlong ,long attid);\n\t\n\t\t@Query(\"delete from Attends a where a.attendsId=?1\")\n\t\t@Modifying\n\t\tInteger delete(long aid);\n\t\t\n\t//查找某用户当天下班的考勤记录id\n\t@Query(nativeQuery=true,value=\"select a.attends_id from aoa_attends_list a WHERE DATE_format(a.attends_time,'%Y-%m-%d') like %?1% and a.attends_user_id=?2 and a.type_id=9 \")\n\tLong findoffworkid(String date,long userid);\n\t\n\t//查找某用户某天总共的记录\n\t@Query(nativeQuery=true,value=\"SELECT COUNT(*) from aoa_attends_list a WHERE DATE_format(a.attends_time,'%Y-%m-%d') like %?1% and a.attends_user_id=?2 \")\n\tInteger countrecord(String date,long userid);\n\t\n\t//查找某用户某天最新记录用来显示用户最新的类型和考勤时间\n@Query(nativeQuery=true,value=\"SELECT * from aoa_attends_list a WHERE DATE_format(a.attends_time,'%Y-%m-%d') like %?1% and a.attends_user_id=?2 ORDER BY a.attends_time DESC LIMIT 1\")\nAttends findlastest(String date,long userid);\n\n\n@Query(\"from Attends a where a.user.userId=:userId ORDER BY a.attendsTime DESC\")\n Page<Attends> findByUserOrderByAttendsTimeDesc(@Param(\"userId\")long userid,Pageable pa);\n\n//按照某个用户模糊查找\n@Query(\"from Attends a where (a.attendsRemark like %?1% or DATE_format(a.attendsTime,'%Y-%m-%d') like %?1% or a.user.userName like %?1% or \"\n \t\t+ \"a.typeId in (select t.typeId from SystemTypeList t where t.typeName like %?1%) or \"\n \t\t+ \"a.statusId in (select s.statusId from SystemStatusList s where s.statusName like %?1%)) and a.user.userId=?2\")\nPage<Attends> findonemohu(String baseKey,long userid,Pageable pa);\n\n\n\n @Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.attendsTime DESC \")\n Page<Attends> findByUserOrderByAttendsTimeDesc(@Param(\"ids\") List<Long> user,Pageable pa);\n \n //按一些用户模糊查找\n @Query(\"from Attends a where (a.attendsRemark like %?1% or DATE_format(a.attendsTime,'%Y-%m-%d') like %?1% or a.user.userName like %?1% or \"\n \t\t+ \"a.typeId in (select t.typeId from SystemTypeList t where t.typeName like %?1%) or \"\n \t\t+ \"a.statusId in (select s.statusId from SystemStatusList s where s.statusName like %?1%)) and a.user.userId in ?2\")\n Page<Attends> findsomemohu(String baseKey, List<Long> user,Pageable pa);\n//类型\n //通过类型降序排序\n\t@Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.typeId DESC \")\n\tPage<Attends> findByUserOrderByTypeIdDesc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t\n\t//通过类型升序排序\n\t@Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.typeId ASC \")\n\t\tPage<Attends> findByUserOrderByTypeIdAsc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t\n\t//状态\n\t //通过状态降序排序\n\t\t@Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.statusId DESC \")\n\t\tPage<Attends> findByUserOrderByStatusIdDesc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t\t\n\t//通过状态升序排序\n\t @Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.statusId ASC \")\n\t\t\tPage<Attends> findByUserOrderByStatusIdAsc(@Param(\"ids\") List<Long> user,Pageable pa);\n\t \n\t //时间\n\t \t\t//时间降序在开始的时候就已经默认了\n\t //通过时间升序排序\n\t @Query(\"from Attends a where a.user.userId in (:ids) ORDER BY a.attendsTime ASC \")\n\t \t\t\tPage<Attends> findByUserOrderByAttendsTimeAsc(@Param(\"ids\") List<Long> user,Pageable pa);\n \n \n @Query(\"SELECT count(*) from Attends a where DATE_FORMAT(a.attendsTime,'%Y-%m') like %?1% and a.statusId=?2 and a.user.userId=?3\")\n Integer countnum(String month,long statusId,long userid);\n \n @Query(\"SELECT sum(a.holidayDays) from Attends a where DATE_FORMAT(a.holidayStart,'%Y-%m') like %?1% and a.statusId=?2 and a.user.userId=?3\")\n Integer countothernum(String month,long statusId,long userid);\n \n //统计当月上班次数\n @Query(\"SELECT count(*) from Attends a where DATE_FORMAT(a.attendsTime,'%Y-%m') like %?1% and a.user.userId=?2 and a.typeId=8\")\n Integer counttowork(String month,long userid);\n \n //统计当月下班次数\n @Query(\"SELECT count(*) from Attends a where DATE_FORMAT(a.attendsTime,'%Y-%m') like %?1% and a.user.userId=?2 and a.typeId=9\")\n Integer countoffwork(String month,long userid);\n \n @Query(\"FROM Attends a where a.attendsTime>?1 and a.attendsTime<?2 and a.user.userId in ?3\")\n List<Attends> findoneweek(Date start,Date end,List<Long> user);\n \n //更改备注\n @Query(\"update Attends a set a.attendsRemark=?1 where a.attendsId=?2\")\n @Modifying\n Integer updateremark(String attendsRemark,long attendsId);\n \n \n //类型\n //通过类型降序排序\n\t@Query(\"from Attends a where a.user.userId=?1 ORDER BY a.typeId DESC \")\n\tPage<Attends> findByUserOrderByTypeIdDesc(long userid,Pageable pa);\n\t\n\t//通过类型升序排序\n\t@Query(\"from Attends a where a.user.userId=?1 ORDER BY a.typeId ASC \")\n\t\tPage<Attends> findByUserOrderByTypeIdAsc(long userid,Pageable pa);\n\t\n\t//状态\n\t //通过状态降序排序\n\t\t@Query(\"from Attends a where a.user.userId=?1 ORDER BY a.statusId DESC \")\n\t\tPage<Attends> findByUserOrderByStatusIdDesc(long userid,Pageable pa);\n\t\t\n\t//通过状态升序排序\n\t @Query(\"from Attends a where a.user.userId=?1 ORDER BY a.statusId ASC \")\n\t\t\tPage<Attends> findByUserOrderByStatusIdAsc(long userid,Pageable pa);\n\t \n\t //时间\n\t \t\t//时间降序在开始的时候就已经默认了\n\t //通过时间升序排序\n\t \t @Query(\"from Attends a where a.user.userId=?1 ORDER BY a.attendsTime ASC \")\n\t \t\t\tPage<Attends> findByUserOrderByAttendsTimeAsc(long userid,Pageable pa);\n\t\n \n} " }, { "identifier": "AttendceService", "path": "src/main/java/cn/gson/oasys/model/dao/attendcedao/AttendceService.java", "snippet": "@Service\n@Transactional\npublic class AttendceService {\n\n\t@Autowired\n\tAttendceDao attendceDao;\n\n\t// 删除\n\tpublic Integer delete(long aid) {\n\t\treturn attendceDao.delete(aid);\n\t}\n\n\t// 更改考勤时间\n\tpublic Integer updatetime(Date date, String hourmin, Long statusIdlong, long attid) {\n\t\treturn attendceDao.updateatttime(date, hourmin, statusIdlong, attid);\n\t}\n\n\t// 更新备注\n\tpublic Integer updatereamrk(String attendsRemark, long attendsId) {\n\t\treturn attendceDao.updateremark(attendsRemark, attendsId);\n\t}\n\n\t//查找在这个时间段的每个用户的考勤\n//\tpublic Page<Attends> findoneweekatt(int page, String baseKey, Date start,Date end, List<Long> user) {\n//\t\tPageable pa =new PageRequest(page, 10);\n//\t\tif (!StringUtils.isEmpty(baseKey)) {\n//\t\t\t// 模糊查询\n//\t\t}else{\n//\t\t\treturn attendceDao.findoneweek(start, end, user, pa);\n//\t\t}\n//\t\treturn null;\n//\t\t\n//\t}\n\t\n\t// 分页\n\tpublic Page<Attends> paging(int page, String baseKey, List<Long> user, Object type, Object status, Object time) {\n\t\tPageable pa =new PageRequest(page, 10);\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 模糊查询\n\t\t\treturn attendceDao.findsomemohu(baseKey, user, pa);\n\t\t}if (!StringUtils.isEmpty(type)) {\n\t\t\tif(type.toString().equals(\"0\")){\n\t\t\t\t//降序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdDesc(user, pa);\n\t\t\t}else{System.out.println(\"22\");\n\t\t\t\t//升序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdAsc(user, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(status)) {\n\t\t\tif(status.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdDesc(user, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdAsc(user, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(time)) {\n\t\t\tif(time.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(user, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeAsc(user, pa);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(user, pa);\n\t\t}\n\n\n\t}\n\n\t// 单个用户分页\n\tpublic Page<Attends> singlepage(int page, String baseKey, long userid, Object type, Object status, Object time) {\n\t\tPageable pa = new PageRequest(page, 10);\n\t\t//0为降序 1为升序\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 查询\n\t\t\tSystem.out.println(baseKey);\n\t\t\tattendceDao.findonemohu(baseKey, userid, pa);\n\t\t}\n\t\tif (!StringUtils.isEmpty(type)) {\n\t\t\tif(type.toString().equals(\"0\")){\n\t\t\t\t//降序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdDesc(userid, pa);\n\t\t\t}else{\n\t\t\t\t//升序\n\t\t\t\treturn attendceDao.findByUserOrderByTypeIdAsc(userid, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(status)) {\n\t\t\tif(status.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdDesc(userid, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByStatusIdAsc(userid, pa);\n\t\t\t}\n\t\t}\n\t\tif (!StringUtils.isEmpty(time)) {\n\t\t\tif(time.toString().equals(\"0\")){\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(userid, pa);\n\t\t\t}else{\n\t\t\t\treturn attendceDao.findByUserOrderByAttendsTimeAsc(userid, pa);\n\t\t\t}\n\t\t} else {\n\t\t\t// 第几页 以及页里面数据的条数\n\t\t\treturn attendceDao.findByUserOrderByAttendsTimeDesc(userid, pa);\n\t\t}\n\n\t}\n}" }, { "identifier": "StatusDao", "path": "src/main/java/cn/gson/oasys/model/dao/system/StatusDao.java", "snippet": "@Repository\npublic interface StatusDao extends PagingAndSortingRepository<SystemStatusList, Long>{\n\t\n\t//根据模块名和名字查找到唯一对象\n\tSystemStatusList findByStatusModelAndStatusName(String statusModel,String statusName);\n\t\n\t//根据模块名查找到状态集合\n\tList<SystemStatusList> findByStatusModel(String statusModel);\n\t\n\tList<SystemStatusList> findByStatusNameLikeOrStatusModelLike(String name,String name2);\n\t\n\t\n\t\n\t@Query(\"select sl.statusName from SystemStatusList sl where sl.statusId=:id\")\n\tString findname(@Param(\"id\")Long id);\n\t\n\t@Query(\"select sl.statusColor from SystemStatusList sl where sl.statusId=:id\")\n\tString findcolor(@Param(\"id\")Long id);\n\t\n\n}" }, { "identifier": "TypeDao", "path": "src/main/java/cn/gson/oasys/model/dao/system/TypeDao.java", "snippet": "@Repository\npublic interface TypeDao extends PagingAndSortingRepository<SystemTypeList, Long>{\n\t\n\t//根据模块名和名称查找唯一对象\n\tSystemTypeList findByTypeModelAndTypeName(String typeModel,String typeName);\n\t\n\t//根据模块名查找到类型集合\n\tList<SystemTypeList> findByTypeModel(String typeModel);\n\t\n\tList<SystemTypeList> findByTypeNameLikeOrTypeModelLike(String name,String name2);\n\t\n\t\n\t\n\t@Query(\"select type.typeName from SystemTypeList type where type.typeId=:id\")\n\tString findname(@Param(\"id\")Long id);\n\t\n\t\n}" }, { "identifier": "UserDao", "path": "src/main/java/cn/gson/oasys/model/dao/user/UserDao.java", "snippet": "public interface UserDao extends JpaRepository<User, Long>{\n \n\tList<User> findByUserId(Long id);\n\t\n\tList<User> findByFatherId(Long parentid);\n\n\t@Query(\"select u from User u \")\n\tList<User> findAll();\n\n\t@Query(\"select u from User u \")\n\tPage<User> findAllPage(Pageable pa);\n\t\n\tPage<User> findByFatherId(Long parentid,Pageable pa);\n\t\n\t//名字模糊查找\n\t@Query(\"select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 \")\n\tPage<User> findbyFatherId(String name,Long parentid,Pageable pa);\n\n\t//名字模糊查找\n\t@Query(\"select u from User u where (u.userName like %?1% or u.realName like %?1%)\")\n\tPage<User> findAllUserByName(String name,Pageable pa);\n\t\n\t@Query(\"select u from User u where u.userName=:name\")\n\tUser findid(@Param(\"name\")String name);\n\t\n\t@Query(\"select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid\")\n\tLong findpkId(@Param(\"taskid\")Long taskid,@Param(\"userid\")Long userid);\n\t\n\t//根据名字找用户\n\tUser findByUserName(String title);\n\t\n\t//根据用户名模糊查找\n\t@Query(\"from User u where u.userName like %:name% or u.realName like %:name%\")\n\tPage<User> findbyUserNameLike(@Param(\"name\")String name,Pageable pa);\n\t//根据真实姓名模糊查找\n\tPage<User> findByrealNameLike(String title,Pageable pa);\n\t\n\t//根据姓名首拼模糊查找,并分页\n\tPage<User> findByPinyinLike(String pinyin,Pageable pa);\n\t\n\t//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页\n\t@Query(\"from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2\")\n\tPage<User> findSelectUsers(String baseKey,String pinyinm,Pageable pa);\n\t\n\t//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页\n\t@Query(\"from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2\")\n\tPage<User> findUsers(String baseKey,String baseKey2,Pageable pa);\n\t/**\n\t * 用户管理查询可用用户\n\t * @param isLock\n\t * @param pa\n\t * @return\n\t */\n\tPage<User> findByIsLock(Integer isLock,Pageable pa);\n\t\n\t\n\t@Query(\"from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%\")\n\tPage<User> findnamelike(String name,Pageable pa);\n\t\n\tList<User> findByDept(Dept dept);\n\t@Query(\"select u from User u where u.role.roleId=?1\")\n\tList<User> findrole(Long lid); \n\t\n\t/*通过(用户名或者电话号码)+密码查找用户*/\n\t@Query(\"from User u where (u.userName = ?1 or u.userTel = ?1) and u.password =?2\")\n\tUser findOneUser(String userName,String password);\n}" }, { "identifier": "UserService", "path": "src/main/java/cn/gson/oasys/model/dao/user/UserService.java", "snippet": "@Transactional\n@Service\npublic class UserService {\n\n\t@Autowired\n\tUserDao userDao;\n\t\n\t//找到该管理员下面的所有用户并且分页\n\tpublic Page<User> findmyemployuser(int page, String baseKey,long parentid) {\n\t\tPageable pa=new PageRequest(page, 10);\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 模糊查询\n\t\t\treturn userDao.findbyFatherId(baseKey, parentid, pa);\n\t\t}\n\t\telse{\n\t\t\treturn userDao.findByFatherId(parentid, pa);\n\t\t}\n\t\t\n\t}\n\n\t//找到所有用户并且分页\n\tpublic Page<User> findAllmyemployuser(int page, String baseKey) {\n\t\tPageable pa=new PageRequest(page, 10);\n\t\tif (!StringUtils.isEmpty(baseKey)) {\n\t\t\t// 模糊查询\n\t\t\treturn userDao.findAllUserByName(baseKey, pa);\n\t\t}\n\t\telse{\n\t\t\treturn userDao.findAllPage(pa);\n\t\t}\n\n\t}\n}" }, { "identifier": "Attends", "path": "src/main/java/cn/gson/oasys/model/entity/attendce/Attends.java", "snippet": "@Entity\n@Table(name=\"aoa_attends_list\")\npublic class Attends {\n\n\t@Id\n\t@Column(name=\"attends_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long attendsId; \n\t\n\t@Column(name=\"type_id\")\n\tprivate Long typeId; //类型id\n\t\n\t@Column(name=\"status_id\")\n\tprivate Long statusId; //状态id\n\t\n\t@Column(name=\"attends_time\")\n\tprivate Date attendsTime; //考勤时间\n\t\n\t@Column(name=\"attend_hmtime\")\n\tprivate String attendHmtime; //考勤时分\n\t\n\t@Column(name=\"week_ofday\")\n\tprivate String weekOfday; //星期几\n\t\n\t@Column(name=\"attends_ip\")\n\tprivate String attendsIp; //登陆ip\n\t\n\t@Column(name=\"attends_remark\")\n\tprivate String attendsRemark; //考勤备注\n\t\n\t@Column(name=\"holiday_start\")//请假开始时间\n\tprivate Date holidayStart;\n\t\n\t@Column(name=\"holiday_days\")//请假开始时间\n\tprivate Double holidayDays;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"attends_user_id\")\n\tprivate User user;\n\t\n\t\n\t\n\tpublic String getAttendHmtime() {\n\t\treturn attendHmtime;\n\t}\n\n\tpublic void setAttendHmtime(String attendHmtime) {\n\t\tthis.attendHmtime = attendHmtime;\n\t}\n\n\tpublic String getWeekOfday() {\n\t\treturn weekOfday;\n\t}\n\n\tpublic void setWeekOfday(String weekOfday) {\n\t\tthis.weekOfday = weekOfday;\n\t}\n\n\tpublic Long getAttendsId() {\n\t\treturn attendsId;\n\t}\n\n\tpublic void setAttendsId(Long attendsId) {\n\t\tthis.attendsId = attendsId;\n\t}\n\n\tpublic Date getAttendsTime() {\n\t\treturn attendsTime;\n\t}\n\n\tpublic void setAttendsTime(Date attendsTime) {\n\t\tthis.attendsTime = attendsTime;\n\t}\n\n\tpublic String getAttendsIp() {\n\t\treturn attendsIp;\n\t}\n\n\tpublic void setAttendsIp(String attendsIp) {\n\t\tthis.attendsIp = attendsIp;\n\t}\n\n\tpublic String getAttendsRemark() {\n\t\treturn attendsRemark;\n\t}\n\n\tpublic void setAttendsRemark(String attendsRemark) {\n\t\tthis.attendsRemark = attendsRemark;\n\t}\n\n\t\n\t\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Long getTypeId() {\n\t\treturn typeId;\n\t}\n\n\tpublic void setTypeId(Long typeId) {\n\t\tthis.typeId = typeId;\n\t}\n\n\tpublic Long getStatusId() {\n\t\treturn statusId;\n\t}\n\n\tpublic void setStatusId(Long statusId) {\n\t\tthis.statusId = statusId;\n\t}\n\n\tpublic Double getHolidayDays() {\n\t\treturn holidayDays;\n\t}\n\n\tpublic void setHolidayDays(Double holidayDays) {\n\t\tthis.holidayDays = holidayDays;\n\t}\n\t\n\t\n\n\tpublic Date getHolidayStart() {\n\t\treturn holidayStart;\n\t}\n\n\tpublic void setHolidayStart(Date holidayStart) {\n\t\tthis.holidayStart = holidayStart;\n\t}\n\n\tpublic Attends() {\n\t\tsuper();\n\t\t// TODO Auto-generated constructor stub\n\t} \n\t\n\t\n\tpublic Attends(Long typeId, Long statusId, Date attendsTime, String attendsIp, String attendsRemark, User user) {\n\t\tsuper();\n\t\tthis.typeId = typeId;\n\t\tthis.statusId = statusId;\n\t\tthis.attendsTime = attendsTime;\n\t\tthis.attendsIp = attendsIp;\n\t\tthis.attendsRemark = attendsRemark;\n\t\tthis.user = user;\n\t}\n\t\n\tpublic Attends(Long typeId, Long statusId, Date attendsTime, String attendHmtime, String weekOfday,\n\t\t\tString attendsIp, User user) {\n\t\tsuper();\n\t\tthis.typeId = typeId;\n\t\tthis.statusId = statusId;\n\t\tthis.attendsTime = attendsTime;\n\t\tthis.attendHmtime = attendHmtime;\n\t\tthis.weekOfday = weekOfday;\n\t\tthis.attendsIp = attendsIp;\n\t\tthis.user = user;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Attends [attendsId=\" + attendsId + \", typeId=\" + typeId + \", statusId=\" + statusId + \", attendsTime=\"\n\t\t\t\t+ attendsTime + \", attendHmtime=\" + attendHmtime + \", weekOfday=\" + weekOfday + \", attendsIp=\"\n\t\t\t\t+ attendsIp + \", attendsRemark=\" + attendsRemark + \"]\";\n\t}\n\n\t\n\t\n\t\n}" }, { "identifier": "SystemStatusList", "path": "src/main/java/cn/gson/oasys/model/entity/system/SystemStatusList.java", "snippet": "@Entity\n@Table(name = \"aoa_status_list\")\npublic class SystemStatusList {\n\n\t@Id\n\t@Column(name = \"status_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long statusId; // 状态id\n\n\t@Column(name = \"status_name\")\n\t@NotEmpty(message=\"状态名称不能为空\")\n\tprivate String statusName; // 状态名称\n\n\t@Column(name = \"sort_value\")\n\tprivate Integer statusSortValue; // 状态排序值\n\n\t@Column(name = \"status_model\")\n\tprivate String statusModel; // 状态模块\n\n\t@Column(name = \"status_color\")\n\tprivate String statusColor; // 状态颜色\n\t\n\t@Column(name = \"sort_precent\")\n\tprivate String statusPrecent;//百分比\n\n\tpublic SystemStatusList() {\n\t}\n\n\tpublic Long getStatusId() {\n\t\treturn statusId;\n\t}\n\n\tpublic void setStatusId(Long statusId) {\n\t\tthis.statusId = statusId;\n\t}\n\n\tpublic String getStatusName() {\n\t\treturn statusName;\n\t}\n\n\tpublic void setStatusName(String statusName) {\n\t\tthis.statusName = statusName;\n\t}\n\n\tpublic Integer getStatusSortValue() {\n\t\treturn statusSortValue;\n\t}\n\n\tpublic void setStatusSortValue(Integer statusSortValue) {\n\t\tthis.statusSortValue = statusSortValue;\n\t}\n\n\tpublic String getStatusModel() {\n\t\treturn statusModel;\n\t}\n\n\tpublic void setStatusModel(String statusModel) {\n\t\tthis.statusModel = statusModel;\n\t}\n\n\tpublic String getStatusColor() {\n\t\treturn statusColor;\n\t}\n\n\tpublic void setStatusColor(String statusColor) {\n\t\tthis.statusColor = statusColor;\n\t}\n\t\n\t\n\n\tpublic String getStatusPrecent() {\n\t\treturn statusPrecent;\n\t}\n\n\tpublic void setStatusPrecent(String statusPrecent) {\n\t\tthis.statusPrecent = statusPrecent;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SystemStatusList [statusId=\" + statusId + \", statusName=\" + statusName + \", statusSortValue=\"\n\t\t\t\t+ statusSortValue + \", statusModel=\" + statusModel + \", statusColor=\" + statusColor + \", statusPrecent=\"\n\t\t\t\t+ statusPrecent + \"]\";\n\t}\n\n\t\n\n}" }, { "identifier": "SystemTypeList", "path": "src/main/java/cn/gson/oasys/model/entity/system/SystemTypeList.java", "snippet": "@Entity\n@Table(name=\"aoa_type_list\")\npublic class SystemTypeList {\n\t\n\t@Id\n\t@Column(name=\"type_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long typeId;\t\t\t//类型id\n\t\n\t@Column(name=\"type_name\")\n\t@NotEmpty(message=\"类型名称不能为空\")\n\tprivate String typeName;\t\t//类型名字\n\t\n\t@Column(name=\"sort_value\")\n\tprivate Integer typeSortValue;\t//排序值\n\t\n\t@Column(name=\"type_model\")\n\tprivate String typeModel;\t\t//所属模块\n\t\n\t@Column(name=\"type_color\")\n\tprivate String typeColor;\t\t//类型颜色\n\n\tpublic Long getTypeId() {\n\t\treturn typeId;\n\t}\n\n\tpublic void setTypeId(Long typeId) {\n\t\tthis.typeId = typeId;\n\t}\n\n\tpublic String getTypeName() {\n\t\treturn typeName;\n\t}\n\n\tpublic void setTypeName(String typeName) {\n\t\tthis.typeName = typeName;\n\t}\n\n\tpublic Integer getTypeSortValue() {\n\t\treturn typeSortValue;\n\t}\n\n\tpublic void setTypeSortValue(Integer typeSortValue) {\n\t\tthis.typeSortValue = typeSortValue;\n\t}\n\n\tpublic String getTypeModel() {\n\t\treturn typeModel;\n\t}\n\n\tpublic void setTypeModel(String typeModel) {\n\t\tthis.typeModel = typeModel;\n\t}\n\n\tpublic String getTypeColor() {\n\t\treturn typeColor;\n\t}\n\n\tpublic void setTypeColor(String typeColor) {\n\t\tthis.typeColor = typeColor;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SystemTypeList [typeId=\" + typeId + \", typeName=\" + typeName + \", typeSortValue=\" + typeSortValue\n\t\t\t\t+ \", typeModel=\" + typeModel + \", typeColor=\" + typeColor + \"]\";\n\t}\n\t\n\t\n}" }, { "identifier": "User", "path": "src/main/java/cn/gson/oasys/model/entity/user/User.java", "snippet": "@Entity\n@Table(name=\"aoa_user\")\npublic class User {\n\t\n\t@Id\n\t@Column(name=\"user_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long userId;\t\t//用户id\n\t\n\t@Column(name=\"user_name\")\n\t@NotEmpty(message=\"用户名不能为空\")\n\tprivate String userName;\t//登录用户名\n\t\n\t@Column(name=\"user_tel\")\n\t@NotEmpty(message=\"电话不能为空\")\n\tprivate String userTel;\t\t//用户电话\n\t\n\t@Column(name=\"real_name\")\n\t@NotEmpty(message=\"真实姓名不能为空\")\n\tprivate String realName; //真实姓名\n\t\n\tprivate String pinyin;\n\t\n\t@NotEmpty(message=\"邮箱不能为空\")\n\t@Pattern(regexp=\"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\\\.[a-zA-Z0-9_-]{2,3}){1,2})$\",message=\"请填写正确邮箱号\")\n\tprivate String eamil;\t\t//邮件\n\t\n\t@NotEmpty(message=\"地址不能为空\")\n\tprivate String address;\t\t//地址\n\t\n\t@Column(name=\"user_edu\")\n\t@NotEmpty(message=\"学历不能为空\")\n\tprivate String userEdu;\t\t//用户学历\n\t\n\t\n\tprivate Boolean superman=false;\n\t\n\t@Column(name=\"user_school\")\n\t@NotEmpty(message=\"毕业院校不能为空\")\n\tprivate String school;\t\t//学校\n\t\n\t@Column(name=\"user_idcard\")\n\t@Pattern(regexp=\"^(\\\\d{6})(19|20)(\\\\d{2})(1[0-2]|0[1-9])(0[1-9]|[1-2][0-9]|3[0-1])(\\\\d{3})(\\\\d|X|x)?$\",message=\"请填写正确身份证号\")\n\tprivate String idCard;\t\t//用户身份证\n\t\n\t@NotEmpty(message=\"卡号不能为空\")\n\t@Length(min=16, max=19,message=\"银行卡号长度必须在16到19之间!\")\n\tprivate String bank;\t\t//银行\n\t\n\tprivate String sex;\t\t\t//性别\n\t\n\t@Column(name=\"theme_skin\")\n\tprivate String themeSkin;\t//主题皮肤\n\t\n\tprivate Date birth;\t\t\t//生日\n\t\n\t@Column(name=\"user_sign\")\n\tprivate String userSign;\t//用户签名\n\t\n\tprivate String password;\t//用户密码\n\t\n\tprivate String salary;\t\t//用户薪水\n\t\n\t@Column(name=\"img_path\")\n\tprivate String imgPath;\t\t//用户头像路径\n\t\n\t@Column(name=\"hire_time\")\n\tprivate Date hireTime;\t\t//入职时间\n\t\n\t@Column(name=\"is_lock\")\n\tprivate Integer isLock=0;\t\t//该用户是否被禁用\n\t\n\t@Column(name=\"last_login_ip\")\n\tprivate String lastLoginIp;\t//用户最后登录ip;\n\t\n\t@Column(name=\"last_login_time\")\n\tprivate Date lastLoginTime;\t//最后登录时间\n\t\n\t@Column(name=\"modify_time\")\n\tprivate Date modifyTime;\t\t//最后修改时间\n\t\n\t@Column(name=\"modify_user_id\")\n\tprivate Long modifyUserId;\t//最后修改此用户的用户id\n\t\n\t@Column(name=\"father_id\")\n\tprivate Long fatherId;\t\t//上司id\n\t\n\tprivate Integer holiday; //请假天数\n\n\t@ManyToOne()\n\t@JoinColumn(name = \"position_id\")\n\tprivate Position position;\t//外键关联 职位表\n\t\n\t@ManyToOne()\n\t@JoinColumn(name = \"dept_id\")\n\tprivate Dept dept;\t\t\t//外键关联 部门表\n\t\n\t@ManyToOne()\n\t@JoinColumn(name = \"role_id\")\n\tprivate Role role;\t\t\t//外键关联 角色表\n\t\n\n\t@ManyToMany(mappedBy = \"users\")\n\tprivate List<ScheduleList> scheduleLists;\n\t\n\t@ManyToMany(mappedBy = \"users\")\n\tprivate List<Reply> replys;\n\t\n\t@ManyToMany(mappedBy = \"users\")\n\tprivate List<Discuss> discuss;\n\t\n\t@ManyToMany(mappedBy = \"userss\")\n\tprivate List<Note> note;\n\n\t@OneToMany(mappedBy=\"user\",cascade=CascadeType.ALL,fetch=FetchType.EAGER)\n\tprivate Set<Attends> aSet;\n\t\n\t\n\t\n\t\n\tpublic String getPinyin() {\n\t\treturn pinyin;\n\t}\n\n\tpublic void setPinyin(String pinyin) {\n\t\tthis.pinyin = pinyin;\n\t}\n\n\tpublic List<Discuss> getDiscuss() {\n\t\treturn discuss;\n\t}\n\n\tpublic void setDiscuss(List<Discuss> discuss) {\n\t\tthis.discuss = discuss;\n\t}\n\n\tpublic User() {}\t\t\n\n public Set<Attends> getaSet() {\n\t\treturn aSet;\n\t}\n\npublic void setaSet(Set<Attends> aSet) {\n\t\tthis.aSet = aSet;\n\t}\n\n\t\n\tpublic Boolean getSuperman() {\n\treturn superman;\n}\n\npublic void setSuperman(Boolean superman) {\n\tthis.superman = superman;\n}\n\n\tpublic Long getUserId() {\n\t\treturn userId;\n\t}\n\n\tpublic void setUserId(Long userId) {\n\t\tthis.userId = userId;\n\t}\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n\tpublic String getUserTel() {\n\t\treturn userTel;\n\t}\n\n\tpublic void setUserTel(String userTel) {\n\t\tthis.userTel = userTel;\n\t}\n\n\tpublic String getRealName() {\n\t\treturn realName;\n\t}\n\n\tpublic void setRealName(String realName) {\n\t\tthis.realName = realName;\n\t}\n\n\tpublic String getEamil() {\n\t\treturn eamil;\n\t}\n\n\tpublic void setEamil(String eamil) {\n\t\tthis.eamil = eamil;\n\t}\n\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n\n\tpublic String getUserEdu() {\n\t\treturn userEdu;\n\t}\n\n\tpublic void setUserEdu(String userEdu) {\n\t\tthis.userEdu = userEdu;\n\t}\n\n\tpublic String getSchool() {\n\t\treturn school;\n\t}\n\n\tpublic void setSchool(String school) {\n\t\tthis.school = school;\n\t}\n\n\tpublic String getIdCard() {\n\t\treturn idCard;\n\t}\n\n\tpublic void setIdCard(String idCard) {\n\t\tthis.idCard = idCard;\n\t}\n\n\tpublic String getBank() {\n\t\treturn bank;\n\t}\n\n\tpublic void setBank(String bank) {\n\t\tthis.bank = bank;\n\t}\n\n\tpublic String getSex() {\n\t\treturn sex;\n\t}\n\n\tpublic void setSex(String sex) {\n\t\tthis.sex = sex;\n\t}\n\n\tpublic String getThemeSkin() {\n\t\treturn themeSkin;\n\t}\n\n\tpublic void setThemeSkin(String themeSkin) {\n\t\tthis.themeSkin = themeSkin;\n\t}\n\n\tpublic Date getBirth() {\n\t\treturn birth;\n\t}\n\n\tpublic void setBirth(Date birth) {\n\t\tthis.birth = birth;\n\t}\n\n\tpublic String getUserSign() {\n\t\treturn userSign;\n\t}\n\n\tpublic void setUserSign(String userSign) {\n\t\tthis.userSign = userSign;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getSalary() {\n\t\treturn salary;\n\t}\n\n\tpublic void setSalary(String salary) {\n\t\tthis.salary = salary;\n\t}\n\n\tpublic String getImgPath() {\n\t\treturn imgPath;\n\t}\n\n\tpublic void setImgPath(String imgPath) {\n\t\tthis.imgPath = imgPath;\n\t}\n\n\tpublic Date getHireTime() {\n\t\treturn hireTime;\n\t}\n\n\tpublic void setHireTime(Date hireTime) {\n\t\tthis.hireTime = hireTime;\n\t}\n\n\tpublic Integer getIsLock() {\n\t\treturn isLock;\n\t}\n\n\tpublic void setIsLock(Integer isLock) {\n\t\tthis.isLock = isLock;\n\t}\n\n\tpublic String getLastLoginIp() {\n\t\treturn lastLoginIp;\n\t}\n\n\tpublic void setLastLoginIp(String lastLoginIp) {\n\t\tthis.lastLoginIp = lastLoginIp;\n\t}\n\n\tpublic Date getLastLoginTime() {\n\t\treturn lastLoginTime;\n\t}\n\n\tpublic void setLastLoginTime(Date lastLoginTime) {\n\t\tthis.lastLoginTime = lastLoginTime;\n\t}\n\n\tpublic Date getModifyTime() {\n\t\treturn modifyTime;\n\t}\n\n\tpublic void setModifyTime(Date modifyTime) {\n\t\tthis.modifyTime = modifyTime;\n\t}\n\n\tpublic Long getModifyUserId() {\n\t\treturn modifyUserId;\n\t}\n\n\tpublic void setModifyUserId(Long modifyUserId) {\n\t\tthis.modifyUserId = modifyUserId;\n\t}\n\n\tpublic Long getFatherId() {\n\t\treturn fatherId;\n\t}\n\n\tpublic void setFatherId(Long fatherId) {\n\t\tthis.fatherId = fatherId;\n\t}\n\n\tpublic Position getPosition() {\n\t\treturn position;\n\t}\n\n\tpublic void setPosition(Position position) {\n\t\tthis.position = position;\n\t}\n\n\n\tpublic Dept getDept() {\n\t\treturn dept;\n\t}\n\n\n\tpublic void setDept(Dept dept) {\n\t\tthis.dept = dept;\n\t}\n\n\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n\t\n\tpublic List<ScheduleList> getScheduleLists() {\n\t\treturn scheduleLists;\n\t}\n\n\n\tpublic void setScheduleLists(List<ScheduleList> scheduleLists) {\n\t\tthis.scheduleLists = scheduleLists;\n\t}\n\n\n\tpublic List<Reply> getReplys() {\n\t\treturn replys;\n\t}\n\n\n\tpublic void setReplys(List<Reply> replys) {\n\t\tthis.replys = replys;\n\t}\n\n\n\tpublic List<Note> getNote() {\n\t\treturn note;\n\t}\n\n\n\tpublic void setNote(List<Note> note) {\n\t\tthis.note = note;\n\t}\n\n\t\n\n\tpublic Integer getHoliday() {\n\t\treturn holiday;\n\t}\n\n\tpublic void setHoliday(Integer holiday) {\n\t\tthis.holiday = holiday;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [userId=\" + userId + \", userName=\" + userName + \", userTel=\" + userTel + \", realName=\" + realName\n\t\t\t\t+ \", eamil=\" + eamil + \", address=\" + address + \", userEdu=\" + userEdu + \", school=\" + school\n\t\t\t\t+ \", idCard=\" + idCard + \", bank=\" + bank + \", sex=\" + sex + \", themeSkin=\" + themeSkin + \", birth=\"\n\t\t\t\t+ birth + \", userSign=\" + userSign + \", password=\" + password + \", salary=\" + salary + \", imgPath=\"\n\t\t\t\t+ imgPath + \", hireTime=\" + hireTime + \", isLock=\" + isLock + \", lastLoginIp=\" + lastLoginIp\n\t\t\t\t+ \", lastLoginTime=\" + lastLoginTime + \", modifyTime=\" + modifyTime + \", modifyUserId=\" + modifyUserId\n\t\t\t\t+ \", fatherId=\" + fatherId + \", holiday=\" + holiday + \",superman=\" + superman + \",pinyin=\" + pinyin + \"]\";\n\t}\n\t\n\t\n\t\n\t\n}" } ]
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
10,647
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao;
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao;
List<Attends> alist;
7
2023-11-03 02:08:22+00:00
12k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/actions/JarMergeAction.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME = \"fusioner\";\n public static final String MANIFEST_KEY = \"ModFusioner-Version\";\n\n public static Set<PosixFilePermission> filePerms = new HashSet<>();\n\n static {\n filePerms.add(PosixFilePermission.OTHERS_EXECUTE);\n filePerms.add(PosixFilePermission.OTHERS_WRITE);\n filePerms.add(PosixFilePermission.OTHERS_READ);\n filePerms.add(PosixFilePermission.OWNER_EXECUTE);\n filePerms.add(PosixFilePermission.OWNER_WRITE);\n filePerms.add(PosixFilePermission.OWNER_READ);\n filePerms.add(PosixFilePermission.GROUP_EXECUTE);\n filePerms.add(PosixFilePermission.GROUP_WRITE);\n filePerms.add(PosixFilePermission.GROUP_READ);\n }\n\n}" }, { "identifier": "FusionerExtension", "path": "src/main/java/com/hypherionmc/modfusioner/plugin/FusionerExtension.java", "snippet": "public class FusionerExtension {\n\n // Group, or package names that will be used for the final jar\n @Getter\n @Setter\n String packageGroup;\n\n // The name of the final jar\n @Getter @Setter\n String mergedJarName;\n\n // The name of the final jar\n @Getter @Setter\n String jarVersion;\n\n // Duplicate packages that will be de-duplicated upon merge\n @Getter\n List<String> duplicateRelocations;\n\n // The output directory for the merged jar\n @Getter @Setter\n String outputDirectory;\n\n // Forge Project Configuration\n @Getter @Setter\n FusionerExtension.ForgeConfiguration forgeConfiguration;\n\n // Fabric Project Configuration\n @Getter @Setter\n FusionerExtension.FabricConfiguration fabricConfiguration;\n\n // Quilt Project Configuration\n @Getter @Setter\n FusionerExtension.QuiltConfiguration quiltConfiguration;\n\n // Custom Project Configurations\n @Getter\n List<FusionerExtension.CustomConfiguration> customConfigurations = new ArrayList<>();\n\n /**\n * Main extension entry point\n */\n public FusionerExtension() {\n if (packageGroup == null || packageGroup.isEmpty()) {\n if (ModFusionerPlugin.rootProject.hasProperty(\"group\") && ModFusionerPlugin.rootProject.property(\"group\") != null) {\n packageGroup = ModFusionerPlugin.rootProject.property(\"group\").toString();\n } else {\n ModFusionerPlugin.logger.error(\"\\\"group\\\" is not defined and cannot be set automatically\");\n }\n }\n\n if (mergedJarName == null || mergedJarName.isEmpty()) {\n mergedJarName = \"MergedJar\";\n }\n\n if (jarVersion != null && jarVersion.isEmpty()) {\n if (ModFusionerPlugin.rootProject.hasProperty(\"version\") && ModFusionerPlugin.rootProject.property(\"version\") != null) {\n jarVersion = ModFusionerPlugin.rootProject.property(\"version\").toString();\n } else {\n jarVersion = \"1.0\";\n }\n }\n\n if (outputDirectory == null || outputDirectory.isEmpty())\n outputDirectory = \"artifacts/fused\";\n }\n\n /**\n * Add a duplicate package to be de-duplicated\n * @param duplicate - The package name. For example: com.mymod.mylibrary\n */\n public void relocateDuplicate(String duplicate) {\n if (duplicateRelocations == null) duplicateRelocations = new ArrayList<>();\n duplicateRelocations.add(duplicate);\n }\n\n /**\n * Add duplicate packages to be de-duplicated\n * @param duplicates - List of package names. For example: [\"com.mymod.mylibrary\", \"com.google.gson\"]\n */\n public void relocateDuplicates(List<String> duplicates) {\n if (duplicateRelocations == null) duplicateRelocations = new ArrayList<>();\n duplicateRelocations.addAll(duplicates);\n }\n\n /**\n * Set up the forge project configurations\n */\n public FusionerExtension.ForgeConfiguration forge(Closure<FusionerExtension.ForgeConfiguration> closure) {\n forgeConfiguration = new FusionerExtension.ForgeConfiguration();\n ModFusionerPlugin.rootProject.configure(forgeConfiguration, closure);\n return forgeConfiguration;\n }\n\n /**\n * Set up the fabric project configurations\n */\n public FusionerExtension.FabricConfiguration fabric(Closure<FusionerExtension.FabricConfiguration> closure) {\n fabricConfiguration = new FusionerExtension.FabricConfiguration();\n ModFusionerPlugin.rootProject.configure(fabricConfiguration, closure);\n return fabricConfiguration;\n }\n\n /**\n * Set up the quilt project configurations\n */\n public FusionerExtension.QuiltConfiguration quilt(Closure<FusionerExtension.QuiltConfiguration> closure) {\n quiltConfiguration = new FusionerExtension.QuiltConfiguration();\n ModFusionerPlugin.rootProject.configure(quiltConfiguration, closure);\n return quiltConfiguration;\n }\n\n /**\n * Set up custom project configurations\n */\n public FusionerExtension.CustomConfiguration custom(Closure<FusionerExtension.CustomConfiguration> closure) {\n FusionerExtension.CustomConfiguration customConfiguration = new FusionerExtension.CustomConfiguration();\n ModFusionerPlugin.rootProject.configure(customConfiguration, closure);\n\n if (customConfiguration.getProjectName() == null || customConfiguration.getProjectName().isEmpty()) {\n throw new IllegalStateException(\"Custom project configurations need to specify a \\\"projectName\\\"\");\n }\n customConfigurations.add(customConfiguration);\n return customConfiguration;\n }\n\n /**\n * Forge Configuration Structure\n */\n public static class ForgeConfiguration {\n\n // The name of the gradle module that contains the forge code\n @Getter @Setter\n public String projectName = \"forge\";\n\n // The file that will be used as the input\n @Getter @Setter\n String inputFile;\n\n // The name of the task to run to get the input file\n @Getter @Setter\n String inputTaskName;\n\n // Packages that should be relocated, instead of duplicated\n @Getter\n Map<String, String> relocations = new LinkedHashMap<>();\n\n // Forge Mixin Configs\n @Getter\n List<String> mixins = new ArrayList<>();\n\n /**\n * Add a package to relocate, instead of duplicating\n * @param from - The original name of the package. For example: com.google.gson\n * @param to - The new name of the package. For example: forge.com.google.gson\n */\n public void addRelocate(String from, String to) {\n this.relocations.put(from, to);\n }\n\n /**\n * Add a mixin config file\n * @param mixin - The name of the mixin config file\n */\n public void mixin(String mixin) {\n this.mixins.add(mixin);\n }\n }\n\n /**\n * Fabric project configuration\n */\n public static class FabricConfiguration {\n\n // The name of the gradle module that contains the fabric code\n @Getter @Setter\n String projectName = \"fabric\";\n\n // The file that will be used as the input\n @Getter @Setter\n String inputFile;\n\n // The name of the task to run to get the input file\n @Getter @Setter\n String inputTaskName;\n\n // Packages that should be relocated, instead of duplicated\n @Getter\n Map<String, String> relocations = new HashMap<>();\n\n /**\n * Add a package to relocate, instead of duplicating\n * @param from - The original name of the package. For example: com.google.gson\n * @param to - The new name of the package. For example: forge.com.google.gson\n */\n public void addRelocate(String from, String to) {\n this.relocations.put(from, to);\n }\n }\n\n /**\n * Quilt project configuration\n */\n public static class QuiltConfiguration {\n\n // The name of the gradle module that contains the quilt code\n @Getter @Setter\n String projectName = \"quilt\";\n\n // The file that will be used as the input\n @Getter @Setter\n String inputFile;\n\n // The name of the task to run to get the input file\n @Getter @Setter\n String inputTaskName;\n\n // Packages that should be relocated, instead of duplicated\n @Getter\n Map<String, String> relocations = new HashMap<>();\n\n /**\n * Add a package to relocate, instead of duplicating\n * @param from - The original name of the package. For example: com.google.gson\n * @param to - The new name of the package. For example: forge.com.google.gson\n */\n public void addRelocate(String from, String to) {\n this.relocations.put(from, to);\n }\n }\n\n /**\n * Custom project configuration\n */\n public static class CustomConfiguration {\n\n // The name of the gradle module that contains the custom code\n @Getter @Setter\n String projectName;\n\n // The file that will be used as the input\n @Getter @Setter\n String inputFile;\n\n // The name of the task to run to get the input file\n @Getter @Setter\n String inputTaskName;\n\n // Packages that should be relocated, instead of duplicated\n @Getter\n Map<String, String> relocations = new HashMap<>();\n\n /**\n * Add a package to relocate, instead of duplicating\n * @param from - The original name of the package. For example: com.google.gson\n * @param to - The new name of the package. For example: forge.com.google.gson\n */\n public void addRelocation(String from, String to) {\n this.relocations.put(from, to);\n }\n }\n\n}" }, { "identifier": "FileTools", "path": "src/main/java/com/hypherionmc/modfusioner/utils/FileTools.java", "snippet": "public class FileTools {\n\n // Name of the META-INF directory inside the mods\n private static final String META_DIR = \"META-INF\";\n\n // Fabric folder name of \"shaded\" jars\n private static final String JARS_DIR = \"jars\";\n\n // Forge folder name of Jar in Jar jars\n private static final String JARJAR_DIR = \"jarjar\";\n\n // Services folder name\n private static final String SERVICES_DIR = \"services\";\n\n /**\n * Test to see if input file is not null, and exists on the drive\n * @param file - The file to test\n * @return - True if not null and exists on drive\n */\n public static boolean exists(File file) {\n return file != null && file.exists();\n }\n\n /**\n * Create a directory if it doesn't exist\n * @param file - The directory to create\n * @return - The \"now existent\" directory\n */\n public static File getOrCreate(File file) {\n if (!file.exists())\n file.mkdirs();\n\n return file;\n }\n\n /**\n * Move a directory from one location to another\n * @param sourceDir - The directory to copy from\n * @param outDir - The directory to copy to\n * @throws IOException - Thrown if an IO error occurs\n */\n public static void moveDirectory(File sourceDir, File outDir) throws IOException {\n if (!exists(sourceDir))\n return;\n\n File[] files = sourceDir.listFiles();\n if (files == null)\n return;\n\n for (File f : files) {\n File outPath = new File(outDir, f.getName());\n\n if (f.isDirectory()) {\n moveDirectoryInternal(f, outPath);\n }\n\n if (f.isFile()) {\n moveFileInternal(f, outPath, StandardCopyOption.REPLACE_EXISTING);\n }\n }\n }\n\n /**\n * Copied from Apache Commons, with the \"Directory Must Not Exist\" check removed\n * @param srcDir - The source directory\n * @param destDir - The destination directory\n * @throws IOException - Thrown if an IO error occurs\n */\n private static void moveDirectoryInternal(final File srcDir, final File destDir) throws IOException {\n validateMoveParameters(srcDir, destDir);\n requireDirectory(srcDir, \"srcDir\");\n\n if (!srcDir.renameTo(destDir)) {\n if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath() + File.separator)) {\n throw new IOException(\"Cannot move directory: \" + srcDir + \" to a subdirectory of itself: \" + destDir);\n }\n copyDirectory(srcDir, destDir);\n deleteDirectory(srcDir);\n if (srcDir.exists()) {\n throw new IOException(\"Failed to delete original directory '\" + srcDir +\n \"' after copy to '\" + destDir + \"'\");\n }\n }\n }\n\n /**\n * Copied from Apache Commons, with the \"File Must Not Exist\" check removed\n * @param srcFile - The source file\n * @param destFile - The destination file\n * @param copyOptions - {@link StandardCopyOption} to be used with the move process\n * @throws IOException - Thrown if an IO error occurs\n */\n public static void moveFileInternal(final File srcFile, final File destFile, final CopyOption... copyOptions)\n throws IOException {\n validateMoveParameters(srcFile, destFile);\n requireFile(srcFile, \"srcFile\");\n final boolean rename = srcFile.renameTo(destFile);\n if (!rename) {\n copyFile(srcFile, destFile, copyOptions);\n if (!srcFile.delete()) {\n FileUtils.deleteQuietly(destFile);\n throw new IOException(\"Failed to delete original file '\" + srcFile +\n \"' after copy to '\" + destFile + \"'\");\n }\n }\n }\n\n /**\n * Check that input values are not null and that the source file/directory exists\n * @param source - The source file/directory\n * @param destination - The destination file/directory\n * @throws FileNotFoundException - Thrown if the source file/directory does not exist\n */\n private static void validateMoveParameters(final File source, final File destination) throws FileNotFoundException {\n Objects.requireNonNull(source, \"source\");\n Objects.requireNonNull(destination, \"destination\");\n if (!source.exists()) {\n throw new FileNotFoundException(\"Source '\" + source + \"' does not exist\");\n }\n }\n\n /**\n * Check if the source input is a directory\n * @param directory - The source directory\n * @param name - Identifier for the error message\n * @return - Return the directory if it's valid\n */\n private static File requireDirectory(final File directory, final String name) {\n Objects.requireNonNull(directory, name);\n if (!directory.isDirectory()) {\n throw new IllegalArgumentException(\"Parameter '\" + name + \"' is not a directory: '\" + directory + \"'\");\n }\n return directory;\n }\n\n /**\n * Check if the source input is not a directory\n * @param file - The source file\n * @param name - Identifier for the error message\n * @return - Return the file if it's valid\n */\n private static File requireFile(final File file, final String name) {\n Objects.requireNonNull(file, name);\n if (!file.isFile()) {\n throw new IllegalArgumentException(\"Parameter '\" + name + \"' is not a file: \" + file);\n }\n return file;\n }\n\n /**\n * Get a list of embedded jar files from the input jar\n * @param dir - The directory the jar was extracted to\n * @return - List of embedded jars\n */\n @NotNull\n public static List<File> embeddedJars(File dir) {\n List<File> returnJars = new ArrayList<>();\n\n // Directories\n File metaInf = new File(dir, META_DIR);\n File jarsDir = new File(metaInf, JARS_DIR);\n File jarJarDir = new File(metaInf, JARJAR_DIR);\n\n if (jarsDir.exists()) {\n File[] list = jarsDir.listFiles();\n\n if (list != null) {\n for (File jar : list) {\n if (FilenameUtils.getExtension(jar.getName()).equalsIgnoreCase(\"jar\"))\n returnJars.add(jar);\n }\n }\n }\n\n if (jarJarDir.exists()) {\n File[] list = jarJarDir.listFiles();\n\n if (list != null) {\n for (File jar : list) {\n if (FilenameUtils.getExtension(jar.getName()).equalsIgnoreCase(\"jar\"))\n returnJars.add(jar);\n }\n }\n }\n\n return returnJars;\n }\n\n /**\n * Get all text files from the input jar\n * @param dir - The directory the jar was extracted to\n * @return - List of text files\n */\n @NotNull\n public static List<File> getTextFiles(@NotNull File dir) throws IOException {\n List<File> returnFiles = new ArrayList<>();\n File[] list = dir.listFiles();\n if (list == null)\n return returnFiles;\n\n for (File file : list) {\n if (file.isDirectory()) {\n returnFiles.addAll(getTextFiles(file));\n } else {\n if (!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase(\"class\")) {\n if (!FileChecks.isBinary(file))\n returnFiles.add(file);\n }\n }\n }\n\n return returnFiles;\n }\n\n /**\n * Get a list of mixin configurations from the input jar\n * @param dir - The directory the jar was extracted to\n * @param includeRefmaps - Should reference maps be included in the search\n * @return - List of mixin configs and optionally refmaps\n * @throws IOException - Thrown when an IO error occurs\n */\n @NotNull\n public static List<File> getMixins(@NotNull File dir, boolean includeRefmaps) throws IOException {\n List<File> files = getTextFiles(dir);\n List<File> returnMixins = new ArrayList<>();\n\n for (File file : files) {\n if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase(\"json\")) {\n String text = FileUtils.readFileToString(file, Charset.defaultCharset());\n\n if (includeRefmaps) {\n if (text.contains(\"\\\"mappings\\\":\") || text.contains(\"\\\"data\\\":\")) {\n returnMixins.add(file);\n continue;\n }\n }\n\n if (text.contains(\"\\\"package\\\":\")) {\n returnMixins.add(file);\n }\n }\n }\n\n return returnMixins;\n }\n\n /**\n * Get a list of refmaps from input jar\n * @param dir - The directory the jar was extracted to\n * @return - A list of mixin refmaps\n * @throws IOException - Thrown when an IO error occurs\n */\n @NotNull\n public static List<File> getRefmaps(@NotNull File dir) throws IOException {\n List<File> files = getTextFiles(dir);\n List<File> refmaps = new ArrayList<>();\n\n for (File file : files) {\n if (FilenameUtils.getExtension(file.getName()).equals(\"json\")) {\n String text = FileUtils.readFileToString(file, Charset.defaultCharset());\n if (text.contains(\"\\\"mappings\\\":\") || text.contains(\"\\\"data\\\":\"))\n refmaps.add(file);\n }\n }\n\n return refmaps;\n }\n\n /**\n * Get a list of accesswideners from the input jar\n * @param dir - The directory the jar was extracted to\n * @return - A list of access wideners\n * @throws IOException - Thrown when an IO error occurs\n */\n @NotNull\n public static List<File> getAccessWideners(@NotNull File dir) throws IOException {\n List<File> files = getTextFiles(dir);\n List<File> wideners = new ArrayList<>();\n\n for (File file : files) {\n if (FilenameUtils.getExtension(file.getName()).equals(\"accesswidener\")) {\n wideners.add(file);\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n Scanner scanner = new Scanner(fis);\n if (scanner.hasNext()) {\n if (scanner.nextLine().startsWith(\"accessWidener\"))\n wideners.add(file);\n }\n scanner.close();\n fis.close();\n }\n\n return wideners;\n }\n\n /**\n * Get a list of platform services from the input jar\n * @param dir - The directory the jar was extracted to\n * @param group - The group to search for\n * @return - A list of service files\n */\n @NotNull\n public static List<File> getPlatformServices(@NotNull File dir, @NotNull String group) {\n List<File> services = new ArrayList<>();\n\n File metaInf = new File(dir, META_DIR);\n File servicesLocation = new File(metaInf, SERVICES_DIR);\n\n if (servicesLocation.exists()) {\n File[] list = servicesLocation.listFiles();\n if (list != null) {\n for (File service : list) {\n if (FilenameUtils.getBaseName(service.getName()).contains(group))\n services.add(service);\n }\n }\n }\n\n return services;\n }\n\n /**\n * Get the first directory from a file name\n * @param fileName - The input file name\n * @return - The name of the first directory specified in the file name\n */\n @NotNull\n public static String getFirstDirectory(@NotNull String fileName) {\n int end = fileName.indexOf(File.separator);\n if (end != -1) {\n return fileName.substring(0, end);\n }\n end = fileName.indexOf(\"/\");\n if (end != -1) {\n return fileName.substring(0, end);\n }\n return \"\";\n }\n\n /**\n * Create a directory if it doesn't exist, or delete and recreate it if it does\n * @param dir - The input directory\n * @return - The new directory\n * @throws IOException - Thrown when an IO exception occurs\n */\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n @NotNull\n public static File createOrReCreate(@NotNull File dir) throws IOException {\n if (dir.exists())\n FileUtils.deleteQuietly(dir);\n\n if (!dir.exists())\n dir.mkdirs();\n\n return dir;\n }\n\n /**\n * Create a file if it doesn't exist, or delete and recreate it if it does\n * @param dir - The input directory\n * @return - The new file\n * @throws IOException - Thrown when an IO error occurs\n */\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n @NotNull\n public static File createOrReCreateF(@NotNull File dir) throws IOException {\n if (dir.exists())\n FileUtils.deleteQuietly(dir);\n\n if (!dir.exists())\n dir.createNewFile();\n\n return dir;\n }\n\n public static File resolveFile(Project project, Object obj) {\n if (obj == null) {\n throw new NullPointerException(\"Null Path\");\n }\n\n if (obj instanceof String) {\n Task t = project.getTasks().getByName((String) obj);\n if (t instanceof AbstractArchiveTask)\n return ((AbstractArchiveTask)t).getArchiveFile().get().getAsFile();\n }\n\n if (obj instanceof File) {\n return (File) obj;\n }\n\n if (obj instanceof AbstractArchiveTask) {\n return ((AbstractArchiveTask)obj).getArchiveFile().get().getAsFile();\n }\n return project.file(obj);\n }\n}" }, { "identifier": "logger", "path": "src/main/java/com/hypherionmc/modfusioner/plugin/ModFusionerPlugin.java", "snippet": "public static Logger logger;" }, { "identifier": "modFusionerExtension", "path": "src/main/java/com/hypherionmc/modfusioner/plugin/ModFusionerPlugin.java", "snippet": "public static FusionerExtension modFusionerExtension;" }, { "identifier": "FileTools", "path": "src/main/java/com/hypherionmc/modfusioner/utils/FileTools.java", "snippet": "public class FileTools {\n\n // Name of the META-INF directory inside the mods\n private static final String META_DIR = \"META-INF\";\n\n // Fabric folder name of \"shaded\" jars\n private static final String JARS_DIR = \"jars\";\n\n // Forge folder name of Jar in Jar jars\n private static final String JARJAR_DIR = \"jarjar\";\n\n // Services folder name\n private static final String SERVICES_DIR = \"services\";\n\n /**\n * Test to see if input file is not null, and exists on the drive\n * @param file - The file to test\n * @return - True if not null and exists on drive\n */\n public static boolean exists(File file) {\n return file != null && file.exists();\n }\n\n /**\n * Create a directory if it doesn't exist\n * @param file - The directory to create\n * @return - The \"now existent\" directory\n */\n public static File getOrCreate(File file) {\n if (!file.exists())\n file.mkdirs();\n\n return file;\n }\n\n /**\n * Move a directory from one location to another\n * @param sourceDir - The directory to copy from\n * @param outDir - The directory to copy to\n * @throws IOException - Thrown if an IO error occurs\n */\n public static void moveDirectory(File sourceDir, File outDir) throws IOException {\n if (!exists(sourceDir))\n return;\n\n File[] files = sourceDir.listFiles();\n if (files == null)\n return;\n\n for (File f : files) {\n File outPath = new File(outDir, f.getName());\n\n if (f.isDirectory()) {\n moveDirectoryInternal(f, outPath);\n }\n\n if (f.isFile()) {\n moveFileInternal(f, outPath, StandardCopyOption.REPLACE_EXISTING);\n }\n }\n }\n\n /**\n * Copied from Apache Commons, with the \"Directory Must Not Exist\" check removed\n * @param srcDir - The source directory\n * @param destDir - The destination directory\n * @throws IOException - Thrown if an IO error occurs\n */\n private static void moveDirectoryInternal(final File srcDir, final File destDir) throws IOException {\n validateMoveParameters(srcDir, destDir);\n requireDirectory(srcDir, \"srcDir\");\n\n if (!srcDir.renameTo(destDir)) {\n if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath() + File.separator)) {\n throw new IOException(\"Cannot move directory: \" + srcDir + \" to a subdirectory of itself: \" + destDir);\n }\n copyDirectory(srcDir, destDir);\n deleteDirectory(srcDir);\n if (srcDir.exists()) {\n throw new IOException(\"Failed to delete original directory '\" + srcDir +\n \"' after copy to '\" + destDir + \"'\");\n }\n }\n }\n\n /**\n * Copied from Apache Commons, with the \"File Must Not Exist\" check removed\n * @param srcFile - The source file\n * @param destFile - The destination file\n * @param copyOptions - {@link StandardCopyOption} to be used with the move process\n * @throws IOException - Thrown if an IO error occurs\n */\n public static void moveFileInternal(final File srcFile, final File destFile, final CopyOption... copyOptions)\n throws IOException {\n validateMoveParameters(srcFile, destFile);\n requireFile(srcFile, \"srcFile\");\n final boolean rename = srcFile.renameTo(destFile);\n if (!rename) {\n copyFile(srcFile, destFile, copyOptions);\n if (!srcFile.delete()) {\n FileUtils.deleteQuietly(destFile);\n throw new IOException(\"Failed to delete original file '\" + srcFile +\n \"' after copy to '\" + destFile + \"'\");\n }\n }\n }\n\n /**\n * Check that input values are not null and that the source file/directory exists\n * @param source - The source file/directory\n * @param destination - The destination file/directory\n * @throws FileNotFoundException - Thrown if the source file/directory does not exist\n */\n private static void validateMoveParameters(final File source, final File destination) throws FileNotFoundException {\n Objects.requireNonNull(source, \"source\");\n Objects.requireNonNull(destination, \"destination\");\n if (!source.exists()) {\n throw new FileNotFoundException(\"Source '\" + source + \"' does not exist\");\n }\n }\n\n /**\n * Check if the source input is a directory\n * @param directory - The source directory\n * @param name - Identifier for the error message\n * @return - Return the directory if it's valid\n */\n private static File requireDirectory(final File directory, final String name) {\n Objects.requireNonNull(directory, name);\n if (!directory.isDirectory()) {\n throw new IllegalArgumentException(\"Parameter '\" + name + \"' is not a directory: '\" + directory + \"'\");\n }\n return directory;\n }\n\n /**\n * Check if the source input is not a directory\n * @param file - The source file\n * @param name - Identifier for the error message\n * @return - Return the file if it's valid\n */\n private static File requireFile(final File file, final String name) {\n Objects.requireNonNull(file, name);\n if (!file.isFile()) {\n throw new IllegalArgumentException(\"Parameter '\" + name + \"' is not a file: \" + file);\n }\n return file;\n }\n\n /**\n * Get a list of embedded jar files from the input jar\n * @param dir - The directory the jar was extracted to\n * @return - List of embedded jars\n */\n @NotNull\n public static List<File> embeddedJars(File dir) {\n List<File> returnJars = new ArrayList<>();\n\n // Directories\n File metaInf = new File(dir, META_DIR);\n File jarsDir = new File(metaInf, JARS_DIR);\n File jarJarDir = new File(metaInf, JARJAR_DIR);\n\n if (jarsDir.exists()) {\n File[] list = jarsDir.listFiles();\n\n if (list != null) {\n for (File jar : list) {\n if (FilenameUtils.getExtension(jar.getName()).equalsIgnoreCase(\"jar\"))\n returnJars.add(jar);\n }\n }\n }\n\n if (jarJarDir.exists()) {\n File[] list = jarJarDir.listFiles();\n\n if (list != null) {\n for (File jar : list) {\n if (FilenameUtils.getExtension(jar.getName()).equalsIgnoreCase(\"jar\"))\n returnJars.add(jar);\n }\n }\n }\n\n return returnJars;\n }\n\n /**\n * Get all text files from the input jar\n * @param dir - The directory the jar was extracted to\n * @return - List of text files\n */\n @NotNull\n public static List<File> getTextFiles(@NotNull File dir) throws IOException {\n List<File> returnFiles = new ArrayList<>();\n File[] list = dir.listFiles();\n if (list == null)\n return returnFiles;\n\n for (File file : list) {\n if (file.isDirectory()) {\n returnFiles.addAll(getTextFiles(file));\n } else {\n if (!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase(\"class\")) {\n if (!FileChecks.isBinary(file))\n returnFiles.add(file);\n }\n }\n }\n\n return returnFiles;\n }\n\n /**\n * Get a list of mixin configurations from the input jar\n * @param dir - The directory the jar was extracted to\n * @param includeRefmaps - Should reference maps be included in the search\n * @return - List of mixin configs and optionally refmaps\n * @throws IOException - Thrown when an IO error occurs\n */\n @NotNull\n public static List<File> getMixins(@NotNull File dir, boolean includeRefmaps) throws IOException {\n List<File> files = getTextFiles(dir);\n List<File> returnMixins = new ArrayList<>();\n\n for (File file : files) {\n if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase(\"json\")) {\n String text = FileUtils.readFileToString(file, Charset.defaultCharset());\n\n if (includeRefmaps) {\n if (text.contains(\"\\\"mappings\\\":\") || text.contains(\"\\\"data\\\":\")) {\n returnMixins.add(file);\n continue;\n }\n }\n\n if (text.contains(\"\\\"package\\\":\")) {\n returnMixins.add(file);\n }\n }\n }\n\n return returnMixins;\n }\n\n /**\n * Get a list of refmaps from input jar\n * @param dir - The directory the jar was extracted to\n * @return - A list of mixin refmaps\n * @throws IOException - Thrown when an IO error occurs\n */\n @NotNull\n public static List<File> getRefmaps(@NotNull File dir) throws IOException {\n List<File> files = getTextFiles(dir);\n List<File> refmaps = new ArrayList<>();\n\n for (File file : files) {\n if (FilenameUtils.getExtension(file.getName()).equals(\"json\")) {\n String text = FileUtils.readFileToString(file, Charset.defaultCharset());\n if (text.contains(\"\\\"mappings\\\":\") || text.contains(\"\\\"data\\\":\"))\n refmaps.add(file);\n }\n }\n\n return refmaps;\n }\n\n /**\n * Get a list of accesswideners from the input jar\n * @param dir - The directory the jar was extracted to\n * @return - A list of access wideners\n * @throws IOException - Thrown when an IO error occurs\n */\n @NotNull\n public static List<File> getAccessWideners(@NotNull File dir) throws IOException {\n List<File> files = getTextFiles(dir);\n List<File> wideners = new ArrayList<>();\n\n for (File file : files) {\n if (FilenameUtils.getExtension(file.getName()).equals(\"accesswidener\")) {\n wideners.add(file);\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n Scanner scanner = new Scanner(fis);\n if (scanner.hasNext()) {\n if (scanner.nextLine().startsWith(\"accessWidener\"))\n wideners.add(file);\n }\n scanner.close();\n fis.close();\n }\n\n return wideners;\n }\n\n /**\n * Get a list of platform services from the input jar\n * @param dir - The directory the jar was extracted to\n * @param group - The group to search for\n * @return - A list of service files\n */\n @NotNull\n public static List<File> getPlatformServices(@NotNull File dir, @NotNull String group) {\n List<File> services = new ArrayList<>();\n\n File metaInf = new File(dir, META_DIR);\n File servicesLocation = new File(metaInf, SERVICES_DIR);\n\n if (servicesLocation.exists()) {\n File[] list = servicesLocation.listFiles();\n if (list != null) {\n for (File service : list) {\n if (FilenameUtils.getBaseName(service.getName()).contains(group))\n services.add(service);\n }\n }\n }\n\n return services;\n }\n\n /**\n * Get the first directory from a file name\n * @param fileName - The input file name\n * @return - The name of the first directory specified in the file name\n */\n @NotNull\n public static String getFirstDirectory(@NotNull String fileName) {\n int end = fileName.indexOf(File.separator);\n if (end != -1) {\n return fileName.substring(0, end);\n }\n end = fileName.indexOf(\"/\");\n if (end != -1) {\n return fileName.substring(0, end);\n }\n return \"\";\n }\n\n /**\n * Create a directory if it doesn't exist, or delete and recreate it if it does\n * @param dir - The input directory\n * @return - The new directory\n * @throws IOException - Thrown when an IO exception occurs\n */\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n @NotNull\n public static File createOrReCreate(@NotNull File dir) throws IOException {\n if (dir.exists())\n FileUtils.deleteQuietly(dir);\n\n if (!dir.exists())\n dir.mkdirs();\n\n return dir;\n }\n\n /**\n * Create a file if it doesn't exist, or delete and recreate it if it does\n * @param dir - The input directory\n * @return - The new file\n * @throws IOException - Thrown when an IO error occurs\n */\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n @NotNull\n public static File createOrReCreateF(@NotNull File dir) throws IOException {\n if (dir.exists())\n FileUtils.deleteQuietly(dir);\n\n if (!dir.exists())\n dir.createNewFile();\n\n return dir;\n }\n\n public static File resolveFile(Project project, Object obj) {\n if (obj == null) {\n throw new NullPointerException(\"Null Path\");\n }\n\n if (obj instanceof String) {\n Task t = project.getTasks().getByName((String) obj);\n if (t instanceof AbstractArchiveTask)\n return ((AbstractArchiveTask)t).getArchiveFile().get().getAsFile();\n }\n\n if (obj instanceof File) {\n return (File) obj;\n }\n\n if (obj instanceof AbstractArchiveTask) {\n return ((AbstractArchiveTask)obj).getArchiveFile().get().getAsFile();\n }\n return project.file(obj);\n }\n}" } ]
import com.hypherionmc.jarmanager.JarManager; import com.hypherionmc.jarrelocator.Relocation; import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.utils.FileTools; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.Deflater; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.logger; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.utils.FileTools.*;
9,864
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.actions; /** * @author HypherionSA * The main logic class of the plugin. This class is responsible for * extracting, remapping, de-duplicating and finally merging the input jars */ @RequiredArgsConstructor(staticName = "of") public class JarMergeAction { // File Inputs @Setter private File forgeInput; @Setter private File fabricInput; @Setter private File quiltInput; private final Map<FusionerExtension.CustomConfiguration, File> customInputs; // Relocations @Setter private Map<String, String> forgeRelocations; @Setter private Map<String, String> fabricRelocations; @Setter private Map<String, String> quiltRelocations; // Mixins @Setter private List<String> forgeMixins; // Custom private Map<FusionerExtension.CustomConfiguration, Map<File, File>> customTemps; // Relocations private final List<String> ignoredPackages; private final Map<String, String> ignoredDuplicateRelocations = new HashMap<>(); private final Map<String, String> removeDuplicateRelocationResources = new HashMap<>(); private final List<Relocation> relocations = new ArrayList<>(); JarManager jarManager = JarManager.getInstance(); // Settings private final String group; private final File tempDir; private final String outJarName; /** * Start the merge process * @param skipIfExists - Should the task be cancelled if an existing merged jar is found * @return - The fully merged jar file * @throws IOException - Thrown when an IO Exception occurs */ public File mergeJars(boolean skipIfExists) throws IOException { jarManager.setCompressionLevel(Deflater.BEST_COMPRESSION); File outJar = new File(tempDir, outJarName); if (outJar.exists()) { if (skipIfExists) return outJar; outJar.delete(); } logger.lifecycle("Cleaning output Directory");
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.actions; /** * @author HypherionSA * The main logic class of the plugin. This class is responsible for * extracting, remapping, de-duplicating and finally merging the input jars */ @RequiredArgsConstructor(staticName = "of") public class JarMergeAction { // File Inputs @Setter private File forgeInput; @Setter private File fabricInput; @Setter private File quiltInput; private final Map<FusionerExtension.CustomConfiguration, File> customInputs; // Relocations @Setter private Map<String, String> forgeRelocations; @Setter private Map<String, String> fabricRelocations; @Setter private Map<String, String> quiltRelocations; // Mixins @Setter private List<String> forgeMixins; // Custom private Map<FusionerExtension.CustomConfiguration, Map<File, File>> customTemps; // Relocations private final List<String> ignoredPackages; private final Map<String, String> ignoredDuplicateRelocations = new HashMap<>(); private final Map<String, String> removeDuplicateRelocationResources = new HashMap<>(); private final List<Relocation> relocations = new ArrayList<>(); JarManager jarManager = JarManager.getInstance(); // Settings private final String group; private final File tempDir; private final String outJarName; /** * Start the merge process * @param skipIfExists - Should the task be cancelled if an existing merged jar is found * @return - The fully merged jar file * @throws IOException - Thrown when an IO Exception occurs */ public File mergeJars(boolean skipIfExists) throws IOException { jarManager.setCompressionLevel(Deflater.BEST_COMPRESSION); File outJar = new File(tempDir, outJarName); if (outJar.exists()) { if (skipIfExists) return outJar; outJar.delete(); } logger.lifecycle("Cleaning output Directory");
FileTools.createOrReCreate(tempDir);
5
2023-11-03 23:19:08+00:00
12k
data-harness-cloud/data_harness-be
application-webadmin/src/main/java/supie/webadmin/app/model/PlanningClassification.java
[ { "identifier": "SysUser", "path": "application-webadmin/src/main/java/supie/webadmin/upms/model/SysUser.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(value = \"sdt_sys_user\")\npublic class SysUser extends BaseModel {\n\n /**\n * 用户Id。\n */\n @TableId(value = \"user_id\")\n private Long userId;\n\n /**\n * 登录用户名。\n */\n private String loginName;\n\n /**\n * 用户密码。\n */\n private String password;\n\n /**\n * 用户显示名称。\n */\n private String showName;\n\n /**\n * 用户部门Id。\n */\n private Long deptId;\n\n /**\n * 用户类型(0: 管理员 1: 系统管理用户 2: 系统业务用户)。\n */\n private Integer userType;\n\n /**\n * 用户头像的Url。\n */\n @UploadFlagColumn(storeType = UploadStoreTypeEnum.LOCAL_SYSTEM)\n private String headImageUrl;\n\n /**\n * 用户状态(0: 正常 1: 锁定)。\n */\n private Integer userStatus;\n\n /**\n * 逻辑删除标记字段(1: 正常 -1: 已删除)。\n */\n @TableLogic\n private Integer deletedFlag;\n\n /**\n * createTime 范围过滤起始值(>=)。\n */\n @TableField(exist = false)\n private String createTimeStart;\n\n /**\n * createTime 范围过滤结束值(<=)。\n */\n @TableField(exist = false)\n private String createTimeEnd;\n\n /**\n * 多对多用户部门岗位数据集合。\n */\n @RelationManyToMany(\n relationMasterIdField = \"userId\",\n relationModelClass = SysUserPost.class)\n @TableField(exist = false)\n private List<SysUserPost> sysUserPostList;\n\n /**\n * 多对多用户角色数据集合。\n */\n @RelationManyToMany(\n relationMasterIdField = \"userId\",\n relationModelClass = SysUserRole.class)\n @TableField(exist = false)\n private List<SysUserRole> sysUserRoleList;\n\n /**\n * 多对多用户数据权限数据集合。\n */\n @RelationManyToMany(\n relationMasterIdField = \"userId\",\n relationModelClass = SysDataPermUser.class)\n @TableField(exist = false)\n private List<SysDataPermUser> sysDataPermUserList;\n\n /**\n * userId 的多对多关联表数据对象。\n */\n @TableField(exist = false)\n private ProjectMember projectMember;\n\n @RelationDict(\n masterIdField = \"deptId\",\n slaveModelClass = SysDept.class,\n slaveIdField = \"deptId\",\n slaveNameField = \"deptName\")\n @TableField(exist = false)\n private Map<String, Object> deptIdDictMap;\n\n @RelationConstDict(\n masterIdField = \"userType\",\n constantDictClass = SysUserType.class)\n @TableField(exist = false)\n private Map<String, Object> userTypeDictMap;\n\n @RelationConstDict(\n masterIdField = \"userStatus\",\n constantDictClass = SysUserStatus.class)\n @TableField(exist = false)\n private Map<String, Object> userStatusDictMap;\n\n @Mapper\n public interface SysUserModelMapper extends BaseModelMapper<SysUserVo, SysUser> {\n /**\n * 转换Vo对象到实体对象。\n *\n * @param sysUserVo 域对象。\n * @return 实体对象。\n */\n @Mapping(target = \"projectMember\", expression = \"java(mapToBean(sysUserVo.getProjectMember(), supie.webadmin.app.model.ProjectMember.class))\")\n @Mapping(target = \"sysUserRoleList\", expression = \"java(mapToBean(sysUserVo.getSysUserRoleList(), supie.webadmin.upms.model.SysUserRole.class))\")\n @Mapping(target = \"sysUserPostList\", expression = \"java(mapToBean(sysUserVo.getSysUserPostList(), supie.webadmin.upms.model.SysUserPost.class))\")\n @Mapping(target = \"sysDataPermUserList\", expression = \"java(mapToBean(sysUserVo.getSysDataPermUserList(), supie.webadmin.upms.model.SysDataPermUser.class))\")\n @Override\n SysUser toModel(SysUserVo sysUserVo);\n /**\n * 转换实体对象到VO对象。\n *\n * @param sysUser 实体对象。\n * @return 域对象。\n */\n @Mapping(target = \"projectMember\", expression = \"java(beanToMap(sysUser.getProjectMember(), false))\")\n @Mapping(target = \"sysUserRoleList\", expression = \"java(beanToMap(sysUser.getSysUserRoleList(), false))\")\n @Mapping(target = \"sysUserPostList\", expression = \"java(beanToMap(sysUser.getSysUserPostList(), false))\")\n @Mapping(target = \"sysDataPermUserList\", expression = \"java(beanToMap(sysUser.getSysDataPermUserList(), false))\")\n @Override\n SysUserVo fromModel(SysUser sysUser);\n }\n public static final SysUserModelMapper INSTANCE = Mappers.getMapper(SysUserModelMapper.class);\n}" }, { "identifier": "MyCommonUtil", "path": "common/common-core/src/main/java/supie/common/core/util/MyCommonUtil.java", "snippet": "public class MyCommonUtil {\n\n private static final Validator VALIDATOR;\n\n static {\n VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();\n }\n\n /**\n * 创建uuid。\n *\n * @return 返回uuid。\n */\n public static String generateUuid() {\n return UUID.randomUUID().toString().replace(\"-\", \"\");\n }\n\n /**\n * 对用户密码进行加盐后加密。\n *\n * @param password 明文密码。\n * @param passwordSalt 盐值。\n * @return 加密后的密码。\n */\n public static String encrptedPassword(String password, String passwordSalt) {\n return DigestUtil.md5Hex(password + passwordSalt);\n }\n\n /**\n * 这个方法一般用于Controller对于入口参数的基本验证。\n * 对于字符串,如果为空字符串,也将视为Blank,同时返回true。\n *\n * @param objs 一组参数。\n * @return 返回是否存在null或空字符串的参数。\n */\n public static boolean existBlankArgument(Object...objs) {\n for (Object obj : objs) {\n if (MyCommonUtil.isBlankOrNull(obj)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 结果和 existBlankArgument 相反。\n *\n * @param objs 一组参数。\n * @return 返回是否存在null或空字符串的参数。\n */\n public static boolean existNotBlankArgument(Object...objs) {\n for (Object obj : objs) {\n if (!MyCommonUtil.isBlankOrNull(obj)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 验证参数是否为空。\n *\n * @param obj 待判断的参数。\n * @return 空或者null返回true,否则false。\n */\n public static boolean isBlankOrNull(Object obj) {\n if (obj instanceof Collection) {\n return CollUtil.isEmpty((Collection<?>) obj);\n }\n return obj == null || (obj instanceof CharSequence && StrUtil.isBlank((CharSequence) obj));\n }\n\n /**\n * 验证参数是否为非空。\n *\n * @param obj 待判断的参数。\n * @return 空或者null返回false,否则true。\n */\n public static boolean isNotBlankOrNull(Object obj) {\n return !isBlankOrNull(obj);\n }\n\n /**\n * 判断source是否等于其中任何一个对象值。\n *\n * @param source 源对象。\n * @param others 其他对象。\n * @return 等于其中任何一个返回true,否则false。\n */\n public static boolean equalsAny(Object source, Object...others) {\n for (Object one : others) {\n if (ObjectUtil.equal(source, one)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断模型对象是否通过校验,没有通过返回具体的校验错误信息。\n *\n * @param model 带校验的model。\n * @param groups Validate绑定的校验组。\n * @return 没有错误返回null,否则返回具体的错误信息。\n */\n public static <T> String getModelValidationError(T model, Class<?>...groups) {\n if (model != null) {\n Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(model, groups);\n if (!constraintViolations.isEmpty()) {\n Iterator<ConstraintViolation<T>> it = constraintViolations.iterator();\n ConstraintViolation<T> constraint = it.next();\n return constraint.getMessage();\n }\n }\n return null;\n }\n\n /**\n * 判断模型对象是否通过校验,没有通过返回具体的校验错误信息。\n *\n * @param model 带校验的model。\n * @param forUpdate 是否为更新。\n * @return 没有错误返回null,否则返回具体的错误信息。\n */\n public static <T> String getModelValidationError(T model, boolean forUpdate) {\n if (model != null) {\n Set<ConstraintViolation<T>> constraintViolations;\n if (forUpdate) {\n constraintViolations = VALIDATOR.validate(model, Default.class, UpdateGroup.class);\n } else {\n constraintViolations = VALIDATOR.validate(model, Default.class, AddGroup.class);\n }\n if (!constraintViolations.isEmpty()) {\n Iterator<ConstraintViolation<T>> it = constraintViolations.iterator();\n ConstraintViolation<T> constraint = it.next();\n return constraint.getMessage();\n }\n }\n return null;\n }\n\n /**\n * 判断模型对象是否通过校验,没有通过返回具体的校验错误信息。\n *\n * @param modelList 带校验的model列表。\n * @param groups Validate绑定的校验组。\n * @return 没有错误返回null,否则返回具体的错误信息。\n */\n public static <T> String getModelValidationError(List<T> modelList, Class<?>... groups) {\n if (CollUtil.isNotEmpty(modelList)) {\n for (T model : modelList) {\n String errorMessage = getModelValidationError(model, groups);\n if (StrUtil.isNotBlank(errorMessage)) {\n return errorMessage;\n }\n }\n }\n return null;\n }\n\n /**\n * 判断模型对象是否通过校验,没有通过返回具体的校验错误信息。\n *\n * @param modelList 带校验的model列表。\n * @param forUpdate 是否为更新。\n * @return 没有错误返回null,否则返回具体的错误信息。\n */\n public static <T> String getModelValidationError(List<T> modelList, boolean forUpdate) {\n if (CollUtil.isNotEmpty(modelList)) {\n for (T model : modelList) {\n String errorMessage = getModelValidationError(model, forUpdate);\n if (StrUtil.isNotBlank(errorMessage)) {\n return errorMessage;\n }\n }\n }\n return null;\n }\n\n /**\n * 拼接参数中的字符串列表,用指定分隔符进行分割,同时每个字符串对象用单引号括起来。\n *\n * @param dataList 字符串集合。\n * @param separator 分隔符。\n * @return 拼接后的字符串。\n */\n public static String joinString(Collection<String> dataList, final char separator) {\n int index = 0;\n StringBuilder sb = new StringBuilder(128);\n for (String data : dataList) {\n sb.append(\"'\").append(data).append(\"'\");\n if (index++ != dataList.size() - 1) {\n sb.append(separator);\n }\n }\n return sb.toString();\n }\n\n /**\n * 将SQL Like中的通配符替换为字符本身的含义,以便于比较。\n *\n * @param str 待替换的字符串。\n * @return 替换后的字符串。\n */\n public static String replaceSqlWildcard(String str) {\n if (StrUtil.isBlank(str)) {\n return str;\n }\n return StrUtil.replaceChars(StrUtil.replaceChars(str, \"_\", \"\\\\_\"), \"%\", \"\\\\%\");\n }\n\n /**\n * 获取对象中,非空字段的名字列表。\n *\n * @param object 数据对象。\n * @param clazz 数据对象的class类型。\n * @param <T> 数据对象类型。\n * @return 数据对象中,值不为NULL的字段数组。\n */\n public static <T> String[] getNotNullFieldNames(T object, Class<T> clazz) {\n Field[] fields = ReflectUtil.getFields(clazz);\n List<String> fieldNameList = Arrays.stream(fields)\n .filter(f -> ReflectUtil.getFieldValue(object, f) != null)\n .map(Field::getName).collect(Collectors.toList());\n if (CollUtil.isNotEmpty(fieldNameList)) {\n return fieldNameList.toArray(new String[]{});\n }\n return new String[]{};\n }\n\n /**\n * 获取请求头中的设备信息。\n *\n * @return 设备类型,具体值可参考AppDeviceType常量类。\n */\n public static int getDeviceType() {\n // 缺省都按照Web登录方式设置,如果前端header中的值为不合法值,这里也不会报错,而是使用Web缺省方式。\n int deviceType = AppDeviceType.WEB;\n String deviceTypeString = ContextUtil.getHttpRequest().getHeader(\"deviceType\");\n if (StrUtil.isNotBlank(deviceTypeString)) {\n Integer type = Integer.valueOf(deviceTypeString);\n if (AppDeviceType.isValid(type)) {\n deviceType = type;\n }\n }\n return deviceType;\n }\n\n /**\n * 按(User-Agent)获取设备类型\n *\n * @return 字符串\n * @author 王立宏\n * @date 2023/11/22 02:34\n */\n public static String getDeviceTypeByUserAgent() {\n String userAgent = ContextUtil.getHttpRequest().getHeader(\"User-Agent\");\n if (userAgent != null) {\n userAgent = userAgent.toLowerCase();\n if (userAgent.contains(\"android\")) {\n return \"Android\";\n } else if (userAgent.contains(\"iphone\") || userAgent.contains(\"ipad\")) {\n return \"IOS\";\n } else if (userAgent.contains(\"windows phone\")) {\n return \"Windows Phone\";\n } else if (userAgent.contains(\"windows\")) {\n return \"Windows\";\n } else {\n return \"Unknown device type\";\n }\n } else {\n return \"Unknown device type\";\n }\n }\n\n /**\n * 获取客户端 IP 地址\n *\n * @return IP 地址\n * @author 王立宏\n * @date 2023/11/22 02:32\n */\n public static String getClientIpAddress() {\n String ipAddress = ContextUtil.getHttpRequest().getHeader(\"X-Forwarded-For\");\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"Proxy-Client-IP\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_X_FORWARDED_FOR\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_X_FORWARDED\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_X_CLUSTER_CLIENT_IP\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_CLIENT_IP\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_FORWARDED_FOR\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_FORWARDED\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"HTTP_VIA\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getHeader(\"REMOTE_ADDR\");\n }\n if (ipAddress == null || ipAddress.isEmpty() || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = ContextUtil.getHttpRequest().getRemoteAddr();\n }\n // 如果 IP 地址包含多个值,则提取第一个值\n if (ipAddress != null && ipAddress.contains(\",\")) {\n ipAddress = ipAddress.split(\",\")[0].trim();\n }\n return ipAddress;\n }\n\n /**\n * 转换为字典格式的数据列表。\n *\n * @param dataList 源数据列表。\n * @param idGetter 获取字典Id字段值的函数方法。\n * @param nameGetter 获取字典名字段值的函数方法。\n * @param <M> 源数据对象类型。\n * @param <R> 字典Id的类型。\n * @return 字典格式的数据列表。\n */\n public static <M, R> List<Map<String, Object>> toDictDataList(\n Collection<M> dataList, Function<M, R> idGetter, Function<M, String> nameGetter) {\n if (CollUtil.isEmpty(dataList)) {\n return new LinkedList<>();\n }\n return dataList.stream().map(item -> {\n Map<String, Object> dataMap = new HashMap<>(2);\n dataMap.put(ApplicationConstant.DICT_ID, idGetter.apply(item));\n dataMap.put(ApplicationConstant.DICT_NAME, nameGetter.apply(item));\n return dataMap;\n }).collect(Collectors.toList());\n }\n\n /**\n * 转换为树形字典格式的数据列表。\n *\n * @param dataList 源数据列表。\n * @param idGetter 获取字典Id字段值的函数方法。\n * @param nameGetter 获取字典名字段值的函数方法。\n * @param parentIdGetter 获取字典Id父字段值的函数方法。\n * @param <M> 源数据对象类型。\n * @param <R> 字典Id的类型。\n * @return 字典格式的数据列表。\n */\n public static <M, R> List<Map<String, Object>> toDictDataList(\n Collection<M> dataList,\n Function<M, R> idGetter,\n Function<M, String> nameGetter,\n Function<M, R> parentIdGetter) {\n if (CollUtil.isEmpty(dataList)) {\n return new LinkedList<>();\n }\n return dataList.stream().map(item -> {\n Map<String, Object> dataMap = new HashMap<>(2);\n dataMap.put(ApplicationConstant.DICT_ID, idGetter.apply(item));\n dataMap.put(ApplicationConstant.DICT_NAME, nameGetter.apply(item));\n dataMap.put(ApplicationConstant.PARENT_ID, parentIdGetter.apply(item));\n return dataMap;\n }).collect(Collectors.toList());\n }\n\n /**\n * 转换为字典格式的数据列表,同时支持一个附加字段。\n *\n * @param dataList 源数据列表。\n * @param idGetter 获取字典Id字段值的函数方法。\n * @param nameGetter 获取字典名字段值的函数方法。\n * @param extraName 附加字段名。。\n * @param extraGetter 获取附加字段值的函数方法。\n * @param <M> 源数据对象类型。\n * @param <R> 字典Id的类型。\n * @param <E> 附加字段值的类型。\n * @return 字典格式的数据列表。\n */\n public static <M, R, E> List<Map<String, Object>> toDictDataList(\n Collection<M> dataList,\n Function<M, R> idGetter,\n Function<M, String> nameGetter,\n String extraName,\n Function<M, E> extraGetter) {\n if (CollUtil.isEmpty(dataList)) {\n return new LinkedList<>();\n }\n return dataList.stream().map(item -> {\n Map<String, Object> dataMap = new HashMap<>(2);\n dataMap.put(ApplicationConstant.DICT_ID, idGetter.apply(item));\n dataMap.put(ApplicationConstant.DICT_NAME, nameGetter.apply(item));\n dataMap.put(extraName, extraGetter.apply(item));\n return dataMap;\n }).collect(Collectors.toList());\n }\n\n /**\n * 私有构造函数,明确标识该常量类的作用。\n */\n private MyCommonUtil() {\n }\n}" }, { "identifier": "BaseModel", "path": "common/common-core/src/main/java/supie/common/core/base/model/BaseModel.java", "snippet": "@Data\npublic class BaseModel {\n\n /**\n * 创建者Id。\n */\n @TableField(value = \"create_user_id\")\n private Long createUserId;\n\n /**\n * 创建时间。\n */\n @TableField(value = \"create_time\")\n private Date createTime;\n\n /**\n * 更新者Id。\n */\n @TableField(value = \"update_user_id\")\n private Long updateUserId;\n\n /**\n * 更新时间。\n */\n @TableField(value = \"update_time\")\n private Date updateTime;\n}" }, { "identifier": "BaseModelMapper", "path": "common/common-core/src/main/java/supie/common/core/base/mapper/BaseModelMapper.java", "snippet": "public interface BaseModelMapper<D, M> {\n\n /**\n * 转换Model实体对象到Domain域对象。\n *\n * @param model Model实体对象。\n * @return Domain域对象。\n */\n D fromModel(M model);\n\n /**\n * 转换Model实体对象列表到Domain域对象列表。\n *\n * @param modelList Model实体对象列表。\n * @return Domain域对象列表。\n */\n List<D> fromModelList(List<M> modelList);\n\n /**\n * 转换Domain域对象到Model实体对象。\n *\n * @param domain Domain域对象。\n * @return Model实体对象。\n */\n M toModel(D domain);\n\n /**\n * 转换Domain域对象列表到Model实体对象列表。\n *\n * @param domainList Domain域对象列表。\n * @return Model实体对象列表。\n */\n List<M> toModelList(List<D> domainList);\n\n /**\n * 转换bean到map\n *\n * @param bean bean对象。\n * @param ignoreNullValue 值为null的字段是否转换到Map。\n * @param <T> bean类型。\n * @return 转换后的map对象。\n */\n default <T> Map<String, Object> beanToMap(T bean, boolean ignoreNullValue) {\n return BeanUtil.beanToMap(bean, false, ignoreNullValue);\n }\n\n /**\n * 转换bean集合到map集合\n *\n * @param dataList bean对象集合。\n * @param ignoreNullValue 值为null的字段是否转换到Map。\n * @param <T> bean类型。\n * @return 转换后的map对象集合。\n */\n default <T> List<Map<String, Object>> beanToMap(List<T> dataList, boolean ignoreNullValue) {\n if (CollUtil.isEmpty(dataList)) {\n return new LinkedList<>();\n }\n return dataList.stream()\n .map(o -> BeanUtil.beanToMap(o, false, ignoreNullValue))\n .collect(Collectors.toList());\n }\n\n /**\n * 转换map到bean。\n *\n * @param map map对象。\n * @param beanClazz bean的Class对象。\n * @param <T> bean类型。\n * @return 转换后的bean对象。\n */\n default <T> T mapToBean(Map<String, Object> map, Class<T> beanClazz) {\n return BeanUtil.toBeanIgnoreError(map, beanClazz);\n }\n\n /**\n * 转换map集合到bean集合。\n *\n * @param mapList map对象集合。\n * @param beanClazz bean的Class对象。\n * @param <T> bean类型。\n * @return 转换后的bean对象集合。\n */\n default <T> List<T> mapToBean(List<Map<String, Object>> mapList, Class<T> beanClazz) {\n if (CollUtil.isEmpty(mapList)) {\n return new LinkedList<>();\n }\n return mapList.stream()\n .map(m -> BeanUtil.toBeanIgnoreError(m, beanClazz))\n .collect(Collectors.toList());\n }\n\n /**\n * 对于Map字段到Map字段的映射场景,MapStruct会根据方法签名自动选择该函数\n * 作为对象copy的函数。由于该函数是直接返回的,因此没有对象copy,效率更高。\n * 如果没有该函数,MapStruct会生成如下代码:\n * Map<String, Object> map = courseDto.getTeacherIdDictMap();\n * if ( map != null ) {\n * course.setTeacherIdDictMap( new HashMap<String, Object>( map ) );\n * }\n *\n * @param map map对象。\n * @return 直接返回的map。\n */\n default Map<String, Object> mapToMap(Map<String, Object> map) {\n return map;\n }\n}" }, { "identifier": "PlanningClassificationVo", "path": "application-webadmin/src/main/java/supie/webadmin/app/vo/PlanningClassificationVo.java", "snippet": "@ApiModel(\"PlanningClassificationVO视图对象\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class PlanningClassificationVo extends BaseVo {\n\n /**\n * 租户号。\n */\n @ApiModelProperty(value = \"租户号\")\n private Long id;\n\n /**\n * 数据所属人。\n */\n @ApiModelProperty(value = \"数据所属人\")\n private Long dataUserId;\n\n /**\n * 数据所属部门。\n */\n @ApiModelProperty(value = \"数据所属部门\")\n private Long dataDeptId;\n\n /**\n * 关联项目id。\n */\n @ApiModelProperty(value = \"关联项目id\")\n private Long projectId;\n\n /**\n * 分类名称。\n */\n @ApiModelProperty(value = \"分类名称\")\n private String classificationName;\n\n /**\n * 分类代码。\n */\n @ApiModelProperty(value = \"分类代码\")\n private String classificationCode;\n\n /**\n * 分类状态。\n */\n @ApiModelProperty(value = \"分类状态\")\n private String classificationStatus;\n\n /**\n * 分类描述。\n */\n @ApiModelProperty(value = \"分类描述\")\n private String classificationDescription;\n\n /**\n * createUserId 字典关联数据。\n */\n @ApiModelProperty(value = \"createUserId 字典关联数据\")\n private Map<String, Object> createUserIdDictMap;\n\n /**\n * updateUserId 字典关联数据。\n */\n @ApiModelProperty(value = \"updateUserId 字典关联数据\")\n private Map<String, Object> updateUserIdDictMap;\n\n /**\n * dataUserId 字典关联数据。\n */\n @ApiModelProperty(value = \"dataUserId 字典关联数据\")\n private Map<String, Object> dataUserIdDictMap;\n}" } ]
import com.baomidou.mybatisplus.annotation.*; import supie.webadmin.upms.model.SysUser; import supie.common.core.util.MyCommonUtil; import supie.common.core.annotation.*; import supie.common.core.base.model.BaseModel; import supie.common.core.base.mapper.BaseModelMapper; import supie.webadmin.app.vo.PlanningClassificationVo; import lombok.Data; import lombok.EqualsAndHashCode; import org.mapstruct.*; import org.mapstruct.factory.Mappers; import java.util.Map;
7,599
package supie.webadmin.app.model; /** * PlanningClassification实体对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Data @EqualsAndHashCode(callSuper = true) @TableName(value = "sdt_planning_classification") public class PlanningClassification extends BaseModel { /** * 租户号。 */ @TableId(value = "id") private Long id; /** * 数据所属人。 */ @UserFilterColumn private Long dataUserId; /** * 数据所属部门。 */ @DeptFilterColumn private Long dataDeptId; /** * 逻辑删除标记字段(1: 正常 -1: 已删除)。 */ @TableLogic private Integer isDelete; /** * 关联项目id。 */ private Long projectId; /** * 分类名称。 */ private String classificationName; /** * 分类代码。 */ private String classificationCode; /** * 分类状态。 */ private String classificationStatus; /** * 分类描述。 */ private String classificationDescription; /** * updateTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String updateTimeStart; /** * updateTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String updateTimeEnd; /** * createTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String createTimeStart; /** * createTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String createTimeEnd; /** * classification_name / classification_code / classification_status / classification_description LIKE搜索字符串。 */ @TableField(exist = false) private String searchString; public void setSearchString(String searchString) { this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); } @RelationDict( masterIdField = "createUserId",
package supie.webadmin.app.model; /** * PlanningClassification实体对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Data @EqualsAndHashCode(callSuper = true) @TableName(value = "sdt_planning_classification") public class PlanningClassification extends BaseModel { /** * 租户号。 */ @TableId(value = "id") private Long id; /** * 数据所属人。 */ @UserFilterColumn private Long dataUserId; /** * 数据所属部门。 */ @DeptFilterColumn private Long dataDeptId; /** * 逻辑删除标记字段(1: 正常 -1: 已删除)。 */ @TableLogic private Integer isDelete; /** * 关联项目id。 */ private Long projectId; /** * 分类名称。 */ private String classificationName; /** * 分类代码。 */ private String classificationCode; /** * 分类状态。 */ private String classificationStatus; /** * 分类描述。 */ private String classificationDescription; /** * updateTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String updateTimeStart; /** * updateTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String updateTimeEnd; /** * createTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String createTimeStart; /** * createTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String createTimeEnd; /** * classification_name / classification_code / classification_status / classification_description LIKE搜索字符串。 */ @TableField(exist = false) private String searchString; public void setSearchString(String searchString) { this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); } @RelationDict( masterIdField = "createUserId",
slaveModelClass = SysUser.class,
0
2023-11-04 12:36:44+00:00
12k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> sequenceList) {\n if (sequenceList.size() == 0) throw new EmptySequenceException();\n\n this.sequenceList = Collections.unmodifiableList(sequenceList);\n }\n\n public Pose2d start() {\n return sequenceList.get(0).getStartPose();\n }\n\n public Pose2d end() {\n return sequenceList.get(sequenceList.size() - 1).getEndPose();\n }\n\n public double duration() {\n double total = 0.0;\n\n for (SequenceSegment segment : sequenceList) {\n total += segment.getDuration();\n }\n\n return total;\n }\n\n public SequenceSegment get(int i) {\n return sequenceList.get(i);\n }\n\n public int size() {\n return sequenceList.size();\n }\n}" }, { "identifier": "TrajectorySequenceBuilder", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequenceBuilder.java", "snippet": "public class TrajectorySequenceBuilder {\n private final double resolution = 0.25;\n\n private final TrajectoryVelocityConstraint baseVelConstraint;\n private final TrajectoryAccelerationConstraint baseAccelConstraint;\n\n private TrajectoryVelocityConstraint currentVelConstraint;\n private TrajectoryAccelerationConstraint currentAccelConstraint;\n\n private final double baseTurnConstraintMaxAngVel;\n private final double baseTurnConstraintMaxAngAccel;\n\n private double currentTurnConstraintMaxAngVel;\n private double currentTurnConstraintMaxAngAccel;\n\n private final List<SequenceSegment> sequenceSegments;\n\n private final List<TemporalMarker> temporalMarkers;\n private final List<DisplacementMarker> displacementMarkers;\n private final List<SpatialMarker> spatialMarkers;\n\n private Pose2d lastPose;\n\n private double tangentOffset;\n\n private boolean setAbsoluteTangent;\n private double absoluteTangent;\n\n private TrajectoryBuilder currentTrajectoryBuilder;\n\n private double currentDuration;\n private double currentDisplacement;\n\n private double lastDurationTraj;\n private double lastDisplacementTraj;\n\n public TrajectorySequenceBuilder(\n Pose2d startPose,\n Double startTangent,\n TrajectoryVelocityConstraint baseVelConstraint,\n TrajectoryAccelerationConstraint baseAccelConstraint,\n double baseTurnConstraintMaxAngVel,\n double baseTurnConstraintMaxAngAccel\n ) {\n this.baseVelConstraint = baseVelConstraint;\n this.baseAccelConstraint = baseAccelConstraint;\n\n this.currentVelConstraint = baseVelConstraint;\n this.currentAccelConstraint = baseAccelConstraint;\n\n this.baseTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.baseTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n sequenceSegments = new ArrayList<>();\n\n temporalMarkers = new ArrayList<>();\n displacementMarkers = new ArrayList<>();\n spatialMarkers = new ArrayList<>();\n\n lastPose = startPose;\n\n tangentOffset = 0.0;\n\n setAbsoluteTangent = (startTangent != null);\n absoluteTangent = startTangent != null ? startTangent : 0.0;\n\n currentTrajectoryBuilder = null;\n\n currentDuration = 0.0;\n currentDisplacement = 0.0;\n\n lastDurationTraj = 0.0;\n lastDisplacementTraj = 0.0;\n }\n\n public TrajectorySequenceBuilder(\n Pose2d startPose,\n TrajectoryVelocityConstraint baseVelConstraint,\n TrajectoryAccelerationConstraint baseAccelConstraint,\n double baseTurnConstraintMaxAngVel,\n double baseTurnConstraintMaxAngAccel\n ) {\n this(\n startPose, null,\n baseVelConstraint, baseAccelConstraint,\n baseTurnConstraintMaxAngVel, baseTurnConstraintMaxAngAccel\n );\n }\n\n public TrajectorySequenceBuilder lineTo(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineTo(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToConstantHeading(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToConstantHeading(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToLinearHeading(Pose2d endPose) {\n return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToLinearHeading(\n Pose2d endPose,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToSplineHeading(Pose2d endPose) {\n return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToSplineHeading(\n Pose2d endPose,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeTo(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeTo(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder forward(double distance) {\n return addPath(() -> currentTrajectoryBuilder.forward(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder forward(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.forward(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder back(double distance) {\n return addPath(() -> currentTrajectoryBuilder.back(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder back(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.back(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeLeft(double distance) {\n return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeLeft(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeRight(double distance) {\n return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeRight(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineTo(Vector2d endPosition, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineTo(\n Vector2d endPosition,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToConstantHeading(Vector2d endPosition, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToConstantHeading(\n Vector2d endPosition,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToLinearHeading(Pose2d endPose, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToLinearHeading(\n Pose2d endPose,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToSplineHeading(Pose2d endPose, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToSplineHeading(\n Pose2d endPose,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, velConstraint, accelConstraint));\n }\n\n private TrajectorySequenceBuilder addPath(AddPathCallback callback) {\n if (currentTrajectoryBuilder == null) newPath();\n\n try {\n callback.run();\n } catch (PathContinuityViolationException e) {\n newPath();\n callback.run();\n }\n\n Trajectory builtTraj = currentTrajectoryBuilder.build();\n\n double durationDifference = builtTraj.duration() - lastDurationTraj;\n double displacementDifference = builtTraj.getPath().length() - lastDisplacementTraj;\n\n lastPose = builtTraj.end();\n currentDuration += durationDifference;\n currentDisplacement += displacementDifference;\n\n lastDurationTraj = builtTraj.duration();\n lastDisplacementTraj = builtTraj.getPath().length();\n\n return this;\n }\n\n public TrajectorySequenceBuilder setTangent(double tangent) {\n setAbsoluteTangent = true;\n absoluteTangent = tangent;\n\n pushPath();\n\n return this;\n }\n\n private TrajectorySequenceBuilder setTangentOffset(double offset) {\n setAbsoluteTangent = false;\n\n this.tangentOffset = offset;\n this.pushPath();\n\n return this;\n }\n\n public TrajectorySequenceBuilder setReversed(boolean reversed) {\n return reversed ? this.setTangentOffset(Math.toRadians(180.0)) : this.setTangentOffset(0.0);\n }\n\n public TrajectorySequenceBuilder setConstraints(\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n this.currentVelConstraint = velConstraint;\n this.currentAccelConstraint = accelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetConstraints() {\n this.currentVelConstraint = this.baseVelConstraint;\n this.currentAccelConstraint = this.baseAccelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) {\n this.currentVelConstraint = velConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetVelConstraint() {\n this.currentVelConstraint = this.baseVelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) {\n this.currentAccelConstraint = accelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetAccelConstraint() {\n this.currentAccelConstraint = this.baseAccelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) {\n this.currentTurnConstraintMaxAngVel = maxAngVel;\n this.currentTurnConstraintMaxAngAccel = maxAngAccel;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetTurnConstraint() {\n this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n return this;\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) {\n return this.addTemporalMarker(currentDuration, callback);\n }\n\n public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) {\n return this.addTemporalMarker(currentDuration + offset, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) {\n return this.addTemporalMarker(0.0, time, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) {\n return this.addTemporalMarker(time -> scale * time + offset, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) {\n this.temporalMarkers.add(new TemporalMarker(time, callback));\n return this;\n }\n\n public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) {\n this.spatialMarkers.add(new SpatialMarker(point, callback));\n return this;\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) {\n return this.addDisplacementMarker(currentDisplacement, callback);\n }\n\n public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) {\n return this.addDisplacementMarker(currentDisplacement + offset, callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) {\n return this.addDisplacementMarker(0.0, displacement, callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) {\n return addDisplacementMarker((displacement -> scale * displacement + offset), callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) {\n displacementMarkers.add(new DisplacementMarker(displacement, callback));\n\n return this;\n }\n\n public TrajectorySequenceBuilder turn(double angle) {\n return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel);\n }\n\n public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) {\n pushPath();\n\n MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile(\n new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0),\n new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0),\n maxAngVel,\n maxAngAccel\n );\n\n sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList()));\n\n lastPose = new Pose2d(\n lastPose.getX(), lastPose.getY(),\n Angle.norm(lastPose.getHeading() + angle)\n );\n\n currentDuration += turnProfile.duration();\n\n return this;\n }\n\n public TrajectorySequenceBuilder waitSeconds(double seconds) {\n pushPath();\n sequenceSegments.add(new WaitSegment(lastPose, seconds, Collections.emptyList()));\n\n currentDuration += seconds;\n return this;\n }\n\n public TrajectorySequenceBuilder addTrajectory(Trajectory trajectory) {\n pushPath();\n\n sequenceSegments.add(new TrajectorySegment(trajectory));\n return this;\n }\n\n private void pushPath() {\n if (currentTrajectoryBuilder != null) {\n Trajectory builtTraj = currentTrajectoryBuilder.build();\n sequenceSegments.add(new TrajectorySegment(builtTraj));\n }\n\n currentTrajectoryBuilder = null;\n }\n\n private void newPath() {\n if (currentTrajectoryBuilder != null)\n pushPath();\n\n lastDurationTraj = 0.0;\n lastDisplacementTraj = 0.0;\n\n double tangent = setAbsoluteTangent ? absoluteTangent : Angle.norm(lastPose.getHeading() + tangentOffset);\n\n currentTrajectoryBuilder = new TrajectoryBuilder(lastPose, tangent, currentVelConstraint, currentAccelConstraint, resolution);\n }\n\n public TrajectorySequence build() {\n pushPath();\n\n List<TrajectoryMarker> globalMarkers = convertMarkersToGlobal(\n sequenceSegments,\n temporalMarkers, displacementMarkers, spatialMarkers\n );\n\n return new TrajectorySequence(projectGlobalMarkersToLocalSegments(globalMarkers, sequenceSegments));\n }\n\n private List<TrajectoryMarker> convertMarkersToGlobal(\n List<SequenceSegment> sequenceSegments,\n List<TemporalMarker> temporalMarkers,\n List<DisplacementMarker> displacementMarkers,\n List<SpatialMarker> spatialMarkers\n ) {\n ArrayList<TrajectoryMarker> trajectoryMarkers = new ArrayList<>();\n\n // Convert temporal markers\n for (TemporalMarker marker : temporalMarkers) {\n trajectoryMarkers.add(\n new TrajectoryMarker(marker.getProducer().produce(currentDuration), marker.getCallback())\n );\n }\n\n // Convert displacement markers\n for (DisplacementMarker marker : displacementMarkers) {\n double time = displacementToTime(\n sequenceSegments,\n marker.getProducer().produce(currentDisplacement)\n );\n\n trajectoryMarkers.add(\n new TrajectoryMarker(\n time,\n marker.getCallback()\n )\n );\n }\n\n // Convert spatial markers\n for (SpatialMarker marker : spatialMarkers) {\n trajectoryMarkers.add(\n new TrajectoryMarker(\n pointToTime(sequenceSegments, marker.getPoint()),\n marker.getCallback()\n )\n );\n }\n\n return trajectoryMarkers;\n }\n\n private List<SequenceSegment> projectGlobalMarkersToLocalSegments(List<TrajectoryMarker> markers, List<SequenceSegment> sequenceSegments) {\n if (sequenceSegments.isEmpty()) return Collections.emptyList();\n\n double totalSequenceDuration = 0;\n for (SequenceSegment segment : sequenceSegments) {\n totalSequenceDuration += segment.getDuration();\n }\n\n for (TrajectoryMarker marker : markers) {\n SequenceSegment segment = null;\n int segmentIndex = 0;\n double segmentOffsetTime = 0;\n\n double currentTime = 0;\n for (int i = 0; i < sequenceSegments.size(); i++) {\n SequenceSegment seg = sequenceSegments.get(i);\n\n double markerTime = Math.min(marker.getTime(), totalSequenceDuration);\n\n if (currentTime + seg.getDuration() >= markerTime) {\n segment = seg;\n segmentIndex = i;\n segmentOffsetTime = markerTime - currentTime;\n\n break;\n } else {\n currentTime += seg.getDuration();\n }\n }\n\n SequenceSegment newSegment = null;\n\n if (segment instanceof WaitSegment) {\n List<TrajectoryMarker> newMarkers = new ArrayList<>(segment.getMarkers());\n\n newMarkers.addAll(sequenceSegments.get(segmentIndex).getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n WaitSegment thisSegment = (WaitSegment) segment;\n newSegment = new WaitSegment(thisSegment.getStartPose(), thisSegment.getDuration(), newMarkers);\n } else if (segment instanceof TurnSegment) {\n List<TrajectoryMarker> newMarkers = new ArrayList<>(segment.getMarkers());\n\n newMarkers.addAll(sequenceSegments.get(segmentIndex).getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n TurnSegment thisSegment = (TurnSegment) segment;\n newSegment = new TurnSegment(thisSegment.getStartPose(), thisSegment.getTotalRotation(), thisSegment.getMotionProfile(), newMarkers);\n } else if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getTrajectory().getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new TrajectorySegment(new Trajectory(thisSegment.getTrajectory().getPath(), thisSegment.getTrajectory().getProfile(), newMarkers));\n }\n\n sequenceSegments.set(segmentIndex, newSegment);\n }\n\n return sequenceSegments;\n }\n\n // Taken from Road Runner's TrajectoryGenerator.displacementToTime() since it's private\n // note: this assumes that the profile position is monotonic increasing\n private Double motionProfileDisplacementToTime(MotionProfile profile, double s) {\n double tLo = 0.0;\n double tHi = profile.duration();\n while (!(Math.abs(tLo - tHi) < 1e-6)) {\n double tMid = 0.5 * (tLo + tHi);\n if (profile.get(tMid).getX() > s) {\n tHi = tMid;\n } else {\n tLo = tMid;\n }\n }\n return 0.5 * (tLo + tHi);\n }\n\n private Double displacementToTime(List<SequenceSegment> sequenceSegments, double s) {\n double currentTime = 0.0;\n double currentDisplacement = 0.0;\n\n for (SequenceSegment segment : sequenceSegments) {\n if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n double segmentLength = thisSegment.getTrajectory().getPath().length();\n\n if (currentDisplacement + segmentLength > s) {\n double target = s - currentDisplacement;\n double timeInSegment = motionProfileDisplacementToTime(\n thisSegment.getTrajectory().getProfile(),\n target\n );\n\n return currentTime + timeInSegment;\n } else {\n currentDisplacement += segmentLength;\n currentTime += thisSegment.getTrajectory().duration();\n }\n } else {\n currentTime += segment.getDuration();\n }\n }\n\n return 0.0;\n }\n\n private Double pointToTime(List<SequenceSegment> sequenceSegments, Vector2d point) {\n class ComparingPoints {\n private final double distanceToPoint;\n private final double totalDisplacement;\n private final double thisPathDisplacement;\n\n public ComparingPoints(double distanceToPoint, double totalDisplacement, double thisPathDisplacement) {\n this.distanceToPoint = distanceToPoint;\n this.totalDisplacement = totalDisplacement;\n this.thisPathDisplacement = thisPathDisplacement;\n }\n }\n\n List<ComparingPoints> projectedPoints = new ArrayList<>();\n\n for (SequenceSegment segment : sequenceSegments) {\n if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n double displacement = thisSegment.getTrajectory().getPath().project(point, 0.25);\n Vector2d projectedPoint = thisSegment.getTrajectory().getPath().get(displacement).vec();\n double distanceToPoint = point.minus(projectedPoint).norm();\n\n double totalDisplacement = 0.0;\n\n for (ComparingPoints comparingPoint : projectedPoints) {\n totalDisplacement += comparingPoint.totalDisplacement;\n }\n\n totalDisplacement += displacement;\n\n projectedPoints.add(new ComparingPoints(distanceToPoint, displacement, totalDisplacement));\n }\n }\n\n ComparingPoints closestPoint = null;\n\n for (ComparingPoints comparingPoint : projectedPoints) {\n if (closestPoint == null) {\n closestPoint = comparingPoint;\n continue;\n }\n\n if (comparingPoint.distanceToPoint < closestPoint.distanceToPoint)\n closestPoint = comparingPoint;\n }\n\n return displacementToTime(sequenceSegments, closestPoint.thisPathDisplacement);\n }\n\n private interface AddPathCallback {\n void run();\n }\n}" }, { "identifier": "TrajectorySequenceRunner", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequenceRunner.java", "snippet": "@Config\npublic class TrajectorySequenceRunner {\n public static String COLOR_INACTIVE_TRAJECTORY = \"#4caf507a\";\n public static String COLOR_INACTIVE_TURN = \"#7c4dff7a\";\n public static String COLOR_INACTIVE_WAIT = \"#dd2c007a\";\n\n public static String COLOR_ACTIVE_TRAJECTORY = \"#4CAF50\";\n public static String COLOR_ACTIVE_TURN = \"#7c4dff\";\n public static String COLOR_ACTIVE_WAIT = \"#dd2c00\";\n\n public static int POSE_HISTORY_LIMIT = 100;\n\n private final TrajectoryFollower follower;\n\n private final PIDFController turnController;\n\n private final NanoClock clock;\n\n private TrajectorySequence currentTrajectorySequence;\n private double currentSegmentStartTime;\n private int currentSegmentIndex;\n private int lastSegmentIndex;\n\n private Pose2d lastPoseError = new Pose2d();\n\n List<TrajectoryMarker> remainingMarkers = new ArrayList<>();\n\n private final FtcDashboard dashboard;\n private final LinkedList<Pose2d> poseHistory = new LinkedList<>();\n\n private VoltageSensor voltageSensor;\n\n private List<Integer> lastDriveEncPositions, lastDriveEncVels, lastTrackingEncPositions, lastTrackingEncVels;\n\n public TrajectorySequenceRunner(\n TrajectoryFollower follower, PIDCoefficients headingPIDCoefficients, VoltageSensor voltageSensor,\n List<Integer> lastDriveEncPositions, List<Integer> lastDriveEncVels, List<Integer> lastTrackingEncPositions, List<Integer> lastTrackingEncVels\n ) {\n this.follower = follower;\n\n turnController = new PIDFController(headingPIDCoefficients);\n turnController.setInputBounds(0, 2 * Math.PI);\n\n this.voltageSensor = voltageSensor;\n\n this.lastDriveEncPositions = lastDriveEncPositions;\n this.lastDriveEncVels = lastDriveEncVels;\n this.lastTrackingEncPositions = lastTrackingEncPositions;\n this.lastTrackingEncVels = lastTrackingEncVels;\n\n clock = NanoClock.system();\n\n dashboard = FtcDashboard.getInstance();\n dashboard.setTelemetryTransmissionInterval(25);\n }\n\n public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {\n currentTrajectorySequence = trajectorySequence;\n currentSegmentStartTime = clock.seconds();\n currentSegmentIndex = 0;\n lastSegmentIndex = -1;\n }\n\n public @Nullable\n DriveSignal update(Pose2d poseEstimate, Pose2d poseVelocity) {\n Pose2d targetPose = null;\n DriveSignal driveSignal = null;\n\n TelemetryPacket packet = new TelemetryPacket();\n Canvas fieldOverlay = packet.fieldOverlay();\n\n SequenceSegment currentSegment = null;\n\n if (currentTrajectorySequence != null) {\n if (currentSegmentIndex >= currentTrajectorySequence.size()) {\n for (TrajectoryMarker marker : remainingMarkers) {\n marker.getCallback().onMarkerReached();\n }\n\n remainingMarkers.clear();\n\n currentTrajectorySequence = null;\n }\n\n if (currentTrajectorySequence == null)\n return new DriveSignal();\n\n double now = clock.seconds();\n boolean isNewTransition = currentSegmentIndex != lastSegmentIndex;\n\n currentSegment = currentTrajectorySequence.get(currentSegmentIndex);\n\n if (isNewTransition) {\n currentSegmentStartTime = now;\n lastSegmentIndex = currentSegmentIndex;\n\n for (TrajectoryMarker marker : remainingMarkers) {\n marker.getCallback().onMarkerReached();\n }\n\n remainingMarkers.clear();\n\n remainingMarkers.addAll(currentSegment.getMarkers());\n Collections.sort(remainingMarkers, (t1, t2) -> Double.compare(t1.getTime(), t2.getTime()));\n }\n\n double deltaTime = now - currentSegmentStartTime;\n\n if (currentSegment instanceof TrajectorySegment) {\n Trajectory currentTrajectory = ((TrajectorySegment) currentSegment).getTrajectory();\n\n if (isNewTransition)\n follower.followTrajectory(currentTrajectory);\n\n if (!follower.isFollowing()) {\n currentSegmentIndex++;\n\n driveSignal = new DriveSignal();\n } else {\n driveSignal = follower.update(poseEstimate, poseVelocity);\n lastPoseError = follower.getLastError();\n }\n\n targetPose = currentTrajectory.get(deltaTime);\n } else if (currentSegment instanceof TurnSegment) {\n MotionState targetState = ((TurnSegment) currentSegment).getMotionProfile().get(deltaTime);\n\n turnController.setTargetPosition(targetState.getX());\n\n double correction = turnController.update(poseEstimate.getHeading());\n\n double targetOmega = targetState.getV();\n double targetAlpha = targetState.getA();\n\n lastPoseError = new Pose2d(0, 0, turnController.getLastError());\n\n Pose2d startPose = currentSegment.getStartPose();\n targetPose = startPose.copy(startPose.getX(), startPose.getY(), targetState.getX());\n\n driveSignal = new DriveSignal(\n new Pose2d(0, 0, targetOmega + correction),\n new Pose2d(0, 0, targetAlpha)\n );\n\n if (deltaTime >= currentSegment.getDuration()) {\n currentSegmentIndex++;\n driveSignal = new DriveSignal();\n }\n } else if (currentSegment instanceof WaitSegment) {\n lastPoseError = new Pose2d();\n\n targetPose = currentSegment.getStartPose();\n driveSignal = new DriveSignal();\n\n if (deltaTime >= currentSegment.getDuration()) {\n currentSegmentIndex++;\n }\n }\n\n while (remainingMarkers.size() > 0 && deltaTime > remainingMarkers.get(0).getTime()) {\n remainingMarkers.get(0).getCallback().onMarkerReached();\n remainingMarkers.remove(0);\n }\n }\n\n poseHistory.add(poseEstimate);\n\n if (POSE_HISTORY_LIMIT > -1 && poseHistory.size() > POSE_HISTORY_LIMIT) {\n poseHistory.removeFirst();\n }\n\n final double NOMINAL_VOLTAGE = 12.0;\n double voltage = voltageSensor.getVoltage();\n if (driveSignal != null && !DriveConstants.RUN_USING_ENCODER) {\n driveSignal = new DriveSignal(\n driveSignal.getVel().times(NOMINAL_VOLTAGE / voltage),\n driveSignal.getAccel().times(NOMINAL_VOLTAGE / voltage)\n );\n }\n\n if (targetPose != null) {\n LogFiles.record(\n targetPose, poseEstimate, voltage,\n lastDriveEncPositions, lastDriveEncVels, lastTrackingEncPositions, lastTrackingEncVels\n );\n }\n\n packet.put(\"x\", poseEstimate.getX());\n packet.put(\"y\", poseEstimate.getY());\n packet.put(\"heading (deg)\", Math.toDegrees(poseEstimate.getHeading()));\n\n packet.put(\"xError\", getLastPoseError().getX());\n packet.put(\"yError\", getLastPoseError().getY());\n packet.put(\"headingError (deg)\", Math.toDegrees(getLastPoseError().getHeading()));\n\n draw(fieldOverlay, currentTrajectorySequence, currentSegment, targetPose, poseEstimate);\n\n dashboard.sendTelemetryPacket(packet);\n\n return driveSignal;\n }\n\n private void draw(\n Canvas fieldOverlay,\n TrajectorySequence sequence, SequenceSegment currentSegment,\n Pose2d targetPose, Pose2d poseEstimate\n ) {\n if (sequence != null) {\n for (int i = 0; i < sequence.size(); i++) {\n SequenceSegment segment = sequence.get(i);\n\n if (segment instanceof TrajectorySegment) {\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_INACTIVE_TRAJECTORY);\n\n DashboardUtil.drawSampledPath(fieldOverlay, ((TrajectorySegment) segment).getTrajectory().getPath());\n } else if (segment instanceof TurnSegment) {\n Pose2d pose = segment.getStartPose();\n\n fieldOverlay.setFill(COLOR_INACTIVE_TURN);\n fieldOverlay.fillCircle(pose.getX(), pose.getY(), 2);\n } else if (segment instanceof WaitSegment) {\n Pose2d pose = segment.getStartPose();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_INACTIVE_WAIT);\n fieldOverlay.strokeCircle(pose.getX(), pose.getY(), 3);\n }\n }\n }\n\n if (currentSegment != null) {\n if (currentSegment instanceof TrajectorySegment) {\n Trajectory currentTrajectory = ((TrajectorySegment) currentSegment).getTrajectory();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_ACTIVE_TRAJECTORY);\n\n DashboardUtil.drawSampledPath(fieldOverlay, currentTrajectory.getPath());\n } else if (currentSegment instanceof TurnSegment) {\n Pose2d pose = currentSegment.getStartPose();\n\n fieldOverlay.setFill(COLOR_ACTIVE_TURN);\n fieldOverlay.fillCircle(pose.getX(), pose.getY(), 3);\n } else if (currentSegment instanceof WaitSegment) {\n Pose2d pose = currentSegment.getStartPose();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_ACTIVE_WAIT);\n fieldOverlay.strokeCircle(pose.getX(), pose.getY(), 3);\n }\n }\n\n if (targetPose != null) {\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(\"#4CAF50\");\n DashboardUtil.drawRobot(fieldOverlay, targetPose);\n }\n\n fieldOverlay.setStroke(\"#3F51B5\");\n DashboardUtil.drawPoseHistory(fieldOverlay, poseHistory);\n\n fieldOverlay.setStroke(\"#3F51B5\");\n DashboardUtil.drawRobot(fieldOverlay, poseEstimate);\n }\n\n public Pose2d getLastPoseError() {\n return lastPoseError;\n }\n\n public boolean isBusy() {\n return currentTrajectorySequence != null;\n }\n}" }, { "identifier": "LynxModuleUtil", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/LynxModuleUtil.java", "snippet": "public class LynxModuleUtil {\n\n private static final LynxFirmwareVersion MIN_VERSION = new LynxFirmwareVersion(1, 8, 2);\n\n /**\n * Parsed representation of a Lynx module firmware version.\n */\n public static class LynxFirmwareVersion implements Comparable<LynxFirmwareVersion> {\n public final int major;\n public final int minor;\n public final int eng;\n\n public LynxFirmwareVersion(int major, int minor, int eng) {\n this.major = major;\n this.minor = minor;\n this.eng = eng;\n }\n\n @Override\n public boolean equals(Object other) {\n if (other instanceof LynxFirmwareVersion) {\n LynxFirmwareVersion otherVersion = (LynxFirmwareVersion) other;\n return major == otherVersion.major && minor == otherVersion.minor &&\n eng == otherVersion.eng;\n } else {\n return false;\n }\n }\n\n @Override\n public int compareTo(LynxFirmwareVersion other) {\n int majorComp = Integer.compare(major, other.major);\n if (majorComp == 0) {\n int minorComp = Integer.compare(minor, other.minor);\n if (minorComp == 0) {\n return Integer.compare(eng, other.eng);\n } else {\n return minorComp;\n }\n } else {\n return majorComp;\n }\n }\n\n @Override\n public String toString() {\n return Misc.formatInvariant(\"%d.%d.%d\", major, minor, eng);\n }\n }\n\n /**\n * Retrieve and parse Lynx module firmware version.\n * @param module Lynx module\n * @return parsed firmware version\n */\n public static LynxFirmwareVersion getFirmwareVersion(LynxModule module) {\n String versionString = module.getNullableFirmwareVersionString();\n if (versionString == null) {\n return null;\n }\n\n String[] parts = versionString.split(\"[ :,]+\");\n try {\n // note: for now, we ignore the hardware entry\n return new LynxFirmwareVersion(\n Integer.parseInt(parts[3]),\n Integer.parseInt(parts[5]),\n Integer.parseInt(parts[7])\n );\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n /**\n * Exception indicating an outdated Lynx firmware version.\n */\n public static class LynxFirmwareVersionException extends RuntimeException {\n public LynxFirmwareVersionException(String detailMessage) {\n super(detailMessage);\n }\n }\n\n /**\n * Ensure all of the Lynx modules attached to the robot satisfy the minimum requirement.\n * @param hardwareMap hardware map containing Lynx modules\n */\n public static void ensureMinimumFirmwareVersion(HardwareMap hardwareMap) {\n Map<String, LynxFirmwareVersion> outdatedModules = new HashMap<>();\n for (LynxModule module : hardwareMap.getAll(LynxModule.class)) {\n LynxFirmwareVersion version = getFirmwareVersion(module);\n if (version == null || version.compareTo(MIN_VERSION) < 0) {\n for (String name : hardwareMap.getNamesOf(module)) {\n outdatedModules.put(name, version);\n }\n }\n }\n if (outdatedModules.size() > 0) {\n StringBuilder msgBuilder = new StringBuilder();\n msgBuilder.append(\"One or more of the attached Lynx modules has outdated firmware\\n\");\n msgBuilder.append(Misc.formatInvariant(\"Mandatory minimum firmware version for Road Runner: %s\\n\",\n MIN_VERSION.toString()));\n for (Map.Entry<String, LynxFirmwareVersion> entry : outdatedModules.entrySet()) {\n msgBuilder.append(Misc.formatInvariant(\n \"\\t%s: %s\\n\", entry.getKey(),\n entry.getValue() == null ? \"Unknown\" : entry.getValue().toString()));\n }\n throw new LynxFirmwareVersionException(msgBuilder.toString());\n }\n }\n}" }, { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 60;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ANG_ACCEL = 3;" }, { "identifier": "MAX_ANG_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ANG_VEL = 3;" }, { "identifier": "MAX_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_VEL = 60;" }, { "identifier": "MOTOR_VELO_PID", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static PIDFCoefficients MOTOR_VELO_PID = new PIDFCoefficients(0, 0, 0,\n getMotorVelocityF(MAX_RPM / 60 * TICKS_PER_REV));" }, { "identifier": "RUN_USING_ENCODER", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static final boolean RUN_USING_ENCODER = false;" }, { "identifier": "TRACK_WIDTH", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double TRACK_WIDTH = 16.4; // in" }, { "identifier": "encoderTicksToInches", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double encoderTicksToInches(double ticks) {\n return WHEEL_RADIUS * 2 * Math.PI * GEAR_RATIO * ticks / TICKS_PER_REV;\n}" }, { "identifier": "kA", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double kA = 0.004;" }, { "identifier": "kStatic", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double kStatic = 0;" }, { "identifier": "kV", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double kV = 0.011;" } ]
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
10,764
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL);
4
2023-11-03 13:32:48+00:00
12k
beminder/BeautyMinder
java/src/test/java/app/beautyminder/service/UserServiceTest.java
[ { "identifier": "PasswordResetToken", "path": "java/src/main/java/app/beautyminder/domain/PasswordResetToken.java", "snippet": "@Document(collection = \"password_tokens\")\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\npublic class PasswordResetToken {\n\n @Id\n private String id;\n\n @CreatedDate\n private LocalDateTime createdAt;\n\n @Setter\n @Indexed(unique = true)\n private String token;\n\n @Indexed(unique = true)\n private String email;\n @Setter\n private LocalDateTime expiryDate;\n\n @Builder\n public PasswordResetToken(String email, String token, LocalDateTime expiryDate) {\n this.email = email;\n this.token = token;\n this.expiryDate = expiryDate;\n }\n}" }, { "identifier": "User", "path": "java/src/main/java/app/beautyminder/domain/User.java", "snippet": "@Document(collection = \"users\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor\n@Getter\npublic class User implements UserDetails {\n\n public static final Integer MAX_HISTORY_SIZE = 10;\n\n @Id\n private String id;\n\n @Indexed(unique = true)\n private String email;\n private String password;\n\n @Setter\n private String nickname;\n @Setter\n private String profileImage;\n @Setter\n private String phoneNumber;\n\n @CreatedDate\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS\")\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n private LocalDateTime createdAt;\n\n @LastModifiedDate\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS\")\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n private LocalDateTime updatedAt;\n\n @Setter\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS\")\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n private LocalDateTime lastLogin;\n\n @JsonDeserialize(using = AuthoritiesDeserializer.class)\n private Set<String> authorities = new HashSet<>();\n\n @Setter\n @Getter\n private Set<String> cosmeticIds = new HashSet<>(); // favourites\n\n @Setter\n @Getter\n private Set<String> keywordHistory = new HashSet<>(); // search history with order\n\n @Indexed\n @Setter\n private String baumann;\n\n @Setter\n private Map<String, Double> baumannScores;\n\n @Builder\n public User(String email, String password, String nickname) {\n this.email = email;\n this.password = password;\n this.nickname = nickname;\n this.authorities = new HashSet<>(Collections.singletonList(\"ROLE_USER\"));\n }\n\n @Builder\n public User(String email, String password, String nickname, String profileImage) {\n this.email = email;\n this.password = password;\n this.nickname = nickname;\n this.profileImage = profileImage;\n this.authorities = new HashSet<>(Collections.singletonList(\"ROLE_USER\"));\n }\n\n @Builder\n public User(String email, String password, String nickname, Set<String> authorities) {\n this.email = email;\n this.password = password;\n this.nickname = nickname;\n this.authorities = authorities;\n }\n\n public User update(String nickname) {\n this.nickname = nickname;\n return this;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return authorities.stream()\n .map(SimpleGrantedAuthority::new)\n .collect(Collectors.toList());\n }\n\n public User addCosmetic(String cosmeticId) {\n this.cosmeticIds.add(cosmeticId);\n return this;\n }\n\n public User removeCosmetic(String cosmeticId) {\n this.cosmeticIds.remove(cosmeticId);\n return this;\n }\n\n public void addAuthority(String authority) {\n this.authorities.add(authority);\n }\n\n public void removeAuthority(String authority) {\n this.authorities.remove(authority);\n }\n\n @Override\n public String getUsername() {\n return email;\n }\n\n @Override\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String newPassword) {\n this.password = newPassword;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public Set<Map.Entry<String, Double>> getBaumannScoreEntries() {\n return this.baumannScores != null ? this.baumannScores.entrySet() : Collections.emptySet();\n }\n}" }, { "identifier": "PasswordResetTokenRepository", "path": "java/src/main/java/app/beautyminder/repository/PasswordResetTokenRepository.java", "snippet": "public interface PasswordResetTokenRepository extends MongoRepository<PasswordResetToken, String> {\n\n Optional<PasswordResetToken> findByToken(String token);\n\n Optional<PasswordResetToken> findByEmail(String email);\n\n void deleteByEmail(String email);\n\n void deleteByExpiryDateBefore(LocalDateTime expiryDate);\n}" }, { "identifier": "RefreshTokenRepository", "path": "java/src/main/java/app/beautyminder/repository/RefreshTokenRepository.java", "snippet": "public interface RefreshTokenRepository extends MongoRepository<RefreshToken, String> {\n\n Optional<RefreshToken> findByUserId(String userId);\n\n Optional<RefreshToken> findByRefreshToken(String refreshToken);\n\n @Query(\"{'expiresAt': {'$lt': ?0}}\")\n List<RefreshToken> findAllExpiredTokens(LocalDateTime now);\n\n List<RefreshToken> findAllByUserId(String userId);\n\n @Query(value = \"{ 'user.$id': ?0 }\", delete = true)\n // delete ALL\n void deleteByUserId(ObjectId userId);\n\n void deleteByRefreshToken(String refreshToken);\n\n void deleteByExpiresAtBefore(LocalDateTime now);\n}" }, { "identifier": "TodoRepository", "path": "java/src/main/java/app/beautyminder/repository/TodoRepository.java", "snippet": "public interface TodoRepository extends MongoRepository<Todo, String> {\n\n List<Todo> findByUserId(String userId);\n\n List<Todo> findByDate(LocalDate date);\n\n @Query(\"{'user.id': ?0, 'date': ?1}\")\n List<Todo> findByUserIdAndDate(String userId, LocalDate date);\n\n @Query(\"{'date': {'$gte': ?0, '$lte': ?1}}\")\n List<Todo> findBetweenDates(LocalDate startDate, LocalDate endDate);\n\n @Query(\"{'user.id': ?0, 'date': {'$gte': ?1, '$lte': ?2}}\")\n List<Todo> findBetweenDatesByUserId(String userId, LocalDate startDate, LocalDate endDate);\n\n @Query(\"{'tasks': {'$regex': ?0, '$options': 'i'}}\")\n List<Todo> findByTaskKeyword(String keyword);\n\n @Query(\"{'user.id': ?0, 'tasks': {'$regex': ?1, '$options': 'i'}}\")\n List<Todo> findByTaskKeywordAndUserId(String userId, String keyword);\n\n @Query(value = \"{ 'user.$id': ?0 }\", delete = true)\n // delete ALL\n void deleteByUserId(ObjectId userId);\n\n boolean existsByDateAndUserId(LocalDate date, String userId);\n\n @Query(\"{ '_id': ?0, 'user.$id': ?1 }\")\n Optional<Todo> findByTodoIdAndUserId(ObjectId todoId, ObjectId userId);\n}" }, { "identifier": "UserRepository", "path": "java/src/main/java/app/beautyminder/repository/UserRepository.java", "snippet": "public interface UserRepository extends MongoRepository<User, String> {\n\n Optional<User> findByEmail(String email);\n\n Optional<User> findByPhoneNumber(String phoneNumber);\n\n Optional<User> findByNickname(String nickname);\n\n List<User> findByProfileImageIsNotNull();\n\n List<User> findByCreatedAtAfter(LocalDateTime date);\n\n List<User> findByBaumann(String baumannSkinType);\n\n @Aggregation(pipeline = {\n \"{ $match: { 'baumannSkinType': ?0 } }\",\n \"{ $sample: { size: 10 } }\"\n })\n List<User> findRandomByBaumann(String baumannSkinType);\n\n @Query(\"{'$or': [{'email': ?0}, {'nickname': ?1}]}\")\n Optional<User> findByEmailOrNickname(String email, String nickname);\n\n Optional<User> findByEmailAndPassword(String email, String password);\n\n @Query(\"{'authorities': ?0}\")\n List<User> findByAuthority(String authority);\n\n void deleteUserByEmail(String email);\n\n void deleteById(@NotNull String userId);\n\n}" }, { "identifier": "EmailService", "path": "java/src/main/java/app/beautyminder/service/auth/EmailService.java", "snippet": "@Slf4j\n@Service\n@RequiredArgsConstructor\npublic class EmailService {\n\n private final JavaMailSender emailSender;\n private final SpringTemplateEngine templateEngine;\n @Value(\"${spring.mail.username}\")\n\n private String FROM_ADDRESS;\n @Value(\"${server.https-text}\")\n private String server;\n\n public MimeMessageHelper createMimeMessageHelper(MimeMessage message) throws MessagingException {\n return new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_NO, StandardCharsets.UTF_8.name());\n }\n\n @Async\n public void sendVerificationEmail(String to, String token) {\n String subject = \"[BeautyMinder] 이메일 인증\";\n\n // HTML content\n Context context = new Context();\n context.setVariable(\"token\", token);\n\n String htmlContent = templateEngine.process(\"passcode\", context);\n\n// String htmlContent = localFileService.readHtmlTemplate(\"templates/passcode.html\");\n// htmlContent = htmlContent.replace(\"${token}\", token);\n// log.info(\"BEMINDER: content: {}\", htmlContent);\n\n try {\n MimeMessage message = emailSender.createMimeMessage();\n MimeMessageHelper helper = createMimeMessageHelper(message);\n\n helper.setTo(to);\n helper.setSubject(subject);\n helper.setText(htmlContent, true); // Set to 'true' to send HTML\n\n emailSender.send(message);\n } catch (MessagingException e) {\n log.error(e.getMessage());\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, \"failed to send an email.\");\n }\n }\n\n @Async\n public void sendPasswordResetEmail(String to, String token) {\n String subject = \"[BeautyMinder] 비밀번호 초기화\";\n\n // HTML content\n String resetUrl = server + \"/user/reset-password?token=\" + token;\n Context context = new Context();\n context.setVariable(\"link\", resetUrl);\n\n String htmlContent = templateEngine.process(\"reset-password-email\", context);\n\n try {\n MimeMessage message = emailSender.createMimeMessage();\n MimeMessageHelper helper = createMimeMessageHelper(message);\n\n helper.setTo(to);\n helper.setSubject(subject);\n helper.setText(htmlContent, true); // Set to 'true' to send HTML\n\n emailSender.send(message);\n } catch (MessagingException e) {\n log.error(e.getMessage());\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, \"failed to send an email.\");\n }\n }\n//\n// @Async\n// public void sendPasswordResetEmail(String to, String token) {\n// String subject = \"[BeautyMinder] 비밀번호 초기화\";\n// String resetUrl = server + \"/user/reset-password?token=\" + token;\n// String text = \"초기화하려면 다음 링크를 가주세요: \" + resetUrl;\n//\n// sendSimpleMessage(to, subject, text);\n// }\n\n public void sendSimpleMessage(String to, String subject, String text) {\n SimpleMailMessage message = new SimpleMailMessage();\n message.setFrom(FROM_ADDRESS);\n message.setTo(to);\n message.setTo(FROM_ADDRESS);\n message.setSubject(subject);\n message.setText(text);\n emailSender.send(message);\n }\n}" }, { "identifier": "TokenService", "path": "java/src/main/java/app/beautyminder/service/auth/TokenService.java", "snippet": "@RequiredArgsConstructor\n@Service\npublic class TokenService {\n\n private static final String CHARACTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n private static final SecureRandom RANDOM = new SecureRandom();\n private final PasswordResetTokenRepository passwordResetTokenRepository;\n private final PasscodeTokenRepository passcodeTokenRepository;\n private final int LENGTH = 6;\n private final long VALID_HOURS = 2;\n private final long VALID_MINUTES = 5;\n\n public static String generateToken(int length) {\n StringBuilder token = new StringBuilder(length);\n\n IntStream.range(0, length).forEach(\n i -> {\n var index = RANDOM.nextInt(CHARACTERS.length());\n token.append(CHARACTERS.charAt(index));\n }\n );\n// for (int i = 0; i < length; i++) {\n// int index = RANDOM.nextInt(CHARACTERS.length());\n// token.append(CHARACTERS.charAt(index));\n// }\n return token.toString();\n }\n\n public PasscodeToken createPasscode(String email) {\n String token = generateToken(LENGTH);\n LocalDateTime expiryDate = LocalDateTime.now().plusMinutes(VALID_MINUTES);\n\n PasscodeToken passwordResetToken = passcodeTokenRepository.findByEmail(email)\n .map(existingToken -> {\n existingToken.setToken(token);\n existingToken.setExpiryDate(expiryDate);\n existingToken.setVerified(false);\n return existingToken;\n })\n .or(() -> Optional.of(PasscodeToken.builder()\n .email(email)\n .token(token)\n .expiryDate(expiryDate)\n .build()))\n .get();\n\n passcodeTokenRepository.save(passwordResetToken);\n\n return passwordResetToken;\n }\n\n public PasswordResetToken createPasswordResetToken(User user) {\n String token = generateToken(LENGTH);\n LocalDateTime expiryDate = LocalDateTime.now().plusHours(VALID_HOURS);\n\n // Using Optional's or() method for cleaner code\n PasswordResetToken passwordResetToken = passwordResetTokenRepository.findByEmail(user.getEmail())\n .map(existingToken -> {\n existingToken.setToken(token);\n existingToken.setExpiryDate(expiryDate);\n return existingToken;\n })\n .or(() -> Optional.of(PasswordResetToken.builder()\n .email(user.getEmail())\n .token(token)\n .expiryDate(expiryDate)\n .build()))\n .get();\n\n passwordResetTokenRepository.save(passwordResetToken);\n\n return passwordResetToken;\n }\n\n public boolean validateVerificationToken(String token) {\n Optional<PasscodeToken> passcodeTokenOpt = passcodeTokenRepository.findByToken(token);\n\n if (passcodeTokenOpt.isEmpty() || passcodeTokenOpt.get().getExpiryDate().isBefore(LocalDateTime.now())) {\n // Token is invalid or expired\n return false;\n }\n\n PasscodeToken passcodeToken = passcodeTokenOpt.get();\n passcodeToken.setVerified(true); // Mark the email as verified\n passcodeTokenRepository.save(passcodeToken);\n\n return true; // Token is valid and email is marked as verified\n }\n\n public void validateAgainAndRemove(String email) {\n Optional<PasscodeToken> passcodeTokenOpt = passcodeTokenRepository.findByEmail(email);\n\n if (passcodeTokenOpt.isEmpty() || passcodeTokenOpt.get().getExpiryDate().isBefore(LocalDateTime.now())) {\n // Token is invalid or expired\n passcodeTokenRepository.deleteByEmail(email);\n }\n }\n\n public PasswordResetToken validateResetToken(String token) {\n PasswordResetToken passwordResetToken = passwordResetTokenRepository.findByToken(token)\n .orElseThrow(() -> new IllegalArgumentException(\"Invalid reset token\"));\n\n if (passwordResetToken.getExpiryDate().isBefore(LocalDateTime.now())) {\n throw new IllegalArgumentException(\"Reset token has expired\");\n }\n\n return passwordResetToken;\n }\n\n public boolean isEmailVerified(String email) {\n return passcodeTokenRepository.findByEmail(email)\n .map(PasscodeToken::isVerified) // Maps the Optional<PasscodeToken> to Optional<Boolean>\n .orElse(false); // Returns false if the Optional is empty (i.e., no token found or email not verified)\n }\n\n public void removePassCodeFor(String email) {\n passcodeTokenRepository.deleteByEmail(email);\n }\n\n\n @PostConstruct\n @Scheduled(cron = \"0 0 2 * * WED\", zone = \"Asia/Seoul\") // Delete all expired tokens at wednesday 2am\n public void deleteAllExpiredTokensOften() {\n passwordResetTokenRepository.deleteByExpiryDateBefore(LocalDateTime.now());\n passcodeTokenRepository.deleteByExpiryDateBefore(LocalDateTime.now());\n }\n}" }, { "identifier": "UserService", "path": "java/src/main/java/app/beautyminder/service/auth/UserService.java", "snippet": "@Slf4j\n@RequiredArgsConstructor\n@Service\npublic class UserService {\n\n private final UserRepository userRepository;\n private final TodoRepository todoRepository;\n private final RefreshTokenRepository refreshTokenRepository;\n private final PasswordResetTokenRepository passwordResetTokenRepository;\n private final EmailService emailService;\n private final TokenService tokenService;\n private final ReviewService reviewService;\n private final CosmeticExpiryService expiryService;\n private final FileStorageService fileStorageService;\n\n private final BCryptPasswordEncoder bCryptPasswordEncoder; // 비용이 높은 작업\n @Value(\"${server.default.user}\")\n private String defaultUserProfilePic;\n @Value(\"${server.default.admin}\")\n private String defaultAdminProfilePic;\n\n // 일반 사용자 저장\n public User saveUser(AddUserRequest dto) throws ResponseStatusException {\n // Email duplicate check\n checkDuplicatedUser(dto.getEmail(), dto.getPhoneNumber());\n\n // User creation\n var user = buildUserFromRequest(dto, defaultUserProfilePic);\n user.addAuthority(\"ROLE_USER\");\n\n return userRepository.save(user);\n }\n\n // 관리자 저장\n public User saveAdmin(AddUserRequest dto) {\n // Email duplicate check\n checkDuplicatedUser(dto.getEmail(), dto.getPhoneNumber());\n\n // Admin creation\n var admin = buildUserFromRequest(dto, defaultAdminProfilePic);\n admin.addAuthority(\"ROLE_ADMIN\");\n\n return userRepository.save(admin);\n }\n\n private User buildUserFromRequest(AddUserRequest dto, String defaultProfilePic) {\n var user = User.builder()\n .email(dto.getEmail())\n .password(bCryptPasswordEncoder.encode(dto.getPassword()))\n .build();\n\n if (dto.getNickname() != null) {\n user.setNickname(dto.getNickname());\n }\n user.setProfileImage(dto.getProfileImage() != null ? dto.getProfileImage() : defaultProfilePic);\n\n var phoneNumber = dto.getPhoneNumber();\n if (phoneNumber != null) {\n phoneNumber = phoneNumber.replace(\"-\", \"\");\n if (isValidKoreanPhoneNumber(phoneNumber)) {\n user.setPhoneNumber(phoneNumber);\n }\n }\n\n if (user.getCosmeticIds() == null) {\n user.setCosmeticIds(new HashSet<>());\n }\n\n return user;\n }\n\n private void checkDuplicatedUser(String email, String phoneNumber) {\n List<String> errors = new ArrayList<>();\n\n userRepository.findByEmail(email)\n .ifPresent(u -> errors.add(\"이메일이 이미 사용 중입니다.\"));\n\n if (phoneNumber != null && !phoneNumber.isEmpty()) {\n userRepository.findByPhoneNumber(phoneNumber)\n .ifPresent(u -> errors.add(\"전화번호가 이미 사용 중입니다.\"));\n }\n\n if (!errors.isEmpty()) {\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, String.join(\" \", errors));\n }\n }\n\n // 사용자 ID로 조회\n// throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"not found\");\n public User findById(String userId) {\n return userRepository.findById(userId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, \"User not found: \" + userId));\n }\n\n // 이메일로 조회\n public Optional<User> findByEmail(String email) {\n return userRepository.findByEmail(email);\n }\n\n // 닉네임으로 조회\n public User findByNickname(String nickname) {\n return userRepository.findByNickname(nickname).orElseThrow(() -> new IllegalArgumentException(\"해당 사용자를 찾을 수 없습니다.\"));\n }\n\n // 프로필 이미지가 있는 사용자 조회\n public List<User> findUsersWithProfileImage() {\n return userRepository.findByProfileImageIsNotNull();\n }\n\n // 특정 날짜 이후에 생성된 사용자 조회\n public List<User> findUsersCreatedAfter(LocalDateTime date) {\n return userRepository.findByCreatedAtAfter(date);\n }\n\n // 이메일이나 닉네임으로 조회\n public User findByEmailOrNickname(String email, String nickname) {\n return userRepository.findByEmailOrNickname(email, nickname).orElseThrow(() -> new IllegalArgumentException(\"해당 사용자를 찾을 수 없습니다.\"));\n }\n\n public Optional<User> findUserByPhoneNumber(String phoneNumber) {\n return userRepository.findByPhoneNumber(phoneNumber);\n }\n\n // 이메일과 비밀번호로 사용자 조회 (로그인)\n public User findByEmailAndPassword(String email, String password) {\n return userRepository.findByEmailAndPassword(email, password).orElseThrow(() -> new IllegalArgumentException(\"이메일 혹은 비밀번호가 틀립니다.\"));\n }\n\n public User addCosmeticById(String userId, String cosmeticId) {\n return userRepository.findById(userId).map(user -> {\n user.addCosmetic(cosmeticId);\n return userRepository.save(user); // Save the updated user to the database\n }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, \"No user found with id: \" + userId));\n }\n\n public User removeCosmeticById(String userId, String cosmeticId) {\n return userRepository.findById(userId).map(user -> {\n user.removeCosmetic(cosmeticId);\n return userRepository.save(user); // Save the updated user to the database\n }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, \"No user found with id: \" + userId));\n }\n\n /*\n Cascading\n If a User is deleted, consider what should happen to their Todo items.\n Should they be deleted as well, or should they remain in the database?\n */\n @Transactional\n public void deleteUserAndRelatedData(String userId) {\n User user = userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException(\"Wrong user id.\"));\n\n // Delete all Todo entries related to the user\n todoRepository.deleteByUserId(new ObjectId(userId));\n\n // Delete all RefreshToken entries related to the user\n refreshTokenRepository.deleteByUserId(new ObjectId(userId));\n\n // Delete user profile picture from S3\n String userProfileImage = user.getProfileImage();\n if (userProfileImage != null && !userProfileImage.isEmpty() &&\n !List.of(defaultUserProfilePic, defaultAdminProfilePic).contains(userProfileImage)) {\n fileStorageService.deleteFile(userProfileImage);\n }\n\n // Delete all reviews made by the user and update cosmetics' scores\n for (var review : reviewService.findAllByUser(user)) {\n reviewService.deleteReview(user, review.getId());\n }\n\n // Delete all expiry items\n expiryService.deleteAllByUserId(userId);\n\n // Delete the User\n userRepository.deleteById(userId);\n\n }\n\n public PasscodeToken requestPassCode(String email) {\n PasscodeToken token = tokenService.createPasscode(email);\n emailService.sendVerificationEmail(email, token.getToken());\n return token;\n }\n\n public void requestPasswordReset(String email) {\n User user = userRepository.findByEmail(email).orElseThrow(() -> new UsernameNotFoundException(\"User not found\"));\n\n PasswordResetToken token = tokenService.createPasswordResetToken(user);\n emailService.sendPasswordResetEmail(user.getEmail(), token.getToken());\n }\n\n\n public PasswordResetResponse requestPasswordResetByNumber(String phoneNumber) {\n User user = userRepository.findByPhoneNumber(phoneNumber).orElseThrow(() -> new UsernameNotFoundException(\"User not found\"));\n PasswordResetToken token = tokenService.createPasswordResetToken(user);\n return new PasswordResetResponse(token, user);\n }\n\n\n public void resetPassword(String token, String newPassword) {\n PasswordResetToken resetToken = passwordResetTokenRepository.findByToken(token).orElseThrow(() -> new IllegalArgumentException(\"Invalid token\"));\n\n if (resetToken.getExpiryDate().isBefore(LocalDateTime.now())) {\n passwordResetTokenRepository.delete(resetToken);\n throw new IllegalArgumentException(\"Token has expired\");\n }\n\n User user = userRepository.findByEmail(resetToken.getEmail()).orElseThrow(() -> new UsernameNotFoundException(\"User not found\"));\n\n user.setPassword(bCryptPasswordEncoder.encode(newPassword));\n userRepository.save(user);\n passwordResetTokenRepository.delete(resetToken);\n }\n\n public void updatePassword(String userId, String currentPassword, String newPassword) {\n userRepository.findById(userId).ifPresentOrElse(\n user -> {\n if (!bCryptPasswordEncoder.matches(currentPassword, user.getPassword())) {\n throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, \"Current password is incorrect.\");\n } else if (bCryptPasswordEncoder.matches(newPassword, user.getPassword())) {\n // If new password is the same as current password\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, \"New password cannot be the same as current password.\");\n }\n\n // Update the password\n user.setPassword(bCryptPasswordEncoder.encode(newPassword));\n userRepository.save(user);\n },\n () -> {\n // If there's no user associated with that ID, throw an exception\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"No user exists with the given ID.\");\n }\n );\n }\n\n public boolean isValidKoreanPhoneNumber(String phoneNumber) {\n return phoneNumber != null && !phoneNumber.isEmpty() && phoneNumber.matches(\"^010\\\\d{8}$\");\n }\n}" }, { "identifier": "CosmeticExpiryService", "path": "java/src/main/java/app/beautyminder/service/cosmetic/CosmeticExpiryService.java", "snippet": "@RequiredArgsConstructor\n@Service\npublic class CosmeticExpiryService {\n\n private final CosmeticExpiryRepository cosmeticExpiryRepository;\n private final MongoService mongoService;\n\n private static void validateAndSetDate(String dateString, DateTimeFormatter formatter,\n java.util.function.Consumer<String> dateSetter) {\n LocalDate.parse(dateString, formatter); // Will throw DateTimeParseException if invalid\n dateSetter.accept(dateString);\n }\n\n public CosmeticExpiry createCosmeticExpiry(String userId, AddExpiryProduct cosmeticExpiryDTO) {\n CosmeticExpiry.CosmeticExpiryBuilder builder = CosmeticExpiry.builder();\n\n // Set values from DTO to builder, checking for null\n if (cosmeticExpiryDTO.getBrandName() != null) {\n builder.brandName(cosmeticExpiryDTO.getBrandName());\n }\n if (cosmeticExpiryDTO.getImageUrl() != null) {\n builder.imageUrl(cosmeticExpiryDTO.getImageUrl());\n }\n if (cosmeticExpiryDTO.getCosmeticId() != null) {\n builder.cosmeticId(cosmeticExpiryDTO.getCosmeticId());\n }\n\n // MUST\n DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;\n\n try {\n validateAndSetDate(cosmeticExpiryDTO.getExpiryDate(), formatter, builder::expiryDate);\n validateAndSetDate(cosmeticExpiryDTO.getOpenedDate(), formatter, builder::openedDate);\n } catch (DateTimeParseException e) {\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, \"Not invalid dates\");\n }\n\n builder.productName(cosmeticExpiryDTO.getProductName());\n builder.expiryRecognized(cosmeticExpiryDTO.isExpiryRecognized());\n builder.opened(cosmeticExpiryDTO.isOpened());\n\n\n // Set the user ID from the User object\n builder.userId(userId);\n\n // Build the CosmeticExpiry object\n CosmeticExpiry cosmeticExpiry = builder.build();\n\n // Save to repository\n return cosmeticExpiryRepository.save(cosmeticExpiry);\n }\n\n public List<CosmeticExpiry> getAllCosmeticExpiriesByUserId(String userId) {\n return cosmeticExpiryRepository.findAllByUserIdOrderByExpiryDateAsc(userId);\n }\n\n public Page<CosmeticExpiry> getPagedAllCosmeticExpiriesByUserId(String userId, Pageable pageable) {\n return cosmeticExpiryRepository.findAllByUserId(userId, pageable);\n }\n\n public CosmeticExpiry getCosmeticExpiry(String userId, String expiryId) {\n Optional<CosmeticExpiry> existingExpiry = cosmeticExpiryRepository.findByUserIdAndId(userId, expiryId);\n if (existingExpiry.isPresent()) {\n return existingExpiry.get();\n } else {\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Cosmetic expiry not found\");\n }\n }\n\n public Optional<CosmeticExpiry> updateCosmeticExpiry(String expiryId, Map<String, Object> updates) {\n return mongoService.updateFields(expiryId, updates, CosmeticExpiry.class);\n }\n\n public void deleteCosmeticExpiry(String userId, String expiryId) {\n Optional<CosmeticExpiry> existingExpiry = cosmeticExpiryRepository.findByUserIdAndId(userId, expiryId);\n if (existingExpiry.isPresent()) {\n cosmeticExpiryRepository.deleteById(expiryId);\n } else {\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Cosmetic expiry not found\");\n }\n }\n\n public List<CosmeticExpiry> filterCosmeticExpiries(String userId, String start, String end) {\n LocalDateTime startDateTime = LocalDate.parse(start).atStartOfDay(); // 00:00:00 of start day\n LocalDateTime endDateTime = LocalDate.parse(end).plusDays(1).atStartOfDay(); // 00:00:00 of the day after end day\n\n return cosmeticExpiryRepository.findAllByUserIdAndExpiryDateBetween(userId, startDateTime, endDateTime);\n }\n\n private DateTimeFormatter parser(String dateStr) {\n DateTimeFormatter formatter;\n if (dateStr.contains(\"-\")) {\n formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\");\n } else {\n formatter = DateTimeFormatter.ofPattern(\"yyyyMMdd\");\n }\n return formatter;\n// return LocalDate.parse(dateStr, formatter);\n }\n\n public void deleteAllByUserId(String userId) {\n cosmeticExpiryRepository.deleteAllByUserId(userId);\n }\n\n public Optional<CosmeticExpiry> findByUserIdAndId(String userId, String expiryId) {\n return cosmeticExpiryRepository.findByUserIdAndId(userId, expiryId);\n }\n}" }, { "identifier": "ReviewService", "path": "java/src/main/java/app/beautyminder/service/review/ReviewService.java", "snippet": "@Slf4j\n@RequiredArgsConstructor\n@Service\npublic class ReviewService {\n\n private final ReviewRepository reviewRepository;\n private final FileStorageService fileStorageService;\n private final CosmeticService cosmeticService;\n private final UserRepository userRepository;\n private final CosmeticRepository cosmeticRepository;\n private final MongoTemplate mongoTemplate;\n private final NlpService nlpService;\n\n public Optional<Review> findById(String id) {\n return reviewRepository.findById(id);\n }\n\n public List<Review> findAllByUser(User user) {\n return reviewRepository.findByUser(user);\n }\n\n public void deleteReview(User user, String id) {\n var review = getReviewById(id)\n .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, \"Review not found\"));\n\n if (!Objects.equals(review.getUser().getId(), user.getId())) {\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Review not found for the user\");\n }\n\n var cosmetic = cosmeticService.findById(review.getCosmetic().getId())\n .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, \"Cosmetic not found\"));\n\n // Update cosmetic's review score and save it\n cosmetic.removeRating(review.getRating());\n cosmeticRepository.save(cosmetic);\n\n review.getImages().forEach(fileStorageService::deleteFile);\n\n // Delete the review by id\n reviewRepository.deleteById(id);\n }\n\n public Review createReview(User user, ReviewDTO reviewDTO, MultipartFile[] images) {\n // Check if the user has already left a review for the cosmetic\n if (HasUserReviewedCosmetic(user.getId(), reviewDTO.getCosmeticId()).isPresent()) {\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, \"User has already reviewed this cosmetic.\");\n }\n\n if (reviewDTO.getContent().isEmpty()) {\n throw new ResponseStatusException(HttpStatus.BAD_REQUEST, \"Don't send empty content.\");\n }\n\n // Find the user and cosmetic, throwing exceptions if not found\n userRepository.findById(user.getId())\n .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, \"User not found\"));\n\n var cosmetic = cosmeticService.findById(reviewDTO.getCosmeticId())\n .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, \"Cosmetic not found\"));\n\n // Create a new review from the DTO\n var review = Review.builder()\n .content(reviewDTO.getContent())\n .rating(reviewDTO.getRating())\n .user(user)\n .cosmetic(cosmetic)\n .isFiltered(false)\n .images(new ArrayList<>()) // Ensure the image list is initialized\n .build();\n\n // Update cosmetic's review score and save it\n cosmetic.increaseTotalCount();\n cosmetic.updateAverageRating(0, review.getRating());\n cosmeticRepository.save(cosmetic);\n\n // Store images and set image URLs in review\n if (images != null) {\n for (var image : images) {\n var imageUrl = fileStorageService.storeFile(image, \"review/\", false);\n review.getImages().add(imageUrl);\n }\n }\n\n // Save the review\n Review savedReview = reviewRepository.save(review);\n\n // !async: Python NLP work\n nlpService.processReviewAsync(savedReview);\n\n return savedReview;\n }\n\n public Optional<Review> updateReview(String revId, User user, ReviewUpdateDTO reviewUpdateDetails, MultipartFile[] images) {\n var query = new Query(Criteria.where(\"id\").is(revId));\n var review = mongoTemplate.findOne(query, Review.class);\n\n if (review != null) {\n if (!Objects.equals(review.getUser().getId(), user.getId())) {\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Review not found for the user\");\n }\n\n int oldRating = review.getRating(); // Store the old rating\n\n // Handle deleted images\n if (reviewUpdateDetails.getImagesToDelete() != null) {\n reviewUpdateDetails.getImagesToDelete().forEach(imageId -> {\n fileStorageService.deleteFile(imageId);\n review.getImages().removeIf(img -> img.equals(imageId));\n });\n }\n\n boolean contentChanged = reviewUpdateDetails.getContent() != null && !reviewUpdateDetails.getContent().equals(review.getContent());\n\n // Update the fields from ReviewDTO\n if (reviewUpdateDetails.getContent() != null) {\n review.setContent(reviewUpdateDetails.getContent());\n }\n if (contentChanged) {\n // Call NLP processing asynchronously\n // If it fails to call the api server, it'll try to queue and rerun periodically\n nlpService.processReviewAsync(review);\n }\n if (reviewUpdateDetails.getRating() != null) {\n review.setRating(reviewUpdateDetails.getRating());\n // Update the cosmetic's average rating\n var cosmetic = review.getCosmetic();\n cosmetic.updateAverageRating(oldRating, review.getRating()); // Update with old and new ratings\n cosmeticRepository.save(cosmetic);\n }\n\n // Handle image upload\n if (images != null) {\n for (var image : images) {\n var originalFilename = image.getOriginalFilename();\n if (originalFilename != null) {\n // Remove the old image if it exists\n review.getImages().removeIf(img -> img.contains(originalFilename));\n // Store the new image and add its URL to the review\n var imageUrl = fileStorageService.storeFile(image, \"review/\", false);\n review.getImages().add(imageUrl);\n }\n }\n }\n\n // Save the updated review\n mongoTemplate.save(review);\n\n return Optional.of(review);\n } else {\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Review not found with id: \" + revId);\n }\n }\n\n public List<Review> getAllReviewsByCosmetic(Cosmetic cosmetic) {\n return reviewRepository.findByCosmetic(cosmetic);\n }\n\n public Page<Review> getAllReviewsByCosmeticInPage(Cosmetic cosmetic, User user, Pageable pageable) {\n // Check if the user has reviewed the cosmetic\n Optional<Review> userReview = reviewRepository.findByUserIdAndCosmeticId(new ObjectId(user.getId()), new ObjectId(cosmetic.getId()));\n\n // Fetch other reviews, excluding the user's review if it exists\n Page<Review> otherReviews = userReview.isPresent()\n ? reviewRepository.findByCosmeticAndUserNot(cosmetic, user, pageable)\n : reviewRepository.findByCosmetic(cosmetic, pageable);\n\n // If the user's review is present, add it to the beginning of the list\n if (userReview.isPresent()) {\n List<Review> reviews = new ArrayList<>();\n reviews.add(userReview.get());\n reviews.addAll(otherReviews.getContent());\n\n // Creating a new PageImpl to maintain pagination\n return new PageImpl<>(reviews, pageable, otherReviews.getTotalElements() + 1);\n }\n\n return otherReviews;\n }\n\n public Optional<Review> getReviewById(String id) {\n return reviewRepository.findById(id);\n }\n\n public List<Review> getReviewsOfBaumann(Integer minRating, String userBaumann) {\n if (userBaumann.isEmpty()) {\n userBaumann = \"OSNT\"; // As default, user Koreans' average one.\n }\n // First, find all users with the specified Baumann skin type.\n List<User> usersWithBaumann = userRepository.findRandomByBaumann(userBaumann);\n\n // Extract the IDs from the users and convert them to ObjectId instances.\n List<ObjectId> userIds = usersWithBaumann.stream()\n .map(user -> new ObjectId(user.getId()))\n .collect(Collectors.toList());\n\n // Now, find all reviews that have a minimum rating and whose user ID is in the list of user IDs.\n Pageable pageable = PageRequest.of(0, 10);\n return reviewRepository.findReviewsByRatingAndUserIds(minRating, userIds, pageable);\n }\n\n public List<Review> getReviewsForRecommendation(Integer minRating, String userBaumann) {\n if (userBaumann.isEmpty()) {\n userBaumann = \"OSNT\"; // As default, user Koreans' average one.\n }\n // Split the user's Baumann skin type into individual characters\n String[] baumannTypes = userBaumann.split(\"\");\n\n // Initialize the criteria for the rating\n Criteria ratingCriteria = Criteria.where(\"rating\").gte(minRating);\n\n // List to hold combined criteria for any two Baumann types\n List<Criteria> combinedBaumannCriteria = new ArrayList<>();\n\n // Combine each Baumann type with every other type to check for any two matches\n for (int i = 0; i < baumannTypes.length; i++) {\n for (int j = i + 1; j < baumannTypes.length; j++) {\n Criteria firstTypeCriteria = Criteria.where(\"nlpAnalysis.\" + baumannTypes[i]).gt(Double.valueOf(\"0.5\"));\n Criteria secondTypeCriteria = Criteria.where(\"nlpAnalysis.\" + baumannTypes[j]).gt(Double.valueOf(\"0.5\"));\n combinedBaumannCriteria.add(new Criteria().andOperator(firstTypeCriteria, secondTypeCriteria));\n }\n }\n\n // Create the final criteria using 'or' operator to combine all two-type matches\n Criteria finalCriteria = ratingCriteria.andOperator(new Criteria().orOperator(combinedBaumannCriteria.toArray(new Criteria[0])));\n\n // Define the aggregation pipeline\n MatchOperation matchOperation = Aggregation.match(finalCriteria);\n SampleOperation sampleOperation = Aggregation.sample(20);\n\n Aggregation aggregation = Aggregation.newAggregation(matchOperation, sampleOperation);\n\n // Execute the aggregation to fetch the random filtered reviews\n AggregationResults<Review> results = mongoTemplate.aggregate(aggregation, Review.class, Review.class);\n return results.getMappedResults();\n }\n\n public Optional<Review> HasUserReviewedCosmetic(String userId, String cosmeticId) {\n return reviewRepository.findByUserIdAndCosmeticId(new ObjectId(userId), new ObjectId(cosmeticId));\n }\n\n public List<Review> findRandomReviewsByRatingAndCosmetic(Integer minRating, Integer maxRating, String cosmeticId, Integer limit) {\n return reviewRepository.findRandomReviewsByRatingAndCosmetic(minRating, maxRating, new ObjectId(cosmeticId), limit);\n }\n}" } ]
import app.beautyminder.domain.PasswordResetToken; import app.beautyminder.domain.User; import app.beautyminder.repository.PasswordResetTokenRepository; import app.beautyminder.repository.RefreshTokenRepository; import app.beautyminder.repository.TodoRepository; import app.beautyminder.repository.UserRepository; import app.beautyminder.service.auth.EmailService; import app.beautyminder.service.auth.TokenService; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticExpiryService; import app.beautyminder.service.review.ReviewService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.server.ResponseStatusException; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*;
10,113
package app.beautyminder.service; @Slf4j @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private UserRepository userRepository; @Mock private TodoRepository todoRepository; @Mock private RefreshTokenRepository refreshTokenRepository; @Mock private PasswordResetTokenRepository passwordResetTokenRepository; @Mock private EmailService emailService; @Mock
package app.beautyminder.service; @Slf4j @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private UserRepository userRepository; @Mock private TodoRepository todoRepository; @Mock private RefreshTokenRepository refreshTokenRepository; @Mock private PasswordResetTokenRepository passwordResetTokenRepository; @Mock private EmailService emailService; @Mock
private TokenService tokenService;
7
2023-11-01 12:37:16+00:00
12k
FallenDeity/GameEngine2DJava
src/main/java/engine/ruby/Window.java
[ { "identifier": "GameObject", "path": "src/main/java/engine/components/GameObject.java", "snippet": "public class GameObject {\n\tprivate static int ID_COUNTER = 0;\n\tprivate final List<Component> components = new ArrayList<>();\n\tpublic transient Transform transform;\n\tprivate String name;\n\tprivate int uid;\n\tprivate boolean serializable = true;\n\tprivate boolean isDestroyed = false;\n\n\tpublic GameObject(String name) {\n\t\tthis.name = name;\n\t\tuid = ID_COUNTER++;\n\t}\n\n\tpublic static void setIdCounter(int id) {\n\t\tID_COUNTER = id;\n\t}\n\n\tpublic <T extends Component> T getComponent(Class<T> componentClass) {\n\t\tfor (Component component : components) {\n\t\t\tif (componentClass.isAssignableFrom(component.getClass())) {\n\t\t\t\ttry {\n\t\t\t\t\treturn componentClass.cast(component);\n\t\t\t\t} catch (ClassCastException e) {\n\t\t\t\t\tLogger logger = Logger.getLogger(name);\n\t\t\t\t\tlogger.severe(e.getMessage());\n\t\t\t\t\tassert false\n\t\t\t\t\t\t\t: \"Error: (GameObject) Could not cast component '\" + componentClass.getName() + \"'\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic <T extends Component> void removeComponent(Class<T> componentClass) {\n\t\tfor (int i = 0; i < components.size(); i++) {\n\t\t\tComponent component = components.get(i);\n\t\t\tif (componentClass.isAssignableFrom(component.getClass())) {\n\t\t\t\tcomponents.remove(component);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<Component> getComponents() {\n\t\treturn components;\n\t}\n\n\tpublic void addComponent(Component component) {\n\t\tcomponent.generateUid();\n\t\tcomponents.add(component);\n\t\tcomponent.gameObject = this;\n\t}\n\n\tpublic void editorUpdate(float dt) {\n\t\tcomponents.forEach(component -> component.editorUpdate(dt));\n\t}\n\n\tpublic void update(float dt) {\n\t\tcomponents.forEach(component -> component.update(dt));\n\t}\n\n\tpublic void start() {\n\t\tcomponents.forEach(Component::start);\n\t}\n\n\tpublic void imGui() {\n\t\tcomponents.forEach(component -> {\n\t\t\tif (ImGui.collapsingHeader(component.getClass().getSimpleName())) {\n\t\t\t\tcomponent.imGui();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void destroy() {\n\t\tif (isDestroyed) return;\n\t\tisDestroyed = true;\n\t\tcomponents.forEach(Component::destroy);\n\t}\n\n\tpublic GameObject copy() {\n\t\tGson gson = new GsonBuilder()\n\t\t\t\t.registerTypeAdapter(Component.class, new ComponentDeserializer())\n\t\t\t\t.registerTypeAdapter(GameObject.class, new GameObjectDeserializer())\n\t\t\t\t.enableComplexMapKeySerialization()\n\t\t\t\t.create();\n\t\tString json = gson.toJson(this);\n\t\tGameObject obj = gson.fromJson(json, GameObject.class);\n\t\tobj.generateUid();\n\t\tobj.getComponents().forEach(Component::generateUid);\n\t\tSpriteRenderer spr = obj.getComponent(SpriteRenderer.class);\n\t\tif (spr != null && spr.getTexture() != null) {\n\t\t\tspr.setTexture(AssetPool.getTexture(spr.getTexture().getFilePath()));\n\t\t}\n\t\treturn obj;\n\t}\n\n\tpublic boolean isDestroyed() {\n\t\treturn isDestroyed;\n\t}\n\n\tpublic void generateUid() {\n\t\tuid = ID_COUNTER++;\n\t}\n\n\tpublic int getUid() {\n\t\treturn uid;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic void setNotSerializable() {\n\t\tserializable = false;\n\t}\n\n\tpublic boolean isSerializable() {\n\t\treturn serializable;\n\t}\n}" }, { "identifier": "EventSystem", "path": "src/main/java/engine/observers/EventSystem.java", "snippet": "public class EventSystem {\n\tprivate static EventSystem instance = null;\n\tprivate final List<Observer> observers;\n\n\tprivate EventSystem() {\n\t\tobservers = new ArrayList<>();\n\t}\n\n\tpublic static EventSystem getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new EventSystem();\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic void addObserver(Observer observer) {\n\t\tobservers.add(observer);\n\t}\n\n\tpublic void removeObserver(Observer observer) {\n\t\tobservers.remove(observer);\n\t}\n\n\tpublic void notify(GameObject gameObject, Event event) {\n\t\tobservers.forEach(observer -> observer.onNotify(gameObject, event));\n\t}\n\n}" }, { "identifier": "Observer", "path": "src/main/java/engine/observers/Observer.java", "snippet": "public interface Observer {\n\tvoid onNotify(GameObject gameObject, Event event);\n}" }, { "identifier": "Event", "path": "src/main/java/engine/observers/events/Event.java", "snippet": "public class Event {\n\tprivate final EventType eventType;\n\n\tpublic Event(EventType eventType) {\n\t\tthis.eventType = eventType;\n\t}\n\n\tpublic EventType getEventType() {\n\t\treturn eventType;\n\t}\n}" }, { "identifier": "Physics2D", "path": "src/main/java/engine/physics2d/Physics2D.java", "snippet": "public class Physics2D {\n\tprivate final Vec2 gravity = new Vec2(0, -10.0f);\n\tprivate final World world = new World(gravity);\n\tprivate float accumulator = 0.0f;\n\n\tpublic Physics2D() {\n\t\tworld.setContactListener(new ContactListener());\n\t}\n\n\tpublic void add(GameObject gameObject) {\n\t\tRigidBody2D rigidBody2D = gameObject.getComponent(RigidBody2D.class);\n\t\tif (rigidBody2D != null && rigidBody2D.getRawBody() == null) {\n\t\t\tTransform tf = gameObject.transform;\n\t\t\tBodyDef bodyDef = new BodyDef();\n\t\t\tbodyDef.angle = (float) Math.toRadians(tf.getRotation());\n\t\t\tbodyDef.angularVelocity = rigidBody2D.getAngularVelocity();\n\t\t\tbodyDef.linearVelocity.set(rigidBody2D.getVelocity().x, rigidBody2D.getVelocity().y);\n\t\t\tbodyDef.position.set(tf.getPosition().x, tf.getPosition().y);\n\t\t\tbodyDef.angularDamping = rigidBody2D.getAngularDamping();\n\t\t\tbodyDef.linearDamping = rigidBody2D.getLinearDamping();\n\t\t\tbodyDef.fixedRotation = rigidBody2D.isFixedRotation();\n\t\t\tbodyDef.bullet = rigidBody2D.isContinuousCollision();\n\t\t\tbodyDef.userData = rigidBody2D.getGameObject();\n\t\t\tbodyDef.gravityScale = rigidBody2D.getGravityScale();\n\n\t\t\tswitch (rigidBody2D.getBodyType()) {\n\t\t\t\tcase DYNAMIC -> bodyDef.type = BodyType.DYNAMIC;\n\t\t\t\tcase KINEMATIC -> bodyDef.type = BodyType.KINEMATIC;\n\t\t\t\tcase STATIC -> bodyDef.type = BodyType.STATIC;\n\t\t\t}\n\n\t\t\tBody body = world.createBody(bodyDef);\n\t\t\tbody.m_mass = rigidBody2D.getMass();\n\t\t\trigidBody2D.setRawBody(body);\n\n\t\t\tCircleCollider circleCollider = gameObject.getComponent(CircleCollider.class);\n\n\t\t\tif (circleCollider != null) {\n\t\t\t\taddCircleCollider(rigidBody2D, circleCollider);\n\t\t\t}\n\n\t\t\tBox2DCollider box2DCollider = gameObject.getComponent(Box2DCollider.class);\n\n\t\t\tif (box2DCollider != null) {\n\t\t\t\taddBox2DCollider(rigidBody2D, box2DCollider);\n\t\t\t}\n\n\t\t\tPillboxCollider pillboxCollider = gameObject.getComponent(PillboxCollider.class);\n\n\t\t\tif (pillboxCollider != null) {\n\t\t\t\taddPillboxCollider(rigidBody2D, pillboxCollider);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic RaycastInfo raycast(GameObject requestedGameObject, Vector2f point1, Vector2f point2) {\n\t\tRaycastInfo raycastInfo = new RaycastInfo(requestedGameObject);\n\t\tworld.raycast(raycastInfo, new Vec2(point1.x, point1.y), new Vec2(point2.x, point2.y));\n\t\treturn raycastInfo;\n\t}\n\n\tpublic void destroyGameObject(GameObject gameObject) {\n\t\tRigidBody2D rigidBody2D = gameObject.getComponent(RigidBody2D.class);\n\t\tif (rigidBody2D != null && rigidBody2D.getRawBody() != null) {\n\t\t\tworld.destroyBody(rigidBody2D.getRawBody());\n\t\t\trigidBody2D.setRawBody(null);\n\t\t}\n\t}\n\n\tpublic void update(float dt) {\n\t\taccumulator += dt;\n\t\tif (accumulator >= 0.0f) {\n\t\t\tfloat timeStep = 1.0f / 60.0f;\n\t\t\taccumulator -= timeStep;\n\t\t\tint velocityIterations = 10;\n\t\t\tint positionIterations = 3;\n\t\t\tworld.step(timeStep, velocityIterations, positionIterations);\n\t\t}\n\t}\n\n\tpublic void resetCircleCollider(RigidBody2D rb, CircleCollider collider) {\n\t\tBody body = rb.getRawBody();\n\t\tif (body == null) return;\n\t\tint fixtureCount = fixtureListSize(body);\n\t\tfor (int i = 0; i < fixtureCount; i++) {\n\t\t\tbody.destroyFixture(body.getFixtureList());\n\t\t}\n\t\taddCircleCollider(rb, collider);\n\t\tbody.resetMassData();\n\t}\n\n\tpublic void resetBox2DCollider(RigidBody2D rb, Box2DCollider collider) {\n\t\tBody body = rb.getRawBody();\n\t\tif (body == null) return;\n\t\tint fixtureCount = fixtureListSize(body);\n\t\tfor (int i = 0; i < fixtureCount; i++) {\n\t\t\tbody.destroyFixture(body.getFixtureList());\n\t\t}\n\t\taddBox2DCollider(rb, collider);\n\t\tbody.resetMassData();\n\t}\n\n\tpublic void resetPillboxCollider(RigidBody2D rb, PillboxCollider collider) {\n\t\tBody body = rb.getRawBody();\n\t\tif (body == null) return;\n\t\tint fixtureCount = fixtureListSize(body);\n\t\tfor (int i = 0; i < fixtureCount; i++) {\n\t\t\tbody.destroyFixture(body.getFixtureList());\n\t\t}\n\t\taddPillboxCollider(rb, collider);\n\t\tbody.resetMassData();\n\t}\n\n\tpublic void addPillboxCollider(RigidBody2D rb, PillboxCollider collider) {\n\t\tBody body = rb.getRawBody();\n\t\tassert body != null : \"RigidBody2D does not have a raw body\";\n\t\taddCircleCollider(rb, collider.getBottomCircle());\n\t\taddBox2DCollider(rb, collider.getBox());\n\t}\n\n\tpublic void addCircleCollider(RigidBody2D rb, CircleCollider collider) {\n\t\tBody body = rb.getRawBody();\n\t\tassert body != null : \"RigidBody2D does not have a raw body\";\n\t\tCircleShape circleShape = new CircleShape();\n\t\tcircleShape.setRadius(collider.getRadius());\n\t\tcircleShape.m_p.set(collider.getOffset().x, collider.getOffset().y);\n\t\tFixtureDef fixtureDef = new FixtureDef();\n\t\tfixtureDef.shape = circleShape;\n\t\tfixtureDef.friction = rb.getFriction();\n\t\tfixtureDef.isSensor = rb.isSensor();\n\t\tfixtureDef.density = 1;\n\t\tfixtureDef.userData = collider.getGameObject();\n\t\tbody.createFixture(fixtureDef);\n\t}\n\n\tpublic void addBox2DCollider(RigidBody2D rb, Box2DCollider collider) {\n\t\tBody body = rb.getRawBody();\n\t\tassert body != null : \"RigidBody2D does not have a raw body\";\n\t\tVector2f size = new Vector2f(collider.getHalfSize()).mul(0.5f);\n\t\tVector2f offset = new Vector2f(collider.getOffset());\n\t\tPolygonShape polygonShape = new PolygonShape();\n\t\tpolygonShape.setAsBox(size.x, size.y, new Vec2(offset.x, offset.y), 0.0f);\n\t\tFixtureDef fixtureDef = new FixtureDef();\n\t\tfixtureDef.shape = polygonShape;\n\t\tfixtureDef.density = 1;\n\t\tfixtureDef.userData = collider.getGameObject();\n\t\tfixtureDef.friction = rb.getFriction();\n\t\tfixtureDef.isSensor = rb.isSensor();\n\t\tbody.createFixture(fixtureDef);\n\t}\n\n\tprivate int fixtureListSize(Body body) {\n\t\tint count = 0;\n\t\tfor (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) {\n\t\t\tcount++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tpublic void setIsSensor(RigidBody2D rigidBody2D) {\n\t\tBody body = rigidBody2D.getRawBody();\n\t\tif (body == null) return;\n\t\tfor (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) {\n\t\t\tfixture.setSensor(rigidBody2D.isSensor());\n\t\t}\n\t}\n\n\tpublic boolean isLocked() {\n\t\treturn world.isLocked();\n\t}\n\n\tpublic Vector2f getGravity() {\n\t\treturn new Vector2f(world.getGravity().x, world.getGravity().y);\n\t}\n\n\tpublic boolean checkOnGround(GameObject gameObject, float innerWidth, float height) {\n\t\tVector2f begin = new Vector2f(gameObject.transform.getPosition()).sub(innerWidth / 2.0f, 0.0f);\n\t\tVector2f end = new Vector2f(begin).add(0.0f, height);\n\t\tRaycastInfo infoB = Window.getPhysics2D().raycast(gameObject, begin, end);\n\t\tVector2f otherEnd = new Vector2f(end).add(innerWidth, 0.0f);\n\t\tVector2f otherBegin = new Vector2f(begin).add(innerWidth, 0.0f);\n\t\tRaycastInfo infoE = Window.getPhysics2D().raycast(gameObject, otherBegin, otherEnd);\n\t\tif (CONSTANTS.DEBUG.getIntValue() == 1) {\n\t\t\tDebugDraw.addLine(otherBegin, otherEnd);\n\t\t\tDebugDraw.addLine(begin, end);\n\t\t}\n\t\treturn (infoB.hit && infoB.hitGameObject != null && infoB.hitGameObject.getComponent(Ground.class) != null) || (infoE.hit && infoE.hitGameObject != null && infoE.hitGameObject.getComponent(Ground.class) != null);\n\t}\n}" }, { "identifier": "LevelEditorScene", "path": "src/main/java/engine/scenes/LevelEditorScene.java", "snippet": "public class LevelEditorScene extends Scene {\n\tprivate final SpriteSheet blocks;\n\tprivate final GameObject editor;\n\n\tpublic LevelEditorScene() {\n\t\teditor = createGameObject(\"Editor\");\n\t\teditor.setNotSerializable();\n\t\teditor.addComponent(new MouseControls());\n\t\teditor.addComponent(new KeyControls());\n\t\teditor.addComponent(new GridLines());\n\t\teditor.addComponent(new EditorCamera(camera));\n\t\teditor.addComponent(new GizmoSystem(this, editor));\n\t\tblocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81);\n\t\taddGameObjectToScene(editor);\n\t\tAssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + \"main-theme-overworld.ogg\").stop();\n\t}\n\n\tpublic boolean gizmoActive() {\n\t\tGizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class);\n\t\treturn gizmoSystem.gizmoActive();\n\t}\n\n\tprivate List<Sound> loadSounds() {\n\t\tString sound_dir = CONSTANTS.SOUNDS_PATH.getValue();\n\t\tFile[] files = new File(sound_dir).listFiles();\n\t\tif (files != null) {\n\t\t\tfor (File file : files) {\n\t\t\t\tif (file.isFile() && file.getName().endsWith(\".ogg\")) {\n\t\t\t\t\tString path = file.getAbsolutePath();\n\t\t\t\t\tAssetPool.getSound(path, false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new ArrayList<>(AssetPool.getSounds());\n\t}\n\n\tprivate void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) {\n\t\tSprite sprite = sheet.getSprite(i);\n\t\tfloat spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3;\n\t\tVector2f[] texCoords = sprite.getTexCoords();\n\t\tint id = sprite.getTextureID();\n\t\tImGui.pushID(i);\n\t\tif (ImGui.imageButton(\n\t\t\t\tid,\n\t\t\t\tspriteWidth,\n\t\t\t\tspriteHeight,\n\t\t\t\ttexCoords[2].x,\n\t\t\t\ttexCoords[0].y,\n\t\t\t\ttexCoords[0].x,\n\t\t\t\ttexCoords[2].y)) {\n\t\t\tGameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue());\n\t\t\tif (!decoration) {\n\t\t\t\tRigidBody2D rb = new RigidBody2D();\n\t\t\t\trb.setBodyType(BodyType.STATIC);\n\t\t\t\tob.addComponent(rb);\n\t\t\t\tBox2DCollider collider = new Box2DCollider();\n\t\t\t\tcollider.setHalfSize(new Vector2f(CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()));\n\t\t\t\tob.addComponent(collider);\n\t\t\t\tob.addComponent(new Ground());\n\t\t\t\tif (i == 12 || i == 33) ob.addComponent(new BreakableBrick());\n\t\t\t}\n\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t}\n\t\tImGui.popID();\n\t\tImVec2 lastButtonPos = ImGui.getItemRectMax();\n\t\tfloat lastButtonX = lastButtonPos.x;\n\t\tfloat nextButtonX = lastButtonX + itemSpacing.x + sprite.getWidth() * 3;\n\t\tif (i + 1 < blocks.getNumSprites() && nextButtonX < windowX + windowSize.x - 30) {\n\t\t\tImGui.sameLine();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void imGui() {\n\t\tImGui.begin(\"Editor\");\n\t\tWindow.getScene().setDefaultScene(JImGui.inputText(\"Scene Name\", Window.getScene().getDefaultScene()));\n\t\teditor.imGui();\n\t\tImGui.end();\n\n\t\tImGui.begin(\"World Blocks\");\n\t\tImVec2 windowPos = ImGui.getWindowPos(), windowSize = ImGui.getWindowSize(), itemSpacing = ImGui.getStyle().getItemSpacing();\n\t\tfloat windowX = windowPos.x + itemSpacing.x;\n\t\tif (ImGui.beginTabBar(\"Tabs\")) {\n\t\t\tif (ImGui.beginTabItem(\"Solid Blocks\")) {\n\t\t\t\tfor (int i = 0; i < blocks.getNumSprites(); i++) {\n\t\t\t\t\tif (i == 34 || (i >= 38 && i < 61)) continue;\n\t\t\t\t\taddBlock(blocks, i, windowSize, itemSpacing, windowX, false);\n\t\t\t\t}\n\t\t\t\tImGui.endTabItem();\n\t\t\t}\n\t\t\tif (ImGui.beginTabItem(\"Decoration Blocks\")) {\n\t\t\t\tfor (int i = 34; i < 61; i++) {\n\t\t\t\t\tif ((i >= 35 && i < 38) || (i >= 42 && i < 45)) continue;\n\t\t\t\t\taddBlock(blocks, i, windowSize, itemSpacing, windowX, true);\n\t\t\t\t}\n\t\t\t\tImGui.endTabItem();\n\t\t\t}\n\t\t\tif (ImGui.beginTabItem(\"Prefabs\")) {\n\t\t\t\tint uid = 0;\n\t\t\t\tSpriteSheet players = AssetPool.getSpriteSheet(CONSTANTS.SPRITE_SHEET_PATH.getValue(), 16, 16, 0, 26);\n\t\t\t\tSprite sprite = players.getSprite(0);\n\t\t\t\tfloat spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3;\n\t\t\t\tint id = sprite.getTextureID();\n\t\t\t\tVector2f[] texCoords = sprite.getTexCoords();\n\t\t\t\tImGui.pushID(uid++);\n\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\tGameObject ob = Prefabs.generateMario();\n\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t}\n\t\t\t\tImGui.popID();\n\t\t\t\tImGui.sameLine();\n\t\t\t\tSpriteSheet items = AssetPool.getSpriteSheet(CONSTANTS.ITEM_SHEET_PATH.getValue(), 16, 16, 0, 43);\n\t\t\t\tsprite = items.getSprite(0);\n\t\t\t\tid = sprite.getTextureID();\n\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\tImGui.pushID(uid++);\n\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\tGameObject ob = Prefabs.generateQuestionBlock();\n\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t}\n\t\t\t\tImGui.popID();\n\t\t\t\tImGui.sameLine();\n\t\t\t\tsprite = items.getSprite(7);\n\t\t\t\tid = sprite.getTextureID();\n\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\tImGui.pushID(uid++);\n\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\tGameObject ob = Prefabs.generateCoin();\n\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t}\n\t\t\t\tImGui.popID();\n\t\t\t\tImGui.sameLine();\n\t\t\t\tint[] goombaFrames = {14, 20};\n\t\t\t\tfor (int i : goombaFrames) {\n\t\t\t\t\tsprite = players.getSprite(i);\n\t\t\t\t\tid = sprite.getTextureID();\n\t\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\t\tImGui.pushID(uid++);\n\t\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\t\tGameObject ob = Prefabs.generateGoomba(i == 20);\n\t\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t\t}\n\t\t\t\t\tImGui.popID();\n\t\t\t\t\tImGui.sameLine();\n\t\t\t\t}\n\t\t\t\tSpriteSheet pipes = AssetPool.getSpriteSheet(CONSTANTS.PIPES_SHEET_PATH.getValue(), 32, 32, 0, 4);\n\t\t\t\tPipeDirection[] directions = List.of(PipeDirection.values()).toArray(new PipeDirection[0]);\n\t\t\t\tint pipeIndex = 0;\n\t\t\t\tfor (PipeDirection direction : directions) {\n\t\t\t\t\tsprite = pipes.getSprite(pipeIndex++);\n\t\t\t\t\tid = sprite.getTextureID();\n\t\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\t\tImGui.pushID(uid++);\n\t\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\t\tGameObject ob = Prefabs.generatePipe(direction);\n\t\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t\t}\n\t\t\t\t\tImGui.popID();\n\t\t\t\t\tImGui.sameLine();\n\t\t\t\t}\n\t\t\t\tSpriteSheet turtles = AssetPool.getSpriteSheet(CONSTANTS.TURTLE_SHEET_PATH.getValue(), 16, 24, 0, 4);\n\t\t\t\tsprite = turtles.getSprite(0);\n\t\t\t\tid = sprite.getTextureID();\n\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\tImGui.pushID(uid++);\n\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\tGameObject ob = Prefabs.generateTurtle();\n\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t}\n\t\t\t\tImGui.popID();\n\t\t\t\tImGui.sameLine();\n\t\t\t\tsprite = items.getSprite(6);\n\t\t\t\tid = sprite.getTextureID();\n\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\tImGui.pushID(uid++);\n\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\tGameObject ob = Prefabs.generateFlag(true);\n\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t}\n\t\t\t\tImGui.popID();\n\t\t\t\tImGui.sameLine();\n\t\t\t\tsprite = items.getSprite(33);\n\t\t\t\tid = sprite.getTextureID();\n\t\t\t\ttexCoords = sprite.getTexCoords();\n\t\t\t\tImGui.pushID(uid++);\n\t\t\t\tif (ImGui.imageButton(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tspriteWidth,\n\t\t\t\t\t\tspriteHeight,\n\t\t\t\t\t\ttexCoords[2].x,\n\t\t\t\t\t\ttexCoords[0].y,\n\t\t\t\t\t\ttexCoords[0].x,\n\t\t\t\t\t\ttexCoords[2].y)) {\n\t\t\t\t\tGameObject ob = Prefabs.generateFlag(false);\n\t\t\t\t\teditor.getComponent(MouseControls.class).setActiveGameObject(ob);\n\t\t\t\t}\n\t\t\t\tImGui.popID();\n\t\t\t\tImGui.sameLine();\n\t\t\t\tImGui.endTabItem();\n\t\t\t}\n\t\t\tif (ImGui.beginTabItem(\"Sounds\")) {\n\t\t\t\tList<Sound> sounds = loadSounds();\n\t\t\t\tfor (Sound sound : sounds) {\n\t\t\t\t\tif (ImGui.button(new File(sound.getPath()).getName())) {\n\t\t\t\t\t\tif (sound.isPlaying()) {\n\t\t\t\t\t\t\tsound.stop();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsound.play();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tImVec2 lastButtonPos = ImGui.getItemRectMax();\n\t\t\t\t\tif (lastButtonPos.x + itemSpacing.x + 100 < windowX + windowSize.x - 70) {\n\t\t\t\t\t\tImGui.sameLine();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tImGui.endTabItem();\n\t\t\t}\n\t\t\tImGui.endTabBar();\n\t\t}\n\t\tImGui.end();\n\t}\n}" }, { "identifier": "LevelScene", "path": "src/main/java/engine/scenes/LevelScene.java", "snippet": "public class LevelScene extends Scene {\n\tprivate final GameObject coin;\n\tpublic int coins = 0;\n\n\tpublic LevelScene() {\n\t\tSpriteSheet items = AssetPool.getSpriteSheet(CONSTANTS.ITEM_SHEET_PATH.getValue(), 16, 16, 0, 43);\n\t\tcoin = Prefabs.generateSpriteObject(items.getSprite(7), 0.2f, 0.2f);\n\t\tGameObject gameUtils = new GameObject(\"GameUtils\");\n\t\tgameUtils.addComponent(new GameCamera(getCamera()));\n\t\taddGameObjectToScene(gameUtils);\n\t\taddGameObjectToScene(coin);\n\t\tAssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + \"main-theme-overworld.ogg\").play();\n\t}\n\n\t@Override\n\tpublic void update(float dt) {\n\t\tsuper.update(dt);\n\t\tfloat x = getCamera().getPosition().x + 5.3f;\n\t\tfloat y = getCamera().getPosition().y + 2.825f;\n\t\tcoin.transform.setPosition(new Vector2f(x, y));\n\t}\n}" }, { "identifier": "Scene", "path": "src/main/java/engine/scenes/Scene.java", "snippet": "public abstract class Scene {\n\tprotected final Renderer renderer = new Renderer();\n\tprotected final List<GameObject> gameObjects = new ArrayList<>();\n\tprotected final Physics2D physics2D;\n\tprotected final Camera camera;\n\tprivate final List<GameObject> pendingGameObjects = new ArrayList<>();\n\tprivate final String storePath = \"%s/scenes\".formatted(CONSTANTS.RESOURCE_PATH.getValue());\n\tprivate boolean isRunning = false;\n\n\tprotected Scene() {\n\t\tload();\n\t\tfor (GameObject g : gameObjects) {\n\t\t\tif (g.getComponent(SpriteRenderer.class) != null) {\n\t\t\t\tSprite sp = g.getComponent(SpriteRenderer.class).getSprite();\n\t\t\t\tif (sp.getTexture() != null) {\n\t\t\t\t\tsp.setTexture(AssetPool.getTexture(sp.getTexture().getFilePath()));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (g.getComponent(StateMachine.class) != null) {\n\t\t\t\tStateMachine sm = g.getComponent(StateMachine.class);\n\t\t\t\tsm.refresh();\n\t\t\t}\n\t\t}\n\t\tcamera = new Camera(new Vector2f());\n\t\tphysics2D = new Physics2D();\n\t}\n\n\tpublic static GameObject createGameObject(String name) {\n\t\tGameObject gameObject = new GameObject(name);\n\t\tgameObject.addComponent(new Transform());\n\t\tgameObject.transform = gameObject.getComponent(Transform.class);\n\t\treturn gameObject;\n\t}\n\n\tpublic final void start() {\n\t\tif (isRunning) return;\n\t\tisRunning = true;\n\t\tfor (GameObject gameObject : gameObjects) {\n\t\t\tgameObject.start();\n\t\t\trenderer.add(gameObject);\n\t\t\tphysics2D.add(gameObject);\n\t\t}\n\t}\n\n\tpublic final void addGameObjectToScene(GameObject gameObject) {\n\t\tif (isRunning) {\n\t\t\tpendingGameObjects.add(gameObject);\n\t\t} else {\n\t\t\tgameObjects.add(gameObject);\n\t\t}\n\t}\n\n\tpublic final void destroy() {\n\t\tgameObjects.forEach(GameObject::destroy);\n\t}\tprivate String defaultScene = Window.getScene() == null ? \"default\" : Window.getScene().getDefaultScene();\n\n\tpublic void update(float dt) {\n\t\tcamera.adjustProjectionMatrix();\n\t\tphysics2D.update(dt);\n\t\tfor (int i = 0; i < gameObjects.size(); i++) {\n\t\t\tGameObject go = gameObjects.get(i);\n\t\t\tgo.update(dt);\n\t\t\tif (go.isDestroyed()) {\n\t\t\t\tgameObjects.remove(i);\n\t\t\t\trenderer.destroyGameObject(go);\n\t\t\t\tphysics2D.destroyGameObject(go);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\tfor (GameObject gameObject : pendingGameObjects) {\n\t\t\tgameObjects.add(gameObject);\n\t\t\tgameObject.start();\n\t\t\trenderer.add(gameObject);\n\t\t\tphysics2D.add(gameObject);\n\t\t}\n\t\tpendingGameObjects.clear();\n\t}\n\n\tpublic void editorUpdate(float dt) {\n\t\tcamera.adjustProjectionMatrix();\n\t\tfor (int i = 0; i < gameObjects.size(); i++) {\n\t\t\tGameObject go = gameObjects.get(i);\n\t\t\tgo.editorUpdate(dt);\n\t\t\tif (go.isDestroyed()) {\n\t\t\t\tgameObjects.remove(i);\n\t\t\t\trenderer.destroyGameObject(go);\n\t\t\t\tphysics2D.destroyGameObject(go);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\tfor (GameObject gameObject : pendingGameObjects) {\n\t\t\tgameObjects.add(gameObject);\n\t\t\tgameObject.start();\n\t\t\trenderer.add(gameObject);\n\t\t\tphysics2D.add(gameObject);\n\t\t}\n\t\tpendingGameObjects.clear();\n\t}\n\n\tpublic void render() {\n\t\trenderer.render();\n\t}\n\n\tpublic final Camera getCamera() {\n\t\treturn camera;\n\t}\n\n\tpublic void imGui() {\n\t}\n\n\tpublic GameObject getGameObject(int uid) {\n\t\treturn gameObjects.stream().filter(gameObject -> gameObject.getUid() == uid).findFirst().orElse(null);\n\t}\n\n\tpublic GameObject getGameObject(String name) {\n\t\treturn gameObjects.stream().filter(gameObject -> gameObject.getName().equals(name)).findFirst().orElse(null);\n\t}\n\n\tpublic <T extends Component> GameObject getGameObject(Class<T> componentClass) {\n\t\treturn gameObjects.stream().filter(gameObject -> gameObject.getComponent(componentClass) != null).findFirst().orElse(null);\n\t}\n\n\tpublic List<GameObject> getGameObjects() {\n\t\treturn gameObjects;\n\t}\n\n\tpublic Physics2D getPhysics2D() {\n\t\treturn physics2D;\n\t}\n\n\tpublic String getDefaultScene() {\n\t\treturn defaultScene;\n\t}\n\n\tpublic void setDefaultScene(String defaultScene) {\n\t\tthis.defaultScene = defaultScene;\n\t}\n\n\tpublic final void export() {\n\t\tGsonBuilder gsonb = new GsonBuilder();\n\t\tgsonb.registerTypeAdapter(Component.class, new ComponentDeserializer());\n\t\tgsonb.registerTypeAdapter(GameObject.class, new GameObjectDeserializer());\n\t\tgsonb.enableComplexMapKeySerialization();\n\t\tGson gson = gsonb.setPrettyPrinting().create();\n\t\ttry {\n\t\t\tFiles.createDirectories(Path.of(storePath));\n\t\t\tString path = \"%s/%s.json\".formatted(storePath, defaultScene);\n\t\t\tFileWriter writer = new FileWriter(path);\n\t\t\twriter.write(gson.toJson(gameObjects.stream().filter(GameObject::isSerializable).toArray()));\n\t\t\twriter.close();\n\t\t\tSystem.out.println(\"Exported scene to: \" + path);\n\t\t} catch (IOException e) {\n\t\t\tLogger logger = Logger.getLogger(getClass().getSimpleName());\n\t\t\tlogger.severe(e.getMessage());\n\t\t}\n\t}\n\n\tpublic final void load() {\n\t\tGsonBuilder gsonb = new GsonBuilder();\n\t\tgsonb.registerTypeAdapter(Component.class, new ComponentDeserializer());\n\t\tgsonb.registerTypeAdapter(GameObject.class, new GameObjectDeserializer());\n\t\tgsonb.enableComplexMapKeySerialization();\n\t\tGson gson = gsonb.create();\n\t\ttry {\n\t\t\tString path = \"%s/%s.json\".formatted(storePath, defaultScene);\n\t\t\tString json = Objects.requireNonNull(Files.readString(Path.of(path)));\n\t\t\tint gId = -1, cId = -1;\n\t\t\tGameObject[] gameObjects = gson.fromJson(json, GameObject[].class);\n\t\t\tgId = Stream.of(gameObjects).mapToInt(GameObject::getUid).max().orElse(gId);\n\t\t\tfor (GameObject gameObject : gameObjects) {\n\t\t\t\taddGameObjectToScene(gameObject);\n\t\t\t\tcId = gameObject.getComponents().stream().mapToInt(Component::getUid).max().orElse(cId);\n\t\t\t}\n\t\t\tGameObject.setIdCounter(++gId);\n\t\t\tComponent.setIdCounter(++cId);\n\t\t\tSystem.out.println(\"Loaded scene from: \" + path);\n\t\t} catch (Exception e) {\n\t\t\tLogger logger = Logger.getLogger(getClass().getSimpleName());\n\t\t\tlogger.severe(e.getMessage());\n\t\t}\n\t}\n\n\n\n\n}" }, { "identifier": "Scenes", "path": "src/main/java/engine/scenes/Scenes.java", "snippet": "public enum Scenes {\n\tLEVEL_EDITOR,\n\tLEVEL_SCENE\n}" }, { "identifier": "AssetPool", "path": "src/main/java/engine/util/AssetPool.java", "snippet": "public class AssetPool {\n\tprivate static final Map<String, Shader> shaders = new HashMap<>();\n\tprivate static final Map<String, Texture> textures = new HashMap<>();\n\tprivate static final Map<String, SpriteSheet> spriteSheets = new HashMap<>();\n\tprivate static final Map<String, Sound> sounds = new HashMap<>();\n\n\tpublic static Shader getShader(String path) {\n\t\tFile file = new File(path);\n\t\tString name = file.getAbsolutePath();\n\t\tif (shaders.containsKey(name)) {\n\t\t\treturn shaders.get(name);\n\t\t}\n\t\tShader shader = new Shader(name).compile();\n\t\tshaders.put(name, shader);\n\t\treturn shader;\n\t}\n\n\tpublic static Texture getTexture(String path) {\n\t\tFile file = new File(path);\n\t\tString name = file.getAbsolutePath();\n\t\tif (textures.containsKey(name)) {\n\t\t\treturn textures.get(name);\n\t\t}\n\t\tTexture texture = new Texture().loadTexture(path);\n\t\ttextures.put(name, texture);\n\t\treturn texture;\n\t}\n\n\tpublic static Texture getTexture(String name, ByteBuffer image, int width, int height, int channels) {\n\t\tif (textures.containsKey(name)) {\n\t\t\treturn textures.get(name);\n\t\t}\n\t\tTexture texture = new Texture();\n\t\ttexture.loadTexture(image, width, height, channels);\n\t\ttextures.put(name, texture);\n\t\treturn texture;\n\t}\n\n\tpublic static SpriteSheet getSpriteSheet(String path, int w, int h, int s, int totalSprites) {\n\t\tFile file = new File(path);\n\t\tString name = file.getAbsolutePath();\n\t\tif (spriteSheets.containsKey(name)) {\n\t\t\treturn spriteSheets.get(name);\n\t\t}\n\t\tSpriteSheet sheet = new SpriteSheet(getTexture(path), w, h, s, totalSprites);\n\t\tspriteSheets.put(name, sheet);\n\t\treturn sheet;\n\t}\n\n\tpublic static Sound getSound(String path) {\n\t\treturn getSound(path, false);\n\t}\n\n\tpublic static Sound getSound(String path, boolean loop) {\n\t\tFile file = new File(path);\n\t\tString name = file.getAbsolutePath();\n\t\tif (sounds.containsKey(name)) {\n\t\t\treturn sounds.get(name);\n\t\t}\n\t\tSound sound = new Sound(path, loop);\n\t\tsounds.put(name, sound);\n\t\treturn sound;\n\t}\n\n\tpublic static Collection<Sound> getSounds() {\n\t\treturn sounds.values();\n\t}\n}" }, { "identifier": "CONSTANTS", "path": "src/main/java/engine/util/CONSTANTS.java", "snippet": "public enum CONSTANTS {\n\tDEBUG(0),\n\tGRID_WIDTH(0.25f),\n\tGRID_HEIGHT(0.25f),\n\tIMGUI_PATH(\"bin/imgui/\"),\n\tRESOURCE_PATH(\"bin/savefiles/\"),\n\tLOGO_PATH(\"assets/images/logo.png\"),\n\tGIZMOS_PATH(\"assets/images/gizmos.png\"),\n\tGAME_FONT_PATH(\"assets/textures/fonts/mario.ttf\"),\n\tFONT_PATH(\"assets/textures/fonts/segoeui.ttf\"),\n\tSOUNDS_PATH(\"assets/sounds/\"),\n\tTURTLE_SHEET_PATH(\"assets/textures/sprites/turtle.png\"),\n\tPIPES_SHEET_PATH(\"assets/textures/sprites/pipes.png\"),\n\tPOWER_SHEET_PATH(\"assets/textures/sprites/power_sprites.png\"),\n\tITEM_SHEET_PATH(\"assets/textures/sprites/items.png\"),\n\tBLOCK_SHEET_PATH(\"assets/textures/sprites/blocks.png\"),\n\tSPRITE_SHEET_PATH(\"assets/textures/sprites/spritesheet.png\"),\n\tFONT_SHADER_PATH(\"assets/shaders/font.glsl\"),\n\tPICKER_SHADER_PATH(\"assets/shaders/picker.glsl\"),\n\tDEFAULT_SHADER_PATH(\"assets/shaders/default.glsl\"),\n\tLINE2D_SHADER_PATH(\"assets/shaders/line2d.glsl\");\n\n\tprivate final String value;\n\tprivate final float intValue;\n\n\tCONSTANTS(float intValue) {\n\t\tthis.intValue = intValue;\n\t\tthis.value = String.valueOf(intValue);\n\t}\n\n\tCONSTANTS(String value) {\n\t\tthis.value = value;\n\t\tthis.intValue = 0;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\tpublic float getIntValue() {\n\t\treturn intValue;\n\t}\n}" } ]
import engine.components.GameObject; import engine.observers.EventSystem; import engine.observers.Observer; import engine.observers.events.Event; import engine.physics2d.Physics2D; import engine.renderer.*; import engine.scenes.LevelEditorScene; import engine.scenes.LevelScene; import engine.scenes.Scene; import engine.scenes.Scenes; import engine.util.AssetPool; import engine.util.CONSTANTS; import org.joml.Vector3f; import org.joml.Vector4f; import org.lwjgl.BufferUtils; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWImage; import org.lwjgl.openal.AL; import org.lwjgl.openal.ALC; import org.lwjgl.openal.ALC10; import org.lwjgl.openal.ALCCapabilities; import org.lwjgl.opengl.GL; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.Objects; import java.util.logging.Logger; import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.openal.ALC10.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.stb.STBImage.stbi_image_free; import static org.lwjgl.stb.STBImage.stbi_load; import static org.lwjgl.system.MemoryUtil.NULL;
9,216
package engine.ruby; public class Window implements Observer { private static final String iconPath = CONSTANTS.LOGO_PATH.getValue(); private static final String title = "Mario"; public static int maxWidth = 0, maxHeight = 0; private static int width = 640, height = 480; private static Window instance = null; private static Scene currentScene = null; private static ImGuiLayer imGuiLayer = null; private static FontRenderer fontRenderer = null; private long glfwWindow, audioDevice, audioContext; private FrameBuffer frameBuffer; private Picker picker; private GameObject currentGameObject = null; private boolean runtimePlaying = false; private double timer = 0; private Window() { EventSystem.getInstance().addObserver(this); } public static Window getInstance() { if (instance == null) { instance = new Window(); } return instance; } public static Scene getScene() { return currentScene; }
package engine.ruby; public class Window implements Observer { private static final String iconPath = CONSTANTS.LOGO_PATH.getValue(); private static final String title = "Mario"; public static int maxWidth = 0, maxHeight = 0; private static int width = 640, height = 480; private static Window instance = null; private static Scene currentScene = null; private static ImGuiLayer imGuiLayer = null; private static FontRenderer fontRenderer = null; private long glfwWindow, audioDevice, audioContext; private FrameBuffer frameBuffer; private Picker picker; private GameObject currentGameObject = null; private boolean runtimePlaying = false; private double timer = 0; private Window() { EventSystem.getInstance().addObserver(this); } public static Window getInstance() { if (instance == null) { instance = new Window(); } return instance; } public static Scene getScene() { return currentScene; }
public static LevelScene getLevelScene() {
6
2023-11-04 13:19:21+00:00
12k
RezaGooner/University-food-ordering
Frames/Profile/NewUserFrame.java
[ { "identifier": "Gender", "path": "Classes/Roles/Gender.java", "snippet": "public enum Gender {\r\n MALE(\"مرد\"),\r\n FEMALE(\"زن\");\r\n\r\n Gender(String label) {\r\n }\r\n}\r" }, { "identifier": "Organization", "path": "Classes/Roles/Organization.java", "snippet": "public enum Organization {\r\n NOT (\"سایر\"),\r\n KOMITE(\"کمیته امام\"),\r\n BEHZISTI(\"سازمان بهزیستی\"),\r\n MOMTAZ(\"دانشجوی ممتاز\");\r\n\r\n private final String label;\r\n\r\n Organization(String label) {\r\n this.label = label;\r\n }\r\n\r\n public String toString() {\r\n return label;\r\n }\r\n}\r" }, { "identifier": "StyledButtonUI", "path": "Classes/Theme/StyledButtonUI.java", "snippet": "public class StyledButtonUI extends BasicButtonUI {\r\n\r\n @Override\r\n public void installUI (JComponent c) {\r\n super.installUI(c);\r\n AbstractButton button = (AbstractButton) c;\r\n button.setOpaque(false);\r\n button.setBorder(new EmptyBorder(5, 15, 5, 15));\r\n }\r\n\r\n @Override\r\n public void paint (Graphics g, JComponent c) {\r\n AbstractButton b = (AbstractButton) c;\r\n paintBackground(g, b, b.getModel().isPressed() ? 2 : 0);\r\n super.paint(g, c);\r\n }\r\n\r\n private void paintBackground (Graphics g, JComponent c, int yOffset) {\r\n Dimension size = c.getSize();\r\n Graphics2D g2 = (Graphics2D) g;\r\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\r\n g.setColor(c.getBackground().darker());\r\n g.fillRoundRect(0, yOffset, size.width, size.height - yOffset, 10, 10);\r\n g.setColor(c.getBackground());\r\n g.fillRoundRect(0, yOffset, size.width, size.height + yOffset - 5, 10, 10);\r\n }\r\n}" }, { "identifier": "LoginFrame", "path": "Frames/LoginFrame.java", "snippet": "public class LoginFrame extends JFrame {\r\n\r\n public static boolean isNumeric(String str) {\r\n if (str == null || str.length() == 0) {\r\n return false;\r\n }\r\n try {\r\n Long.parseLong(str);\r\n } catch (NumberFormatException nfe) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n\r\n private static JTextField idField;\r\n private final JPasswordField passwordField;\r\n private final JLabel statusLabel;\r\n private final JCheckBox showPasswordCheckbox;\r\n private String name , lastName , gender , organization;\r\n public static Color colorButton = new Color(255,255,255);\r\n public static Color colorBackground = new Color(241,255,85);\r\n private String tempID;\r\n\r\n\r\n\r\n\r\n\r\n public LoginFrame() {\r\n setTitle(\"ورود\");\r\n setIconImage(icon.getImage());\r\n setSize(375, 175);\r\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n setLocationRelativeTo(null);\r\n setBackground(colorBackground);\r\n\r\n JLabel idLabel = new JLabel(\": شماره دانشجویی\");\r\n idLabel.setHorizontalAlignment(SwingConstants.CENTER);\r\n idField = new JTextField(10);\r\n JLabel passwordLabel = new JLabel(\": کلمـــه عبــور\");\r\n passwordLabel.setHorizontalAlignment(SwingConstants.CENTER);\r\n passwordField = new JPasswordField(10);\r\n passwordField.setEchoChar('\\u25cf');\r\n showPasswordCheckbox = new JCheckBox(\"نمایش کلمه عبور\");\r\n showPasswordCheckbox.setBackground(colorBackground);\r\n JButton loginButton = new JButton(\"ورود\");\r\n loginButton.setUI(new StyledButtonUI());\r\n loginButton.setBackground(colorButton);\r\n statusLabel = new JLabel(\"\");\r\n\r\n JPanel panel = new JPanel(new GridLayout(4, 1));\r\n panel.setBackground(colorBackground);\r\n panel.add(idLabel);\r\n panel.add(idField);\r\n panel.add(passwordLabel);\r\n panel.add(passwordField);\r\n panel.add(showPasswordCheckbox);\r\n panel.add(loginButton);\r\n panel.add(statusLabel);\r\n\r\n JButton helpButton = new JButton(\"اطلاعیه ها\");\r\n panel.add(helpButton);\r\n\r\n helpButton.addActionListener(new ActionListener() {\r\n\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n\r\n JFrame subWindow = new JFrame();\r\n setIconImage(icon.getImage());\r\n subWindow.setTitle(\"\");\r\n subWindow.setSize(300, 200);\r\n subWindow.setVisible(true);\r\n\r\n try {\r\n FileReader fileReader = new FileReader(HelpPath);\r\n BufferedReader bufferedReader = new BufferedReader(fileReader);\r\n String line;\r\n JPanel panel = new JPanel();\r\n panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));\r\n while ((line = bufferedReader.readLine()) != null) {\r\n if (line.equals(\"***\")) {\r\n panel.add(new JSeparator(JSeparator.HORIZONTAL));\r\n } else {\r\n JLabel label = new JLabel(line);\r\n label.setFont(new Font(\"Arial\", Font.BOLD, 20));\r\n label.setForeground(Color.RED);\r\n panel.add(label);\r\n }\r\n }\r\n JScrollPane scrollPane = new JScrollPane(panel);\r\n subWindow.add(scrollPane);\r\n bufferedReader.close();\r\n } catch (IOException exception) {\r\n }\r\n\r\n JPanel panel = new JPanel();\r\n panel.setLayout(new BorderLayout());\r\n panel.add(helpButton, BorderLayout.CENTER);\r\n panel.addMouseListener(new MouseAdapter() {\r\n public void mouseClicked(MouseEvent e) {\r\n subWindow.setVisible(true);\r\n }\r\n });\r\n\r\n add(panel);\r\n\r\n\r\n FontMetrics fm = helpButton.getFontMetrics(helpButton.getFont());\r\n int textWidth = fm.stringWidth(helpButton.getText());\r\n int textHeight = fm.getHeight();\r\n helpButton.setPreferredSize(new Dimension(textWidth, textHeight));\r\n }\r\n });\r\n\r\n\r\n JMenuBar menuBar = new JMenuBar();\r\n menuBar.setBackground(colorButton);\r\n setJMenuBar(menuBar);\r\n JMenu menu = new JMenu(\"حساب کاربری\");\r\n menu.setBackground(colorButton);\r\n menuBar.add(menu);\r\n JMenuItem adminItem = new JMenuItem(\"ورود مدیریت\");\r\n adminItem.setBackground(colorButton);\r\n menu.add(adminItem);\r\n JMenuItem forgotItem = new JMenuItem(\"فراموشی رمز\");\r\n forgotItem.setBackground(colorButton);\r\n menu.add(forgotItem);\r\n JMenuItem changePassword = new JMenuItem(\"تغییر رمز\");\r\n changePassword.setBackground(colorButton);\r\n menu.add(changePassword);\r\n JMenuItem historyLoginButton = new JMenuItem(\"سابقه ورود\");\r\n historyLoginButton.setBackground(colorButton);\r\n menu.add(historyLoginButton);\r\n JMenuItem newUserItem = new JMenuItem(\"جدید\");\r\n newUserItem.setBackground(colorButton);\r\n menu.add(newUserItem);\r\n JMenuItem exitItem = new JMenuItem(\"خروج\");\r\n exitItem.setBackground(colorButton);\r\n menuBar.add(exitItem);\r\n\r\n adminItem.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n try {\r\n OpenAdminWindow();\r\n } catch (Exception ex) {\r\n }\r\n }\r\n });\r\n\r\n\r\n historyLoginButton.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n try {\r\n showLoginHistory();\r\n } catch (Exception ex) {\r\n }\r\n }\r\n });\r\n\r\n changePassword.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n dispose();\r\n new ChangePasswordFrame();\r\n }\r\n });\r\n\r\n forgotItem.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n dispose();\r\n new ForgotPassword();\r\n }\r\n });\r\n\r\n newUserItem.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n dispose();\r\n new NewUserFrame();\r\n }\r\n });\r\n\r\n exitItem.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n\r\n Object[] options = {\"خیر\", \"بله\"};\r\n\r\n int exitResult = JOptionPane.showOptionDialog(panel, \"آیا خارج می شوید؟\", \"خروج\",\r\n JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,\r\n null, options, options[0]);\r\n if (exitResult == JOptionPane.NO_OPTION) dispose();\r\n }\r\n });\r\n\r\n\r\n\r\n\r\n add(panel);\r\n\r\n loginButton.addActionListener(new LoginButtonListener());\r\n showPasswordCheckbox.addActionListener(new ShowPasswordCheckboxListener());\r\n\r\n\r\n setResizable(false);\r\n setVisible(true);\r\n }\r\n\r\n private boolean isValidLogin(String id, String password) {\r\n boolean isValid = false;\r\n\r\n if (id.length() == 0 ) {\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n statusLabel.setText(\"لطفا شماره دانشجویی را وارد نمایید\");\r\n statusLabel.setForeground(Color.red);\r\n idField.setBackground(Color.YELLOW);\r\n idField.setForeground(Color.black);\r\n\r\n\r\n }else if (! isNumeric(id) ) {\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n statusLabel.setText(\"شماره دانشجویی باید فقط شامل عدد باشد\");\r\n statusLabel.setForeground(Color.red);\r\n idField.setBackground(Color.YELLOW);\r\n idField.setForeground(Color.black);\r\n\r\n\r\n } else if (!isNumeric(id) || id.length() != 10) {\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n statusLabel.setText(\"شماره دانشجویی باید 10 رقمی باشد\");\r\n statusLabel.setForeground(Color.red);\r\n idField.setBackground(Color.YELLOW);\r\n idField.setForeground(Color.black);\r\n\r\n } else if (password.length() == 0 ){\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n statusLabel.setText(\"لطفا کلمه عبور را وارد نمایید\");\r\n statusLabel.setForeground(Color.red);\r\n passwordField.setBackground(Color.YELLOW);\r\n passwordField.setForeground(Color.black);\r\n\r\n\r\n } else if ((password.length() < 8 )||(password.length() > 16) ) {\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n statusLabel.setText(\"کلمه عبور باید بین 8 تا 16 کاراکتر باشد\");\r\n statusLabel.setForeground(Color.red);\r\n passwordField.setBackground(Color.YELLOW);\r\n passwordField.setForeground(Color.black);\r\n\r\n } else {\r\n try {\r\n BufferedReader reader = new BufferedReader(new FileReader(UserPassPath));\r\n String line;\r\n while ((line = reader.readLine()) != null) {\r\n String[] parts = line.split(\",\");\r\n tempID = parts[0] ;\r\n if (tempID.equals(id) && parts[1].equals(password)) {\r\n name = parts[2];\r\n lastName = parts[3];\r\n gender = parts[4];\r\n organization = parts[6];\r\n isValid = true;\r\n break;\r\n }\r\n }\r\n reader.close();\r\n } catch (IOException e) {\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n } }\r\n if (!isValid) {\r\n try {\r\n errorSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n writeLog(\"ناموفق\");\r\n\r\n statusLabel.setText(\"شماره دانشجویی یا کلمه عبور اشتباه است\");\r\n statusLabel.setForeground(Color.red);\r\n Object[] options = { \"خیر\", \"بله\",\"ساخت حساب کاربری جدید\"};\r\n\r\n int noFoundUser = JOptionPane.showOptionDialog(this,\"کاربری با این اطلاعات یافت نشد.\\nآیا مایل هستید رمز خود را بازیابی کنید؟\" , \"خروج\",\r\n JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,\r\n null , options , options[0]);\r\n if (noFoundUser == JOptionPane.NO_OPTION){\r\n dispose();\r\n new ForgotPassword();\r\n } else if (noFoundUser == JOptionPane.CANCEL_OPTION){\r\n dispose();\r\n NewUserFrame frame = new NewUserFrame();\r\n frame.setVisible(true);\r\n }\r\n idField.setBackground(Color.RED);\r\n idField.setForeground(Color.WHITE);\r\n passwordField.setBackground(Color.RED);\r\n passwordField.setForeground(Color.WHITE);\r\n\r\n }\r\n }\r\n\r\n return isValid;\r\n }\r\n\r\n private class LoginButtonListener implements ActionListener {\r\n public void actionPerformed(ActionEvent e) {\r\n String id = idField.getText();\r\n String password = new String(passwordField.getPassword());\r\n statusLabel.setForeground(Color.black);\r\n idField.setBackground(Color.white);\r\n idField.setForeground(Color.black);\r\n passwordField.setBackground(Color.white);\r\n passwordField.setForeground(Color.black);\r\n\r\n if (isValidLogin(id, password)) {\r\n writeLog(\"موفق\");\r\n if (gender.equals(\"MALE\")) {\r\n try {\r\n wellcomeSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n JOptionPane.showMessageDialog(null , \"آقای \" + name + \" \" + lastName + \" خوش آمدید!\");\r\n dispose();\r\n try {\r\n new UniversitySelfRestaurant(id, name + \" \" + lastName , organization);\r\n } catch (FileNotFoundException ex) {\r\n throw new RuntimeException(ex);\r\n }\r\n } else {\r\n try {\r\n wellcomeSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n JOptionPane.showMessageDialog(null , \"خانم \" + name + \" \" + lastName + \" خوش آمدید!\");\r\n dispose();\r\n UniversitySelfRestaurant frame = null;\r\n try {\r\n frame = new UniversitySelfRestaurant(id, name + \" \" + lastName , organization);\r\n } catch (FileNotFoundException ex) {\r\n throw new RuntimeException(ex);\r\n }\r\n frame.setVisible(true);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private class ShowPasswordCheckboxListener implements ActionListener {\r\n public void actionPerformed(ActionEvent e) {\r\n if (showPasswordCheckbox.isSelected()) {\r\n passwordField.setEchoChar((char) 0);\r\n } else {\r\n passwordField.setEchoChar('\\u25cf');\r\n }\r\n }\r\n }\r\n\r\n\r\n public static void writeLog(String message) {\r\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\r\n Date dateTime = new Date();\r\n String datetime = dateTime.toString();\r\n\r\n try {\r\n FileWriter writer = new FileWriter(LogPath, true);\r\n writer.write(idField.getText() + \" , \" + datetime + \" , \" + message + \"\\n\");\r\n writer.close();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n public void showLoginHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException {\r\n String input = (JOptionPane.showInputDialog(null , \"لطفا کد دانشجویی خود را وارد کنید\"));\r\n boolean isFind = false;\r\n\r\n\r\n String[] columnNames = {\" تاریخ \", \" نتیجه ورود \"};\r\n ArrayList<Object[]> dataList = new ArrayList<>();\r\n\r\n Scanner scanner;\r\n try {\r\n scanner = new Scanner(new File(LogPath));\r\n\r\n while (scanner.hasNextLine()) {\r\n String line = scanner.nextLine();\r\n String[] fields = line.split(\" , \");\r\n\r\n if (fields[0].equals(input)) {\r\n String datetime = fields[1];\r\n String result = fields[2];\r\n dataList.add(new Object[]{datetime, result});\r\n isFind = true;\r\n\r\n }\r\n }\r\n\r\n scanner.close();\r\n } catch (FileNotFoundException e) {\r\n errorSound();\r\n JOptionPane.showMessageDialog(null , \" خطا در خواندن فایل \" + e.getMessage() , \"خطا !\" , JOptionPane.ERROR_MESSAGE);\r\n }\r\n\r\n if (isFind) {\r\n Object[][] data = new Object[dataList.size()][];\r\n for (int i = 0; i < dataList.size(); i++) {\r\n data[i] = dataList.get(i);\r\n }\r\n\r\n JTable table = new JTable(data, columnNames);\r\n table.setBackground(colorBackground);\r\n table.setDefaultRenderer(Object.class, new CustomRendererLoginHistory());\r\n table.getTableHeader().setReorderingAllowed(false);\r\n JScrollPane scrollPane = new JScrollPane(table);\r\n\r\n JFrame frame = new JFrame();\r\n frame.setBackground(colorBackground);\r\n frame.setTitle(\" تاریخچه ورود کاربر \" + input);\r\n frame.add(scrollPane);\r\n scrollPane.setPreferredSize(new Dimension(500, table.getPreferredSize().height + 50));\r\n frame.setResizable(false);\r\n frame.pack();\r\n frame.setVisible(true);\r\n } else {\r\n errorSound();\r\n JOptionPane.showMessageDialog(null , \"شما سابقه ورود ندارید!\" , \"توجه!\" , JOptionPane.ERROR_MESSAGE);\r\n }\r\n }\r\n\r\n}\r" }, { "identifier": "BalanceHandler", "path": "Frames/Order/BalanceHandler.java", "snippet": "public class BalanceHandler {\r\n\r\n\r\n\r\n\r\n public static String getBalance(String id) {\r\n\r\n try (BufferedReader br = new BufferedReader(new FileReader(BalancesPath))) {\r\n String line;\r\n /*\r\n در هر خط از فایل اطلاعات بدین صورت ذخیره شده است :\r\n ID : Balance\r\n */\r\n while ((line = br.readLine()) != null) {\r\n if (id.equals(line.split(\" : \")[0])) {\r\n return line.split(\" : \")[1];\r\n }\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n return \"خطا\";\r\n }\r\n\r\n public static void decreaseBalance(String id, int price) {\r\n try (BufferedReader br = new BufferedReader(new FileReader(BalancesPath))) {\r\n StringBuilder sb = new StringBuilder();\r\n String line;\r\n while ((line = br.readLine()) != null) {\r\n if (line.startsWith(id + \" : \")) {\r\n try {\r\n int oldValue = Integer.parseInt(line.split(\" : \")[1].trim());\r\n int newValue = oldValue - price;\r\n sb.append(id).append(\" : \").append(newValue).append(\"\\n\");\r\n } catch (NumberFormatException e) {\r\n sb.append(line).append(\"\\n\");\r\n }\r\n } else {\r\n sb.append(line).append(\"\\n\");\r\n }\r\n }\r\n try (FileWriter writer = new FileWriter(BalancesPath)) {\r\n writer.write(sb.toString());\r\n }\r\n\r\n } catch (FileNotFoundException e) {\r\n throw new RuntimeException(e);\r\n } catch (IOException e) {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n\r\n public static void increaseBalance(String id) throws UnsupportedAudioFileException, LineUnavailableException, IOException {\r\n String input = JOptionPane.showInputDialog(\"میزان مبلغ مورد نظر را وارد نمایید : \");\r\n if ((!input.equals(null)) && (!input.isEmpty())) {\r\n if (!(Integer.parseInt(input) <= 0)) {\r\n int value = Integer.parseInt(input);\r\n try (BufferedReader br = new BufferedReader(new FileReader(BalancesPath))) {\r\n StringBuilder sb = new StringBuilder();\r\n String line;\r\n while ((line = br.readLine()) != null) {\r\n if (line.startsWith(id + \" : \")) {\r\n try {\r\n int oldValue = Integer.parseInt(line.split(\" : \")[1].trim());\r\n int newValue = Integer.parseInt(input) + oldValue;\r\n sb.append(id).append(\" : \").append(newValue).append(\"\\n\");\r\n } catch (NumberFormatException e) {\r\n sb.append(line).append(\"\\n\");\r\n }\r\n } else {\r\n sb.append(line).append(\"\\n\");\r\n }\r\n }\r\n try (FileWriter writer = new FileWriter(BalancesPath)) {\r\n writer.write(sb.toString());\r\n try {\r\n successSound();\r\n } catch (Exception ex) {\r\n\r\n }\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n writeChargeBalance(input, id);\r\n JOptionPane.showMessageDialog(null, \"حساب شما به اندازه \" + input + \" تومان شارژ شذ!\");\r\n } else {\r\n errorSound();\r\n JOptionPane.showMessageDialog(null , \"مقدار نامعتبر !\");\r\n }\r\n }\r\n }\r\n\r\n public static void addNewUser(String id) {\r\n try (FileWriter writer = new FileWriter(BalancesPath, true)) {\r\n writer.write(id + \" : 0\\n\");\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n public static void writeChargeBalance(String cash , String id) throws UnsupportedAudioFileException, LineUnavailableException, IOException {\r\n LocalDate date = LocalDate.now();\r\n LocalTime time = LocalTime.now();\r\n String timeString = time.toString().substring(0 , 7);\r\n String dateTimeString = date.toString();\r\n\r\n try {\r\n FileWriter fileWriter = new FileWriter(ChargeHistoryPath, true);\r\n fileWriter.write(\"\\n\" + id + \" , \" + dateTimeString + \" , \" + timeString + \" , \" + cash);\r\n fileWriter.close();\r\n } catch (Exception e) {\r\n errorSound();\r\n JOptionPane.showMessageDialog(null , e.getMessage());\r\n }\r\n }\r\n\r\n public static void returningOrderCost(String id, int cost) {\r\n try (BufferedReader br = new BufferedReader(new FileReader(BalancesPath))) {\r\n StringBuilder sb = new StringBuilder();\r\n String line;\r\n while ((line = br.readLine()) != null) {\r\n if (line.startsWith(id + \" : \")) {\r\n try {\r\n int oldValue = Integer.parseInt(line.split(\" : \")[1].trim());\r\n int newValue = cost + oldValue;\r\n sb.append(id).append(\" : \").append(newValue).append(\"\\n\");\r\n } catch (NumberFormatException e) {\r\n sb.append(line).append(\"\\n\");\r\n }\r\n } else {\r\n sb.append(line).append(\"\\n\");\r\n }\r\n }\r\n try (FileWriter writer = new FileWriter(BalancesPath)) {\r\n writer.write(sb.toString());\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n public static boolean checkBalance(String id , int cost){\r\n if (getBalance(id).equals(\"0\")){\r\n return false;\r\n } else if (Integer.parseInt(getBalance(id)) < cost) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n}\r" }, { "identifier": "icon", "path": "Classes/Pathes/FilesPath.java", "snippet": "public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r" }, { "identifier": "errorSound", "path": "Classes/Theme/SoundEffect.java", "snippet": "public static void errorSound() throws IOException, UnsupportedAudioFileException, LineUnavailableException {\r\n Path filePath = Paths.get(ErrorSoundPath);\r\n String absolutePath = filePath.toAbsolutePath().toString();\r\n AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(absolutePath));\r\n\r\n Clip clip = AudioSystem.getClip();\r\n\r\n clip.open(audioInputStream);\r\n\r\n clip.start();\r\n}\r" }, { "identifier": "successSound", "path": "Classes/Theme/SoundEffect.java", "snippet": "public static void successSound() throws IOException, UnsupportedAudioFileException, LineUnavailableException {\r\n\r\n Path filePath = Paths.get(SuccessSoundPath);\r\n String absolutePath = filePath.toAbsolutePath().toString();\r\n AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(absolutePath));\r\n\r\n Clip clip = AudioSystem.getClip();\r\n\r\n clip.open(audioInputStream);\r\n\r\n clip.start();\r\n}\r" }, { "identifier": "isNumeric", "path": "Frames/LoginFrame.java", "snippet": "public static boolean isNumeric(String str) {\r\n if (str == null || str.length() == 0) {\r\n return false;\r\n }\r\n try {\r\n Long.parseLong(str);\r\n } catch (NumberFormatException nfe) {\r\n return false;\r\n }\r\n return true;\r\n}\r" }, { "identifier": "UserPassPath", "path": "Classes/Pathes/FilesPath.java", "snippet": "public static String UserPassPath = \"userpass.txt\";\r" } ]
import java.awt.event.*; import java.io.*; import java.util.Scanner; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Classes.Theme.SoundEffect.successSound; import static Frames.LoginFrame.isNumeric; import static Classes.Pathes.FilesPath.UserPassPath; import Classes.Roles.Gender; import Classes.Roles.Organization; import Classes.Theme.StyledButtonUI; import Frames.LoginFrame; import Frames.Order.BalanceHandler; import javax.swing.*; import java.awt.*;
7,465
JLabel genderLabel = new JLabel(": جنسیت"); genderLabel.setHorizontalAlignment(SwingConstants.CENTER); genderComboBox = new JComboBox<>(Gender.values()); genderComboBox.setBackground(colorBackground); employeeCheckBox = new JCheckBox("کارمند"); employeeCheckBox.setBackground(colorBackground); studentCheckBox = new JCheckBox("دانشجو"); studentCheckBox.setBackground(colorBackground); vipStudentCheckBox = new JCheckBox("دانشجوی ویژه"); vipStudentCheckBox.setBackground(colorBackground); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenuItem exitItem = new JMenuItem("بازگشت"); exitItem.setForeground(Color.white); exitItem.setBackground(colorButton); menuBar.add(exitItem); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); new LoginFrame(); } } }); organizationComboBox = new JComboBox<>(Organization.values()); organizationComboBox.setBackground(colorBackground); organizationComboBox.setEnabled(false); JButton registerButton = new JButton("ثبت نام"); registerButton.setUI(new StyledButtonUI()); registerButton.setForeground(Color.white); registerButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(10, 1)); panel.setBackground(colorBackground); panel.add(firstNameLabel); panel.add(firstNameField); panel.add(lastNameLabel); panel.add(lastNameField); panel.add(idLabel); panel.add(idField); panel.add(numberLabel); panel.add(numberField); panel.add(passwordLabel); panel.add(passwordField); panel.add(confirmPasswordLabel); panel.add(confirmPasswordField); panel.add(genderLabel); panel.add(genderComboBox); panel.add(employeeCheckBox); panel.add(studentCheckBox); panel.add(vipStudentCheckBox); panel.add(organizationComboBox); panel.add(registerButton); panel.add(statusLabel); add(panel); setVisible(true); employeeCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (employeeCheckBox.isSelected()) { studentCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); studentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (studentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); vipStudentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vipStudentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); studentCheckBox.setSelected(false); organizationComboBox.setEnabled(true); } else { organizationComboBox.setEnabled(false); } } }); registerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String firstName = firstNameField.getText(); String lastName = lastNameField.getText(); String id = idField.getText(); Gender gender = (Gender) genderComboBox.getSelectedItem(); String password = new String(passwordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); String number = numberField.getText();
package Frames.Profile; /* این کلاس برای ایجاد حساب کاربری جدید ساخته شده است در اغاز پنجره ای باز می شود با ورودی های firstNameField , lastNameField , idField , numberField و همچنین genderComboBox , organizationComboBox و گزینه های Student , VIPStudent و Employee . در ورودی های تعریف شده کاربر بایستی نام و نام خانوادگی ، شناسه و همچنین شماره همراه خود را وارد کند شناسه باید ده عددی ده رقمی باشد . همچنین بسته به نوع کاربر با انتخاب هر کدام از checkBox های دانشجو و کارمند و دانشجوی ویژه باید با عددی خاص شروع شود. شماره همراه نیز باید عددی یازده رقمی باشد. در ضمن همه فیلد های ورودی باید پر شوند. کاربر باید جنسیت خود را از genderComboBox انتخاب کرده و اگر تیک بخش VIPStudent را فعال کند بایستی وضعیت خود را در organizationComboBox مشخص کند تا تخفیف های خرید غذا شامل وی شود سپس بعد از وارد کردن و تایید شدن اطلاعات ، داده ها در مسیر فایل مشخص شده ، به صورت جداشده با کاما نوشته میشوند. */ public class NewUserFrame extends JFrame { private final JTextField firstNameField; private final JTextField lastNameField; private final JTextField idField; private final JTextField numberField; private final JComboBox<Gender> genderComboBox; private final JComboBox<Organization> organizationComboBox; private final JCheckBox employeeCheckBox; private final JCheckBox studentCheckBox; private final JCheckBox vipStudentCheckBox; private final JPasswordField passwordField; private final JPasswordField confirmPasswordField; private final JLabel statusLabel; private String organization ; public static Color colorButton = new Color(19,56,190); public static Color colorBackground = new Color(136,226,242); public NewUserFrame() { setTitle("ثبت نام"); setIconImage(icon.getImage()); setSize(400, 350); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); JLabel firstNameLabel = new JLabel(": نام"); firstNameLabel.setHorizontalAlignment(SwingConstants.CENTER); firstNameField = new JTextField(10); JLabel lastNameLabel = new JLabel(": نام خانوادگی"); lastNameLabel.setHorizontalAlignment(SwingConstants.CENTER); lastNameField = new JTextField(10); JLabel idLabel = new JLabel(": شناسه"); idLabel.setHorizontalAlignment(SwingConstants.CENTER); idField = new JTextField(10); JLabel numberLabel = new JLabel(": شماره همراه"); numberLabel.setHorizontalAlignment(SwingConstants.CENTER); numberField = new JTextField(11); JLabel passwordLabel = new JLabel(": رمز عبور"); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); passwordField = new JPasswordField(10); JLabel confirmPasswordLabel = new JLabel(": تکرار رمز عبور"); confirmPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER); confirmPasswordField = new JPasswordField(10); JLabel genderLabel = new JLabel(": جنسیت"); genderLabel.setHorizontalAlignment(SwingConstants.CENTER); genderComboBox = new JComboBox<>(Gender.values()); genderComboBox.setBackground(colorBackground); employeeCheckBox = new JCheckBox("کارمند"); employeeCheckBox.setBackground(colorBackground); studentCheckBox = new JCheckBox("دانشجو"); studentCheckBox.setBackground(colorBackground); vipStudentCheckBox = new JCheckBox("دانشجوی ویژه"); vipStudentCheckBox.setBackground(colorBackground); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenuItem exitItem = new JMenuItem("بازگشت"); exitItem.setForeground(Color.white); exitItem.setBackground(colorButton); menuBar.add(exitItem); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); new LoginFrame(); } } }); organizationComboBox = new JComboBox<>(Organization.values()); organizationComboBox.setBackground(colorBackground); organizationComboBox.setEnabled(false); JButton registerButton = new JButton("ثبت نام"); registerButton.setUI(new StyledButtonUI()); registerButton.setForeground(Color.white); registerButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(10, 1)); panel.setBackground(colorBackground); panel.add(firstNameLabel); panel.add(firstNameField); panel.add(lastNameLabel); panel.add(lastNameField); panel.add(idLabel); panel.add(idField); panel.add(numberLabel); panel.add(numberField); panel.add(passwordLabel); panel.add(passwordField); panel.add(confirmPasswordLabel); panel.add(confirmPasswordField); panel.add(genderLabel); panel.add(genderComboBox); panel.add(employeeCheckBox); panel.add(studentCheckBox); panel.add(vipStudentCheckBox); panel.add(organizationComboBox); panel.add(registerButton); panel.add(statusLabel); add(panel); setVisible(true); employeeCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (employeeCheckBox.isSelected()) { studentCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); studentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (studentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); vipStudentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vipStudentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); studentCheckBox.setSelected(false); organizationComboBox.setEnabled(true); } else { organizationComboBox.setEnabled(false); } } }); registerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String firstName = firstNameField.getText(); String lastName = lastNameField.getText(); String id = idField.getText(); Gender gender = (Gender) genderComboBox.getSelectedItem(); String password = new String(passwordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); String number = numberField.getText();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(UserPassPath, true))) {
9
2023-11-03 08:35:22+00:00
12k
af19git5/EasyImage
src/main/java/io/github/af19git5/builder/ImageBuilder.java
[ { "identifier": "Image", "path": "src/main/java/io/github/af19git5/entity/Image.java", "snippet": "@Getter\npublic class Image extends Item {\n\n private final BufferedImage bufferedImage;\n\n private int overrideWidth = -1;\n\n private int overrideHeight = -1;\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param file 圖片檔案\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, int y, @NonNull File file) throws ImageException {\n this.setX(x);\n this.setY(y);\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param file 圖片檔案\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, int y, @NonNull File file, int overrideWidth, int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setX(x);\n this.setY(y);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param path 圖片檔案路徑\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, int y, @NonNull String path) throws ImageException {\n this.setX(x);\n this.setY(y);\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param path 圖片檔案路徑\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, int y, @NonNull String path, int overrideWidth, int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setX(x);\n this.setY(y);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param inputStream 資料流\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, int y, @NonNull InputStream inputStream) throws ImageException {\n this.setX(x);\n this.setY(y);\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param inputStream 資料流\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n int x, int y, @NonNull InputStream inputStream, int overrideWidth, int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setX(x);\n this.setY(y);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param file 圖片檔案\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(@NonNull PositionX positionX, int y, @NonNull File file) throws ImageException {\n this.setPositionX(positionX);\n this.setY(y);\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param file 圖片檔案\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n int y,\n @NonNull File file,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setPositionX(positionX);\n this.setY(y);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param path 圖片檔案路徑\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(@NonNull PositionX positionX, int y, @NonNull String path) throws ImageException {\n this.setPositionX(positionX);\n this.setY(y);\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param path 圖片檔案路徑\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n int y,\n @NonNull String path,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setPositionX(positionX);\n this.setY(y);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param inputStream 資料流\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(@NonNull PositionX positionX, int y, @NonNull InputStream inputStream)\n throws ImageException {\n this.setPositionX(positionX);\n this.setY(y);\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param inputStream 資料流\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n int y,\n @NonNull InputStream inputStream,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setPositionX(positionX);\n this.setY(y);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param file 圖片檔案\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, @NonNull PositionY positionY, @NonNull File file) throws ImageException {\n this.setX(x);\n this.setPositionY(positionY);\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param file 圖片檔案\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n int x,\n @NonNull PositionY positionY,\n @NonNull File file,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setX(x);\n this.setPositionY(positionY);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param path 圖片檔案路徑\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, @NonNull PositionY positionY, @NonNull String path) throws ImageException {\n this.setX(x);\n this.setPositionY(positionY);\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param path 圖片檔案路徑\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n int x,\n @NonNull PositionY positionY,\n @NonNull String path,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setX(x);\n this.setPositionY(positionY);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param inputStream 資料流\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(int x, @NonNull PositionY positionY, @NonNull InputStream inputStream)\n throws ImageException {\n this.setX(x);\n this.setPositionY(positionY);\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param inputStream 資料流\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n int x,\n @NonNull PositionY positionY,\n @NonNull InputStream inputStream,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setX(x);\n this.setPositionY(positionY);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param file 圖片檔案\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(@NonNull PositionX positionX, @NonNull PositionY positionY, @NonNull File file)\n throws ImageException {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param file 圖片檔案\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull File file,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(file);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param path 圖片檔案路徑\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(@NonNull PositionX positionX, @NonNull PositionY positionY, @NonNull String path)\n throws ImageException {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param path 圖片檔案路徑\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull String path,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(new File(path));\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param inputStream 資料流\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull InputStream inputStream)\n throws ImageException {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param inputStream 資料流\n * @param overrideWidth 覆寫寬度\n * @param overrideHeight 覆寫高度\n * @throws ImageException 圖檔讀取錯誤\n */\n public Image(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull InputStream inputStream,\n int overrideWidth,\n int overrideHeight)\n throws ImageException {\n if (overrideWidth <= 0 || overrideHeight <= 0) {\n throw new ImageException(\n \"overrideWidth and overrideHeight cannot be less than or equal to 0\");\n }\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.overrideWidth = overrideWidth;\n this.overrideHeight = overrideHeight;\n try {\n bufferedImage = ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new ImageException(e);\n }\n }\n}" }, { "identifier": "Item", "path": "src/main/java/io/github/af19git5/entity/Item.java", "snippet": "@Getter\n@Setter\npublic class Item {\n\n private Integer x = 0;\n\n private Integer y = 0;\n\n private PositionX positionX = PositionX.NONE;\n\n private PositionY positionY = PositionY.NONE;\n}" }, { "identifier": "Text", "path": "src/main/java/io/github/af19git5/entity/Text.java", "snippet": "@Getter\npublic class Text extends Item {\n\n private final String text;\n\n private final Color color;\n\n private final Font font;\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n */\n public Text(int x, int y, @NonNull String text, @NonNull Color color) {\n this.setX(x);\n this.setY(y);\n this.text = text;\n this.color = color;\n this.font = null;\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n */\n public Text(int x, int y, @NonNull String text, @NonNull String colorHex) {\n this.setX(x);\n this.setY(y);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = null;\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n * @param font 文字字體\n */\n public Text(int x, int y, @NonNull String text, @NonNull Color color, Font font) {\n this.setX(x);\n this.setY(y);\n this.text = text;\n this.color = color;\n this.font = font;\n }\n\n /**\n * @param x 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n * @param font 文字字體\n */\n public Text(int x, int y, @NonNull String text, @NonNull String colorHex, Font font) {\n this.setX(x);\n this.setY(y);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = font;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n */\n public Text(@NonNull PositionX positionX, int y, @NonNull String text, @NonNull Color color) {\n this.setPositionX(positionX);\n this.setY(y);\n this.text = text;\n this.color = color;\n this.font = null;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n */\n public Text(\n @NonNull PositionX positionX, int y, @NonNull String text, @NonNull String colorHex) {\n this.setPositionX(positionX);\n this.setY(y);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = null;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n * @param font 文字字體\n */\n public Text(\n @NonNull PositionX positionX,\n int y,\n @NonNull String text,\n @NonNull Color color,\n Font font) {\n this.setPositionX(positionX);\n this.setY(y);\n this.text = text;\n this.color = color;\n this.font = font;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param y 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n * @param font 文字字體\n */\n public Text(\n @NonNull PositionX positionX,\n int y,\n @NonNull String text,\n @NonNull String colorHex,\n Font font) {\n this.setPositionX(positionX);\n this.setY(y);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = font;\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n */\n public Text(int x, @NonNull PositionY positionY, @NonNull String text, @NonNull Color color) {\n this.setX(x);\n this.setPositionY(positionY);\n this.text = text;\n this.color = color;\n this.font = null;\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n */\n public Text(\n int x, @NonNull PositionY positionY, @NonNull String text, @NonNull String colorHex) {\n this.setX(x);\n this.setPositionY(positionY);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = null;\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n * @param font 文字字體\n */\n public Text(\n int x,\n @NonNull PositionY positionY,\n @NonNull String text,\n @NonNull Color color,\n Font font) {\n this.setX(x);\n this.setPositionY(positionY);\n this.text = text;\n this.color = color;\n this.font = font;\n }\n\n /**\n * @param x 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n * @param font 文字字體\n */\n public Text(\n int x,\n @NonNull PositionY positionY,\n @NonNull String text,\n @NonNull String colorHex,\n Font font) {\n this.setX(x);\n this.setPositionY(positionY);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = font;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n */\n public Text(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull String text,\n @NonNull Color color) {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.text = text;\n this.color = color;\n this.font = null;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n */\n public Text(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull String text,\n @NonNull String colorHex) {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = null;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param color 文字顏色\n * @param font 文字字體\n */\n public Text(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull String text,\n @NonNull Color color,\n Font font) {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.text = text;\n this.color = color;\n this.font = font;\n }\n\n /**\n * @param positionX 放置x軸位置\n * @param positionY 放置y軸位置\n * @param text 文字內容\n * @param colorHex 文字顏色(16進位色碼)\n * @param font 文字字體\n */\n public Text(\n @NonNull PositionX positionX,\n @NonNull PositionY positionY,\n @NonNull String text,\n @NonNull String colorHex,\n Font font) {\n this.setPositionX(positionX);\n this.setPositionY(positionY);\n this.text = text;\n this.color = Color.decode(colorHex);\n this.font = font;\n }\n}" }, { "identifier": "ImageException", "path": "src/main/java/io/github/af19git5/exception/ImageException.java", "snippet": "public class ImageException extends Exception {\n\n public ImageException(String message) {\n super(message);\n }\n\n public ImageException(Exception e) {\n super(e);\n }\n}" }, { "identifier": "OutputType", "path": "src/main/java/io/github/af19git5/type/OutputType.java", "snippet": "@Getter\npublic enum OutputType {\n JPG(\"jpg\"),\n\n PNG(\"png\"),\n ;\n\n private final String type;\n\n OutputType(String type) {\n this.type = type;\n }\n}" } ]
import io.github.af19git5.entity.Image; import io.github.af19git5.entity.Item; import io.github.af19git5.entity.Text; import io.github.af19git5.exception.ImageException; import io.github.af19git5.type.OutputType; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import javax.imageio.ImageIO;
8,086
package io.github.af19git5.builder; /** * 圖片建構器 * * @author Jimmy Kang */ public class ImageBuilder { private final int width; private final int height; private final Color backgroundColor; private final List<Item> itemList = new ArrayList<>(); /** * @param width 圖片寬 * @param height 圖片高 */ public ImageBuilder(int width, int height) { this.width = width; this.height = height; this.backgroundColor = Color.WHITE; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColor 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, Color backgroundColor) { this.width = width; this.height = height; this.backgroundColor = backgroundColor; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColorHex 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, String backgroundColorHex) { this.width = width; this.height = height; this.backgroundColor = Color.decode(backgroundColorHex); } /** * 加入文字 * * @param text 文字物件 */ public ImageBuilder add(Text text) { this.itemList.add(text); return this; } /** * 加入圖片 * * @param image 圖片物件 */
package io.github.af19git5.builder; /** * 圖片建構器 * * @author Jimmy Kang */ public class ImageBuilder { private final int width; private final int height; private final Color backgroundColor; private final List<Item> itemList = new ArrayList<>(); /** * @param width 圖片寬 * @param height 圖片高 */ public ImageBuilder(int width, int height) { this.width = width; this.height = height; this.backgroundColor = Color.WHITE; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColor 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, Color backgroundColor) { this.width = width; this.height = height; this.backgroundColor = backgroundColor; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColorHex 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, String backgroundColorHex) { this.width = width; this.height = height; this.backgroundColor = Color.decode(backgroundColorHex); } /** * 加入文字 * * @param text 文字物件 */ public ImageBuilder add(Text text) { this.itemList.add(text); return this; } /** * 加入圖片 * * @param image 圖片物件 */
public ImageBuilder add(Image image) {
0
2023-11-01 03:55:06+00:00
12k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/main/RenderBoard.java
[ { "identifier": "ImageCache", "path": "src/main/java/com/chadfield/shogiexplorer/objects/ImageCache.java", "snippet": "public class ImageCache {\n\n private Map<String, BaseMultiResolutionImage> imageMap = new HashMap<>();\n\n public void putImage(String identifier, BaseMultiResolutionImage image) {\n getImageMap().put(identifier, image);\n }\n\n public BaseMultiResolutionImage getImage(String identifier) {\n if (getImageMap().containsKey(identifier)) {\n return getImageMap().get(identifier);\n } else {\n return null;\n }\n }\n\n /**\n * @return the imageMap\n */\n public Map<String, BaseMultiResolutionImage> getImageMap() {\n return imageMap;\n }\n\n /**\n * @param imageMap the imageMap to set\n */\n public void setImageMap(Map<String, BaseMultiResolutionImage> imageMap) {\n this.imageMap = imageMap;\n }\n}" }, { "identifier": "Koma", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Koma.java", "snippet": "public class Koma {\n\n public enum Type {\n SFU, SGI, SGY, SHI, SKA, SKE, SKI, SKY, SNG, SNK, SNY, SOU, SRY, STO, SUM,\n GFU, GGI, GGY, GHI, GKA, GKE, GKI, GKY, GNG, GNK, GNY, GOU, GRY, GTO, GUM\n }\n\n private final Type type;\n\n public Koma(Type komaType) {\n type = komaType;\n }\n\n /**\n * @return the type\n */\n public Type getType() {\n return type;\n }\n}" }, { "identifier": "Board", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Board.java", "snippet": "public class Board {\n\n public enum Turn {\n SENTE, GOTE\n }\n\n private Koma[][] masu = new Koma[9][9];\n private Map<Koma.Type, Integer> inHandKomaMap;\n private Turn nextTurn;\n private int moveCount;\n private Coordinate source = null;\n private Coordinate destination = null;\n private Coordinate edit = null;\n\n public Board() {\n\n for (int i = 0;\n i < 9; i++) {\n for (int j = 0; j < 9; j++) {\n masu[i][j] = null;\n }\n }\n }\n\n /**\n * @return the masu\n */\n public Koma[][] getMasu() {\n return masu;\n }\n\n /**\n * @param masu the masu to set\n */\n public void setMasu(Koma[][] masu) {\n this.masu = masu;\n }\n\n /**\n * @return the inHandKomaMap\n */\n public Map<Koma.Type, Integer> getInHandKomaMap() {\n return inHandKomaMap;\n }\n\n /**\n * @param inHandKomaMap the inHandKomaMap to set\n */\n public void setInHandKomaMap(Map<Koma.Type, Integer> inHandKomaMap) {\n this.inHandKomaMap = inHandKomaMap;\n }\n\n /**\n * @return the nextTurn\n */\n public Turn getNextTurn() {\n return nextTurn;\n }\n\n /**\n * @param nextTurn the nextTurn to set\n */\n public void setNextTurn(Turn nextTurn) {\n this.nextTurn = nextTurn;\n }\n\n /**\n * @return the moveCount\n */\n public int getMoveCount() {\n return moveCount;\n }\n\n /**\n * @param moveCount the moveCount to set\n */\n public void setMoveCount(int moveCount) {\n this.moveCount = moveCount;\n }\n\n /**\n * @return the source\n */\n public Coordinate getSource() {\n return source;\n }\n\n /**\n * @param source the source to set\n */\n public void setSource(Coordinate source) {\n this.source = source;\n }\n\n /**\n * @return the destination\n */\n public Coordinate getDestination() {\n return destination;\n }\n\n /**\n * @param destination the destination to set\n */\n public void setDestination(Coordinate destination) {\n this.destination = destination;\n }\n\n /**\n * @return the edit\n */\n public Coordinate getEdit() {\n return edit;\n }\n\n /**\n * @param edit the edit to set\n */\n public void setEdit(Coordinate edit) {\n this.edit = edit;\n }\n\n}" }, { "identifier": "MathUtils", "path": "src/main/java/com/chadfield/shogiexplorer/utils/MathUtils.java", "snippet": "public class MathUtils {\n\n public static final int KOMA_X = 43;\n public static final int KOMA_Y = 48;\n public static final int BOARD_XY = 9;\n public static final int COORD_XY = 20;\n\n private MathUtils() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n}" }, { "identifier": "ImageUtils", "path": "src/main/java/com/chadfield/shogiexplorer/utils/ImageUtils.java", "snippet": "public class ImageUtils {\n\n private static final String OS = System.getProperty(\"os.name\").toLowerCase();\n public static final boolean IS_WINDOWS = (OS.contains(\"win\"));\n public static final boolean IS_MAC = (OS.contains(\"mac\"));\n public static final boolean IS_LINUX = (OS.contains(\"nux\"));\n\n private ImageUtils() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n public static JLabel getPieceLabelForKoma(Image image, Coordinate boardCoord, Dimension offset, Coordinate imageLocation) {\n JLabel pieceLabel = new JLabel(new ImageIcon(image));\n pieceLabel.setBounds(\n imageLocation.getX() + (boardCoord.getX() * MathUtils.KOMA_X + offset.getWidth()),\n imageLocation.getY() + (boardCoord.getY() * MathUtils.KOMA_Y + offset.getHeight()),\n MathUtils.KOMA_X,\n MathUtils.KOMA_Y);\n return pieceLabel;\n }\n\n public static JLabel getPieceLabelForKoma(Image image, Coordinate boardCoord, Dimension offset, Coordinate imageLocation, double scale) {\n JLabel pieceLabel = new JLabel(new ImageIcon(image));\n pieceLabel.setBounds(\n (int) Math.round((imageLocation.getX() + (boardCoord.getX() * MathUtils.KOMA_X + offset.getWidth())) * scale),\n (int) Math.round((imageLocation.getY() + (boardCoord.getY() * MathUtils.KOMA_Y + offset.getHeight())) * scale),\n (int) Math.round(MathUtils.KOMA_X * scale),\n (int) Math.round(MathUtils.KOMA_Y * scale));\n return pieceLabel;\n }\n\n public static JLabel getTextLabelForBan(Coordinate boardCoord, Dimension offset, Coordinate imageLocation, String text, double scale) {\n JLabel numberLabel = new JLabel(text);\n numberLabel.setBounds(\n (int) Math.round((imageLocation.getX() + (boardCoord.getX() * MathUtils.KOMA_X + offset.getWidth())) * scale),\n (int) Math.round((imageLocation.getY() + (boardCoord.getY() * MathUtils.KOMA_Y + offset.getHeight())) * scale),\n (int) Math.round(MathUtils.KOMA_X * scale),\n (int) Math.round(MathUtils.KOMA_Y * scale));\n Font labelFont = numberLabel.getFont();\n if (IS_LINUX) {\n numberLabel.setFont(new Font(\"Mincho\", Font.BOLD, labelFont.getSize()));\n } else {\n numberLabel.setFont(new Font(labelFont.getName(), Font.BOLD, labelFont.getSize()));\n }\n return numberLabel;\n }\n\n public static BaseMultiResolutionImage loadPNGImageFromResources(String imageName) {\n BufferedImage image1 = null;\n BufferedImage image2 = null;\n BufferedImage image3 = null;\n BufferedImage image4 = null;\n\n try {\n image1 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \".png\"));\n image2 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"@1.25x.png\"));\n image3 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"@1.5x.png\"));\n image4 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"@2x.png\"));\n } catch (IOException ex) {\n Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);\n }\n BaseMultiResolutionImage mri = new BaseMultiResolutionImage(image1, image2, image3, image4);\n return (mri);\n\n }\n\n public static BaseMultiResolutionImage loadSVGImageFromResources(String imageName, Dimension imageDimension, double scale) {\n BufferedImage image1 = null;\n BufferedImage image2 = null;\n BufferedImage image3 = null;\n BufferedImage image4 = null;\n\n try {\n InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(imageName + \".svg\");\n image1 = transcodeSVGToBufferedImage(inputStream, imageDimension.getWidth() * scale);\n inputStream.close();\n inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(imageName + \".svg\");\n image2 = transcodeSVGToBufferedImage(inputStream, (imageDimension.getWidth() * 1.25) * scale);\n inputStream.close();\n inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(imageName + \".svg\");\n image3 = transcodeSVGToBufferedImage(inputStream, (imageDimension.getWidth() * 1.5) * scale);\n inputStream.close();\n inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(imageName + \".svg\");\n image4 = transcodeSVGToBufferedImage(inputStream, (imageDimension.getWidth() * 2.0) * scale);\n inputStream.close();\n } catch (TranscoderException | IOException ex) {\n Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);\n }\n\n BaseMultiResolutionImage mri = new BaseMultiResolutionImage(image1, image2, image3, image4);\n return (mri);\n }\n\n public static BufferedImage transcodeSVGToBufferedImage(InputStream inputStream, double width) throws TranscoderException {\n // Create a PNG transcoder.\n PNGTranscoder t = new PNGTranscoder();\n\n // Set the transcoding hints.\n t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, (float) width);\n\n try {\n // Create the transcoder input.\n TranscoderInput input = new TranscoderInput(inputStream);\n\n // Create the transcoder output.\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n TranscoderOutput output = new TranscoderOutput(outputStream);\n\n // Save the image.\n t.transcode(input, output);\n\n // Flush and close the stream.\n outputStream.flush();\n outputStream.close();\n\n // Convert the byte stream into an image.\n byte[] imgData = outputStream.toByteArray();\n return ImageIO.read(new ByteArrayInputStream(imgData));\n\n } catch (IOException | TranscoderException ex) {\n Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);\n }\n return null;\n }\n\n public static Image loadIconImageFromResources(String imageName) {\n Image image1 = null;\n Image image2 = null;\n try {\n image1 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_128x128.png\"));\n image2 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_256x256.png\"));\n } catch (IOException ex) {\n Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);\n }\n BaseMultiResolutionImage mri = new BaseMultiResolutionImage(image1, image2);\n return (mri);\n }\n\n public static Image loadTaskbarImageFromResources(String imageName) {\n Image image1 = null;\n Image image2 = null;\n Image image3 = null;\n Image image4 = null;\n Image image5 = null;\n Image image6 = null;\n try {\n image1 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_16x16.png\"));\n image2 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_32x32.png\"));\n image3 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_64x64.png\"));\n image4 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_128x128.png\"));\n image5 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_256x256.png\"));\n image6 = ImageIO.read(ClassLoader.getSystemClassLoader().getResource(imageName + \"_512x512.png\"));\n\n } catch (IOException ex) {\n Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex);\n }\n BaseMultiResolutionImage mri = new BaseMultiResolutionImage(image1, image2, image3, image4, image5, image6);\n return (mri);\n }\n\n public static void drawLabel(JPanel boardPanel, Coordinate imageCoordinate, Dimension imageDimension, Coordinate offset, Color color, double scale) {\n JLabel imageLabel = new JLabel();\n imageLabel.setBounds(\n (int) Math.round((offset.getX() + imageCoordinate.getX()) * scale),\n (int) Math.round((offset.getY() + imageCoordinate.getY()) * scale),\n (int) Math.round((imageDimension.getWidth()) * scale),\n (int) Math.round((imageDimension.getHeight()) * scale));\n imageLabel.setBackground(color);\n imageLabel.setOpaque(true);\n boardPanel.add(imageLabel);\n }\n\n public static void drawPNGImage(ImageCache imageCache, JPanel boardPanel, String imageName, Coordinate imageCoordinate, Dimension imageDimension, Coordinate offset, double scale) {\n BaseMultiResolutionImage imageFile = imageCache.getImage(imageName + scale);\n if (imageFile == null) {\n imageFile = loadPNGImageFromResources(imageName);\n imageCache.putImage(imageName + scale, imageFile);\n }\n JLabel imageLabel = new JLabel(new ImageIcon(imageFile));\n imageLabel.setBounds(\n (int) Math.round((offset.getX() + imageCoordinate.getX()) * scale),\n (int) Math.round((offset.getY() + imageCoordinate.getY()) * scale),\n (int) Math.round((imageDimension.getWidth()) * scale),\n (int) Math.round((imageDimension.getHeight()) * scale));\n boardPanel.add(imageLabel);\n }\n\n public static void drawImage(ImageCache imageCache, JPanel boardPanel, String imageName, Coordinate imageCoordinate, Dimension imageDimension, Coordinate offset, double scale) {\n BaseMultiResolutionImage imageFile = imageCache.getImage(imageName + scale);\n if (imageFile == null) {\n imageFile = loadSVGImageFromResources(imageName, imageDimension, scale);\n imageCache.putImage(imageName + scale, imageFile);\n }\n JLabel imageLabel = new JLabel(new ImageIcon(imageFile));\n imageLabel.setBounds(\n (int) Math.round((offset.getX() + imageCoordinate.getX()) * scale),\n (int) Math.round((offset.getY() + imageCoordinate.getY()) * scale),\n (int) Math.round((imageDimension.getWidth()) * scale),\n (int) Math.round((imageDimension.getHeight()) * scale));\n boardPanel.add(imageLabel);\n }\n}" }, { "identifier": "Turn", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Board.java", "snippet": "public enum Turn {\n SENTE, GOTE\n}" }, { "identifier": "Coordinate", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Coordinate.java", "snippet": "public class Coordinate {\n\n private Integer x;\n private Integer y;\n\n public Coordinate() {\n\n }\n\n public Coordinate(Integer x, Integer y) {\n this.x = x;\n this.y = y;\n }\n\n /**\n * @return the x\n */\n public Integer getX() {\n return x;\n }\n\n /**\n * @param x the x to set\n */\n public void setX(Integer x) {\n this.x = x;\n }\n\n /**\n * @return the y\n */\n public Integer getY() {\n return y;\n }\n\n /**\n * @param y the y to set\n */\n public void setY(Integer y) {\n this.y = y;\n }\n\n public boolean sameValue(Coordinate otherCoordinate) {\n return (Objects.equals(this.x, otherCoordinate.getX())) && (Objects.equals(this.y, otherCoordinate.getY()));\n }\n}" }, { "identifier": "Dimension", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Dimension.java", "snippet": "public class Dimension {\n\n private Integer width;\n private Integer height;\n\n public Dimension() {\n\n }\n\n public Dimension(Integer x, Integer y) {\n this.width = x;\n this.height = y;\n }\n\n /**\n * @return the width\n */\n public Integer getWidth() {\n return width;\n }\n\n /**\n * @param width the width to set\n */\n public void setWidth(Integer width) {\n this.width = width;\n }\n\n /**\n * @return the height\n */\n public Integer getHeight() {\n return height;\n }\n\n /**\n * @param height the height to set\n */\n public void setHeight(Integer height) {\n this.height = height;\n }\n}" }, { "identifier": "substituteKomaName", "path": "src/main/java/com/chadfield/shogiexplorer/utils/StringUtils.java", "snippet": "public static String substituteKomaName(String name) {\n return name.replaceAll(\"^S\", \"0\").replaceAll(\"^G\", \"1\");\n}" }, { "identifier": "substituteKomaNameRotated", "path": "src/main/java/com/chadfield/shogiexplorer/utils/StringUtils.java", "snippet": "public static String substituteKomaNameRotated(String name) {\n return name.replaceAll(\"^S\", \"1\").replaceAll(\"^G\", \"0\");\n}" } ]
import java.util.EnumMap; import java.awt.Image; import com.chadfield.shogiexplorer.objects.ImageCache; import com.chadfield.shogiexplorer.objects.Koma; import com.chadfield.shogiexplorer.objects.Board; import com.chadfield.shogiexplorer.utils.MathUtils; import com.chadfield.shogiexplorer.utils.ImageUtils; import javax.swing.JPanel; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Dimension; import static com.chadfield.shogiexplorer.utils.StringUtils.substituteKomaName; import static com.chadfield.shogiexplorer.utils.StringUtils.substituteKomaNameRotated; import java.awt.Color; import java.awt.image.BaseMultiResolutionImage;
7,863
xOffsetMap.put(Koma.Type.GGI, 0); yOffsetMap.put(Koma.Type.GGI, 0); xCoordMap.put(Koma.Type.GGI, 0); yCoordMap.put(Koma.Type.GGI, 3); xOffsetMap.put(Koma.Type.GKI, 0); yOffsetMap.put(Koma.Type.GKI, 0); xCoordMap.put(Koma.Type.GKI, 0); yCoordMap.put(Koma.Type.GKI, 4); xOffsetMap.put(Koma.Type.GKA, 0); yOffsetMap.put(Koma.Type.GKA, 0); xCoordMap.put(Koma.Type.GKA, 0); yCoordMap.put(Koma.Type.GKA, 5); xOffsetMap.put(Koma.Type.GHI, 0); yOffsetMap.put(Koma.Type.GHI, 0); xCoordMap.put(Koma.Type.GHI, 0); yCoordMap.put(Koma.Type.GHI, 6); xOffsetMap.put(Koma.Type.SFU, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SFU, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SFU, 0); yCoordMap.put(Koma.Type.SFU, 6); xOffsetMap.put(Koma.Type.SKY, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKY, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKY, 0); yCoordMap.put(Koma.Type.SKY, 5); xOffsetMap.put(Koma.Type.SKE, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKE, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKE, 0); yCoordMap.put(Koma.Type.SKE, 4); xOffsetMap.put(Koma.Type.SGI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SGI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SGI, 0); yCoordMap.put(Koma.Type.SGI, 3); xOffsetMap.put(Koma.Type.SKI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKI, 0); yCoordMap.put(Koma.Type.SKI, 2); xOffsetMap.put(Koma.Type.SKA, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKA, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKA, 0); yCoordMap.put(Koma.Type.SKA, 1); xOffsetMap.put(Koma.Type.SHI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SHI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SHI, 0); yCoordMap.put(Koma.Type.SHI, 0); xOffsetMapRotated.put(Koma.Type.SFU, 0); yOffsetMapRotated.put(Koma.Type.SFU, 0); xCoordMapRotated.put(Koma.Type.SFU, 0); yCoordMapRotated.put(Koma.Type.SFU, 0); xOffsetMapRotated.put(Koma.Type.SKY, 0); yOffsetMapRotated.put(Koma.Type.SKY, 0); xCoordMapRotated.put(Koma.Type.SKY, 0); yCoordMapRotated.put(Koma.Type.SKY, 1); xOffsetMapRotated.put(Koma.Type.SKE, 0); yOffsetMapRotated.put(Koma.Type.SKE, 0); xCoordMapRotated.put(Koma.Type.SKE, 0); yCoordMapRotated.put(Koma.Type.SKE, 2); xOffsetMapRotated.put(Koma.Type.SGI, 0); yOffsetMapRotated.put(Koma.Type.SGI, 0); xCoordMapRotated.put(Koma.Type.SGI, 0); yCoordMapRotated.put(Koma.Type.SGI, 3); xOffsetMapRotated.put(Koma.Type.SKI, 0); yOffsetMapRotated.put(Koma.Type.SKI, 0); xCoordMapRotated.put(Koma.Type.SKI, 0); yCoordMapRotated.put(Koma.Type.SKI, 4); xOffsetMapRotated.put(Koma.Type.SKA, 0); yOffsetMapRotated.put(Koma.Type.SKA, 0); xCoordMapRotated.put(Koma.Type.SKA, 0); yCoordMapRotated.put(Koma.Type.SKA, 5); xOffsetMapRotated.put(Koma.Type.SHI, 0); yOffsetMapRotated.put(Koma.Type.SHI, 0); xCoordMapRotated.put(Koma.Type.SHI, 0); yCoordMapRotated.put(Koma.Type.SHI, 6); xOffsetMapRotated.put(Koma.Type.GFU, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GFU, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GFU, 0); yCoordMapRotated.put(Koma.Type.GFU, 6); xOffsetMapRotated.put(Koma.Type.GKY, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKY, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKY, 0); yCoordMapRotated.put(Koma.Type.GKY, 5); xOffsetMapRotated.put(Koma.Type.GKE, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKE, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKE, 0); yCoordMapRotated.put(Koma.Type.GKE, 4); xOffsetMapRotated.put(Koma.Type.GGI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GGI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GGI, 0); yCoordMapRotated.put(Koma.Type.GGI, 3); xOffsetMapRotated.put(Koma.Type.GKI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKI, 0); yCoordMapRotated.put(Koma.Type.GKI, 2); xOffsetMapRotated.put(Koma.Type.GKA, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKA, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKA, 0); yCoordMapRotated.put(Koma.Type.GKA, 1); xOffsetMapRotated.put(Koma.Type.GHI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GHI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GHI, 0); yCoordMapRotated.put(Koma.Type.GHI, 0); //</editor-fold> for (Koma.Type komaType : Koma.Type.values()) { Integer numberHeld = board.getInHandKomaMap().get(komaType); if (numberHeld != null && numberHeld > 0) { BaseMultiResolutionImage pieceImage; if (rotatedView) { String name = PIECE_SET_CLASSIC + "/" + substituteKomaNameRotated(komaType.toString()); pieceImage = imageCache.getImage(name); if (pieceImage == null) { pieceImage = ImageUtils.loadSVGImageFromResources( name, new Dimension(MathUtils.KOMA_X, MathUtils.KOMA_Y), scale); imageCache.putImage(name, pieceImage); } } else {
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class RenderBoard { static final int SBAN_XOFFSET = (MathUtils.BOARD_XY + 1) * MathUtils.KOMA_X + MathUtils.COORD_XY * 5; static final int SBAN_YOFFSET = MathUtils.KOMA_Y * 2 + MathUtils.COORD_XY * 2; static final int CENTRE_X = 5; static final int CENTRE_Y = 5; static final String IMAGE_STR_SENTE = "sente"; static final String IMAGE_STR_GOTE = "gote"; static final String IMAGE_STR_BOARD = "board"; static final String IMAGE_STR_KOMADAI = "komadai"; static final String PIECE_SET_CLASSIC = "classic"; static double scale; private RenderBoard() { throw new IllegalStateException("Utility class"); } public static void loadBoard(Board board, ImageCache imageCache, javax.swing.JPanel boardPanel, boolean rotatedView) { int boardPanelWidth = boardPanel.getWidth(); if (boardPanelWidth == 0) { return; } java.awt.Dimension minimumDimension = boardPanel.getMinimumSize(); double vertScale = boardPanel.getHeight() / minimumDimension.getHeight(); double horizScale = boardPanelWidth / minimumDimension.getWidth(); if (vertScale < horizScale) { scale = vertScale; } else { scale = horizScale; } var highlightColor = new Color(200, 100, 100, 160); // Start with a clean slate. boardPanel.removeAll(); drawPieces(board, imageCache, boardPanel, rotatedView); drawPiecesInHand(board, imageCache, boardPanel, rotatedView); drawCoordinates(boardPanel, rotatedView); drawGrid(imageCache, boardPanel); drawHighlights(board, boardPanel, rotatedView, highlightColor); drawKomadai(imageCache, boardPanel); drawBackground(imageCache, boardPanel); drawTurnNotification(board, imageCache, boardPanel, rotatedView); boardPanel.setVisible(true); boardPanel.repaint(); } private static void drawCoordinates(JPanel boardPanel, boolean rotatedView) { String[] rank = {"一", "二", "三", "四", "五", "六", "七", "八", "九"}; if (rotatedView) { for (int i = 0; i < 9; i++) { boardPanel.add(ImageUtils.getTextLabelForBan( new Coordinate(i, 0), new Dimension( MathUtils.KOMA_X + MathUtils.COORD_XY * 4 - 2, MathUtils.BOARD_XY * MathUtils.KOMA_Y + MathUtils.COORD_XY / 2 - 3), new Coordinate(CENTRE_X, CENTRE_Y), Integer.toString(i + 1), scale )); } for (int i = 0; i < 9; i++) { boardPanel.add( ImageUtils.getTextLabelForBan( new Coordinate(0, i), new Dimension( MathUtils.COORD_XY * 4 + 7, MathUtils.COORD_XY / 2 + 7), new Coordinate(CENTRE_X, CENTRE_Y), rank[8 - i], scale )); } } else { for (int i = 0; i < 9; i++) { boardPanel.add( ImageUtils.getTextLabelForBan( new Coordinate(i, 0), new Dimension( MathUtils.KOMA_X + MathUtils.COORD_XY * 4 - 2, -(MathUtils.COORD_XY / 2) - 3), new Coordinate(CENTRE_X, CENTRE_Y), Integer.toString(9 - i), scale )); } for (int i = 0; i < 9; i++) { boardPanel.add( ImageUtils.getTextLabelForBan( new Coordinate(0, i), new Dimension( MathUtils.KOMA_X * 10 + MathUtils.COORD_XY * 3 + 3, MathUtils.COORD_XY / 2 + 7), new Coordinate(CENTRE_X, CENTRE_Y), rank[i], scale )); } } } private static void drawTurnNotification(Board board, ImageCache imageCache, JPanel boardPanel, boolean rotatedView) { if (board.getNextTurn() == Turn.SENTE) { BaseMultiResolutionImage image = imageCache.getImage(IMAGE_STR_SENTE); if (image == null) { image = ImageUtils.loadSVGImageFromResources(IMAGE_STR_SENTE, new Dimension(MathUtils.KOMA_X, MathUtils.KOMA_Y), scale); imageCache.putImage(IMAGE_STR_SENTE, image); } if (rotatedView) { boardPanel.add( ImageUtils.getPieceLabelForKoma(image, new Coordinate(0, 8), new Dimension(MathUtils.COORD_XY, MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } else { boardPanel.add( ImageUtils.getPieceLabelForKoma( image, new Coordinate(0, -2), new Dimension(SBAN_XOFFSET, SBAN_YOFFSET - MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } } else { BaseMultiResolutionImage image = imageCache.getImage(IMAGE_STR_GOTE); if (image == null) { image = ImageUtils.loadSVGImageFromResources(IMAGE_STR_GOTE, new Dimension(MathUtils.KOMA_X, MathUtils.KOMA_Y), scale); imageCache.putImage(IMAGE_STR_GOTE, image); } if (rotatedView) { boardPanel.add( ImageUtils.getPieceLabelForKoma(image, new Coordinate(0, -2), new Dimension(SBAN_XOFFSET, SBAN_YOFFSET - MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } else { boardPanel.add( ImageUtils.getPieceLabelForKoma( image, new Coordinate(0, 8), new Dimension(MathUtils.COORD_XY, MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } } } private static void drawPiecesInHand(Board board, ImageCache imageCache, JPanel boardPanel, boolean rotatedView) { EnumMap<Koma.Type, Integer> xOffsetMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yOffsetMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> xOffsetMapRotated = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yOffsetMapRotated = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> xCoordMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yCoordMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> xCoordMapRotated = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yCoordMapRotated = new EnumMap<>(Koma.Type.class); //<editor-fold defaultstate="collapsed" desc="Map initialization"> xOffsetMap.put(Koma.Type.GFU, 0); yOffsetMap.put(Koma.Type.GFU, 0); xCoordMap.put(Koma.Type.GFU, 0); yCoordMap.put(Koma.Type.GFU, 0); xOffsetMap.put(Koma.Type.GKY, 0); yOffsetMap.put(Koma.Type.GKY, 0); xCoordMap.put(Koma.Type.GKY, 0); yCoordMap.put(Koma.Type.GKY, 1); xOffsetMap.put(Koma.Type.GKE, 0); yOffsetMap.put(Koma.Type.GKE, 0); xCoordMap.put(Koma.Type.GKE, 0); yCoordMap.put(Koma.Type.GKE, 2); xOffsetMap.put(Koma.Type.GGI, 0); yOffsetMap.put(Koma.Type.GGI, 0); xCoordMap.put(Koma.Type.GGI, 0); yCoordMap.put(Koma.Type.GGI, 3); xOffsetMap.put(Koma.Type.GKI, 0); yOffsetMap.put(Koma.Type.GKI, 0); xCoordMap.put(Koma.Type.GKI, 0); yCoordMap.put(Koma.Type.GKI, 4); xOffsetMap.put(Koma.Type.GKA, 0); yOffsetMap.put(Koma.Type.GKA, 0); xCoordMap.put(Koma.Type.GKA, 0); yCoordMap.put(Koma.Type.GKA, 5); xOffsetMap.put(Koma.Type.GHI, 0); yOffsetMap.put(Koma.Type.GHI, 0); xCoordMap.put(Koma.Type.GHI, 0); yCoordMap.put(Koma.Type.GHI, 6); xOffsetMap.put(Koma.Type.SFU, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SFU, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SFU, 0); yCoordMap.put(Koma.Type.SFU, 6); xOffsetMap.put(Koma.Type.SKY, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKY, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKY, 0); yCoordMap.put(Koma.Type.SKY, 5); xOffsetMap.put(Koma.Type.SKE, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKE, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKE, 0); yCoordMap.put(Koma.Type.SKE, 4); xOffsetMap.put(Koma.Type.SGI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SGI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SGI, 0); yCoordMap.put(Koma.Type.SGI, 3); xOffsetMap.put(Koma.Type.SKI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKI, 0); yCoordMap.put(Koma.Type.SKI, 2); xOffsetMap.put(Koma.Type.SKA, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKA, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKA, 0); yCoordMap.put(Koma.Type.SKA, 1); xOffsetMap.put(Koma.Type.SHI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SHI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SHI, 0); yCoordMap.put(Koma.Type.SHI, 0); xOffsetMapRotated.put(Koma.Type.SFU, 0); yOffsetMapRotated.put(Koma.Type.SFU, 0); xCoordMapRotated.put(Koma.Type.SFU, 0); yCoordMapRotated.put(Koma.Type.SFU, 0); xOffsetMapRotated.put(Koma.Type.SKY, 0); yOffsetMapRotated.put(Koma.Type.SKY, 0); xCoordMapRotated.put(Koma.Type.SKY, 0); yCoordMapRotated.put(Koma.Type.SKY, 1); xOffsetMapRotated.put(Koma.Type.SKE, 0); yOffsetMapRotated.put(Koma.Type.SKE, 0); xCoordMapRotated.put(Koma.Type.SKE, 0); yCoordMapRotated.put(Koma.Type.SKE, 2); xOffsetMapRotated.put(Koma.Type.SGI, 0); yOffsetMapRotated.put(Koma.Type.SGI, 0); xCoordMapRotated.put(Koma.Type.SGI, 0); yCoordMapRotated.put(Koma.Type.SGI, 3); xOffsetMapRotated.put(Koma.Type.SKI, 0); yOffsetMapRotated.put(Koma.Type.SKI, 0); xCoordMapRotated.put(Koma.Type.SKI, 0); yCoordMapRotated.put(Koma.Type.SKI, 4); xOffsetMapRotated.put(Koma.Type.SKA, 0); yOffsetMapRotated.put(Koma.Type.SKA, 0); xCoordMapRotated.put(Koma.Type.SKA, 0); yCoordMapRotated.put(Koma.Type.SKA, 5); xOffsetMapRotated.put(Koma.Type.SHI, 0); yOffsetMapRotated.put(Koma.Type.SHI, 0); xCoordMapRotated.put(Koma.Type.SHI, 0); yCoordMapRotated.put(Koma.Type.SHI, 6); xOffsetMapRotated.put(Koma.Type.GFU, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GFU, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GFU, 0); yCoordMapRotated.put(Koma.Type.GFU, 6); xOffsetMapRotated.put(Koma.Type.GKY, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKY, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKY, 0); yCoordMapRotated.put(Koma.Type.GKY, 5); xOffsetMapRotated.put(Koma.Type.GKE, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKE, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKE, 0); yCoordMapRotated.put(Koma.Type.GKE, 4); xOffsetMapRotated.put(Koma.Type.GGI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GGI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GGI, 0); yCoordMapRotated.put(Koma.Type.GGI, 3); xOffsetMapRotated.put(Koma.Type.GKI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKI, 0); yCoordMapRotated.put(Koma.Type.GKI, 2); xOffsetMapRotated.put(Koma.Type.GKA, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKA, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKA, 0); yCoordMapRotated.put(Koma.Type.GKA, 1); xOffsetMapRotated.put(Koma.Type.GHI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GHI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GHI, 0); yCoordMapRotated.put(Koma.Type.GHI, 0); //</editor-fold> for (Koma.Type komaType : Koma.Type.values()) { Integer numberHeld = board.getInHandKomaMap().get(komaType); if (numberHeld != null && numberHeld > 0) { BaseMultiResolutionImage pieceImage; if (rotatedView) { String name = PIECE_SET_CLASSIC + "/" + substituteKomaNameRotated(komaType.toString()); pieceImage = imageCache.getImage(name); if (pieceImage == null) { pieceImage = ImageUtils.loadSVGImageFromResources( name, new Dimension(MathUtils.KOMA_X, MathUtils.KOMA_Y), scale); imageCache.putImage(name, pieceImage); } } else {
String name = PIECE_SET_CLASSIC + "/" + substituteKomaName(komaType.toString());
8
2023-11-08 09:24:57+00:00
12k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/config/strategy/applyFriend/AbstractApplyFriendStrategy.java
[ { "identifier": "FriendAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/FriendAdapt.java", "snippet": "public class FriendAdapt {\n\n /**\n * 构建保存好友信息\n *\n * @param applyFriendDTO 申请好友 dto\n * @return {@link SysUserApply }\n * @author qingmeng\n * @createTime: 2023/11/27 14:31:48\n */\n public static SysUserApply buildSaveSysUserApply(ApplyFriendDTO applyFriendDTO) {\n SysUserApply sysUserApply = new SysUserApply();\n sysUserApply.setUserId(applyFriendDTO.getUserId());\n sysUserApply.setApplyStatus(ApplyStatusEnum.APPLYING.getCode());\n sysUserApply.setTargetId(applyFriendDTO.getTargetId());\n sysUserApply.setApplyDescribe(applyFriendDTO.getApplyDescribe());\n sysUserApply.setApplyChannel(applyFriendDTO.getApplyChannel());\n sysUserApply.setReadStatus(ReadStatusEnum.UNREAD.getCode());\n return sysUserApply;\n }\n\n /**\n * 构建 好友 记录\n *\n * @param sysUserApply 申请好友记录参数\n * @return {@link SysUserFriendSetting }\n * @author qingmeng\n * @createTime: 2023/11/28 17:38:48\n */\n public static SysUserFriend buildFriendRecord(SysUserApply sysUserApply) {\n SysUserFriend userFriend = new SysUserFriend();\n userFriend.setUserId(sysUserApply.getUserId());\n userFriend.setFriendId(sysUserApply.getTargetId());\n return userFriend;\n }\n\n /**\n * 构建逆向 好友 记录\n *\n * @param sysUserApply 申请好友记录参数\n * @return {@link SysUserFriend }\n * @author qingmeng\n * @createTime: 2023/12/01 16:27:54\n */\n public static SysUserFriend buildFriendRecordReverse(SysUserApply sysUserApply) {\n SysUserFriend userFriend = new SysUserFriend();\n userFriend.setUserId(sysUserApply.getTargetId());\n userFriend.setFriendId(sysUserApply.getUserId());\n return userFriend;\n }\n\n /**\n * 建立 好友申请记录分页列表 VO\n *\n * @param pageList 页面列表\n * @param userList 用户列表\n * @return {@link CommonPageVO }<{@link FriendApplyRecordVO }>\n * @author qingmeng\n * @createTime: 2023/11/29 08:19:32\n */\n public static CommonPageVO<FriendApplyRecordVO> buildFriendApplyRecordPageListVO(IPage<SysUserApply> pageList, List<SysUser> userList) {\n List<FriendApplyRecordVO> voList = buildFriendApplyRecordListVO(pageList.getRecords(), userList);\n return CommonPageVO.init(pageList.getCurrent(), pageList.getSize(), pageList.getTotal(), voList);\n }\n\n\n /**\n * 建立 好友申请记录 列表 VO\n *\n * @param applyList 申请列表\n * @param userList 用户列表\n * @return {@link List }<{@link FriendApplyRecordVO }>\n * @author qingmeng\n * @createTime: 2023/11/29 11:03:59\n */\n public static List<FriendApplyRecordVO> buildFriendApplyRecordListVO(List<SysUserApply> applyList, List<SysUser> userList) {\n return applyList.stream().map(apply -> {\n FriendApplyRecordVO applyRecordVO = new FriendApplyRecordVO();\n applyRecordVO.setApplyId(apply.getId());\n applyRecordVO.setApplyUserId(apply.getUserId());\n applyRecordVO.setApplyChannel(apply.getApplyChannel());\n applyRecordVO.setApplyStatus(apply.getApplyStatus());\n applyRecordVO.setCreateTime(apply.getCreateTime());\n userList.stream()\n .filter(user -> user.getId().equals(apply.getUserId()))\n .findFirst()\n .ifPresent(user -> {\n applyRecordVO.setUserName(user.getUserName());\n applyRecordVO.setUserAvatar(user.getUserAvatar());\n });\n return applyRecordVO;\n }).collect(Collectors.toList());\n }\n\n /**\n * 建立好友列表\n *\n * @param listMap 列表映射\n * @param friendSettingList 好友设置列表\n * @return {@link List }<{@link FriendTypeVO }>\n * @author qingmeng\n * @createTime: 2023/12/03 12:28:59\n */\n public static List<FriendTypeVO> buildFriendList(Map<String, List<SysUser>> listMap, List<SysUserFriendSetting> friendSettingList, Long userId) {\n List<FriendTypeVO> categorizedUserList = new ArrayList<>();\n listMap.forEach((key, value) -> {\n FriendTypeVO vo = new FriendTypeVO();\n vo.setType(key);\n List<SimpleUserInfo> userInfoList = value.stream().map(friendUser -> {\n // 获取 当前用户 对 对方 的设置数据,判断是否进行备注\n SysUserFriendSetting friendSetting = friendSettingList.stream()\n .filter(setting -> {\n // 通过tagKey和userId定位数据 tagKey:1-2 userId:1 表示用户1对用户2的设置\n boolean flagA = setting.getTagKey().equals(CommonUtils.getKeyBySort(Arrays.asList(userId, friendUser.getId())));\n boolean flagB = setting.getUserId().equals(userId);\n return flagA && flagB;\n })\n .findAny()\n .orElse(new SysUserFriendSetting());\n SimpleUserInfo userInfo = new SimpleUserInfo();\n userInfo.setUserAvatar(friendUser.getUserAvatar());\n // 如果有备注则采用备注,否则则使用对方原本的用户名\n userInfo.setUserName(StrUtil.isNotBlank(friendSetting.getNickName()) ? friendSetting.getNickName() : friendUser.getUserName());\n return userInfo;\n }).collect(Collectors.toList());\n vo.setUserList(userInfoList);\n categorizedUserList.add(vo);\n });\n return categorizedUserList;\n }\n\n /**\n * 构造 检查好友列表\n *\n * @param friendIds 好友ID\n * @param checkFriendDTO 检查好友 DTO\n * @return {@link List }<{@link CheckFriendVO }>\n * @author qingmeng\n * @createTime: 2023/12/03 12:53:44\n */\n public static List<CheckFriendVO> buildCheckFriendList(List<Long> friendIds, CheckFriendListDTO checkFriendDTO) {\n return checkFriendDTO.getFriendIdList().stream().map(id -> {\n CheckFriendVO vo = new CheckFriendVO();\n vo.setFriendId(id);\n vo.setCheckStatus(friendIds.contains(id));\n return vo;\n }).collect(Collectors.toList());\n }\n\n /**\n * 构建检查好友\n *\n * @param sysUserFriend sys 用户好友\n * @param checkFriendDTO 检查好友 DTO\n * @return {@link CheckFriendVO }\n * @author qingmeng\n * @createTime: 2023/12/03 13:10:41\n */\n public static CheckFriendVO buildCheckFriend(SysUserFriend sysUserFriend, CheckFriendDTO checkFriendDTO) {\n CheckFriendVO vo = new CheckFriendVO();\n vo.setFriendId(checkFriendDTO.getFriendId());\n vo.setCheckStatus(sysUserFriend.getFriendId().equals(checkFriendDTO.getFriendId()));\n return vo;\n }\n}" }, { "identifier": "WsAdapter", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/WsAdapter.java", "snippet": "public class WsAdapter {\n /**\n * 构造获取登录二维码返回类\n *\n * @param wxMpQrCodeTicket 微信二维码对象\n * @return {@link WsBaseVO }<{@link WsLoginUrlVO }>\n * @author qingmeng\n * @createTime: 2023/11/13 14:34:31\n */\n public static WsBaseVO<WsLoginUrlVO> buildLoginQrcode(WxMpQrCodeTicket wxMpQrCodeTicket) {\n WsBaseVO<WsLoginUrlVO> wsBaseResp = new WsBaseVO<>();\n wsBaseResp.setType(WSResponseTypeEnum.LOGIN_URL.getType());\n wsBaseResp.setData(WsLoginUrlVO.builder().loginUrl(wxMpQrCodeTicket.getUrl()).build());\n return wsBaseResp;\n }\n\n\n /**\n * 构建扫描成功\n *\n * @return {@link WsBaseVO }<{@link String }>\n * @author qingmeng\n * @createTime: 2023/11/20 09:58:45\n */\n public static WsBaseVO<String> buildScanSuccessVO() {\n WsBaseVO<String> wsBaseVO = new WsBaseVO<>();\n wsBaseVO.setType(WSResponseTypeEnum.LOGIN_SCAN_SUCCESS.getType());\n return wsBaseVO;\n }\n\n /**\n * 构建登录成功 vo\n *\n * @param sysUser sys 用户\n * @param tokenName 令牌名称\n * @param tokenValue 令牌值\n * @return {@link WsBaseVO }<{@link WsLoginSuccessVO }>\n * @author qingmeng\n * @createTime: 2023/11/21 22:56:20\n */\n public static WsBaseVO<WsLoginSuccessVO> buildLoginSuccessVO(SysUser sysUser, String tokenName,String tokenValue) {\n WsBaseVO<WsLoginSuccessVO> wsBaseVO = new WsBaseVO<>();\n wsBaseVO.setType(WSResponseTypeEnum.LOGIN_SUCCESS.getType());\n WsLoginSuccessVO wsLoginSuccess = WsLoginSuccessVO.builder()\n .userId(sysUser.getId())\n .avatar(sysUser.getUserAvatar())\n .userName(sysUser.getUserName())\n .tokenName(tokenName)\n .tokenValue(tokenValue)\n .build();\n wsBaseVO.setData(wsLoginSuccess);\n return wsBaseVO;\n }\n\n /**\n * 构建无效令牌 VO\n *\n * @return {@link WsBaseVO }<{@link WsLoginSuccessVO }>\n * @author qingmeng\n * @createTime: 2023/11/21 20:06:08\n */\n public static WsBaseVO<WsLoginSuccessVO> buildInvalidateTokenVO() {\n WsBaseVO<WsLoginSuccessVO> wsBaseVO = new WsBaseVO<>();\n wsBaseVO.setType(WSResponseTypeEnum.INVALIDATE_TOKEN.getType());\n return wsBaseVO;\n }\n\n /**\n * 构建离线通知返回类\n *\n * @param sysUser sys 用户\n * @return {@link WsBaseVO }<{@link WsOnlineOfflineNotifyVO }>\n * @author qingmeng\n * @createTime: 2023/11/22 23:51:53\n */\n public static WsBaseVO<WsOnlineOfflineNotifyVO> buildOfflineNotifyVO(SysUser sysUser) {\n WsBaseVO<WsOnlineOfflineNotifyVO> wsBaseResp = new WsBaseVO<>();\n wsBaseResp.setType(WSResponseTypeEnum.ONLINE_OFFLINE_NOTIFY.getType());\n WsOnlineOfflineNotifyVO onlineOfflineNotify = new WsOnlineOfflineNotifyVO();\n onlineOfflineNotify.setChangeList(Collections.singletonList(buildOfflineInfo(sysUser)));\n //todo 统计在线人数;\n wsBaseResp.setData(onlineOfflineNotify);\n return wsBaseResp;\n }\n\n /**\n * 生成离线信息返回类\n *\n * @param sysUser sys 用户\n * @return {@link ChatMemberVO }\n * @author qingmeng\n * @createTime: 2023/11/22 23:54:10\n */\n private static ChatMemberVO buildOfflineInfo(SysUser sysUser) {\n ChatMemberVO chatMemberVO = new ChatMemberVO();\n BeanUtil.copyProperties(sysUser, chatMemberVO);\n chatMemberVO.setUserId(sysUser.getId());\n chatMemberVO.setActiveStatus(UsageStatusEnum.OFF_LINE.getCode());\n chatMemberVO.setLastOptTime(sysUser.getLastOperateTime());\n return chatMemberVO;\n }\n\n /**\n * 建立在线通知VO\n *\n * @param sysUser sys 用户\n * @return {@link WsBaseVO }<{@link WsOnlineOfflineNotifyVO }>\n * @author qingmeng\n * @createTime: 2023/11/23 16:19:58\n */\n public static WsBaseVO<WsOnlineOfflineNotifyVO> buildOnlineNotifyVO(SysUser sysUser) {\n WsBaseVO<WsOnlineOfflineNotifyVO> wsBaseVO = new WsBaseVO<>();\n wsBaseVO.setType(WSResponseTypeEnum.ONLINE_OFFLINE_NOTIFY.getType());\n WsOnlineOfflineNotifyVO wsOnlineOfflineNotifyVO = new WsOnlineOfflineNotifyVO();\n wsOnlineOfflineNotifyVO.setChangeList(Collections.singletonList(buildOnlineInfo(sysUser)));\n //todo 统计在线人数;\n wsBaseVO.setData(wsOnlineOfflineNotifyVO);\n return wsBaseVO;\n }\n\n /**\n * 建立在线信息\n *\n * @param sysUser sys 用户\n * @return {@link ChatMemberVO }\n * @author qingmeng\n * @createTime: 2023/11/23 16:21:25\n */\n private static ChatMemberVO buildOnlineInfo(SysUser sysUser) {\n ChatMemberVO chatMemberVO = new ChatMemberVO();\n BeanUtil.copyProperties(sysUser, chatMemberVO);\n chatMemberVO.setUserId(sysUser.getId());\n chatMemberVO.setActiveStatus(UsageStatusEnum.ON_LINE.getCode());\n chatMemberVO.setLastOptTime(sysUser.getLastOperateTime());\n return chatMemberVO;\n }\n\n /**\n * 构建申请好友信息\n *\n * @return {@link WsBaseVO }<{@link String }>\n * @author qingmeng\n * @createTime: 2023/11/28 16:53:18\n */\n public static WsBaseVO<String> buildApplyInfoVO() {\n WsBaseVO<String> wsBaseVO = new WsBaseVO<>();\n wsBaseVO.setType(WSResponseTypeEnum.APPLY.getType());\n return wsBaseVO;\n }\n}" }, { "identifier": "UserCache", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/cache/UserCache.java", "snippet": "@Component\npublic class UserCache extends AbstractRedisStringCache<Long, SysUser> {\n @Resource\n private SysUserDao sysUserDao;\n @Resource\n private SysUserFriendDao sysUserFriendDao;\n @Resource\n private UserFriendSettingCache userFriendSettingCache;\n\n /**\n * 根据输入对象获取缓存的键。\n *\n * @param userId 输入对象\n * @return {@link String }\n * @author qingmeng\n * @createTime: 2023/11/22 09:28:29\n */\n @Override\n protected String getKey(Long userId) {\n return RedisConstant.USER_INFO_KEY + userId;\n }\n\n /**\n * 获取缓存的过期时间(秒)。\n *\n * @return {@link Long }\n * @author qingmeng\n * @createTime: 2023/11/22 09:28:26\n */\n @Override\n protected Long getExpireSeconds() {\n return RedisConstant.USER_INFO_EXPIRE * SystemConstant.MINUTE;\n }\n\n /**\n * 批量加载缓存数据。\n *\n * @param userIds id集合\n * @return {@link Map }<{@link Long }, {@link SysUser }>\n * @author qingmeng\n * @createTime: 2023/11/22 09:28:11\n */\n @Override\n protected Map<Long, SysUser> load(List<Long> userIds) {\n List<SysUser> list = sysUserDao.listByIds(userIds);\n return list.stream().collect(Collectors.toMap(SysUser::getId, Function.identity()));\n }\n\n /**\n * 离线\n *\n * @param userId 用户 ID\n * @param lastOperateTime 上次操作时间\n * @author qingmeng\n * @createTime: 2023/11/23 15:59:15\n */\n public void offline(Long userId, Date lastOperateTime) {\n //移除上线线表\n RedisUtils.zRemove(RedisConstant.ONLINE_USERID_KEY, userId);\n //更新上线表\n RedisUtils.zAdd(RedisConstant.OFFLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());\n }\n\n /**\n * 在线\n *\n * @param userId 用户 ID\n * @param lastOperateTime 上次操作时间\n * @author qingmeng\n * @createTime: 2023/11/23 15:59:12\n */\n public void online(Long userId, Date lastOperateTime) {\n //移除离线表\n RedisUtils.zRemove(RedisConstant.OFFLINE_USERID_KEY, userId);\n //更新上线表\n RedisUtils.zAdd(RedisConstant.ONLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());\n }\n\n /**\n * 是否在线\n *\n * @param userId 用户id\n * @return boolean\n * @author qingmeng\n * @createTime: 2023/11/23 16:02:04\n */\n public boolean isOnline(Long userId) {\n return Objects.nonNull(RedisUtils.zScore(RedisConstant.ONLINE_USERID_KEY, userId));\n }\n\n /**\n * 获取好友列表\n *\n * @param userId 用户 ID\n * @return {@link List }<{@link FriendTypeVO }>\n * @author qingmeng\n * @createTime: 2023/12/03 12:37:20\n */\n @Cacheable(value = \"friendList\", key = \"#userId\")\n public List<FriendTypeVO> getFriendList(Long userId) {\n // 获取当前用户的好友id列表\n List<Long> friendIds = sysUserFriendDao.getFriendListById(userId)\n .stream().distinct()\n .map(SysUserFriend::getFriendId)\n .collect(Collectors.toList());\n // 获取完整的好友数据列表\n List<SysUser> sysUsers = new ArrayList<>(getBatch(friendIds).values());\n\n // 根据用户名首字符按照字母分类表进行归类处理\n Map<String, List<SysUser>> listMap = sysUsers.stream().collect(Collectors.groupingBy(user -> {\n char ch = user.getUserName().charAt(0);\n String firstLetter = CommonUtils.getFirstLetter(ch);\n return SystemConstant.ALPHABET_LIST.contains(firstLetter) ? firstLetter : \"#\";\n }));\n // 获取当前用户对好友的设置列表\n List<String> keys = friendIds.stream().map(friendId -> CommonUtils.getFriendSettingCacheKey(userId, friendId)).collect(Collectors.toList());\n List<SysUserFriendSetting> friendSettings = new ArrayList<>(userFriendSettingCache.getBatch(keys).values());\n // 构造最后的信息返回类\n return FriendAdapt.buildFriendList(listMap,friendSettings,userId);\n }\n\n /**\n * 删除好友列表缓存\n *\n * @param userId 用户 ID\n * @author qingmeng\n * @createTime: 2023/12/03 12:40:43\n */\n @CacheEvict(cacheNames = \"friendList\", key = \"#userId\")\n public void evictFriendList(Long userId) {}\n\n}" }, { "identifier": "SysUserApplyDao", "path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/dao/SysUserApplyDao.java", "snippet": "@Service\npublic class SysUserApplyDao extends ServiceImpl<SysUserApplyMapper, SysUserApply> {\n\n /**\n * 同意申请\n *\n * @param applyId 申请 ID\n * @author qingmeng\n * @createTime: 2023/11/28 23:23:50\n */\n public void agreeApply(Long applyId) {\n lambdaUpdate().set(SysUserApply::getApplyStatus, ApplyStatusEnum.ACCEPT.getCode())\n .eq(SysUserApply::getId, applyId)\n .update(new SysUserApply());\n }\n\n /**\n * 根据Id获取好友申请列表\n *\n * @param userId 用户 ID\n * @param page 页\n * @return {@link IPage }<{@link SysUserApply }>\n * @author qingmeng\n * @createTime: 2023/11/29 08:17:45\n */\n public IPage<SysUserApply> getFriendApplyPageListByUserId(Long userId, IPage<SysUserApply> page) {\n return lambdaQuery()\n .eq(SysUserApply::getTargetId, userId)\n .ne(SysUserApply::getApplyStatus, ApplyStatusEnum.BLOCK.getCode())\n .orderByDesc(SysUserApply::getCreateTime)\n .page(page);\n }\n\n\n /**\n * 阅读申请列表\n *\n * @param userId 用户 ID\n * @param applyIds 申请 ID\n * @author qingmeng\n * @createTime: 2023/11/29 08:34:22\n */\n public void readApplyList(Long userId, List<Long> applyIds) {\n lambdaUpdate()\n .set(SysUserApply::getReadStatus, ReadStatusEnum.READ.getCode())\n .eq(SysUserApply::getReadStatus, ReadStatusEnum.UNREAD.getCode())\n .in(SysUserApply::getId, applyIds)\n .eq(SysUserApply::getTargetId, userId)\n .update(new SysUserApply());\n }\n\n /**\n * 更新记录为未读状态\n *\n * @param applyId 应用 ID\n * @author qingmeng\n * @createTime: 2023/11/29 08:54:59\n */\n public void unReadApplyRecord(Long applyId) {\n lambdaUpdate()\n .set(SysUserApply::getReadStatus, ReadStatusEnum.UNREAD.getCode())\n .eq(SysUserApply::getId, applyId)\n .update(new SysUserApply());\n }\n\n /**\n * 更新重新申请状态\n *\n * @param applyId 应用 ID\n * @author qingmeng\n * @createTime: 2023/11/29 08:57:53\n */\n public void updateReapplyStatus(Long applyId) {\n lambdaUpdate()\n .set(SysUserApply::getReadStatus, ReadStatusEnum.UNREAD.getCode())\n .set(SysUserApply::getApplyStatus, ApplyStatusEnum.APPLYING.getCode())\n .eq(SysUserApply::getId, applyId)\n .update(new SysUserApply());\n }\n\n /**\n * 通过两个 ID 获取申请记录\n *\n * @param userId 用户 ID\n * @param targetId 目标 ID\n * @return {@link SysUserApply }\n * @author qingmeng\n * @createTime: 2023/11/29 09:00:43\n */\n public SysUserApply getApplyRecordByBothId(Long userId, Long targetId) {\n return lambdaQuery()\n .eq(SysUserApply::getUserId, userId)\n .eq(SysUserApply::getTargetId, targetId)\n .one();\n }\n\n /**\n * 按用户 ID 获取未读申请记录计数\n *\n * @param userId 用户 ID\n * @return {@link Long }\n * @author qingmeng\n * @createTime: 2023/11/29 09:13:11\n */\n public Long getUnReadApplyRecordCountByUserId(Long userId) {\n return lambdaQuery().eq(SysUserApply::getTargetId, userId)\n .eq(SysUserApply::getReadStatus, ReadStatusEnum.UNREAD.getCode())\n .count();\n }\n\n /**\n * 拉黑申请记录\n *\n * @param applyId 应用 ID\n * @author qingmeng\n * @createTime: 2023/11/29 10:36:25\n */\n public void blockApplyRecord( Long applyId) {\n lambdaUpdate()\n .set(SysUserApply::getApplyStatus, ApplyStatusEnum.BLOCK.getCode())\n .eq(SysUserApply::getId, applyId)\n .update(new SysUserApply());\n }\n\n /**\n * 取消拉黑申请记录\n *\n * @param applyId 应用 ID\n * @author qingmeng\n * @createTime: 2023/11/29 11:24:41\n */\n public void cancelBlockApplyRecord(Long applyId) {\n lambdaUpdate()\n .set(SysUserApply::getApplyStatus, ApplyStatusEnum.APPLYING.getCode())\n .eq(SysUserApply::getId, applyId)\n .update(new SysUserApply());\n }\n\n /**\n * 按用户 ID 获取拉黑申请记录列表\n *\n * @param userId 用户 ID\n * @return {@link List }<{@link SysUserApply }>\n * @author qingmeng\n * @createTime: 2023/11/29 10:57:27\n */\n public List<SysUserApply> getBlockApplyListByUserId(Long userId) {\n return lambdaQuery()\n .eq(SysUserApply::getTargetId, userId)\n .eq(SysUserApply::getApplyStatus, ApplyStatusEnum.BLOCK.getCode())\n .list();\n }\n\n\n}" }, { "identifier": "ApplyFriendDTO", "path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/dto/user/ApplyFriendDTO.java", "snippet": "@Data\npublic class ApplyFriendDTO {\n\n /**\n * 用户id\n */\n @Null\n private Long userId;\n\n /**\n * 目标好友id\n */\n @NotNull\n private Long targetId;\n\n /**\n * 分享卡片者的userId\n */\n private Long shareCardByUserId;\n\n /**\n * 申请描述\n */\n @Length(max = 20)\n private String applyDescribe;\n\n /**\n * 申请渠道\n */\n @NotBlank\n @StringListValue(values = {\"account\",\"phone\",\"card\",\"group\",\"qrcode\"})\n private String applyChannel;\n\n}" }, { "identifier": "SysUser", "path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/entity/SysUser.java", "snippet": "@Data\n@TableName(\"sys_user\")\npublic class SysUser implements Serializable {\n\n private static final long serialVersionUID = 4875299392817609503L;\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 用户名\n */\n private String userName;\n\n /**\n * 用户头像\n */\n private String userAvatar;\n\n /**\n * 用户账号\n */\n private String userAccount;\n\n /**\n * 用户密码\n */\n private String userPassword;\n\n /**\n * 用户手机号\n */\n private String userPhone;\n\n /**\n * 用户性别 0女 1男\n * @see SexEnum\n */\n private Integer userSex;\n\n /**\n * 个人二维码信息\n */\n private String qrcodeUrl;\n\n /**\n * 0 不在线 1在线\n * @see UsageStatusEnum\n */\n private Integer onlineStatus;\n\n /**\n * 最后一次上下线时间\n */\n private Date lastOperateTime;\n\n /**\n * 账号状态 0正常 1封禁\n * @see AccountStatusEnum\n */\n private Integer accountStatus;\n\n /**\n * 修改账号机会\n */\n private Integer alterAccountCount;\n\n /**\n * 维度\n */\n private BigDecimal latitude;\n\n /**\n * 经度\n */\n private BigDecimal longitude;\n\n /**\n * ip归属地\n */\n private String ipLocation;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private Date createTime;\n\n /**\n * 更新时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date updateTime;\n\n /**\n * 逻辑删除 0未删除 1删除\n * @see LogicDeleteEnum\n */\n @TableLogic\n @TableField(fill = FieldFill.INSERT)\n private Integer isDeleted;\n}" }, { "identifier": "SysUserApply", "path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/entity/SysUserApply.java", "snippet": "@Getter\n@Setter\n@TableName(\"sys_user_apply\")\npublic class SysUserApply implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 用户id\n */\n private Long userId;\n\n /**\n * 申请状态 0 申请中 1已同意 2拒绝接受 3拉黑\n * @see com.qingmeng.enums.user.ApplyStatusEnum\n */\n private Integer applyStatus;\n\n /**\n * 目标好友id\n */\n private Long targetId;\n\n /**\n * 申请描述\n */\n private String applyDescribe;\n\n /**\n * 申请渠道\n */\n private String applyChannel;\n\n /**\n * 阅读状态 0未读 1已读\n * @see com.qingmeng.enums.user.ReadStatusEnum\n */\n private Integer readStatus;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private Date createTime;\n\n\n /**\n * 更新时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date updateTime;\n\n /**\n * 逻辑删除\n * @see LogicDeleteEnum\n */\n @TableLogic\n @TableField(fill = FieldFill.INSERT)\n private Integer isDeleted;\n}" }, { "identifier": "ApplyStatusEnum", "path": "talktime-common/src/main/java/com/qingmeng/enums/user/ApplyStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum ApplyStatusEnum {\n /**\n * 好友申请状态枚举\n */\n APPLYING(0, \"申请中\"),\n ACCEPT(1, \"接受\"),\n REJECT(2, \"拒绝\"),\n BLOCK(3, \"拉黑\"),\n ;\n\n private final Integer code;\n private final String msg;\n\n}" }, { "identifier": "WebSocketService", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/netty/service/WebSocketService.java", "snippet": "public interface WebSocketService {\n\n /**\n * ws连接的事件\n * @param channel 连接的通道\n */\n void connect(Channel channel);\n\n /**\n * 处理用户登录请求,需要返回一张带code的二维码\n *\n * @param channel 连接的通道\n */\n void getLoginQrcode(Channel channel);\n\n /**\n * 移除ws连接的事件\n * @param channel 连接的通道\n */\n void removeConnect(Channel channel);\n\n /**\n * 扫描登录成功\n *\n * @param loginCode 登录代码\n * @param userId 用户 ID\n * @author qingmeng\n * @createTime: 2023/11/20 09:00:45\n */\n void scanLoginSuccess(Integer loginCode, Long userId);\n\n /**\n * 扫描成功\n *\n * @param loginCode 登录代码\n * @author qingmeng\n * @createTime: 2023/11/20 09:57:07\n */\n void scanSuccess(Integer loginCode);\n\n /**\n * 授权\n *\n * @param channel 渠道\n * @param authorizeDTO 授权 DTO\n * @author qingmeng\n * @createTime: 2023/11/21 19:35:25\n */\n void authorize(Channel channel, WsAuthorizeDTO authorizeDTO);\n\n /**\n * 推动消息给所有在线的人\n *\n * @param wsBaseVO 发送的消息体\n * @param skipUid 需要跳过的人\n */\n void sendToAllOnline(WsBaseVO<?> wsBaseVO, Long skipUid);\n\n /**\n * 推动消息给所有在线的人\n *\n * @param wsBaseVO 发送的消息体\n */\n void sendToAllOnline(WsBaseVO<?> wsBaseVO);\n\n /**\n * 发送到用户 ID\n *\n * @param wsBaseResp WS 基础 RESP\n * @param userId 用户 ID\n * @author qingmeng\n * @createTime: 2023/11/23 16:22:54\n */\n void sendToUserId(WsBaseVO<?> wsBaseResp, Long userId);\n\n}" }, { "identifier": "AssertUtils", "path": "talktime-common/src/main/java/com/qingmeng/utils/AssertUtils.java", "snippet": "public class AssertUtils {\n\n /**\n * SpringValidatorAdapter 实例。\n */\n public static final SpringValidatorAdapter SPRING_VALIDATOR_ADAPTER = SpringUtils.getBean(SpringValidatorAdapter.class);\n\n\n /**\n * 为 null\n *\n * @param object 对象\n * @param message 消息\n * @author qingmeng\n * @createTime: 2023/11/21 23:04:01\n */\n public static void isNull(Object object, String message) {\n if (Objects.isNull(object)) {\n throwException(null, message);\n }\n }\n\n /**\n * 不为 null\n *\n * @param object 对象\n * @param message 消息\n * @author qingmeng\n * @createTime: 2023/11/21 23:04:18\n */\n public static void isNotNull(Object object, String message) {\n if (Objects.nonNull(object)) {\n throwException(null, message);\n }\n }\n\n\n /**\n * 判断条件是否为真,如果不为真则抛出异常。\n *\n * @param flag 条件值\n * @param message 异常信息\n * @throws TalkTimeException 如果条件不为真\n */\n public static void isTrue(boolean flag, String message) {\n if (!flag) {\n throwException(null, message);\n }\n }\n\n /**\n * 判断条件是否为真,如果不为真则抛出异常。\n *\n * @param expression 条件值\n * @param commonEnum 异常枚举\n * @param args 异常参数\n * @throws TalkTimeException 如果条件不为真\n */\n public static void isTrue(boolean expression, CommonEnum commonEnum, Object... args) {\n if (!expression) {\n throwException(commonEnum, args);\n }\n }\n\n /**\n * 判断条件是否为假,如果不为假则抛出异常。\n *\n * @param expression 条件值\n * @param message 异常信息\n * @throws TalkTimeException 如果条件不为假\n */\n public static void isFalse(boolean expression, String message) {\n if (expression) {\n throwException(null, message);\n }\n }\n\n /**\n * 判断条件是否为假,如果不为假则抛出异常。\n *\n * @param expression 条件值\n * @param commonEnum 异常枚举\n * @param args 异常参数\n * @throws TalkTimeException 如果条件不为假\n */\n public static void isFalse(boolean expression, CommonEnum commonEnum, Object... args) {\n if (expression) {\n throwException(commonEnum, args);\n }\n }\n\n /**\n * 比较两个对象是否相等,如果不相等则抛出异常。\n *\n * @param source 源对象\n * @param target 目标对象\n * @param message 异常信息\n * @throws TalkTimeException 如果对象不相等\n */\n public static void equal(Object source, Object target, String message) {\n if (!ObjectUtil.equal(source, target)) {\n throwException(null, message);\n }\n }\n\n /**\n * 比较两个对象是否不相等,如果相等则抛出异常。\n *\n * @param source 源对象\n * @param target 目标对象\n * @param message 异常信息\n * @throws TalkTimeException 如果对象相等\n */\n public static void notEqual(Object source, Object target, String message) {\n if (ObjectUtil.equal(source, target)) {\n throwException(null, message);\n }\n }\n\n /**\n * 不为空\n *\n * @param object 对象\n * @param msg 信息\n * @author qingmeng\n * @createTime: 2023/12/01 16:39:32\n */\n public static void isNotEmpty(Object object, String msg) {\n if (ObjectUtil.isEmpty(object)) {\n throwException(null,msg);\n }\n }\n\n /**\n * 检查小于\n *\n * @param size 大小\n * @param minNum 最小数量\n * @param msg 信息\n * @author qingmeng\n * @createTime: 2023/12/08 10:50:59\n */\n public static void checkLessThan(int size,int minNum, String msg){\n if (size < minNum) {\n throwException(null,msg);\n }\n }\n\n /**\n * 检查大于\n *\n * @param size 大小\n * @param maxNum 最大数量\n * @param msg 信息\n * @author qingmeng\n * @createTime: 2023/12/08 11:28:56\n */\n public static void checkGreaterThan(Long size,Long maxNum, String msg){\n if (size > maxNum) {\n throwException(null,msg);\n }\n }\n\n\n /**\n * 校验对象。\n *\n * @param object 待校验对象\n * @param isGroup 是否分组校验\n * @param groups 待校验的组\n * @throws TalkTimeException 如果校验不通过\n */\n public static void validateEntity(Object object, Boolean isGroup, Class<?>... groups) {\n Set<ConstraintViolation<Object>> validate;\n if (isGroup) {\n validate = SPRING_VALIDATOR_ADAPTER.validate(object, groups);\n } else {\n validate = SPRING_VALIDATOR_ADAPTER.validate(object);\n }\n Map<Path, String> errorMap = validate.stream().collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage));\n if (CollUtil.isNotEmpty(errorMap)) {\n throw new TalkTimeException(ResultEnum.REQUEST_PARAM_ILLEGAL, errorMap);\n }\n }\n\n /**\n * 抛出异常。\n *\n * @param commonEnum 异常枚举\n * @param arg 异常参数\n * @throws TalkTimeException 异常\n */\n private static void throwException(CommonEnum commonEnum, Object... arg) {\n if (Objects.isNull(commonEnum)) {\n commonEnum = ResultEnum.REQUEST_ERROR;\n }\n throw new TalkTimeException(commonEnum.getCode(), MessageFormat.format(commonEnum.getMsg(), arg));\n }\n}" } ]
import com.qingmeng.config.adapt.FriendAdapt; import com.qingmeng.config.adapt.WsAdapter; import com.qingmeng.config.cache.UserCache; import com.qingmeng.dao.SysUserApplyDao; import com.qingmeng.dto.user.ApplyFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserApply; import com.qingmeng.enums.user.ApplyStatusEnum; import com.qingmeng.config.netty.service.WebSocketService; import com.qingmeng.utils.AssertUtils; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Objects;
10,311
package com.qingmeng.config.strategy.applyFriend; /** * @author 清梦 * @version 1.0.0 * @Description 抽象实现类 * @createTime 2023年11月27日 14:18:00 */ @Component public abstract class AbstractApplyFriendStrategy implements ApplyFriendStrategy { @Resource private SysUserApplyDao sysUserApplyDao; @Resource
package com.qingmeng.config.strategy.applyFriend; /** * @author 清梦 * @version 1.0.0 * @Description 抽象实现类 * @createTime 2023年11月27日 14:18:00 */ @Component public abstract class AbstractApplyFriendStrategy implements ApplyFriendStrategy { @Resource private SysUserApplyDao sysUserApplyDao; @Resource
private WebSocketService webSocketService;
8
2023-11-07 16:04:55+00:00
12k
MonstrousSoftware/Tut3D
core/src/main/java/com/monstrous/tut3d/GameScreen.java
[ { "identifier": "CookBehaviour", "path": "core/src/main/java/com/monstrous/tut3d/behaviours/CookBehaviour.java", "snippet": "public class CookBehaviour extends Behaviour {\n\n private static final float SHOOT_INTERVAL = 2f; // seconds between shots\n\n private float shootTimer;\n private final Vector3 spawnPos = new Vector3();\n private final Vector3 shootDirection = new Vector3();\n private final Vector3 direction = new Vector3();\n private final Vector3 targetDirection = new Vector3();\n private final Vector3 playerVector = new Vector3();\n public NavActor navActor;\n\n\n public CookBehaviour(GameObject go) {\n super(go);\n shootTimer = SHOOT_INTERVAL;\n go.body.setCapsuleCharacteristics();\n }\n\n public Vector3 getDirection() {\n return direction;\n }\n\n @Override\n public void update(World world, float deltaTime ) {\n if (go.health <= 0) // don't do anything when dead\n return;\n\n playerVector.set(world.getPlayer().getPosition()).sub(go.getPosition()); // vector to player in a straight line\n float distance = playerVector.len();\n\n if (navActor == null) { // lazy init because we need world.navMesh\n navActor = new NavActor(world.navMesh);\n }\n\n Vector3 wayPoint = navActor.getWayPoint(go.getPosition(), world.getPlayer().getPosition()); // next point to aim for on the route to target\n\n float climbFactor = 1f;\n if (navActor.getSlope() > 0.1f) { // if we need to climb up, disable the gravity\n go.body.geom.getBody().setGravityMode(false);\n climbFactor = 2f; // and apply some extra force\n } else\n go.body.geom.getBody().setGravityMode(true);\n\n // move towards waypoint\n targetDirection.set(wayPoint).sub(go.getPosition()); // vector towards way point\n if (targetDirection.len() > 1f) { // if we're at the way point, stop turning to avoid nervous jittering\n targetDirection.y = 0; // consider only vector in horizontal plane\n targetDirection.nor(); // make unit vector\n direction.slerp(targetDirection, 0.02f); // smooth rotation towards target direction\n\n if(distance > 5f) // move unless quite close\n go.body.applyForce(targetDirection.scl(deltaTime * 60f * Settings.cookForce * climbFactor));\n }\n\n\n // every so often shoot a pan\n shootTimer -= deltaTime;\n if(shootTimer <= 0 && distance < 20f && world.getPlayer().health > 0) {\n shootTimer = SHOOT_INTERVAL;\n shootPan(world);\n }\n }\n\n private void shootPan(World world) {\n spawnPos.set(direction);\n spawnPos.nor().scl(1f);\n spawnPos.add(go.getPosition()); // spawn from 1 unit in front of the character\n spawnPos.y += 1f;\n GameObject pan = world.spawnObject(GameObjectType.TYPE_ENEMY_BULLET, \"pan\", \"panProxy\", CollisionShapeType.MESH, true, spawnPos );\n shootDirection.set(direction); // shoot forward\n shootDirection.y += 0.5f; // and slightly up\n shootDirection.scl(Settings.panForce); // scale for speed\n pan.body.geom.getBody().setDamping(0.0f, 0.0f);\n pan.body.applyForce(shootDirection);\n pan.body.applyTorque(Vector3.Y); // add some spin\n }\n}" }, { "identifier": "GUI", "path": "core/src/main/java/com/monstrous/tut3d/gui/GUI.java", "snippet": "public class GUI implements Disposable {\n\n public Stage stage;\n private final Skin skin;\n private final World world;\n private final GameScreen screen;\n private Label healthLabel;\n private Label timeLabel;\n private Label enemiesLabel;\n private Label coinsLabel;\n private Label gameOverLabel;\n private Label crossHairLabel;\n private Label fpsLabel;\n private TextButton restartButton;\n private final StringBuffer sb;\n\n public GUI(World world, GameScreen screen) {\n this.world = world;\n this.screen = screen;\n stage = new Stage(new ScreenViewport());\n skin = Main.assets.skin;\n sb = new StringBuffer();\n }\n\n private void rebuild() {\n\n stage.clear();\n\n BitmapFont bitmapFont= Main.assets.uiFont;\n Label.LabelStyle labelStyle = new Label.LabelStyle(bitmapFont, Color.BLUE);\n\n Table screenTable = new Table();\n screenTable.setFillParent(true);\n\n healthLabel = new Label(\"100%\", labelStyle);\n timeLabel = new Label(\"00:00\", labelStyle);\n enemiesLabel = new Label(\"2\", labelStyle);\n coinsLabel = new Label(\"0\", labelStyle);\n fpsLabel = new Label(\"00\", labelStyle);\n gameOverLabel = new Label(\"GAME OVER\", labelStyle);\n restartButton = new TextButton(\"RESTART\", skin);\n\n //screenTable.debug();\n\n screenTable.top();\n // 4 columns: 2 at the left, 2 at the right\n // row 1\n screenTable.add(new Label(\"Health: \", labelStyle)).padLeft(5);\n screenTable.add(healthLabel).left().expandX();\n\n screenTable.add(new Label(\"Time: \", labelStyle));\n screenTable.add(timeLabel).padRight(5);\n screenTable.row();\n\n // row 2\n screenTable.add(new Label(\"Enemies: \", labelStyle)).colspan(3).right();\n screenTable.add(enemiesLabel).padRight(5);\n screenTable.row();\n\n // row 3\n screenTable.add(new Label(\"Coins: \", labelStyle)).colspan(3).right();\n screenTable.add(coinsLabel).padRight(5);\n screenTable.row();\n\n // row 4\n screenTable.add(gameOverLabel).colspan(4).row();\n gameOverLabel.setVisible(false); // hide until needed\n\n // row 5\n screenTable.add(restartButton).colspan(4).pad(20);\n restartButton.setVisible(false); // hide until needed\n screenTable.row();\n\n // row 6 at bottom of screen\n screenTable.add(new Label(\"FPS: \", labelStyle)).expandY().bottom().padLeft(5);\n screenTable.add(fpsLabel).left().expandX().bottom();\n\n screenTable.pack();\n\n stage.addActor(screenTable);\n\n // put cross-hair centre screen\n Table crossHairTable = new Table();\n crossHairTable.setFillParent(true);\n crossHairLabel = new Label(\"+\", skin);\n crossHairTable.add(crossHairLabel);\n stage.addActor(crossHairTable);\n\n\n restartButton.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n super.clicked(event, x, y);\n screen.restart();\n // hide restart button, game-over label and hide mouse cursor\n restartButton.setVisible(false);\n gameOverLabel.setVisible(false);\n Gdx.input.setCursorCatched(true);\n }\n });\n }\n\n private void updateLabels() {\n sb.setLength(0);\n sb.append((int)(world.getPlayer().health*100));\n sb.append(\"%\");\n healthLabel.setText(sb.toString());\n\n sb.setLength(0);\n sb.append(Gdx.graphics.getFramesPerSecond());\n// sb.append(\" player at [x=\");\n// sb.append((int)world.getPlayer().getPosition().x);\n// sb.append(\", z=\");\n// sb.append((int)world.getPlayer().getPosition().z);\n// sb.append(\"]\");\n fpsLabel.setText(sb.toString());\n\n sb.setLength(0);\n int mm = (int) (world.stats.gameTime/60);\n int ss = (int)( world.stats.gameTime - 60*mm);\n if(mm <10)\n sb.append(\"0\");\n sb.append(mm);\n sb.append(\":\");\n if(ss <10)\n sb.append(\"0\");\n sb.append(ss);\n timeLabel.setText(sb.toString());\n\n sb.setLength(0);\n sb.append(world.stats.numEnemies);\n enemiesLabel.setText(sb.toString());\n\n sb.setLength(0);\n sb.append(world.stats.coinsCollected);\n coinsLabel.setText(sb.toString());\n\n if(world.stats.levelComplete){\n gameOverLabel.setText(\"LEVEL COMPLETED IN \"+timeLabel.getText());\n gameOverLabel.setVisible(true);\n restartButton.setVisible(true);\n Gdx.input.setCursorCatched(false);\n }\n else if(world.getPlayer().isDead()) {\n gameOverLabel.setText(\"GAME OVER\");\n gameOverLabel.setVisible(true);\n restartButton.setVisible(true);\n Gdx.input.setCursorCatched(false);\n }\n else {\n gameOverLabel.setVisible(false);\n restartButton.setVisible(false);\n Gdx.input.setCursorCatched(true);\n }\n }\n\n public void showCrossHair( boolean show ){\n crossHairLabel.setVisible(show);\n }\n\n public void render(float deltaTime) {\n updateLabels();\n\n stage.act(deltaTime);\n stage.draw();\n }\n\n public void resize(int width, int height) {\n stage.getViewport().update(width, height, true);\n rebuild();\n }\n\n\n @Override\n public void dispose() {\n stage.dispose();\n skin.dispose();\n }\n}" }, { "identifier": "MyControllerAdapter", "path": "core/src/main/java/com/monstrous/tut3d/inputs/MyControllerAdapter.java", "snippet": "public class MyControllerAdapter extends ControllerAdapter {\n private final static int L2_AXIS = 4;\n private final static int R2_AXIS = 5;\n\n private final PlayerController playerController;\n private final GameScreen gameScreen;\n\n public MyControllerAdapter(PlayerController playerController, GameScreen gameScreen) {\n this.gameScreen = gameScreen;\n this.playerController = playerController;\n }\n\n @Override\n public boolean buttonDown(Controller controller, int buttonIndex) {\n processButtonEvent(controller, buttonIndex, true);\n return false;\n }\n\n @Override\n public boolean buttonUp(Controller controller, int buttonIndex) {\n processButtonEvent(controller, buttonIndex, false);\n return false;\n }\n\n private void processButtonEvent(Controller controller, int buttonIndex, boolean down) {\n //Gdx.app.log(\"Controller button\", \"button: \"+buttonIndex);\n\n // map Dpad to WASD\n if (buttonIndex == controller.getMapping().buttonDpadUp)\n buttonChange(playerController.forwardKey, down);\n if (buttonIndex == controller.getMapping().buttonDpadDown)\n buttonChange(playerController.backwardKey, down);\n if (buttonIndex == controller.getMapping().buttonDpadLeft)\n buttonChange(playerController.strafeLeftKey, down);\n if (buttonIndex == controller.getMapping().buttonDpadRight)\n buttonChange(playerController.strafeRightKey, down);\n\n if (buttonIndex == controller.getMapping().buttonR1 )\n playerController.setScopeMode(down);\n if (buttonIndex == controller.getMapping().buttonL1 )\n playerController.setRunning(down);\n\n if (buttonIndex == controller.getMapping().buttonStart && down)\n gameScreen.restart();\n\n if (buttonIndex == controller.getMapping().buttonX)\n buttonChange(playerController.switchWeaponKey, down);\n if (buttonIndex == controller.getMapping().buttonY && down)\n gameScreen.toggleViewMode();\n }\n\n private void buttonChange(int keyCode, boolean down){\n if(down)\n playerController.keyDown(keyCode);\n else\n playerController.keyUp(keyCode);\n }\n\n\n\n\n @Override\n public boolean axisMoved(Controller controller, int axisIndex, float value) {\n //Gdx.app.log(\"Controller axis\", \"axis: \"+axisIndex + \"value: \"+value);\n\n if(Math.abs(value) < 0.02f ) // dead zone to cope with neutral not being exactly zero\n value = 0;\n\n // right stick for looking\n if(axisIndex == controller.getMapping().axisRightX) // right stick for looking around (X-axis)\n playerController.stickLookX(-value); // rotate view left/right\n if(axisIndex == controller.getMapping().axisRightY) // right stick for looking around (Y-axis)\n playerController.stickLookY(-value); // rotate view up/down\n\n // left stick for moving\n if(axisIndex == controller.getMapping().axisLeftX) // left stick for strafing (X-axis)\n playerController.stickMoveX(value);\n if(axisIndex == controller.getMapping().axisLeftY) // right stick for forward/backwards (Y-axis)\n playerController.stickMoveY(-value);\n\n if(axisIndex == L2_AXIS) // left trigger\n buttonChange(playerController.jumpKey, (value > 0.4f));\n\n if(axisIndex == R2_AXIS) // right trigger\n if(value > 0.8f)\n playerController.fireWeapon();\n\n return false;\n }\n}" }, { "identifier": "CollisionShapeType", "path": "core/src/main/java/com/monstrous/tut3d/physics/CollisionShapeType.java", "snippet": "public enum CollisionShapeType {\n BOX, SPHERE, CAPSULE, CYLINDER, MESH\n}" }, { "identifier": "GameView", "path": "core/src/main/java/com/monstrous/tut3d/views/GameView.java", "snippet": "public class GameView implements Disposable {\n\n private final World world; // reference to World\n private final SceneManager sceneManager;\n private final PerspectiveCamera cam;\n private final Cubemap diffuseCubemap;\n private final Cubemap environmentCubemap;\n private final Cubemap specularCubemap;\n private final Texture brdfLUT;\n private SceneSkybox skybox;\n private final CameraController camController;\n private final boolean isOverlay;\n private float bobAngle; // angle in the camera bob cycle (radians)\n private final float bobScale; // scale factor for camera bobbing\n\n // if the view is an overlay, we don't clear screen on render, only depth buffer\n //\n public GameView(World world, boolean overlay, float near, float far, float bobScale) {\n this.world = world;\n this.isOverlay = overlay;\n this.bobScale = bobScale;\n\n sceneManager = new SceneManager();\n\n cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n cam.position.set(0f, Settings.eyeHeight, 0f);\n cam.lookAt(0,Settings.eyeHeight,10f);\n cam.near = near;\n cam.far = far;\n cam.update();\n\n sceneManager.setCamera(cam);\n camController = new CameraController(cam);\n camController.setThirdPersonMode(true);\n\n // setup light\n DirectionalLightEx light = new net.mgsx.gltf.scene3d.lights.DirectionalShadowLight(Settings.shadowMapSize, Settings.shadowMapSize)\n .setViewport(50,50,10f,100);\n light.direction.set(1, -3, 1).nor();\n light.color.set(Color.WHITE);\n light.intensity = 3f;\n sceneManager.environment.add(light);\n\n // setup quick IBL (image based lighting)\n IBLBuilder iblBuilder = IBLBuilder.createOutdoor(light);\n environmentCubemap = iblBuilder.buildEnvMap(1024);\n diffuseCubemap = iblBuilder.buildIrradianceMap(256);\n specularCubemap = iblBuilder.buildRadianceMap(10);\n iblBuilder.dispose();\n\n // This texture is provided by the library, no need to have it in your assets.\n brdfLUT = new Texture(Gdx.files.classpath(\"net/mgsx/gltf/shaders/brdfLUT.png\"));\n\n sceneManager.setAmbientLight(0.1f);\n sceneManager.environment.set(new PBRTextureAttribute(PBRTextureAttribute.BRDFLUTTexture, brdfLUT));\n sceneManager.environment.set(PBRCubemapAttribute.createSpecularEnv(specularCubemap));\n sceneManager.environment.set(PBRCubemapAttribute.createDiffuseEnv(diffuseCubemap));\n sceneManager.environment.set(new PBRFloatAttribute(PBRFloatAttribute.ShadowBias, 1f/512f)); // reduce shadow acne\n\n // setup skybox\n if(!isOverlay) {\n skybox = new SceneSkybox(environmentCubemap);\n sceneManager.setSkyBox(skybox);\n }\n }\n\n\n public PerspectiveCamera getCamera() {\n return cam;\n }\n\n public void setFieldOfView( float fov ){\n cam.fieldOfView = fov;\n cam.update();\n }\n\n public CameraController getCameraController() {\n return camController;\n }\n\n\n public void refresh() {\n sceneManager.getRenderableProviders().clear(); // remove all scenes\n\n // add scene for each game object\n int num = world.getNumGameObjects();\n for(int i = 0; i < num; i++){\n Scene scene = world.getGameObject(i).scene;\n if (world.getGameObject(i).visible)\n sceneManager.addScene(scene, false);\n }\n }\n\n public boolean inThirdPersonMode() {\n return camController.getThirdPersonMode();\n }\n\n public void render(float delta, float speed ) {\n if(!isOverlay)\n camController.update(world.getPlayer().getPosition(), world.getPlayerController().getViewingDirection());\n else\n cam.position.y = Settings.eyeHeight;\n addHeadBob(delta, speed);\n cam.update();\n refresh();\n sceneManager.update(delta);\n\n Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT); // clear depth buffer only\n sceneManager.render();\n }\n\n private void addHeadBob(float deltaTime, float speed ) {\n if( speed > 0.1f ) {\n bobAngle += speed * deltaTime * Math.PI / Settings.headBobDuration;\n\n // move the head up and down in a sine wave\n cam.position.y += bobScale * Settings.headBobHeight * (float)Math.sin(bobAngle);\n }\n }\n\n public void resize(int width, int height){\n sceneManager.updateViewport(width, height);\n }\n\n\n\n @Override\n public void dispose() {\n sceneManager.dispose();\n environmentCubemap.dispose();\n diffuseCubemap.dispose();\n specularCubemap.dispose();\n brdfLUT.dispose();\n if(!isOverlay)\n skybox.dispose();\n }\n}" }, { "identifier": "GridView", "path": "core/src/main/java/com/monstrous/tut3d/views/GridView.java", "snippet": "public class GridView implements Disposable {\n private final ModelBatch modelBatch;\n private final Array<ModelInstance> instances;\n private final Model arrowModel;\n private final Model gridModel;\n\n public GridView() {\n instances = new Array<>();\n modelBatch = new ModelBatch();\n ModelBuilder modelBuilder = new ModelBuilder();\n\n arrowModel = modelBuilder.createXYZCoordinates(5f, new Material(), VertexAttributes.Usage.Position | VertexAttributes.Usage.ColorPacked);\n instances.add(new ModelInstance(arrowModel, Vector3.Zero));\n\n gridModel = modelBuilder.createLineGrid(100, 100, 1f, 1f, new Material(), VertexAttributes.Usage.Position | VertexAttributes.Usage.ColorPacked);\n instances.add(new ModelInstance(gridModel, Vector3.Zero));\n }\n\n public void render( Camera cam ) {\n modelBatch.begin(cam);\n modelBatch.render(instances);\n modelBatch.end();\n }\n\n @Override\n public void dispose() {\n modelBatch.dispose();\n arrowModel.dispose();\n gridModel.dispose();\n }\n}" }, { "identifier": "NavMeshView", "path": "core/src/main/java/com/monstrous/tut3d/nav/NavMeshView.java", "snippet": "public class NavMeshView implements Disposable {\n\n private final ModelBatch modelBatch;\n private ModelBuilder modelBuilder;\n private Array<ModelInstance> instances;\n private Array<Model> models;\n\n\n public NavMeshView() {\n modelBatch = new ModelBatch();\n instances = new Array<>();\n models = new Array<>();\n }\n\n public void render( Camera cam ) {\n modelBatch.begin(cam);\n modelBatch.render(instances);\n modelBatch.end();\n }\n\n public void update( World world ) {\n for(Model model : models)\n model.dispose();\n models.clear();\n instances.clear();\n\n buildNavNodes(world.navMesh.navNodes);\n\n //buildPortals(NavStringPuller.portals);\n\n int numObjects = world.getNumGameObjects();\n for(int i = 0; i < numObjects; i++) {\n GameObject go = world.getGameObject(i);\n if(go.type != GameObjectType.TYPE_ENEMY)\n continue;\n NavActor actor = ((CookBehaviour)go.behaviour).navActor;\n buildNavNodePath(actor.navNodePath);\n buildPath(actor.path);\n }\n }\n\n public void buildNavNodes(Array<NavNode> path ) {\n if (path == null || path.size == 0) {\n return;\n }\n\n modelBuilder = new ModelBuilder();\n modelBuilder.begin();\n MeshPartBuilder meshBuilder;\n\n for(NavNode navNode : path ) {\n\n Material material = new Material(ColorAttribute.createDiffuse(Color.GRAY));\n meshBuilder = modelBuilder.part(\"part\", GL20.GL_LINES, VertexAttributes.Usage.Position, material);\n\n\n meshBuilder.ensureVertices(3);\n short v0 = meshBuilder.vertex(navNode.p0.x, navNode.p0.y, navNode.p0.z);\n short v1 = meshBuilder.vertex(navNode.p1.x, navNode.p1.y, navNode.p1.z);\n short v2 = meshBuilder.vertex(navNode.p2.x, navNode.p2.y, navNode.p2.z);\n meshBuilder.ensureTriangleIndices(1);\n meshBuilder.triangle(v0, v1, v2);\n }\n Model model = modelBuilder.end();\n ModelInstance instance = new ModelInstance(model, Vector3.Zero);\n models.add(model);\n instances.add(instance);\n }\n\n\n\n public void buildNavNodePath(Array<NavNode> path ) {\n if (path == null || path.size == 0) {\n return;\n }\n\n modelBuilder = new ModelBuilder();\n modelBuilder.begin();\n MeshPartBuilder meshBuilder;\n\n for(NavNode navNode : path ) {\n\n Material material = new Material(ColorAttribute.createDiffuse((float)(16-navNode.steps)/16f, 0, .5f, 1)); // colour shade depends on distance to target\n meshBuilder = modelBuilder.part(\"part\", GL20.GL_TRIANGLES, VertexAttributes.Usage.Position, material);\n\n\n meshBuilder.ensureVertices(3);\n short v0 = meshBuilder.vertex(navNode.p0.x, navNode.p0.y, navNode.p0.z);\n short v1 = meshBuilder.vertex(navNode.p1.x, navNode.p1.y, navNode.p1.z);\n short v2 = meshBuilder.vertex(navNode.p2.x, navNode.p2.y, navNode.p2.z);\n meshBuilder.ensureTriangleIndices(1);\n meshBuilder.triangle(v0, v1, v2);\n }\n Model model = modelBuilder.end();\n ModelInstance instance = new ModelInstance(model, Vector3.Zero);\n models.add(model);\n instances.add(instance);\n }\n\n\n public void buildPath( Array<Vector3> path ) {\n if (path == null || path.size == 0) {\n return;\n }\n\n modelBuilder = new ModelBuilder();\n modelBuilder.begin();\n MeshPartBuilder meshBuilder;\n Material material = new Material(ColorAttribute.createDiffuse(Color.GREEN));\n meshBuilder = modelBuilder.part(\"line\", GL20.GL_LINES, VertexAttributes.Usage.Position, material);\n meshBuilder.ensureVertices(path.size*2);\n meshBuilder.ensureIndices(path.size*2);\n for(int i = 0; i < path.size-1; i++ ) {\n Vector3 v0 = path.get(i);\n Vector3 v1 = path.get(i+1);\n short i0 = meshBuilder.vertex(v0.x, v0.y+0.2f, v0.z); // raise a bit above ground\n short i1 = meshBuilder.vertex(v1.x, v1.y+0.2f, v1.z);\n meshBuilder.line(i0, i1);\n }\n Model model = modelBuilder.end();\n ModelInstance instance = new ModelInstance(model, Vector3.Zero);\n models.add(model);\n instances.add(instance);\n }\n\n public void buildPortals( Array<NavStringPuller.Portal> portals ) {\n if (portals.size == 0) {\n return;\n }\n\n modelBuilder = new ModelBuilder();\n modelBuilder.begin();\n MeshPartBuilder meshBuilder;\n\n Material material = new Material(ColorAttribute.createDiffuse(Color.YELLOW));\n meshBuilder = modelBuilder.part(\"line\", GL20.GL_LINES, VertexAttributes.Usage.Position, material);\n for(NavStringPuller.Portal portal : portals ) {\n\n Vector3 v0 = portal.left;\n Vector3 v1 = portal.right;\n short i0 = meshBuilder.vertex(v0.x, v0.y+0.1f, v0.z); // raise a bit above ground\n short i1 = meshBuilder.vertex(v1.x, v1.y+0.1f, v1.z);\n meshBuilder.line(i0, i1);\n }\n Model model = modelBuilder.end();\n ModelInstance instance = new ModelInstance(model, Vector3.Zero);\n models.add(model);\n instances.add(instance);\n }\n\n\n @Override\n public void dispose() {\n modelBatch.dispose();\n for(Model model : models)\n model.dispose();\n }\n}" }, { "identifier": "PhysicsView", "path": "core/src/main/java/com/monstrous/tut3d/physics/PhysicsView.java", "snippet": "public class PhysicsView implements Disposable {\n\n // colours to use for active vs. sleeping geoms\n static private final Color COLOR_ACTIVE = Color.GREEN;\n static private final Color COLOR_SLEEPING = Color.TEAL;\n static private final Color COLOR_STATIC = Color.GRAY;\n\n private final ModelBatch modelBatch;\n private final World world; // reference\n\n public PhysicsView(World world) {\n this.world = world;\n modelBatch = new ModelBatch();\n }\n\n public void render( Camera cam ) {\n modelBatch.begin(cam);\n int num = world.getNumGameObjects();\n for(int i = 0; i < num; i++) {\n GameObject go = world.getGameObject(i);\n if (go.visible)\n renderCollisionShape(go.body);\n }\n modelBatch.end();\n }\n\n private void renderCollisionShape(PhysicsBody body) {\n // move & orient debug modelInstance in line with geom\n if(body == null)\n return;\n\n body.debugInstance.transform.set(body.getPosition(), body.getBodyOrientation());\n\n // use different colour for static/sleeping/active objects and for active ones\n Color color = COLOR_STATIC;\n if (body.geom.getBody() != null) {\n if (body.geom.getBody().isEnabled())\n color = COLOR_ACTIVE;\n else\n color = COLOR_SLEEPING;\n }\n body.debugInstance.materials.first().set(ColorAttribute.createDiffuse(color)); // set material colour\n\n modelBatch.render(body.debugInstance);\n }\n\n @Override\n public void dispose() {\n modelBatch.dispose();\n }\n}" } ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.math.Vector3; import com.monstrous.tut3d.behaviours.CookBehaviour; import com.monstrous.tut3d.gui.GUI; import com.monstrous.tut3d.inputs.MyControllerAdapter; import com.monstrous.tut3d.physics.CollisionShapeType; import com.monstrous.tut3d.views.GameView; import com.monstrous.tut3d.views.GridView; import com.monstrous.tut3d.nav.NavMeshView; import com.monstrous.tut3d.physics.PhysicsView;
7,297
package com.monstrous.tut3d; public class GameScreen extends ScreenAdapter { private GameView gameView; private GridView gridView; private GameView gunView; private PhysicsView physicsView; private NavMeshView navMeshView; private ScopeOverlay scopeOverlay; private World world; private World gunWorld; private GameObject gun; private GUI gui; private boolean debugRender = false; private boolean thirdPersonView = false; private boolean navScreen = false; private boolean lookThroughScope = false; private int windowedWidth, windowedHeight; @Override public void show() { world = new World(); gui = new GUI(world, this); Populator.populate(world); gameView = new GameView(world,false, 0.1f, 300f, 1f); gameView.getCameraController().setThirdPersonMode(thirdPersonView); world.getPlayer().visible = thirdPersonView; // hide player mesh in first person gridView = new GridView(); physicsView = new PhysicsView(world); scopeOverlay = new ScopeOverlay(); navMeshView = new NavMeshView(); InputMultiplexer im = new InputMultiplexer(); Gdx.input.setInputProcessor(im); im.addProcessor(gui.stage); im.addProcessor(gameView.getCameraController()); im.addProcessor(world.getPlayerController()); if (Settings.supportControllers && Controllers.getCurrent() != null) { MyControllerAdapter controllerAdapter = new MyControllerAdapter(world.getPlayerController(), this); Gdx.app.log("Controller enabled", Controllers.getCurrent().getName()); Controllers.addListener(controllerAdapter); } else Gdx.app.log("No Controller enabled", ""); // hide the mouse cursor and fix it to screen centre, so it doesn't go out the window canvas Gdx.input.setCursorCatched(true); Gdx.input.setCursorPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); Gdx.input.setCatchKey(Input.Keys.F1, true); Gdx.input.setCatchKey(Input.Keys.F2, true); Gdx.input.setCatchKey(Input.Keys.F3, true); Gdx.input.setCatchKey(Input.Keys.F11, true); // load gun model gunWorld = new World(); gunWorld.clear(); gun = gunWorld.spawnObject(GameObjectType.TYPE_STATIC, "GunArmature", null,
package com.monstrous.tut3d; public class GameScreen extends ScreenAdapter { private GameView gameView; private GridView gridView; private GameView gunView; private PhysicsView physicsView; private NavMeshView navMeshView; private ScopeOverlay scopeOverlay; private World world; private World gunWorld; private GameObject gun; private GUI gui; private boolean debugRender = false; private boolean thirdPersonView = false; private boolean navScreen = false; private boolean lookThroughScope = false; private int windowedWidth, windowedHeight; @Override public void show() { world = new World(); gui = new GUI(world, this); Populator.populate(world); gameView = new GameView(world,false, 0.1f, 300f, 1f); gameView.getCameraController().setThirdPersonMode(thirdPersonView); world.getPlayer().visible = thirdPersonView; // hide player mesh in first person gridView = new GridView(); physicsView = new PhysicsView(world); scopeOverlay = new ScopeOverlay(); navMeshView = new NavMeshView(); InputMultiplexer im = new InputMultiplexer(); Gdx.input.setInputProcessor(im); im.addProcessor(gui.stage); im.addProcessor(gameView.getCameraController()); im.addProcessor(world.getPlayerController()); if (Settings.supportControllers && Controllers.getCurrent() != null) { MyControllerAdapter controllerAdapter = new MyControllerAdapter(world.getPlayerController(), this); Gdx.app.log("Controller enabled", Controllers.getCurrent().getName()); Controllers.addListener(controllerAdapter); } else Gdx.app.log("No Controller enabled", ""); // hide the mouse cursor and fix it to screen centre, so it doesn't go out the window canvas Gdx.input.setCursorCatched(true); Gdx.input.setCursorPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); Gdx.input.setCatchKey(Input.Keys.F1, true); Gdx.input.setCatchKey(Input.Keys.F2, true); Gdx.input.setCatchKey(Input.Keys.F3, true); Gdx.input.setCatchKey(Input.Keys.F11, true); // load gun model gunWorld = new World(); gunWorld.clear(); gun = gunWorld.spawnObject(GameObjectType.TYPE_STATIC, "GunArmature", null,
CollisionShapeType.BOX, true, new Vector3(0,0,0));
3
2023-11-04 13:15:48+00:00
12k
Einzieg/EinziegCloud
src/main/java/com/cloud/service/impl/AuthenticationService.java
[ { "identifier": "AuthenticationDTO", "path": "src/main/java/com/cloud/entity/AuthenticationDTO.java", "snippet": "@Data\npublic class AuthenticationDTO implements Serializable, UserDetails {\n\n\t@Serial\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate String id;\n\n\tprivate String email;\n\n\tprivate String password;\n\n\tprivate String name;\n\n\tprivate Boolean state;\n\n\tprivate Boolean locked;\n\n\tprivate String roleCode;\n\n\tprivate String roleName;\n\n\tprivate String roleLevel;\n\n\n\t@Override\n\tpublic String getUsername() {\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic Collection<? extends GrantedAuthority> getAuthorities() {\n\t\treturn roleCode != null ? List.of((GrantedAuthority) () -> roleLevel) : null;\n\t}\n\n\t@Override\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\t/**\n\t * 账户未过期\n\t *\n\t * @return boolean\n\t */\n\t@Override\n\tpublic boolean isAccountNonExpired() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * 账户非锁定\n\t *\n\t * @return boolean\n\t */\n\t@Override\n\tpublic boolean isAccountNonLocked() {\n\t\treturn !locked;\n\t}\n\n\t/**\n\t * 凭证未过期\n\t *\n\t * @return boolean\n\t */\n\t@Override\n\tpublic boolean isCredentialsNonExpired() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * 是否启用\n\t *\n\t * @return boolean\n\t */\n\t@Override\n\tpublic boolean isEnabled() {\n\t\treturn !state;\n\t}\n}" }, { "identifier": "User", "path": "src/main/java/com/cloud/entity/User.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"cloud_user\")\npublic class User {\n\n\t@TableId(value = \"ID\", type = IdType.ASSIGN_ID)\n\tprivate String id;\n\n\t@TableField(\"EMAIL\")\n\tprivate String email;\n\n\t@TableField(\"PASSWORD\")\n\tprivate String password;\n\n\t@TableField(\"NAME\")\n\tprivate String name;\n\n\t@TableField(value = \"REGISTER_DATE\", fill = FieldFill.INSERT)\n\tprivate Date registerDate;\n\n\t@TableField(value = \"LAST_LOGIN_DATE\", fill = FieldFill.INSERT_UPDATE)\n\tprivate Date lastLoginDate;\n\n\t@TableField(value = \"REGISTER_IP\")\n\tprivate String registerIp;\n\n\t@TableField(value = \"LAST_LOGIN_IP\")\n\tprivate String lastLoginIp;\n\n\t@TableField(value = \"STATE\", fill = FieldFill.INSERT)\n\tprivate Boolean state;\n\n\t@TableField(value = \"LOCKED\", fill = FieldFill.INSERT)\n\tprivate Boolean locked;\n\n\t@JsonIgnore\n\t@TableField(value = \"TOKEN\")\n\tprivate String token;\n\n\n}" }, { "identifier": "UserRole", "path": "src/main/java/com/cloud/entity/UserRole.java", "snippet": "@Data\n@Builder\n@TableName(\"cloud_user_role\")\npublic class UserRole {\n\n\t@TableId(value = \"ID\", type = IdType.AUTO)\n\tprivate String id;\n\n\t@TableField(\"USER_ID\")\n\tprivate String userId;\n\n\t@TableField(\"ROLE_ID\")\n\tprivate String roleId;\n\n}" }, { "identifier": "AuthenticationRequest", "path": "src/main/java/com/cloud/entity/request/AuthenticationRequest.java", "snippet": "@Data\n@Builder\npublic class AuthenticationRequest {\n\n\t@NotNull(message = \"用户名不能为空\")\n\t@Size(min = 1, message = \"用户名不能为空\")\n\tprivate String username;\n\n\t@NotNull(message = \"密码不能为空\")\n\t@Size(min = 1, message = \"密码不能为空\")\n\tprivate String password;\n}" }, { "identifier": "RegisterRequest", "path": "src/main/java/com/cloud/entity/request/RegisterRequest.java", "snippet": "@Data\n@Builder\npublic class RegisterRequest {\n\n\t@Size(min = 1, message = \"用户名不能为空\")\n\tprivate String username;\n\n\t@Size(min = 6, message = \"邮箱格式不正确\")\n\t@Email(message = \"邮箱格式不正确\")\n\tprivate String email;\n\n\t@Size(min = 8, max = 16, message = \"密码长度必须在8-16位之间\")\n\tprivate String password;\n\n\t@Size(min = 6, max = 6, message = \"验证码错误\")\n\tprivate String verificationCode;\n\n}" }, { "identifier": "AuthenticationResponse", "path": "src/main/java/com/cloud/entity/response/AuthenticationResponse.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AuthenticationResponse {\n\n\tprivate String token;\n\n\tprivate String name;\n\n\tprivate String email;\n}" }, { "identifier": "AuthenticationMapper", "path": "src/main/java/com/cloud/mapper/AuthenticationMapper.java", "snippet": "public interface AuthenticationMapper extends BaseMapper<AuthenticationDTO> {\n\n\tAuthenticationDTO loadAuthentication(String name);\n}" }, { "identifier": "IAuthenticationService", "path": "src/main/java/com/cloud/service/IAuthenticationService.java", "snippet": "public interface IAuthenticationService extends IService<AuthenticationDTO> {\n\n\tMsg<?> register(RegisterRequest registerRequest);\n\n\tMsg<?> login(AuthenticationRequest auth);\n\n\tMsg<?> logout(HttpServletResponse response, HttpServletRequest request);\n\n\tOptional<AuthenticationDTO> loadUserByName(String Name);\n\n\tOptional<AuthenticationDTO> loadUserByRedis(String Name);\n\n\n}" }, { "identifier": "IUserRoleService", "path": "src/main/java/com/cloud/service/IUserRoleService.java", "snippet": "public interface IUserRoleService extends IService<UserRole> {\n\n\n}" }, { "identifier": "IUserService", "path": "src/main/java/com/cloud/service/IUserService.java", "snippet": "public interface IUserService extends IService<User> {\n\n\tOptional<User> findUserByEmail(String email);\n\n\tOptional<User> findUserByName(String name);\n\n}" }, { "identifier": "HttpUtil", "path": "src/main/java/com/cloud/util/HttpUtil.java", "snippet": "public class HttpUtil {\n\n\tpublic static HttpServletRequest getHttpServletRequest() {\n\t\tServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n\t\treturn attributes != null ? attributes.getRequest() : null;\n\t}\n}" }, { "identifier": "IPUtil", "path": "src/main/java/com/cloud/util/IPUtil.java", "snippet": "@Slf4j\npublic class IPUtil {\n\tprivate static final String IP_UTILS_FLAG = \",\";\n\tprivate static final String UNKNOWN = \"unknown\";\n\tprivate static final String LOCALHOST_IP = \"0:0:0:0:0:0:0:1\";\n\tprivate static final String LOCALHOST_IP1 = \"127.0.0.1\";\n\n\t/**\n\t * 获取IP地址\n\t * <p>\n\t * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址\n\t * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址\n\t */\n\tpublic static String getIpAddr() {\n\t\tHttpServletRequest request = HttpUtil.getHttpServletRequest();\n\t\tString ip = null;\n\t\ttry {\n\t\t\t//以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。\n\t\t\tassert request != null;\n\t\t\tip = request.getHeader(\"X-Original-Forwarded-For\");\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"X-Forwarded-For\");\n\t\t\t}\n\t\t\t//获取nginx等代理的ip\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"x-forwarded-for\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"Proxy-Client-IP\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"WL-Proxy-Client-IP\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"HTTP_CLIENT_IP\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"HTTP_X_FORWARDED_FOR\");\n\t\t\t}\n\t\t\t//兼容k8s集群获取ip\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getRemoteAddr();\n\t\t\t\tif (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {\n\t\t\t\t\t//根据网卡取本机配置的IP\n\t\t\t\t\tInetAddress iNet = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tiNet = InetAddress.getLocalHost();\n\t\t\t\t\t} catch (UnknownHostException e) {\n\t\t\t\t\t\tlog.error(\"获取客户端IP错误:\", e);\n\t\t\t\t\t}\n\t\t\t\t\tip = iNet != null ? iNet.getHostAddress() : null;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"IPUtil ERROR \", e);\n\t\t}\n\t\t//使用代理,则获取第一个IP地址\n\t\tif (StringUtils.hasText(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {\n\t\t\tip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));\n\t\t}\n\n\t\treturn ip;\n\t}\n\n}" }, { "identifier": "JwtUtil", "path": "src/main/java/com/cloud/util/JwtUtil.java", "snippet": "@Service\npublic class JwtUtil {\n\n\tprivate static final String SECRET_KEY =\n\t\t\t\"B?E+ShuviDoura(H+MbQeShVmYq3t6w9z$C&F)J@NcRfUjWnZr4u7x!A%D*G-KaPdSgVkYp3s5vq3t6w9z$C&F)H@McQfTjWnZr4u7x!A%D*G-KaNdRgUkXp2s5v8y/B?E(H+MbQeSh\";\n\n\t/**\n\t * 提取所有声明\n\t *\n\t * @param token 令牌\n\t * @return {@code Claims}\n\t */\n\tprivate static Claims extractAllClaims(String token) {\n\t\treturn Jwts.parserBuilder() // 获取一个Jwt解析器构建器\n\t\t\t\t.setSigningKey(getSignInKey()) // 设置Jwt验证签名\n\t\t\t\t.build()\n\t\t\t\t.parseClaimsJws(token) // 解析Jwt令牌\n\t\t\t\t.getBody(); // 获取Jwt令牌的主体(Body)其中的声明信息\n\t}\n\n\t/**\n\t * 获取签名密钥\n\t *\n\t * @return {@code Key} 用于验证Jwt签名的密钥。签名密钥必须与生成Jwt令牌时使用的密钥相同,否则无法正确验证Jwt的真实性。\n\t */\n\tprivate static Key getSignInKey() {\n\t\tbyte[] keyBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);\n\t\treturn Keys.hmacShaKeyFor(keyBytes);\n\t}\n\n\n\t/**\n\t * 从Jwt提取特定声明(Claims)信息\n\t *\n\t * @param token 令牌\n\t * @param claimsResolver 解析器\n\t * @return {@code T}\n\t */\n\tpublic static <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {\n\t\tfinal Claims claims = extractAllClaims(token); // 获取JWT令牌中的所有声明信息,存储在Claims对象中\n\t\treturn claimsResolver.apply(claims);\n\t}\n\n\t/**\n\t * 生成Jwt令牌\n\t *\n\t * @param extraClaims 额外的声明信息\n\t * @param userDetails 用户详细信息\n\t * @return {@code String}\n\t */\n\tpublic String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {\n\t\treturn Jwts.builder() // 获取一个JWT构建器\n\t\t\t\t.setClaims(extraClaims) // 设置JWT令牌的声明(Claims)部分\n\t\t\t\t.setSubject(userDetails.getUsername()) // 设置JWT令牌的主题(Subject)部分\n\t\t\t\t.setIssuedAt(new Date(System.currentTimeMillis())) // 设置JWT令牌的签发时间\n\t\t\t\t.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24)) // 设置JWT令牌的过期时间(24小时)\n\t\t\t\t.signWith(getSignInKey(), SignatureAlgorithm.HS512) // 对JWT令牌进行签名\n\t\t\t\t.compact(); // 生成最终的JWT令牌字符串\n\t}\n\n\t/**\n\t * 生成Jwt令牌\n\t *\n\t * @param userDetails 用户详细信息\n\t * @return {@code String}\n\t */\n\tpublic String generateToken(UserDetails userDetails) {\n\t\treturn generateToken(new HashMap<>(), userDetails);\n\t}\n\n\t/**\n\t * 令牌是否有效\n\t *\n\t * @param token 令牌\n\t * @param userDetails 用户详细信息\n\t * @return boolean\n\t */\n\tpublic static boolean isTokenValid(String token, UserDetails userDetails) {\n\t\tfinal String username = extractUsername(token);\n\t\treturn (username.equals(userDetails.getUsername()) && !extractClaim(token, Claims::getExpiration).before(new Date()));\n\t}\n\n\t/**\n\t * 提取用户名\n\t *\n\t * @param token 令牌\n\t * @return {@code String}\n\t */\n\tpublic static String extractUsername(String token) {\n\t\treturn extractClaim(token, Claims::getSubject);\n\t}\n\n\n}" }, { "identifier": "RedisUtil", "path": "src/main/java/com/cloud/util/RedisUtil.java", "snippet": "@Slf4j\n@Service\npublic final class RedisUtil {\n\t@Resource\n\tprivate RedisTemplate<String, Object> redisTemplate;\n\n\n\t/**\n\t * 指定缓存失效时间\n\t *\n\t * @param key 键\n\t * @param time 时间(秒)\n\t */\n\tpublic boolean expire(String key, long time) {\n\t\ttry {\n\t\t\tif (time > 0) {\n\t\t\t\tredisTemplate.expire(key, time, TimeUnit.SECONDS);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis expire error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 根据key 获取过期时间\n\t *\n\t * @param key 键 不能为null\n\t * @return 时间(秒) 返回0代表为永久有效\n\t */\n\tpublic long getExpire(String key) {\n\t\treturn Objects.requireNonNull(redisTemplate.getExpire(key, TimeUnit.SECONDS));\n\t}\n\n\n\t/**\n\t * 判断key是否存在\n\t *\n\t * @param key 键\n\t * @return true 存在 false不存在\n\t */\n\tpublic boolean hasKey(String key) {\n\t\ttry {\n\t\t\treturn Boolean.TRUE.equals(redisTemplate.hasKey(key));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis hasKey error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 删除缓存\n\t *\n\t * @param key 可以传一个值 或多个\n\t */\n\tpublic void del(String... key) {\n\t\tif (key != null && key.length > 0) {\n\t\t\tif (key.length == 1) {\n\t\t\t\tredisTemplate.delete(key[0]);\n\t\t\t} else {\n\t\t\t\tredisTemplate.delete(Arrays.asList(key));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * 普通缓存获取\n\t *\n\t * @param key 键\n\t * @return 值\n\t */\n\tpublic Object get(String key) {\n\t\treturn key == null ? null : redisTemplate.opsForValue().get(key);\n\t}\n\n\t/**\n\t * 普通缓存放入\n\t *\n\t * @param key 键\n\t * @param value 值\n\t * @return true成功 false失败\n\t */\n\tpublic boolean set(String key, Object value) {\n\t\ttry {\n\t\t\tredisTemplate.opsForValue().set(key, value);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis set error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 普通缓存放入并设置时间\n\t *\n\t * @param key 键\n\t * @param value 值\n\t * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期\n\t * @return true成功 false 失败\n\t */\n\tpublic boolean set(String key, Object value, long time) {\n\t\ttry {\n\t\t\tif (time > 0) {\n\t\t\t\tredisTemplate.opsForValue().set(key, String.valueOf(value), time, TimeUnit.SECONDS);\n\t\t\t} else {\n\t\t\t\tset(key, value);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis set error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 递增\n\t *\n\t * @param key 键\n\t * @param delta 要增加几(大于0)\n\t */\n\tpublic long increasing(String key, long delta) {\n\t\tif (delta < 0) {\n\t\t\tthrow new RuntimeException(\"递增因子必须大于0\");\n\t\t}\n\t\treturn Objects.requireNonNull(redisTemplate.opsForValue().increment(key, delta));\n\t}\n\n\t/**\n\t * 递减\n\t *\n\t * @param key 键\n\t * @param delta 要减少几(小于0)\n\t */\n\tpublic long degression(String key, long delta) {\n\t\tif (delta < 0) {\n\t\t\tthrow new RuntimeException(\"递减因子必须大于0\");\n\t\t}\n\t\treturn Objects.requireNonNull(redisTemplate.opsForValue().increment(key, -delta));\n\t}\n\n\t/**\n\t * getHash\n\t *\n\t * @param key 键 不能为null\n\t * @param item 项 不能为null\n\t */\n\tpublic Object getHash(String key, String item) {\n\t\treturn redisTemplate.opsForHash().get(key, item);\n\t}\n\n\t/**\n\t * 获取hashKey对应的所有键值\n\t *\n\t * @param key 键\n\t * @return 对应的多个键值\n\t */\n\tpublic Map<Object, Object> getHash(String key) {\n\t\treturn redisTemplate.opsForHash().entries(key);\n\t}\n\n\t/**\n\t * setHash\n\t *\n\t * @param key 键\n\t * @param map 对应多个键值\n\t */\n\tpublic boolean setHash(String key, Map<String, Object> map) {\n\t\ttry {\n\t\t\tredisTemplate.opsForHash().putAll(key, map);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setHash error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * HashSet 并设置时间\n\t *\n\t * @param key 键\n\t * @param map 对应多个键值\n\t * @param time 时间(秒)\n\t * @return true成功 false失败\n\t */\n\tpublic boolean setHash(String key, Map<String, Object> map, long time) {\n\t\ttry {\n\t\t\tredisTemplate.opsForHash().putAll(key, map);\n\t\t\tif (time > 0) {\n\t\t\t\texpire(key, time);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setHash error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 向一张hash表中放入数据,如果不存在将创建\n\t *\n\t * @param key 键\n\t * @param item 项\n\t * @param value 值\n\t * @return true 成功 false失败\n\t */\n\tpublic boolean setHash(String key, String item, Object value) {\n\t\ttry {\n\t\t\tredisTemplate.opsForHash().put(key, item, value);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setHash error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 向一张hash表中放入数据,如果不存在将创建\n\t *\n\t * @param key 键\n\t * @param item 项\n\t * @param value 值\n\t * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间\n\t * @return true 成功 false失败\n\t */\n\tpublic boolean setHash(String key, String item, Object value, long time) {\n\t\ttry {\n\t\t\tredisTemplate.opsForHash().put(key, item, value);\n\t\t\tif (time > 0) {\n\t\t\t\texpire(key, time);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setHash error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 删除hash表中的值\n\t *\n\t * @param key 键 不能为null\n\t * @param item 项 可以使多个 不能为null\n\t */\n\tpublic void delHash(String key, Object... item) {\n\t\tredisTemplate.opsForHash().delete(key, item);\n\t}\n\n\t/**\n\t * 判断hash表中是否有该项的值\n\t *\n\t * @param key 键 不能为null\n\t * @param item 项 不能为null\n\t * @return true 存在 false不存在\n\t */\n\tpublic boolean hashHasKey(String key, String item) {\n\t\treturn redisTemplate.opsForHash().hasKey(key, item);\n\t}\n\n\t/**\n\t * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n\t *\n\t * @param key 键\n\t * @param item 项\n\t * @param by 要增加几(大于0)\n\t */\n\tpublic double increasingHash(String key, String item, double by) {\n\t\treturn redisTemplate.opsForHash().increment(key, item, by);\n\t}\n\n\t/**\n\t * hash递减\n\t *\n\t * @param key 键\n\t * @param item 项\n\t * @param by 要减少记(小于0)\n\t */\n\tpublic double degressionHash(String key, String item, double by) {\n\t\treturn redisTemplate.opsForHash().increment(key, item, -by);\n\t}\n\n\t/**\n\t * 根据key获取Set中的所有值\n\t *\n\t * @param key 键\n\t */\n\tpublic Set<Object> getSetByKey(String key) {\n\t\ttry {\n\t\t\treturn redisTemplate.opsForSet().members(key);\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis getSetByKey error\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * 根据value从一个set中查询,是否存在\n\t *\n\t * @param key 键\n\t * @param value 值\n\t * @return true 存在 false不存在\n\t */\n\tpublic boolean setHasKeyByValue(String key, Object value) {\n\t\ttry {\n\t\t\treturn Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setHasKeyByValue error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 将数据放入set缓存\n\t *\n\t * @param key 键\n\t * @param values 值 可以是多个\n\t * @return 成功个数\n\t */\n\tpublic long setSet(String key, Object... values) {\n\t\ttry {\n\t\t\treturn Objects.requireNonNull(redisTemplate.opsForSet().add(key, values));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setSet error\", e);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * 将set数据放入缓存\n\t *\n\t * @param key 键\n\t * @param time 时间(秒)\n\t * @param values 值 可以是多个\n\t * @return 成功个数\n\t */\n\tpublic long setSet(String key, long time, Object... values) {\n\t\ttry {\n\t\t\tLong count = redisTemplate.opsForSet().add(key, values);\n\t\t\tif (time > 0)\n\t\t\t\texpire(key, time);\n\t\t\treturn Objects.requireNonNull(count);\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setSet error\", e);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * 获取set缓存的长度\n\t *\n\t * @param key 键\n\t */\n\tpublic long getSetSize(String key) {\n\t\ttry {\n\t\t\treturn Objects.requireNonNull(redisTemplate.opsForSet().size(key));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis getSetSize error\", e);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * 移除值为value的set\n\t *\n\t * @param key 键\n\t * @param values 值 可以是多个\n\t * @return 移除的个数\n\t */\n\n\tpublic long removeSet(String key, Object... values) {\n\t\ttry {\n\t\t\treturn Objects.requireNonNull(redisTemplate.opsForSet().remove(key, values));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis removeSet error\", e);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * 获取list缓存的内容\n\t *\n\t * @param key 键\n\t * @param start 开始\n\t * @param end 结束 0 到 -1代表所有值\n\t */\n\tpublic List<Object> getList(String key, long start, long end) {\n\t\ttry {\n\t\t\treturn redisTemplate.opsForList().range(key, start, end);\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis getList error\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * 获取list缓存的长度\n\t *\n\t * @param key 键\n\t */\n\tpublic long getListSize(String key) {\n\t\ttry {\n\t\t\treturn Objects.requireNonNull(redisTemplate.opsForList().size(key));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis getListSize error\", e);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * 通过索引 获取list中的值\n\t *\n\t * @param key 键\n\t * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推\n\t */\n\tpublic Object getListByIndex(String key, long index) {\n\t\ttry {\n\t\t\treturn redisTemplate.opsForList().index(key, index);\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis getListByIndex error\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * 将list放入缓存\n\t *\n\t * @param key 键\n\t * @param value 值\n\t */\n\tpublic boolean setList(String key, Object value) {\n\t\ttry {\n\t\t\tredisTemplate.opsForList().rightPush(key, value);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setList error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 将list放入缓存\n\t *\n\t * @param key 键\n\t * @param value 值\n\t * @param time 时间(秒)\n\t */\n\tpublic boolean setList(String key, Object value, long time) {\n\t\ttry {\n\t\t\tredisTemplate.opsForList().rightPush(key, value);\n\t\t\tif (time > 0)\n\t\t\t\texpire(key, time);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setList error\", e);\n\t\t\treturn false;\n\t\t}\n\n\t}\n\n\t/**\n\t * 将list放入缓存\n\t *\n\t * @param key 键\n\t * @param value 值\n\t * @return true成功 false失败\n\t */\n\tpublic boolean setList(String key, List<Object> value) {\n\t\ttry {\n\t\t\tredisTemplate.opsForList().rightPushAll(key, value);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setList error\", e);\n\t\t\treturn false;\n\t\t}\n\n\t}\n\n\t/**\n\t * 将list放入缓存\n\t *\n\t * @param key 键\n\t * @param value 值\n\t * @param time 时间(秒)\n\t * @return true成功 false失败\n\t */\n\tpublic boolean setList(String key, List<Object> value, long time) {\n\t\ttry {\n\t\t\tredisTemplate.opsForList().rightPushAll(key, value);\n\t\t\tif (time > 0)\n\t\t\t\texpire(key, time);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis setList error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 根据索引修改list中的某条数据\n\t *\n\t * @param key 键\n\t * @param index 索引\n\t * @param value 值\n\t * @return true成功 false失败\n\t */\n\tpublic boolean updateListByIndex(String key, long index, Object value) {\n\t\ttry {\n\t\t\tredisTemplate.opsForList().set(key, index, value);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis updateListByIndex error\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * 移除N个值为value\n\t *\n\t * @param key 键\n\t * @param count 移除多少个\n\t * @param value 值\n\t * @return 移除的个数\n\t */\n\tpublic long removeList(String key, long count, Object value) {\n\t\ttry {\n\t\t\treturn Objects.requireNonNull(redisTemplate.opsForList().remove(key, count, value));\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"redis removeList error\", e);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n}" }, { "identifier": "Msg", "path": "src/main/java/com/cloud/util/msg/Msg.java", "snippet": "@Data\n@AllArgsConstructor\npublic class Msg<T> {\n\n\t// 状态码\n\tprivate Integer code;\n\n\t// 提示信息\n\tprivate String msg;\n\n\t// 返回给浏览器的数据\n\tprivate T data;\n\n\t// 接口请求时间\n\tprivate long timestamp;\n\n\tpublic Msg() {\n\t\tthis.timestamp = System.currentTimeMillis();\n\t}\n\n\t/**\n\t * 默认请求成功\n\t *\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> success() {\n\t\tMsg<?> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.SUCCESS.getCode());\n\t\tmsg.setMsg(ResultCode.SUCCESS.getMsg());\n\t\treturn msg;\n\t}\n\n\t/**\n\t * 请求成功\n\t *\n\t * @param resultCode {@code ResultCode}\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> success(ResultCode resultCode) {\n\t\tMsg<?> result = new Msg<>();\n\t\tresult.setCode(ResultCode.SUCCESS.getCode());\n\t\tresult.setMsg(ResultCode.SUCCESS.getMsg());\n\t\treturn result;\n\t}\n\n\t/**\n\t * 请求成功\n\t * 携带数据返回\n\t *\n\t * @param data 返回数据\n\t * @return {@code Msg<T>}\n\t */\n\tpublic static <T> Msg<T> success(T data) {\n\t\tMsg<T> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.SUCCESS.getCode());\n\t\tmsg.setMsg(ResultCode.SUCCESS.getMsg());\n\t\tmsg.setData(data);\n\t\treturn msg;\n\t}\n\n\t/**\n\t * 默认请求失败\n\t *\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> fail() {\n\t\tMsg<?> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.FAILED.getCode());\n\t\tmsg.setMsg(ResultCode.FAILED.getMsg());\n\t\treturn msg;\n\t}\n\n\t/**\n\t * 定义请求失败\n\t *\n\t * @param resultCode {@code ResultCode}\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> fail(ResultCode resultCode) {\n\t\tMsg<?> result = new Msg<>();\n\t\tresult.setCode(resultCode.getCode());\n\t\tresult.setMsg(resultCode.getMsg());\n\t\treturn result;\n\t}\n\n\t/**\n\t * 请求失败\n\t * 携带数据返回\n\t *\n\t * @param data 返回数据\n\t * @return {@code Msg<T>}\n\t */\n\tpublic static <T> Msg<T> fail(T data) {\n\t\tMsg<T> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.FAILED.getCode());\n\t\tmsg.setMsg(ResultCode.FAILED.getMsg());\n\t\tmsg.setData(data);\n\t\treturn msg;\n\t}\n\n\tpublic Msg(ResultCode resultCode) {\n\t\tthis.code = resultCode.getCode();\n\t\tthis.msg = resultCode.getMsg();\n\t\tthis.timestamp = System.currentTimeMillis();\n\t}\n\n\t/**\n\t * 自定义返回状态码、消息、数据\n\t *\n\t * @param resultCode {@code ResultCode}\n\t * @param data 数据\n\t */\n\tpublic Msg(ResultCode resultCode, T data) {\n\t\tthis.code = resultCode.getCode();\n\t\tthis.msg = resultCode.getMsg();\n\t\tthis.data = data;\n\t\tthis.timestamp = System.currentTimeMillis();\n\t}\n\n\tpublic static void returnMsg(HttpServletResponse response, ResultCode resultCode) throws IOException {\n\t\tresponse.setContentType(\"application/json;charset=utf-8\");\n\t\tServletOutputStream os = response.getOutputStream();\n\t\tString jsonString = JSON.toJSONString(new Msg<>(resultCode));\n\t\tos.write(jsonString.getBytes());\n\t\tos.flush();\n\t\tos.close();\n\t}\n}" }, { "identifier": "ResultCode", "path": "src/main/java/com/cloud/util/msg/ResultCode.java", "snippet": "@Getter\npublic enum ResultCode {\n\n\tSUCCESS(200, \"请求成功\"),\n\n\tFAILED(500, \"请求失败\"),\n\n\tLOGIN_FAILED(500, \"登录失败\"),\n\n\tBODY_NOT_MATCH(400, \"请求体格式错误\"),\n\n\tTOKEN_LAPSE(403, \"凭证已失效\"),\n\n\tTOKEN_FORMAT_ERROR(403, \"凭证错误\"),\n\n\tTOKEN_PARSE_ERROR(403, \"凭证解析失败\"),\n\n\tTOKEN_UNSUPPORTED(403, \"不支持的凭证\"),\n\n\tBAD_CREDENTIALS(403, \"账号或密码错误\"),\n\n\tDISABLE(403, \"账户已被禁用\"),\n\n\tLOCKED(403, \"账户已被锁定\"),\n\n\tVALIDATE_FAILED(405, \"参数校验不通过\"),\n\n\tVALIDATE_CODE_FAILED(405, \"验证码错误\"),\n\n\tVALIDATE_CODE_EXPIRED(405, \"验证码已过期\"),\n\n\tTOO_MANY_REQUESTS(200, \"请求过于频繁\"),\n\n\tALREADY_REGISTERED(507, \"该用户名已存在\"),\n\n\tEMAIL_ALREADY_REGISTERED(507, \"该邮箱已被注册\"),\n\n\tERROR(500, \"未知错误\");\n\n\tprivate final int code;\n\tprivate final String msg;\n\n\tResultCode(int code, String msg) {\n\t\tthis.code = code;\n\t\tthis.msg = msg;\n\t}\n}" } ]
import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cloud.entity.AuthenticationDTO; import com.cloud.entity.User; import com.cloud.entity.UserRole; import com.cloud.entity.request.AuthenticationRequest; import com.cloud.entity.request.RegisterRequest; import com.cloud.entity.response.AuthenticationResponse; import com.cloud.mapper.AuthenticationMapper; import com.cloud.service.IAuthenticationService; import com.cloud.service.IUserRoleService; import com.cloud.service.IUserService; import com.cloud.util.HttpUtil; import com.cloud.util.IPUtil; import com.cloud.util.JwtUtil; import com.cloud.util.RedisUtil; import com.cloud.util.msg.Msg; import com.cloud.util.msg.ResultCode; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Optional;
9,216
package com.cloud.service.impl; /** * 身份验证服务 * * @author Einzieg */ @Slf4j @Service @RequiredArgsConstructor public class AuthenticationService extends ServiceImpl<AuthenticationMapper, AuthenticationDTO> implements IAuthenticationService { private final IUserService userService; private final IUserRoleService userRoleService; private final PasswordEncoder passwordEncoder; private final AuthenticationManager authenticationManager; private final JwtUtil jwtUtil; private final RedisUtil redisUtil; /** * 用户注册 * * @return {@code AuthenticationResponse} */
package com.cloud.service.impl; /** * 身份验证服务 * * @author Einzieg */ @Slf4j @Service @RequiredArgsConstructor public class AuthenticationService extends ServiceImpl<AuthenticationMapper, AuthenticationDTO> implements IAuthenticationService { private final IUserService userService; private final IUserRoleService userRoleService; private final PasswordEncoder passwordEncoder; private final AuthenticationManager authenticationManager; private final JwtUtil jwtUtil; private final RedisUtil redisUtil; /** * 用户注册 * * @return {@code AuthenticationResponse} */
public Msg<?> register(RegisterRequest registerRequest) {
4
2023-11-07 07:27:53+00:00
12k
hlysine/create_power_loader
src/main/java/com/hlysine/create_power_loader/command/ListLoadersCommand.java
[ { "identifier": "ChunkLoadManager", "path": "src/main/java/com/hlysine/create_power_loader/content/ChunkLoadManager.java", "snippet": "public class ChunkLoadManager {\n private static final Logger LOGGER = LogUtils.getLogger();\n private static final int SAVED_CHUNKS_DISCARD_TICKS = 100;\n\n private static final List<Pair<UUID, Set<LoadedChunkPos>>> unforceQueue = new LinkedList<>();\n private static final Map<UUID, Set<LoadedChunkPos>> savedForcedChunks = new HashMap<>();\n private static int savedChunksDiscardCountdown = SAVED_CHUNKS_DISCARD_TICKS;\n /**\n * Only accessible during GlobalRailwayManager#tick\n */\n public static Level tickLevel;\n\n public static final Map<LoaderMode, WeakCollection<ChunkLoader>> allLoaders = new HashMap<>();\n\n public static void addLoader(LoaderMode mode, ChunkLoader loader) {\n allLoaders.computeIfAbsent(mode, $ -> new WeakCollection<>()).add(loader);\n }\n\n public static void removeLoader(LoaderMode mode, ChunkLoader loader) {\n allLoaders.computeIfAbsent(mode, $ -> new WeakCollection<>()).remove(loader);\n }\n\n public static void onServerWorldTick(TickEvent.LevelTickEvent event) {\n if (event.phase == TickEvent.Phase.END)\n return;\n if (event.side == LogicalSide.CLIENT)\n return;\n\n MinecraftServer server = event.level.getServer();\n if (savedChunksDiscardCountdown == 0) {\n for (Map.Entry<UUID, Set<LoadedChunkPos>> entry : savedForcedChunks.entrySet()) {\n unforceAllChunks(server, entry.getKey(), entry.getValue());\n }\n savedForcedChunks.clear();\n } else if (savedChunksDiscardCountdown > 0)\n savedChunksDiscardCountdown--;\n\n if (!unforceQueue.isEmpty()) {\n for (Pair<UUID, Set<LoadedChunkPos>> pair : unforceQueue) {\n unforceAllChunks(server, pair.getFirst(), pair.getSecond());\n }\n unforceQueue.clear();\n }\n }\n\n public static <T extends Comparable<? super T>> void updateForcedChunks(MinecraftServer server, LoadedChunkPos center, T owner, int loadingRange, Set<LoadedChunkPos> forcedChunks) {\n Set<LoadedChunkPos> targetChunks = getChunksAroundCenter(center, loadingRange);\n updateForcedChunks(server, targetChunks, owner, forcedChunks);\n }\n\n public static <T extends Comparable<? super T>> void updateForcedChunks(MinecraftServer server, Collection<LoadedChunkPos> centers, T owner, int loadingRange, Set<LoadedChunkPos> forcedChunks) {\n Set<LoadedChunkPos> targetChunks = new HashSet<>();\n for (LoadedChunkPos center : centers) {\n targetChunks.addAll(getChunksAroundCenter(center, loadingRange));\n }\n updateForcedChunks(server, targetChunks, owner, forcedChunks);\n }\n\n public static <T extends Comparable<? super T>> void updateForcedChunks(MinecraftServer server, Collection<LoadedChunkPos> newChunks, T owner, Set<LoadedChunkPos> forcedChunks) {\n Set<LoadedChunkPos> unforcedChunks = new HashSet<>();\n for (LoadedChunkPos chunk : forcedChunks) {\n if (newChunks.contains(chunk)) {\n newChunks.remove(chunk);\n } else {\n forceChunk(server, owner, chunk.dimension(), chunk.x(), chunk.z(), false);\n unforcedChunks.add(chunk);\n }\n }\n forcedChunks.removeAll(unforcedChunks);\n for (LoadedChunkPos chunk : newChunks) {\n forceChunk(server, owner, chunk.dimension(), chunk.x(), chunk.z(), true);\n forcedChunks.add(chunk);\n }\n if (unforcedChunks.size() > 0 || newChunks.size() > 0)\n LOGGER.debug(\"CPL: update chunks, unloaded {}, loaded {}.\", unforcedChunks.size(), newChunks.size());\n }\n\n public static void enqueueUnforceAll(UUID owner, Set<LoadedChunkPos> forcedChunks) {\n unforceQueue.add(Pair.of(owner, forcedChunks));\n }\n\n public static <T extends Comparable<? super T>> void unforceAllChunks(MinecraftServer server, T owner, Set<LoadedChunkPos> forcedChunks) {\n for (LoadedChunkPos chunk : forcedChunks) {\n forceChunk(server, owner, chunk.dimension(), chunk.x(), chunk.z(), false);\n }\n if (forcedChunks.size() > 0)\n LOGGER.debug(\"CPL: unload all, unloaded {} chunks.\", forcedChunks.size());\n forcedChunks.clear();\n }\n\n private static Set<LoadedChunkPos> getChunksAroundCenter(LoadedChunkPos center, int radius) {\n Set<LoadedChunkPos> ret = new HashSet<>();\n for (int i = center.x() - radius + 1; i <= center.x() + radius - 1; i++) {\n for (int j = center.z() - radius + 1; j <= center.z() + radius - 1; j++) {\n ret.add(new LoadedChunkPos(center.dimension(), i, j));\n }\n }\n return ret;\n }\n\n private static <T extends Comparable<? super T>> void forceChunk(MinecraftServer server, T owner, ResourceLocation dimension, int chunkX, int chunkZ, boolean add) {\n ServerLevel targetLevel = server.getLevel(ResourceKey.create(Registries.DIMENSION, dimension));\n assert targetLevel != null;\n if (owner instanceof BlockPos) {\n ForgeChunkManager.forceChunk(targetLevel, CreatePowerLoader.MODID, (BlockPos) owner, chunkX, chunkZ, add, true);\n } else {\n ForgeChunkManager.forceChunk(targetLevel, CreatePowerLoader.MODID, (UUID) owner, chunkX, chunkZ, add, true);\n }\n }\n\n public static Set<LoadedChunkPos> getSavedForcedChunks(UUID entityUUID) {\n return savedForcedChunks.remove(entityUUID);\n }\n\n public static void validateAllForcedChunks(ServerLevel level, ForgeChunkManager.TicketHelper helper) {\n helper.getBlockTickets().forEach((blockPos, tickets) -> {\n LOGGER.debug(\"CPL: Inspecting level {} position {} which has {} non-ticking tickets and {} ticking tickets.\",\n level.dimension().location(),\n blockPos.toShortString(),\n tickets.getFirst().size(),\n tickets.getSecond().size());\n AbstractChunkLoaderBlockEntity blockEntity = level.getBlockEntity(blockPos, CPLBlockEntityTypes.BRASS_CHUNK_LOADER.get()).orElse(null);\n if (blockEntity == null)\n blockEntity = level.getBlockEntity(blockPos, CPLBlockEntityTypes.ANDESITE_CHUNK_LOADER.get()).orElse(null);\n if (blockEntity == null) {\n helper.removeAllTickets(blockPos);\n LOGGER.debug(\"CPL: level {} position {} unforced: Cannot find block entity.\", level.dimension().location(), blockPos.toShortString());\n return;\n }\n\n for (Long chunk : tickets.getFirst()) {\n ChunkPos chunkPos = new ChunkPos(chunk);\n helper.removeTicket(blockPos, chunk, false);\n LOGGER.debug(\"CPL: level {} position {} unforced non-ticking {}\", level.dimension().location(), blockPos.toShortString(), chunkPos);\n }\n\n Set<LoadedChunkPos> forcedChunks = new HashSet<>();\n for (Long chunk : tickets.getSecond()) {\n ChunkPos chunkPos = new ChunkPos(chunk);\n forcedChunks.add(new LoadedChunkPos(level.dimension().location(), chunkPos));\n }\n blockEntity.reclaimChunks(forcedChunks);\n LOGGER.debug(\"CPL: level {} position {} reclaimed {} chunks.\", level.dimension().location(), blockPos.toShortString(), forcedChunks.size());\n });\n\n helper.getEntityTickets().forEach((entityUUID, tickets) -> {\n // We can't get entities at this point\n // Saving the chunk list for the movement behaviours to use\n\n Set<LoadedChunkPos> savedChunks = new HashSet<>();\n if (savedForcedChunks.containsKey(entityUUID)) {\n savedChunks = savedForcedChunks.get(entityUUID);\n }\n for (Long chunk : tickets.getFirst()) {\n savedChunks.add(new LoadedChunkPos(level, chunk));\n }\n for (Long chunk : tickets.getSecond()) {\n savedChunks.add(new LoadedChunkPos(level, chunk));\n }\n savedForcedChunks.put(entityUUID, savedChunks);\n LOGGER.debug(\"CPL: Inspecting entity {} which has {} non-ticking tickets and {} ticking tickets.\",\n entityUUID,\n tickets.getFirst().size(),\n tickets.getSecond().size());\n });\n savedChunksDiscardCountdown = SAVED_CHUNKS_DISCARD_TICKS;\n }\n\n public static void reclaimChunks(Level level, UUID owner, Map<ResourceKey<Level>, Set<LoadedChunkPos>> reclaimedChunks) {\n // Unload saved chunks when new ones are ready\n // Perhaps this is overcomplicating things because levels with forced chunks should always be loaded?\n Set<LoadedChunkPos> oldChunks = getSavedForcedChunks(owner);\n if (oldChunks != null) {\n for (LoadedChunkPos chunk : oldChunks) {\n ResourceKey<Level> key = ResourceKey.create(Registries.DIMENSION, chunk.dimension());\n Set<LoadedChunkPos> reclaim = reclaimedChunks.get(key);\n if (reclaim != null) {\n reclaim.add(chunk);\n } else {\n reclaim = new HashSet<>();\n reclaim.add(chunk);\n reclaimedChunks.put(key, reclaim);\n }\n }\n }\n\n if (!reclaimedChunks.isEmpty()) {\n MinecraftServer server = level.getServer();\n assert server != null;\n for (Iterator<Map.Entry<ResourceKey<Level>, Set<LoadedChunkPos>>> iterator = reclaimedChunks.entrySet().iterator(); iterator.hasNext(); ) {\n Map.Entry<ResourceKey<Level>, Set<LoadedChunkPos>> entry = iterator.next();\n ServerLevel reclaimLevel = server.getLevel(entry.getKey());\n if (reclaimLevel != null) {\n unforceAllChunks(server, owner, entry.getValue());\n iterator.remove();\n }\n }\n }\n }\n\n public record LoadedChunkPos(@NotNull ResourceLocation dimension, @NotNull ChunkPos chunkPos) {\n\n public LoadedChunkPos(@NotNull Level level, long chunkPos) {\n this(level.dimension().location(), new ChunkPos(chunkPos));\n }\n\n public LoadedChunkPos(@NotNull ResourceLocation level, int pX, int pZ) {\n this(level, new ChunkPos(pX, pZ));\n }\n\n public LoadedChunkPos(@NotNull Level level, BlockPos blockPos) {\n this(level.dimension().location(), new ChunkPos(blockPos));\n }\n\n public int x() {\n return this.chunkPos.x;\n }\n\n public int z() {\n return this.chunkPos.z;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (!(obj instanceof LoadedChunkPos loadedChunk)) return false;\n if (!Objects.equals(loadedChunk.dimension, this.dimension)) return false;\n if (!Objects.equals(loadedChunk.chunkPos, this.chunkPos)) return false;\n return true;\n }\n\n @Override\n public String toString() {\n return dimension + \":\" + chunkPos;\n }\n }\n}" }, { "identifier": "ChunkLoader", "path": "src/main/java/com/hlysine/create_power_loader/content/ChunkLoader.java", "snippet": "public interface ChunkLoader {\n @NotNull\n Set<LoadedChunkPos> getForcedChunks();\n\n LoaderMode getLoaderMode();\n\n LoaderType getLoaderType();\n\n @Nullable\n Pair<ResourceLocation, BlockPos> getLocation();\n\n default void addToManager() {\n ChunkLoadManager.addLoader(getLoaderMode(), this);\n }\n\n default void removeFromManager() {\n ChunkLoadManager.removeLoader(getLoaderMode(), this);\n }\n}" }, { "identifier": "LoaderMode", "path": "src/main/java/com/hlysine/create_power_loader/content/LoaderMode.java", "snippet": "public enum LoaderMode implements StringRepresentable {\n STATIC, CONTRAPTION, TRAIN, STATION;\n\n @Override\n public @NotNull String getSerializedName() {\n return Lang.asId(name());\n }\n}" }, { "identifier": "WeakCollection", "path": "src/main/java/com/hlysine/create_power_loader/content/WeakCollection.java", "snippet": "public class WeakCollection<T> implements Collection<T> {\n private final WeakHashMap<T, Void> items = new WeakHashMap<>();\n\n @Override\n public int size() {\n return items.size();\n }\n\n @Override\n public boolean isEmpty() {\n return items.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n return items.containsKey(o);\n }\n\n @NotNull\n @Override\n public Iterator<T> iterator() {\n return items.keySet().iterator();\n }\n\n @NotNull\n @Override\n public Object[] toArray() {\n return items.keySet().toArray();\n }\n\n @NotNull\n @Override\n public <T1> T1[] toArray(@NotNull T1[] a) {\n return items.keySet().toArray(a);\n }\n\n @Override\n public boolean add(T t) {\n if (items.containsKey(t)) return false;\n items.put(t, null);\n return true;\n }\n\n @Override\n public boolean remove(Object o) {\n return items.remove(o, null);\n }\n\n @Override\n public boolean containsAll(@NotNull Collection<?> c) {\n return items.keySet().containsAll(c);\n }\n\n @Override\n public boolean addAll(@NotNull Collection<? extends T> c) {\n boolean changed = false;\n for (T t : c) {\n if (items.containsKey(t)) continue;\n changed = true;\n items.put(t, null);\n }\n return changed;\n }\n\n @Override\n public boolean removeAll(@NotNull Collection<?> c) {\n return items.keySet().removeAll(c);\n }\n\n @Override\n public boolean retainAll(@NotNull Collection<?> c) {\n return items.keySet().retainAll(c);\n }\n\n @Override\n public void clear() {\n items.clear();\n }\n}" }, { "identifier": "CarriageChunkLoader", "path": "src/main/java/com/hlysine/create_power_loader/content/trains/CarriageChunkLoader.java", "snippet": "public class CarriageChunkLoader implements ChunkLoader {\n public final Carriage carriage;\n public boolean known;\n public boolean andesite;\n public boolean brass;\n public final Set<LoadedChunkPos> forcedChunks = new HashSet<>();\n\n public CarriageChunkLoader(Carriage carriage, boolean known, boolean andesite, boolean brass) {\n this.carriage = carriage;\n this.known = known;\n this.andesite = andesite;\n this.brass = brass;\n }\n\n @Override\n public @NotNull Set<LoadedChunkPos> getForcedChunks() {\n return forcedChunks;\n }\n\n @Override\n public LoaderMode getLoaderMode() {\n return LoaderMode.TRAIN;\n }\n\n @Override\n public LoaderType getLoaderType() {\n return brass ? LoaderType.BRASS : LoaderType.ANDESITE;\n }\n\n @Override\n public Pair<ResourceLocation, BlockPos> getLocation() {\n if (carriage.train.graph == null) return null;\n return Pair.of(\n carriage.leadingBogey().trailing().node1.getLocation().getDimension().location(),\n BlockPos.containing(carriage.leadingBogey().trailing().getPosition(carriage.train.graph))\n );\n }\n\n public void tick(Level level) {\n if (!known) updateCarriage();\n if (!known) return;\n if (!canLoadChunks()) {\n if (!forcedChunks.isEmpty())\n ChunkLoadManager.unforceAllChunks(level.getServer(), carriage.train.id, forcedChunks);\n return;\n }\n\n Set<LoadedChunkPos> loadTargets = new HashSet<>();\n\n addLoadTargets(loadTargets, carriage.leadingBogey().trailing());\n addLoadTargets(loadTargets, carriage.trailingBogey().leading());\n\n ChunkLoadManager.updateForcedChunks(level.getServer(), loadTargets, carriage.train.id, 2, forcedChunks);\n }\n\n public void onRemove() {\n ChunkLoadManager.enqueueUnforceAll(carriage.train.id, forcedChunks);\n }\n\n private void addLoadTargets(Set<LoadedChunkPos> loadTargets, TravellingPoint point) {\n if (point.edge.isInterDimensional()) {\n loadTargets.add(new LoadedChunkPos(\n point.node1.getLocation().getDimension().location(),\n new ChunkPos(BlockPos.containing(point.node1.getLocation().getLocation()))\n ));\n loadTargets.add(new LoadedChunkPos(\n point.node2.getLocation().getDimension().location(),\n new ChunkPos(BlockPos.containing(point.node2.getLocation().getLocation()))\n ));\n } else {\n loadTargets.add(new LoadedChunkPos(\n point.node1.getLocation().getDimension().location(),\n new ChunkPos(BlockPos.containing(point.getPosition(carriage.train.graph)))\n ));\n }\n }\n\n private void updateCarriage() {\n CarriageContraptionEntity entity = carriage.anyAvailableEntity();\n known = entity != null;\n if (!known) return;\n\n Contraption contraption = entity.getContraption();\n andesite = !contraption.isActorTypeDisabled(ItemStack.EMPTY) && !contraption.isActorTypeDisabled(CPLBlocks.ANDESITE_CHUNK_LOADER.asStack());\n brass = !contraption.isActorTypeDisabled(ItemStack.EMPTY) && !contraption.isActorTypeDisabled(CPLBlocks.BRASS_CHUNK_LOADER.asStack());\n if (!andesite && !brass) return;\n\n boolean hasAndesite = false, hasBrass = false;\n for (MutablePair<StructureTemplate.StructureBlockInfo, MovementContext> actor : entity.getContraption().getActors()) {\n if (!hasAndesite && actor.left.state().is(CPLBlocks.ANDESITE_CHUNK_LOADER.get())) {\n hasAndesite = true;\n }\n if (!hasBrass && actor.left.state().is(CPLBlocks.BRASS_CHUNK_LOADER.get())) {\n hasBrass = true;\n }\n if (hasAndesite && hasBrass) break;\n }\n andesite = hasAndesite;\n brass = hasBrass;\n }\n\n private boolean canLoadChunks() {\n if (carriage.train.graph == null) return false;\n return andesite && CPLConfigs.server().andesiteOnContraption.get() || brass && CPLConfigs.server().brassOnContraption.get();\n }\n\n public CompoundTag write() {\n CompoundTag nbt = new CompoundTag();\n if (known) {\n nbt.putBoolean(\"andesite\", andesite);\n nbt.putBoolean(\"brass\", brass);\n }\n return nbt;\n }\n\n public static CarriageChunkLoader read(Carriage carriage, CompoundTag nbt) {\n if (nbt.contains(\"andesite\") && nbt.contains(\"brass\"))\n return new CarriageChunkLoader(carriage, true, nbt.getBoolean(\"andesite\"), nbt.getBoolean(\"brass\"));\n return new CarriageChunkLoader(carriage, false, false, false);\n }\n}" }, { "identifier": "StationChunkLoader", "path": "src/main/java/com/hlysine/create_power_loader/content/trains/StationChunkLoader.java", "snippet": "public class StationChunkLoader implements ChunkLoader {\n private final GlobalStation station;\n public final Set<AttachedLoader> attachments = new HashSet<>();\n\n private final Map<ResourceKey<Level>, Set<LoadedChunkPos>> reclaimedChunks = new HashMap<>();\n public final Set<LoadedChunkPos> forcedChunks = new HashSet<>();\n private boolean registered = false;\n\n\n public StationChunkLoader(GlobalStation station) {\n this.station = station;\n }\n\n @Override\n public @NotNull Set<LoadedChunkPos> getForcedChunks() {\n return forcedChunks;\n }\n\n @Override\n public LoaderMode getLoaderMode() {\n return LoaderMode.STATION;\n }\n\n @Override\n public LoaderType getLoaderType() {\n for (AttachedLoader attachment : attachments) {\n if (attachment.type() == LoaderType.BRASS) return LoaderType.BRASS;\n }\n return LoaderType.ANDESITE;\n }\n\n @Override\n public @Nullable Pair<ResourceLocation, BlockPos> getLocation() {\n return Pair.of(\n station.edgeLocation.getFirst().dimension.location(),\n BlockPos.containing(station.edgeLocation.getFirst().getLocation().add(station.edgeLocation.getSecond().getLocation()).scale(0.5))\n );\n }\n\n @Override\n public void addToManager() {\n if (!registered) {\n ChunkLoader.super.addToManager();\n registered = true;\n }\n }\n\n public void tick(TrackGraph graph, boolean preTrains) {\n if (preTrains) return;\n Level level = ChunkLoadManager.tickLevel;\n if (level == null || level.isClientSide()) return;\n addToManager();\n\n ChunkLoadManager.reclaimChunks(level, station.id, reclaimedChunks);\n\n if (attachments.isEmpty() || station.getPresentTrain() == null) {\n if (!forcedChunks.isEmpty())\n ChunkLoadManager.unforceAllChunks(level.getServer(), station.id, forcedChunks);\n return;\n }\n\n // sanitize in case of read/write errors\n attachments.removeIf(a -> a.pos.distManhattan(station.blockEntityPos) > 1);\n\n Set<LoadedChunkPos> loadTargets = new HashSet<>();\n for (AttachedLoader attachment : attachments) {\n if (isEnabledForStation(attachment.type()))\n loadTargets.add(new LoadedChunkPos(station.blockEntityDimension.location(), new ChunkPos(attachment.pos())));\n }\n ChunkLoadManager.updateForcedChunks(level.getServer(), loadTargets, station.id, 2, forcedChunks);\n }\n\n public static boolean isEnabledForStation(LoaderType type) {\n if (type == LoaderType.ANDESITE)\n return CPLConfigs.server().andesiteOnStation.get();\n else if (type == LoaderType.BRASS)\n return CPLConfigs.server().brassOnStation.get();\n else throw new IllegalArgumentException(\"Unknown LoaderType \" + type);\n }\n\n public void removeAttachment(BlockPos pos) {\n attachments.removeIf(t -> t.pos.equals(pos));\n }\n\n public void addAttachment(LoaderType type, BlockPos pos) {\n removeAttachment(pos);\n attachments.add(new AttachedLoader(type, pos));\n }\n\n public void onRemove() {\n ChunkLoadManager.enqueueUnforceAll(station.id, forcedChunks);\n removeFromManager();\n }\n\n public CompoundTag write() {\n CompoundTag nbt = new CompoundTag();\n nbt.put(\"Attachments\", NBTHelper.writeCompoundList(attachments, AttachedLoader::write));\n return nbt;\n }\n\n public static StationChunkLoader read(GlobalStation station, CompoundTag nbt) {\n StationChunkLoader loader = new StationChunkLoader(station);\n loader.attachments.clear();\n loader.attachments.addAll(NBTHelper.readCompoundList(nbt.getList(\"Attachments\", Tag.TAG_COMPOUND), AttachedLoader::read));\n return loader;\n }\n\n public record AttachedLoader(LoaderType type, BlockPos pos) {\n public CompoundTag write() {\n CompoundTag nbt = new CompoundTag();\n NBTHelper.writeEnum(nbt, \"Type\", type);\n nbt.put(\"Pos\", NbtUtils.writeBlockPos(pos));\n return nbt;\n }\n\n public static AttachedLoader read(CompoundTag nbt) {\n return new AttachedLoader(\n NBTHelper.readEnum(nbt, \"Type\", LoaderType.class),\n NbtUtils.readBlockPos(nbt.getCompound(\"Pos\"))\n );\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) return true;\n if (!(obj instanceof AttachedLoader loader)) return false;\n if (this.type != loader.type) return false;\n if (!Objects.equals(this.pos, loader.pos)) return false;\n return true;\n }\n }\n}" }, { "identifier": "TrainChunkLoader", "path": "src/main/java/com/hlysine/create_power_loader/content/trains/TrainChunkLoader.java", "snippet": "public class TrainChunkLoader implements ChunkLoader {\n private final Train train;\n public final List<CarriageChunkLoader> carriageLoaders = new LinkedList<>();\n private final Map<ResourceKey<Level>, Set<LoadedChunkPos>> reclaimedChunks = new HashMap<>();\n private boolean registered = false;\n\n public TrainChunkLoader(Train train) {\n this.train = train;\n }\n\n @Override\n public @NotNull Set<LoadedChunkPos> getForcedChunks() {\n Set<LoadedChunkPos> allForced = new HashSet<>();\n for (CarriageChunkLoader loader : carriageLoaders) {\n allForced.addAll(loader.getForcedChunks());\n }\n return allForced;\n }\n\n @Override\n public LoaderMode getLoaderMode() {\n return LoaderMode.TRAIN;\n }\n\n @Override\n public LoaderType getLoaderType() {\n for (CarriageChunkLoader carriageLoader : carriageLoaders) {\n if (carriageLoader.getLoaderType() == LoaderType.BRASS) return LoaderType.BRASS;\n }\n return LoaderType.ANDESITE;\n }\n\n @Override\n public Pair<ResourceLocation, BlockPos> getLocation() {\n if (train.graph == null) return null;\n return train.carriages.stream().findFirst()\n .map(carriage -> Pair.of(\n carriage.leadingBogey().trailing().node1.getLocation().getDimension().location(),\n BlockPos.containing(carriage.leadingBogey().trailing().getPosition(train.graph))\n ))\n .orElse(null);\n }\n\n @Override\n public void addToManager() {\n if (!registered) {\n ChunkLoader.super.addToManager();\n registered = true;\n }\n }\n\n public void tick(Level level) {\n if (level.isClientSide()) return;\n addToManager();\n\n // Make sure carriage information is up-to-date\n if (carriageLoaders.size() != train.carriages.size()) {\n List<CarriageChunkLoader> newLoaders = new LinkedList<>();\n for (Carriage carriage : train.carriages) {\n CarriageChunkLoader loader = carriageLoaders.stream()\n .filter(x -> x.carriage == carriage)\n .findFirst()\n .orElseGet(() -> new CarriageChunkLoader(carriage, false, false, false));\n newLoaders.add(loader);\n }\n carriageLoaders.clear();\n carriageLoaders.addAll(newLoaders);\n }\n\n ChunkLoadManager.reclaimChunks(level, train.id, reclaimedChunks);\n\n for (CarriageChunkLoader loader : carriageLoaders) {\n loader.tick(level);\n }\n }\n\n public void onRemove() {\n for (CarriageChunkLoader loader : carriageLoaders) {\n loader.onRemove();\n }\n removeFromManager();\n }\n\n public CompoundTag write() {\n CompoundTag nbt = new CompoundTag();\n nbt.put(\"CarriageLoaders\", NBTHelper.writeCompoundList(carriageLoaders, CarriageChunkLoader::write));\n return nbt;\n }\n\n public static TrainChunkLoader read(Train train, CompoundTag nbt) {\n TrainChunkLoader loader = new TrainChunkLoader(train);\n ListTag list = nbt.getList(\"CarriageLoaders\", Tag.TAG_COMPOUND);\n // do not use saved data if sizes don't match,\n // because we have no idea which saved tag corresponds to which carriage\n if (list.size() == train.carriages.size()) {\n for (int i = 0; i < list.size(); i++) {\n CompoundTag tag = (CompoundTag) list.get(i);\n loader.carriageLoaders.add(CarriageChunkLoader.read(train.carriages.get(i), tag));\n }\n }\n return loader;\n }\n}" } ]
import com.hlysine.create_power_loader.content.ChunkLoadManager; import com.hlysine.create_power_loader.content.ChunkLoader; import com.hlysine.create_power_loader.content.LoaderMode; import com.hlysine.create_power_loader.content.WeakCollection; import com.hlysine.create_power_loader.content.trains.CarriageChunkLoader; import com.hlysine.create_power_loader.content.trains.StationChunkLoader; import com.hlysine.create_power_loader.content.trains.TrainChunkLoader; import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.ArgumentBuilder; import com.simibubi.create.foundation.utility.Components; import com.simibubi.create.foundation.utility.Pair; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.phys.Vec3; import net.minecraftforge.server.command.EnumArgument; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function;
7,494
package com.hlysine.create_power_loader.command; public class ListLoadersCommand { public static ArgumentBuilder<CommandSourceStack, ?> register() { return Commands.literal("list") .requires(cs -> cs.hasPermission(2)) .then(Commands.argument("type", EnumArgument.enumArgument(LoaderMode.class)) .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, true)) ) ).executes(handler(true, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, false)) ) ).executes(handler(true, false, false)) ) ) .then(Commands.literal("all") .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, true)) ) ).executes(handler(false, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, false)) ) ).executes(handler(false, false, false)) ) ); } private static Command<CommandSourceStack> handler(boolean hasMode, boolean hasLimit, boolean activeOnly) { return ctx -> { CommandSourceStack source = ctx.getSource(); fillReport(source.getLevel(), source.getPosition(), hasMode ? ctx.getArgument("type", LoaderMode.class) : null, hasLimit ? ctx.getArgument("limit", Integer.class) : 20, activeOnly, (s, f) -> source.sendSuccess(() -> Components.literal(s).withStyle(st -> st.withColor(f)), false), (c) -> source.sendSuccess(() -> c, false)); return Command.SINGLE_SUCCESS; }; } private static void fillReport(ServerLevel level, Vec3 location, @Nullable LoaderMode mode, int limit, boolean activeOnly, BiConsumer<String, Integer> chat, Consumer<Component> chatRaw) { int white = ChatFormatting.WHITE.getColor(); int gray = ChatFormatting.GRAY.getColor(); int blue = 0xD3DEDC; int darkBlue = 0x5955A1; int orange = 0xFFAD60; List<ChunkLoader> loaders = new LinkedList<>(); if (mode == null) {
package com.hlysine.create_power_loader.command; public class ListLoadersCommand { public static ArgumentBuilder<CommandSourceStack, ?> register() { return Commands.literal("list") .requires(cs -> cs.hasPermission(2)) .then(Commands.argument("type", EnumArgument.enumArgument(LoaderMode.class)) .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, true)) ) ).executes(handler(true, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, false)) ) ).executes(handler(true, false, false)) ) ) .then(Commands.literal("all") .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, true)) ) ).executes(handler(false, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, false)) ) ).executes(handler(false, false, false)) ) ); } private static Command<CommandSourceStack> handler(boolean hasMode, boolean hasLimit, boolean activeOnly) { return ctx -> { CommandSourceStack source = ctx.getSource(); fillReport(source.getLevel(), source.getPosition(), hasMode ? ctx.getArgument("type", LoaderMode.class) : null, hasLimit ? ctx.getArgument("limit", Integer.class) : 20, activeOnly, (s, f) -> source.sendSuccess(() -> Components.literal(s).withStyle(st -> st.withColor(f)), false), (c) -> source.sendSuccess(() -> c, false)); return Command.SINGLE_SUCCESS; }; } private static void fillReport(ServerLevel level, Vec3 location, @Nullable LoaderMode mode, int limit, boolean activeOnly, BiConsumer<String, Integer> chat, Consumer<Component> chatRaw) { int white = ChatFormatting.WHITE.getColor(); int gray = ChatFormatting.GRAY.getColor(); int blue = 0xD3DEDC; int darkBlue = 0x5955A1; int orange = 0xFFAD60; List<ChunkLoader> loaders = new LinkedList<>(); if (mode == null) {
for (WeakCollection<ChunkLoader> list : ChunkLoadManager.allLoaders.values()) {
3
2023-11-09 04:29:33+00:00
12k
dingodb/dingo-expr
runtime/src/main/java/io/dingodb/expr/runtime/compiler/CastingFactory.java
[ { "identifier": "ExprConfig", "path": "runtime/src/main/java/io/dingodb/expr/runtime/ExprConfig.java", "snippet": "public interface ExprConfig {\n ExprConfig SIMPLE = new ExprConfig() {\n };\n\n ExprConfig ADVANCED = new ExprConfig() {\n @Override\n public boolean withSimplification() {\n return true;\n }\n\n @Override\n public boolean withRangeCheck() {\n return true;\n }\n };\n\n default boolean withSimplification() {\n return false;\n }\n\n default boolean withRangeCheck() {\n return false;\n }\n\n default boolean withGeneralOp() {\n return true;\n }\n\n default TimeZone getTimeZone() {\n return TimeZone.getDefault();\n }\n\n default DateTimeFormatter[] getParseDateFormatters() {\n return DateTimeUtils.DEFAULT_PARSE_DATE_FORMATTERS;\n }\n\n default DateTimeFormatter[] getParseTimeFormatters() {\n return DateTimeUtils.DEFAULT_PARSE_TIME_FORMATTERS;\n }\n\n default DateTimeFormatter[] getParseTimestampFormatters() {\n return DateTimeUtils.DEFAULT_PARSE_TIMESTAMP_FORMATTERS;\n }\n\n default DateTimeFormatter getOutputDateFormatter() {\n return DateTimeUtils.DEFAULT_OUTPUT_DATE_FORMATTER;\n }\n\n default DateTimeFormatter getOutputTimeFormatter() {\n return DateTimeUtils.DEFAULT_OUTPUT_TIME_FORMATTER;\n }\n\n default DateTimeFormatter getOutputTimestampFormatter() {\n return DateTimeUtils.DEFAULT_OUTPUT_TIMESTAMP_FORMATTER;\n }\n}" }, { "identifier": "ExprCompileException", "path": "runtime/src/main/java/io/dingodb/expr/runtime/exception/ExprCompileException.java", "snippet": "public class ExprCompileException extends RuntimeException {\n private static final long serialVersionUID = 2987733189942293175L;\n\n /**\n * Exception thrown when there are errors in compiling.\n *\n * @param message the error message\n */\n public ExprCompileException(String message) {\n super(message);\n }\n\n /**\n * Exception thrown when there are errors in compiling.\n *\n * @param cause the cause of the exception\n */\n public ExprCompileException(Throwable cause) {\n super(cause);\n }\n\n /**\n * Exception thrown when there are errors in compiling.\n *\n * @param message the error message\n * @param cause the cause of the exception\n */\n public ExprCompileException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "Exprs", "path": "runtime/src/main/java/io/dingodb/expr/runtime/expr/Exprs.java", "snippet": "public final class Exprs {\n // Castings\n public static final IntCastOpFactory TO_INT = IntCastOpFactory.INSTANCE;\n public static final IntCastCheckOpFactory TO_INT_C = IntCastCheckOpFactory.INSTANCE;\n public static final LongCastOpFactory TO_LONG = LongCastOpFactory.INSTANCE;\n public static final LongCastCheckOpFactory TO_LONG_C = LongCastCheckOpFactory.INSTANCE;\n public static final FloatCastOpFactory TO_FLOAT = FloatCastOpFactory.INSTANCE;\n public static final DoubleCastOpFactory TO_DOUBLE = DoubleCastOpFactory.INSTANCE;\n public static final BoolCastOpFactory TO_BOOL = BoolCastOpFactory.INSTANCE;\n public static final DecimalCastOpFactory TO_DECIMAL = DecimalCastOpFactory.INSTANCE;\n public static final StringCastOpFactory TO_STRING = StringCastOpFactory.INSTANCE;\n public static final BytesCastOpFactory TO_BYTES = BytesCastOpFactory.INSTANCE;\n public static final DateCastOpFactory TO_DATE = DateCastOpFactory.INSTANCE;\n public static final TimeCastOpFactory TO_TIME = TimeCastOpFactory.INSTANCE;\n public static final TimestampCastOpFactory TO_TIMESTAMP = TimestampCastOpFactory.INSTANCE;\n\n // Arithmetics\n public static final PosOpFactory POS = PosOpFactory.INSTANCE;\n public static final NegOpFactory NEG = NegOpFactory.INSTANCE;\n public static final AddOpFactory ADD = AddOpFactory.INSTANCE;\n public static final SubOpFactory SUB = SubOpFactory.INSTANCE;\n public static final MulOpFactory MUL = MulOpFactory.INSTANCE;\n public static final DivOpFactory DIV = DivOpFactory.INSTANCE;\n\n // Relations\n public static final EqOpFactory EQ = EqOpFactory.INSTANCE;\n public static final NeOpFactory NE = NeOpFactory.INSTANCE;\n public static final GtOpFactory GT = GtOpFactory.INSTANCE;\n public static final GeOpFactory GE = GeOpFactory.INSTANCE;\n public static final LtOpFactory LT = LtOpFactory.INSTANCE;\n public static final LeOpFactory LE = LeOpFactory.INSTANCE;\n\n // Logics\n public static final AndOp AND = AndOp.INSTANCE;\n public static final OrOp OR = OrOp.INSTANCE;\n public static final AndFun AND_FUN = AndFun.INSTANCE;\n public static final OrFun OR_FUN = OrFun.INSTANCE;\n public static final NotOpFactory NOT = NotOpFactory.INSTANCE;\n\n // Specials\n public static final IsNullFunFactory IS_NULL = IsNullFunFactory.INSTANCE;\n public static final IsTrueFunFactory IS_TRUE = IsTrueFunFactory.INSTANCE;\n public static final IsFalseFunFactory IS_FALSE = IsFalseFunFactory.INSTANCE;\n public static final CaseFun CASE = CaseFun.INSTANCE;\n\n // Mathematics\n public static final AbsFunFactory ABS = AbsFunFactory.INSTANCE;\n public static final AbsCheckFunFactory ABS_C = AbsCheckFunFactory.INSTANCE;\n public static final ModFunFactory MOD = ModFunFactory.INSTANCE;\n public static final MaxFunFactory MAX = MaxFunFactory.INSTANCE;\n public static final MinFunFactory MIN = MinFunFactory.INSTANCE;\n public static final SinFunFactory SIN = SinFunFactory.INSTANCE;\n public static final CosFunFactory COS = CosFunFactory.INSTANCE;\n public static final TanFunFactory TAN = TanFunFactory.INSTANCE;\n public static final AsinFunFactory ASIN = AsinFunFactory.INSTANCE;\n public static final AcosFunFactory ACOS = AcosFunFactory.INSTANCE;\n public static final AtanFunFactory ATAN = AtanFunFactory.INSTANCE;\n public static final SinhFunFactory SINH = SinhFunFactory.INSTANCE;\n public static final CoshFunFactory COSH = CoshFunFactory.INSTANCE;\n public static final TanhFunFactory TANH = TanhFunFactory.INSTANCE;\n public static final ExpFunFactory EXP = ExpFunFactory.INSTANCE;\n public static final LogFunFactory LOG = LogFunFactory.INSTANCE;\n public static final CeilFunFactory CEIL = CeilFunFactory.INSTANCE;\n public static final FloorFunFactory FLOOR = FloorFunFactory.INSTANCE;\n public static final PowFunFactory POW = PowFunFactory.INSTANCE;\n public static final Round1FunFactory ROUND1 = Round1FunFactory.INSTANCE;\n public static final Round2FunFactory ROUND2 = Round2FunFactory.INSTANCE;\n\n // Strings\n public static final CharLengthFunFactory CHAR_LENGTH = CharLengthFunFactory.INSTANCE;\n public static final ConcatFunFactory CONCAT = ConcatFunFactory.INSTANCE;\n public static final LowerFunFactory LOWER = LowerFunFactory.INSTANCE;\n public static final UpperFunFactory UPPER = UpperFunFactory.INSTANCE;\n public static final LeftFunFactory LEFT = LeftFunFactory.INSTANCE;\n public static final RightFunFactory RIGHT = RightFunFactory.INSTANCE;\n public static final Trim1FunFactory TRIM1 = Trim1FunFactory.INSTANCE;\n public static final Trim2FunFactory TRIM2 = Trim2FunFactory.INSTANCE;\n public static final LTrim1FunFactory LTRIM1 = LTrim1FunFactory.INSTANCE;\n public static final LTrim2FunFactory LTRIM2 = LTrim2FunFactory.INSTANCE;\n public static final RTrim1FunFactory RTRIM1 = RTrim1FunFactory.INSTANCE;\n public static final RTrim2FunFactory RTRIM2 = RTrim2FunFactory.INSTANCE;\n public static final Substr2FunFactory SUBSTR2 = Substr2FunFactory.INSTANCE;\n public static final Substr3FunFactory SUBSTR3 = Substr3FunFactory.INSTANCE;\n public static final Mid2FunFactory MID2 = Mid2FunFactory.INSTANCE;\n public static final Mid3FunFactory MID3 = Mid3FunFactory.INSTANCE;\n public static final RepeatFunFactory REPEAT = RepeatFunFactory.INSTANCE;\n public static final ReverseFunFactory REVERSE = ReverseFunFactory.INSTANCE;\n public static final ReplaceFunFactory REPLACE = ReplaceFunFactory.INSTANCE;\n public static final Locate2FunFactory LOCATE2 = Locate2FunFactory.INSTANCE;\n public static final Locate3FunFactory LOCATE3 = Locate3FunFactory.INSTANCE;\n public static final HexFunFactory HEX = HexFunFactory.INSTANCE;\n public static final NumberFormatFunFactory FORMAT = NumberFormatFunFactory.INSTANCE;\n public static final MatchesFunFactory MATCHES = MatchesFunFactory.INSTANCE;\n public static final MatchesIgnoreCaseFunFactory MATCHES_NC = MatchesIgnoreCaseFunFactory.INSTANCE;\n public static final ConvertTimeFormatFunFactory _CTF = ConvertTimeFormatFunFactory.INSTANCE;\n public static final ConvertPattern1FunFactory _CP1 = ConvertPattern1FunFactory.INSTANCE;\n public static final ConvertPattern2FunFactory _CP2 = ConvertPattern2FunFactory.INSTANCE;\n\n // Index\n public static final IndexOpFactory INDEX = IndexOpFactory.INSTANCE;\n\n // Date and time\n public static final CurrentDateFun CURRENT_DATE = CurrentDateFun.INSTANCE;\n public static final CurrentTimeFun CURRENT_TIME = CurrentTimeFun.INSTANCE;\n public static final CurrentTimestampFun CURRENT_TIMESTAMP = CurrentTimestampFun.INSTANCE;\n public static final DateFormat1FunFactory DATE_FORMAT1 = DateFormat1FunFactory.INSTANCE;\n public static final DateFormat2FunFactory DATE_FORMAT2 = DateFormat2FunFactory.INSTANCE;\n public static final TimeFormat1FunFactory TIME_FORMAT1 = TimeFormat1FunFactory.INSTANCE;\n public static final TimeFormat2FunFactory TIME_FORMAT2 = TimeFormat2FunFactory.INSTANCE;\n public static final TimestampFormat1FunFactory TIMESTAMP_FORMAT1 = TimestampFormat1FunFactory.INSTANCE;\n public static final TimestampFormat2FunFactory TIMESTAMP_FORMAT2 = TimestampFormat2FunFactory.INSTANCE;\n public static final FromUnixTimeFunFactory FROM_UNIXTIME = FromUnixTimeFunFactory.INSTANCE;\n public static final UnixTimestamp0Fun UNIX_TIMESTAMP0 = UnixTimestamp0Fun.INSTANCE;\n public static final UnixTimestamp1FunFactory UNIX_TIMESTAMP1 = UnixTimestamp1FunFactory.INSTANCE;\n public static final DateDiffFunFactory DATEDIFF = DateDiffFunFactory.INSTANCE;\n\n // Collections\n public static final ArrayConstructorOpFactory ARRAY = ArrayConstructorOpFactory.INSTANCE;\n public static final ListConstructorOpFactory LIST = ListConstructorOpFactory.INSTANCE;\n public static final MapConstructorOpFactory MAP = MapConstructorOpFactory.INSTANCE;\n public static final CastArrayOpFactory TO_ARRAY_INT = new CastArrayOpFactory(TO_INT);\n public static final CastArrayOpFactory TO_ARRAY_INT_C = new CastArrayOpFactory(TO_INT_C);\n public static final CastArrayOpFactory TO_ARRAY_LONG = new CastArrayOpFactory(TO_LONG);\n public static final CastArrayOpFactory TO_ARRAY_LONG_C = new CastArrayOpFactory(TO_LONG_C);\n public static final CastArrayOpFactory TO_ARRAY_FLOAT = new CastArrayOpFactory(TO_FLOAT);\n public static final CastArrayOpFactory TO_ARRAY_DOUBLE = new CastArrayOpFactory(TO_DOUBLE);\n public static final CastArrayOpFactory TO_ARRAY_BOOL = new CastArrayOpFactory(TO_BOOL);\n public static final CastArrayOpFactory TO_ARRAY_DECIMAL = new CastArrayOpFactory(TO_DECIMAL);\n public static final CastArrayOpFactory TO_ARRAY_STRING = new CastArrayOpFactory(TO_STRING);\n public static final CastArrayOpFactory TO_ARRAY_BYTES = new CastArrayOpFactory(TO_BYTES);\n public static final CastArrayOpFactory TO_ARRAY_DATE = new CastArrayOpFactory(TO_DATE);\n public static final CastArrayOpFactory TO_ARRAY_TIME = new CastArrayOpFactory(TO_TIME);\n public static final CastArrayOpFactory TO_ARRAY_TIMESTAMP = new CastArrayOpFactory(TO_TIMESTAMP);\n public static final CastListOpFactory TO_LIST_INT = new CastListOpFactory(TO_INT);\n public static final CastListOpFactory TO_LIST_INT_C = new CastListOpFactory(TO_INT_C);\n public static final CastListOpFactory TO_LIST_LONG = new CastListOpFactory(TO_LONG);\n public static final CastListOpFactory TO_LIST_LONG_C = new CastListOpFactory(TO_LONG_C);\n public static final CastListOpFactory TO_LIST_FLOAT = new CastListOpFactory(TO_FLOAT);\n public static final CastListOpFactory TO_LIST_DOUBLE = new CastListOpFactory(TO_DOUBLE);\n public static final CastListOpFactory TO_LIST_BOOL = new CastListOpFactory(TO_BOOL);\n public static final CastListOpFactory TO_LIST_DECIMAL = new CastListOpFactory(TO_DECIMAL);\n public static final CastListOpFactory TO_LIST_STRING = new CastListOpFactory(TO_STRING);\n public static final CastListOpFactory TO_LIST_BYTES = new CastListOpFactory(TO_BYTES);\n public static final CastListOpFactory TO_LIST_DATE = new CastListOpFactory(TO_DATE);\n public static final CastListOpFactory TO_LIST_TIME = new CastListOpFactory(TO_TIME);\n public static final CastListOpFactory TO_LIST_TIMESTAMP = new CastListOpFactory(TO_TIMESTAMP);\n public static final SliceOpFactory SLICE = SliceOpFactory.INSTANCE;\n\n // Aggregations\n public static final CountAgg COUNT_AGG = CountAgg.INSTANCE;\n public static final CountAllAgg COUNT_ALL_AGG = CountAllAgg.INSTANCE;\n public static final MaxAgg MAX_AGG = MaxAgg.INSTANCE;\n public static final MinAgg MIN_AGG = MinAgg.INSTANCE;\n public static final SumAgg SUM_AGG = SumAgg.INSTANCE;\n public static final Sum0Agg SUM0_AGG = Sum0Agg.INSTANCE;\n\n private Exprs() {\n }\n\n public static @NonNull Val val(Object value) {\n return val(value, Types.valueType(value));\n }\n\n public static @NonNull Val val(Object value, Type type) {\n if (value != null) {\n Type valueType = Types.valueType(value);\n if (valueType.equals(type) && value instanceof Boolean) {\n return (Boolean) value ? Val.TRUE : Val.FALSE;\n }\n return new Val(value, type);\n }\n return NullCreator.INSTANCE.visit(type);\n }\n\n public static @NonNull Var var(Object id) {\n return new Var(id, null);\n }\n\n public static @NonNull Var var(Object id, Type type) {\n return new Var(id, type);\n }\n\n public static @NonNull NullaryOpExpr op(\n @NonNull NullaryOp op\n ) {\n return op.createExpr();\n }\n\n public static @NonNull UnaryOpExpr op(\n @NonNull UnaryOp op,\n @NonNull Object operand\n ) {\n Expr expr = transOperand(operand);\n return op.createExpr(expr);\n }\n\n public static @NonNull BinaryOpExpr op(\n @NonNull BinaryOp op,\n @NonNull Object operand0,\n @NonNull Object operand1\n ) {\n Expr expr0 = transOperand(operand0);\n Expr expr1 = transOperand(operand1);\n return op.createExpr(expr0, expr1);\n }\n\n public static @NonNull TertiaryOpExpr op(\n @NonNull TertiaryOp op,\n @NonNull Object operand0,\n @NonNull Object operand1,\n @NonNull Object operand2\n ) {\n Expr expr0 = transOperand(operand0);\n Expr expr1 = transOperand(operand1);\n Expr expr2 = transOperand(operand2);\n return op.createExpr(expr0, expr1, expr2);\n }\n\n public static @NonNull VariadicOpExpr op(\n @NonNull VariadicOp op,\n Object @NonNull ... operands\n ) {\n Expr[] exprs = transOperands(operands);\n return op.createExpr(exprs);\n }\n\n private static @NonNull Expr transOperand(Object operand) {\n return operand instanceof Expr ? (Expr) operand : val(operand);\n }\n\n private static Expr @NonNull [] transOperands(Object @NonNull [] operands) {\n return Arrays.stream(operands)\n .map(Exprs::transOperand)\n .toArray(Expr[]::new);\n }\n\n private static class NullCreator extends TypeVisitorBase<Val, Void> {\n private static final NullCreator INSTANCE = new NullCreator();\n\n @Override\n public Val visitNullType(@NonNull NullType type, Void obj) {\n return Val.NULL;\n }\n\n @Override\n public Val visitIntType(@NonNull IntType type, Void obj) {\n return Val.NULL_INT;\n }\n\n @Override\n public Val visitLongType(@NonNull LongType type, Void obj) {\n return Val.NULL_LONG;\n }\n\n @Override\n public Val visitFloatType(@NonNull FloatType type, Void obj) {\n return Val.NULL_FLOAT;\n }\n\n @Override\n public Val visitDoubleType(@NonNull DoubleType type, Void obj) {\n return Val.NULL_DOUBLE;\n }\n\n @Override\n public Val visitBoolType(@NonNull BoolType type, Void obj) {\n return Val.NULL_BOOL;\n }\n\n @Override\n public Val visitDecimalType(@NonNull DecimalType type, Void obj) {\n return Val.NULL_DECIMAL;\n }\n\n @Override\n public Val visitStringType(@NonNull StringType type, Void obj) {\n return Val.NULL_STRING;\n }\n\n @Override\n public Val visitBytesType(@NonNull BytesType type, Void obj) {\n return Val.NULL_BYTES;\n }\n\n @Override\n public Val visitDateType(@NonNull DateType type, Void obj) {\n return Val.NULL_DATE;\n }\n\n @Override\n public Val visitTimeType(@NonNull TimeType type, Void obj) {\n return Val.NULL_TIME;\n }\n\n @Override\n public Val visitTimestampType(@NonNull TimestampType type, Void obj) {\n return Val.NULL_TIMESTAMP;\n }\n\n @Override\n public Val visitAnyType(@NonNull AnyType type, Void obj) {\n return Val.NULL_ANY;\n }\n\n @Override\n public @NonNull Val visitArrayType(@NonNull ArrayType type, Void obj) {\n return new Val(null, type);\n }\n\n @Override\n public @NonNull Val visitListType(@NonNull ListType type, Void obj) {\n return new Val(null, type);\n }\n\n @Override\n public @NonNull Val visitMapType(@NonNull MapType type, Void obj) {\n return new Val(null, type);\n }\n\n @Override\n public @NonNull Val visitTupleType(@NonNull TupleType type, Void obj) {\n return new Val(null, type);\n }\n }\n}" }, { "identifier": "UnaryOp", "path": "runtime/src/main/java/io/dingodb/expr/runtime/op/UnaryOp.java", "snippet": "public abstract class UnaryOp extends AbstractOp<UnaryOp> {\n private static final long serialVersionUID = 4820294023360498270L;\n\n protected Object evalNonNullValue(@NonNull Object value, ExprConfig config) {\n throw new EvalNotImplemented(this.getClass().getCanonicalName());\n }\n\n public Object evalValue(Object value, ExprConfig config) {\n return (value != null) ? evalNonNullValue(value, config) : null;\n }\n\n public Object eval(@NonNull Expr expr, EvalContext context, ExprConfig config) {\n Object value = expr.eval(context, config);\n return evalValue(value, config);\n }\n\n public Object keyOf(@NonNull Type type) {\n return type;\n }\n\n public Object bestKeyOf(@NonNull Type @NonNull [] types) {\n return keyOf(types[0]);\n }\n\n public @NonNull Expr compile(@NonNull Expr operand, @NonNull ExprConfig config) {\n UnaryOpExpr result;\n Type type = operand.getType();\n UnaryOp op = getOp(keyOf(type));\n if (op != null) {\n result = op.createExpr(operand);\n } else {\n Type[] types = new Type[]{type};\n UnaryOp op1 = getOp(bestKeyOf(types));\n if (op1 != null) {\n result = op1.createExpr(doCast(operand, types[0], config));\n } else if (config.withGeneralOp()) {\n result = new UnaryGeneralOp(this).createExpr(operand);\n } else {\n throw new OperatorTypeNotExist(this, type);\n }\n }\n return config.withSimplification() ? result.simplify(config) : result;\n }\n\n public @NonNull Expr simplify(@NonNull UnaryOpExpr expr, ExprConfig ignoredConfig) {\n assert expr.getOp() == this;\n return expr;\n }\n\n @Override\n public UnaryOp getOp(Object key) {\n return this;\n }\n\n public UnaryOpExpr createExpr(@NonNull Expr operand) {\n return new UnaryOpExpr(this, operand);\n }\n}" }, { "identifier": "CastArrayOpFactory", "path": "runtime/src/main/java/io/dingodb/expr/runtime/op/collection/CastArrayOpFactory.java", "snippet": "public class CastArrayOpFactory extends CastCollectionOpFactory {\n private static final long serialVersionUID = 8968772411673886443L;\n\n @Getter\n protected final ArrayType type;\n @Getter\n protected final ArrayType key;\n\n public CastArrayOpFactory(CastOp castOp) {\n super(castOp);\n type = Types.array(castOp.getType());\n Object k = castOp.getKey();\n key = (k != null ? Types.array((Type) k) : null);\n }\n\n @Override\n public @NonNull String getName() {\n return ArrayConstructorOpFactory.NAME + \"_\" + castOp.getName();\n }\n\n @Override\n public UnaryOp getOp(Object key) {\n if (key instanceof ArrayType) {\n return new CastArrayArrayOp(getCastOp((ArrayType) key));\n } else if (key instanceof ListType) {\n return new CastArrayListOp(getCastOp((ListType) key));\n }\n return null;\n }\n}" }, { "identifier": "CastListOpFactory", "path": "runtime/src/main/java/io/dingodb/expr/runtime/op/collection/CastListOpFactory.java", "snippet": "public class CastListOpFactory extends CastCollectionOpFactory {\n private static final long serialVersionUID = -2079958375710881440L;\n\n @Getter\n protected final ListType type;\n @Getter\n protected final ListType key;\n\n public CastListOpFactory(CastOp castOp) {\n super(castOp);\n type = Types.list(castOp.getType());\n Object k = castOp.getKey();\n key = (k != null ? Types.list((Type) k) : null);\n }\n\n @Override\n public @NonNull String getName() {\n return ListConstructorOpFactory.NAME + \"_\" + castOp.getName();\n }\n\n @Override\n public UnaryOp getOp(Object key) {\n if (key instanceof ArrayType) {\n return new CastListArrayOp(getCastOp((ArrayType) key));\n } else if (key instanceof ListType) {\n return new CastListListOp(getCastOp((ListType) key));\n }\n return null;\n }\n}" }, { "identifier": "ArrayType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/ArrayType.java", "snippet": "public final class ArrayType extends CollectionType {\n public static final String NAME = \"ARRAY\";\n\n private static final int CODE = 1001;\n\n ArrayType(Type elementType) {\n super(elementType);\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitArrayType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE * 31 + elementType.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof ArrayType\n && elementType.equals(((ArrayType) obj).elementType);\n }\n\n @Override\n public @NonNull String toString() {\n return NAME + \"<\" + elementType + \">\";\n }\n}" }, { "identifier": "BoolType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/BoolType.java", "snippet": "public final class BoolType extends ScalarType {\n public static final String NAME = \"BOOL\";\n\n private static final int CODE = 3;\n\n BoolType() {\n super();\n }\n\n @Override\n public int numericPrecedence() {\n return 1;\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitBoolType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "BytesType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/BytesType.java", "snippet": "public final class BytesType extends ScalarType {\n public static final String NAME = \"BYTES\";\n\n private static final int CODE = 8;\n\n BytesType() {\n super();\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitBytesType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "DateType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/DateType.java", "snippet": "public final class DateType extends ScalarType {\n public static final String NAME = \"DATE\";\n\n private static final int CODE = 101;\n\n DateType() {\n super();\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitDateType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "DecimalType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/DecimalType.java", "snippet": "public final class DecimalType extends ScalarType {\n public static final String NAME = \"DECIMAL\";\n\n private static final int CODE = 6;\n\n DecimalType() {\n super();\n }\n\n @Override\n public int numericPrecedence() {\n return 6;\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitDecimalType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "DoubleType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/DoubleType.java", "snippet": "public final class DoubleType extends ScalarType {\n public static final String NAME = \"DOUBLE\";\n\n private static final int CODE = 5;\n\n DoubleType() {\n super();\n }\n\n @Override\n public int numericPrecedence() {\n return 5;\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitDoubleType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "FloatType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/FloatType.java", "snippet": "public final class FloatType extends ScalarType {\n public static final String NAME = \"FLOAT\";\n\n private static final int CODE = 4;\n\n FloatType() {\n super();\n }\n\n @Override\n public int numericPrecedence() {\n return 4;\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitFloatType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "IntType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/IntType.java", "snippet": "public final class IntType extends ScalarType {\n public static final String NAME = \"INT\";\n\n private static final int CODE = 1;\n\n IntType() {\n super();\n }\n\n @Override\n public int numericPrecedence() {\n return 2;\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, @Nullable T obj) {\n return visitor.visitIntType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "ListType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/ListType.java", "snippet": "public final class ListType extends CollectionType {\n public static final String NAME = \"LIST\";\n\n private static final int CODE = 1002;\n\n ListType(Type elementType) {\n super(elementType);\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitListType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE * 31 + elementType.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof ListType\n && elementType.equals(((ListType) obj).elementType);\n }\n\n @Override\n public @NonNull String toString() {\n return NAME + \"<\" + elementType + \">\";\n }\n}" }, { "identifier": "LongType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/LongType.java", "snippet": "public final class LongType extends ScalarType {\n public static final String NAME = \"LONG\";\n\n private static final int CODE = 2;\n\n LongType() {\n super();\n }\n\n @Override\n public int numericPrecedence() {\n return 3;\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitLongType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "StringType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/StringType.java", "snippet": "public final class StringType extends ScalarType {\n public static final String NAME = \"STRING\";\n\n private static final int CODE = 7;\n\n StringType() {\n super();\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitStringType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "TimeType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/TimeType.java", "snippet": "public final class TimeType extends ScalarType {\n public static final String NAME = \"TIME\";\n\n private static final int CODE = 102;\n\n TimeType() {\n super();\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitTimeType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "TimestampType", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/TimestampType.java", "snippet": "public final class TimestampType extends ScalarType {\n public static final String NAME = \"TIMESTAMP\";\n\n private static final int CODE = 103;\n\n TimestampType() {\n super();\n }\n\n @Override\n public <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj) {\n return visitor.visitTimestampType(this, obj);\n }\n\n @Override\n public int hashCode() {\n return CODE;\n }\n\n @Override\n public String toString() {\n return NAME;\n }\n}" }, { "identifier": "Type", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/Type.java", "snippet": "public interface Type {\n int NOT_NUMERIC = 100;\n\n boolean isScalar();\n\n default int numericPrecedence() {\n return NOT_NUMERIC;\n }\n\n default boolean isNumeric() {\n return numericPrecedence() != NOT_NUMERIC;\n }\n\n default boolean matches(@NonNull Type type) {\n // Types.NULL can be converted to any type.\n return type.equals(this) || type.equals(Types.NULL);\n }\n\n <R, T> R accept(@NonNull TypeVisitor<R, T> visitor, T obj);\n}" }, { "identifier": "TypeVisitorBase", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/TypeVisitorBase.java", "snippet": "public abstract class TypeVisitorBase<R, T> implements TypeVisitor<R, T> {\n public R visit(@NonNull Type type) {\n return type.accept(this, null);\n }\n\n public R visit(@NonNull Type type, T obj) {\n return type.accept(this, obj);\n }\n\n @Override\n public R visitNullType(@NonNull NullType type, T obj) {\n return null;\n }\n\n @Override\n public R visitIntType(@NonNull IntType type, T obj) {\n return null;\n }\n\n @Override\n public R visitLongType(@NonNull LongType type, T obj) {\n return null;\n }\n\n @Override\n public R visitFloatType(@NonNull FloatType type, T obj) {\n return null;\n }\n\n @Override\n public R visitDoubleType(@NonNull DoubleType type, T obj) {\n return null;\n }\n\n @Override\n public R visitBoolType(@NonNull BoolType type, T obj) {\n return null;\n }\n\n @Override\n public R visitDecimalType(@NonNull DecimalType type, T obj) {\n return null;\n }\n\n @Override\n public R visitStringType(@NonNull StringType type, T obj) {\n return null;\n }\n\n @Override\n public R visitBytesType(@NonNull BytesType type, T obj) {\n return null;\n }\n\n @Override\n public R visitDateType(@NonNull DateType type, T obj) {\n return null;\n }\n\n @Override\n public R visitTimeType(@NonNull TimeType type, T obj) {\n return null;\n }\n\n @Override\n public R visitTimestampType(@NonNull TimestampType type, T obj) {\n return null;\n }\n\n @Override\n public R visitAnyType(@NonNull AnyType type, T obj) {\n return null;\n }\n\n @Override\n public R visitArrayType(@NonNull ArrayType type, T obj) {\n return null;\n }\n\n @Override\n public R visitListType(@NonNull ListType type, T obj) {\n return null;\n }\n\n @Override\n public R visitMapType(@NonNull MapType type, T obj) {\n return null;\n }\n\n @Override\n public R visitTupleType(@NonNull TupleType type, T obj) {\n return null;\n }\n}" } ]
import io.dingodb.expr.runtime.ExprConfig; import io.dingodb.expr.runtime.exception.ExprCompileException; import io.dingodb.expr.runtime.expr.Exprs; import io.dingodb.expr.runtime.op.UnaryOp; import io.dingodb.expr.runtime.op.collection.CastArrayOpFactory; import io.dingodb.expr.runtime.op.collection.CastListOpFactory; import io.dingodb.expr.runtime.type.ArrayType; import io.dingodb.expr.runtime.type.BoolType; import io.dingodb.expr.runtime.type.BytesType; import io.dingodb.expr.runtime.type.DateType; import io.dingodb.expr.runtime.type.DecimalType; import io.dingodb.expr.runtime.type.DoubleType; import io.dingodb.expr.runtime.type.FloatType; import io.dingodb.expr.runtime.type.IntType; import io.dingodb.expr.runtime.type.ListType; import io.dingodb.expr.runtime.type.LongType; import io.dingodb.expr.runtime.type.StringType; import io.dingodb.expr.runtime.type.TimeType; import io.dingodb.expr.runtime.type.TimestampType; import io.dingodb.expr.runtime.type.Type; import io.dingodb.expr.runtime.type.TypeVisitorBase; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.nullness.qual.NonNull;
9,260
/* * Copyright 2021 DataCanvas * * 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 io.dingodb.expr.runtime.compiler; public final class CastingFactory { private CastingFactory() { } public static @NonNull UnaryOp get(Type toType, @NonNull ExprConfig config) { UnaryOp op = CastOpSelector.INSTANCE.visit(toType, config); if (op != null) { return op; } throw new ExprCompileException("Cannot cast to " + toType + "."); } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class CastOpSelector extends TypeVisitorBase<UnaryOp, ExprConfig> { private static final CastOpSelector INSTANCE = new CastOpSelector(); @Override public UnaryOp visitIntType(@NonNull IntType type, @NonNull ExprConfig obj) { return obj.withRangeCheck() ? Exprs.TO_INT_C : Exprs.TO_INT; } @Override public UnaryOp visitLongType(@NonNull LongType type, @NonNull ExprConfig obj) { return obj.withRangeCheck() ? Exprs.TO_LONG_C : Exprs.TO_LONG; } @Override public UnaryOp visitFloatType(@NonNull FloatType type, ExprConfig obj) { return Exprs.TO_FLOAT; } @Override public UnaryOp visitDoubleType(@NonNull DoubleType type, ExprConfig obj) { return Exprs.TO_DOUBLE; } @Override
/* * Copyright 2021 DataCanvas * * 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 io.dingodb.expr.runtime.compiler; public final class CastingFactory { private CastingFactory() { } public static @NonNull UnaryOp get(Type toType, @NonNull ExprConfig config) { UnaryOp op = CastOpSelector.INSTANCE.visit(toType, config); if (op != null) { return op; } throw new ExprCompileException("Cannot cast to " + toType + "."); } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class CastOpSelector extends TypeVisitorBase<UnaryOp, ExprConfig> { private static final CastOpSelector INSTANCE = new CastOpSelector(); @Override public UnaryOp visitIntType(@NonNull IntType type, @NonNull ExprConfig obj) { return obj.withRangeCheck() ? Exprs.TO_INT_C : Exprs.TO_INT; } @Override public UnaryOp visitLongType(@NonNull LongType type, @NonNull ExprConfig obj) { return obj.withRangeCheck() ? Exprs.TO_LONG_C : Exprs.TO_LONG; } @Override public UnaryOp visitFloatType(@NonNull FloatType type, ExprConfig obj) { return Exprs.TO_FLOAT; } @Override public UnaryOp visitDoubleType(@NonNull DoubleType type, ExprConfig obj) { return Exprs.TO_DOUBLE; } @Override
public UnaryOp visitBoolType(@NonNull BoolType type, ExprConfig obj) {
7
2023-11-04 08:43:49+00:00
12k
Arborsm/ArborCore
src/main/java/org/arbor/gtnn/data/GTNNMachines.java
[ { "identifier": "GTNN", "path": "src/main/java/org/arbor/gtnn/GTNN.java", "snippet": "@Mod(GTNN.MODID)\npublic class GTNN {\n\n public static final String MODID = \"gtnn\";\n public static final Logger LOGGER = LogUtils.getLogger();\n\n public GTNN() {\n MinecraftForge.EVENT_BUS.register(this);\n CommonProxy.init();\n ConfigHandler.init();\n }\n\n public static ResourceLocation id(String path) {\n return new ResourceLocation(MODID, FormattingUtil.toLowerCaseUnder(path));\n }\n\n}" }, { "identifier": "APartAbility", "path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/APartAbility.java", "snippet": "public class APartAbility extends PartAbility {\n public static final PartAbility NEUTRON_ACCELERATOR = new PartAbility(\"neutron_accelerator\");\n public APartAbility(String name) {\n super(name);\n }\n}" }, { "identifier": "ChemicalPlant", "path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/ChemicalPlant.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ChemicalPlant extends CoilWorkableElectricMultiblockMachine implements IChemicalPlantProvider, IGTPPMachine {\n private static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(ChemicalPlant.class, WorkableMultiblockMachine.MANAGED_FIELD_HOLDER);\n\n @Getter\n @Persisted\n @DescSynced\n @RequireRerender\n private int tier;\n private MachineCasingType machineCasingType;\n private PipeType pipeType;\n private PlantCasingType plantCasingType;\n\n public ChemicalPlant(IMachineBlockEntity holder) {\n super(holder);\n }\n\n //////////////////////////////////////\n //*** Multiblock LifeCycle ***//\n //////////////////////////////////////\n @Override\n public void onStructureFormed() {\n scheduleRenderUpdate();\n super.onStructureFormed();\n if (getMultiblockState().getMatchContext().get(\"MachineCasing\") instanceof MachineCasingType machineCasing) {\n this.machineCasingType = machineCasing;\n }\n if (getMultiblockState().getMatchContext().get(\"Pipe\") instanceof PipeType pipe) {\n this.pipeType = pipe;\n }\n if (getMultiblockState().getMatchContext().get(\"PlantCasing\") instanceof PlantCasingType plantCasing) {\n this.plantCasingType = plantCasing;\n }\n this.tier = getPlantCasingTier();\n }\n\n @Override\n public void scheduleRenderUpdate(){\n scheduleRenderUpdate(this);\n }\n\n public int getMachineCasingTier() {\n if (this.machineCasingType != null) {\n return this.machineCasingType.getTier();\n }\n return 0;\n }\n\n public int getPipeTier() {\n if (this.pipeType != null) {\n return this.pipeType.getTier();\n }\n return 0;\n }\n\n public int getPlantCasingTier() {\n if (this.plantCasingType != null) {\n return this.plantCasingType.getTier();\n }\n return 0;\n }\n\n //////////////////////////////////////\n //****** RECIPE LOGIC *******//\n //////////////////////////////////////\n\n @Nullable\n public static GTRecipe chemicalPlantRecipe(MetaMachine machine, @Nonnull GTRecipe recipe) {\n if (machine instanceof ChemicalPlant chemicalPlant) {\n if (RecipeHelper.getRecipeEUtTier(recipe) > chemicalPlant.getMachineCasingTier() + 1) {\n return null;\n }\n if (recipe.conditions.get(0) instanceof PlantCasingCondition plantCasingCondition) {\n if (plantCasingCondition.getPlantCasing().getTier() > chemicalPlant.getPlantCasingTier()) {\n return null;\n }\n }\n\n var maxParallel = 1 + 2 * chemicalPlant.getPipeTier();\n var parallelLimit = Math.min(maxParallel, (int) (chemicalPlant.getMaxVoltage()));\n var result = GTRecipeModifiers.accurateParallel(machine, recipe, parallelLimit, false);\n recipe = result.getA() == recipe ? result.getA().copy() : result.getA();\n int parallelValue = result.getB();\n recipe.duration = Math.max(1, 256 * parallelValue / maxParallel);\n recipe.tickInputs.put(EURecipeCapability.CAP, List.of(new Content((long) parallelValue, 1.0f, 0.0f, null, null)));\n\n GTRecipe finalRecipe = recipe;\n return RecipeHelper.applyOverclock(new OverclockingLogic((recipe1, recipeEUt, maxVoltage, duration, amountOC) -> {\n var pair = OverclockingLogic.NON_PERFECT_OVERCLOCK.getLogic().runOverclockingLogic(finalRecipe, recipeEUt, maxVoltage, duration, amountOC);\n if (chemicalPlant.getCoilTier() > 0) {\n var eu = pair.firstLong() * (1 - chemicalPlant.getCoilTier() * 0.5);\n pair.first((long) Math.max(1, eu));\n }\n return pair;\n }), recipe, chemicalPlant.getMaxVoltage());\n }\n return null;\n }\n\n //////////////////////////////////////\n //****** NBT SAVE *******//\n //////////////////////////////////////\n\n @Override\n public ManagedFieldHolder getFieldHolder() {\n return MANAGED_FIELD_HOLDER;\n }\n}" }, { "identifier": "NeutronActivator", "path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/NeutronActivator.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class NeutronActivator extends WorkableMultiblockMachine implements IFancyUIMachine, IDisplayUIMachine, IExplosionMachine {\n public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(NeutronActivator.class, WorkableMultiblockMachine.MANAGED_FIELD_HOLDER);\n protected int height;\n protected int eV = 0, mCeil = 0, mFloor = 0;\n protected ConditionalSubscriptionHandler tickSubscription;\n private int aTick = 0;\n private float efficiency = 0;\n public final int maxNeutronKineticEnergy = 1200000000;\n public NeutronActivator(IMachineBlockEntity holder, Object... args) {\n super(holder, args);\n this.tickSubscription = new ConditionalSubscriptionHandler(this, this::naTick, this::isFormed);\n }\n\n //////////////////////////////////////\n //*** Multiblock LifeCycle ***//\n //////////////////////////////////////\n @Override\n public void onStructureFormed() {\n height = 0;\n super.onStructureFormed();\n Map<Long, IO> ioMap = getMultiblockState().getMatchContext().getOrCreate(\"ioMap\", Long2ObjectMaps::emptyMap);\n for (IMultiPart part : getParts()) {\n IO io = ioMap.getOrDefault(part.self().getPos().asLong(), IO.BOTH);\n if (io == IO.NONE) continue;\n for (var handler : part.getRecipeHandlers()) {\n var handlerIO = handler.getHandlerIO();\n // If IO not compatible\n if (io != IO.BOTH && handlerIO != IO.BOTH && io != handlerIO) continue;\n if (handler.getCapability() == EURecipeCapability.CAP && handler instanceof IEnergyContainer) {\n traitSubscriptions.add(handler.addChangedListener(tickSubscription::updateSubscription));\n }\n }\n if (part instanceof HighSpeedPipeBlock) height++;\n }\n efficiency = (float) Math.pow(0.9f, height - 4);\n }\n\n @Override\n public void onStructureInvalid() {\n height = 0;\n mCeil = 0;\n mFloor = 0;\n super.onStructureInvalid();\n }\n\n protected void naTick() {\n boolean anyWorking = false;\n if (!getLevel().isClientSide) {\n for (IMultiPart part : getParts()) {\n if (part instanceof NeutronAccelerator na) {\n na.energyTick();\n if(na.isActive()){\n anyWorking = true;\n this.eV += (int) Math.max(\n (ThreadLocalRandom.current().nextInt(na.getMaxEUConsume() + 1) + na.getMaxEUConsume()) * 10\n * Math.pow(0.95, height - 4),\n 10);\n }\n }\n if (part instanceof ItemBusPartMachine itemBusPartMachine){\n var inv = itemBusPartMachine.getInventory();\n for (int i = 0; i < inv.getSlots(); i++){\n if(inv.getStackInSlot(i).is(ChemicalHelper.get(TagPrefix.dust, GTMaterials.Beryllium, 1).getItem()) ||\n (inv.getStackInSlot(i).is(ChemicalHelper.get(TagPrefix.dust, GTMaterials.Graphite, 1).getItem()))\n ){\n int consume = Math.min(this.eV / 10000000, inv.getStackInSlot(i).getCount());\n inv.setStackInSlot(i, ItemStack.EMPTY);\n this.eV -=10000000 * consume;\n }\n }\n }\n }\n if (!anyWorking) {\n if (this.eV >= 72000 && aTick % 20 == 0) {\n this.eV -= 72000;\n } else if (this.eV > 0 && aTick % 20 == 0) {\n this.eV = 0;\n }\n }\n if (this.eV < 0) this.eV = 0;\n if (this.eV > maxNeutronKineticEnergy) doExplosion(4 * 32);\n }\n if (aTick == 20) {\n aTick = 0;\n } else {\n aTick++;\n }\n }\n\n @Override\n public void onPartUnload() {\n super.onPartUnload();\n }\n\n //////////////////////////////////////\n //********** GUI ***********//\n //////////////////////////////////////\n @Override\n public void addDisplayText(List<Component> textList) {\n IDisplayUIMachine.super.addDisplayText(textList);\n if (isFormed()) {\n textList.add(Component.translatable(getRecipeType().registryName.toLanguageKey())\n .setStyle(Style.EMPTY.withColor(ChatFormatting.AQUA)\n .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,\n Component.translatable(\"gtceu.gui.machinemode.title\")))));\n if (!isWorkingEnabled()) {\n textList.add(Component.translatable(\"gtceu.multiblock.work_paused\"));\n } else if (isActive()) {\n textList.add(Component.translatable(\"gtceu.multiblock.running\"));\n int currentProgress = (int) (recipeLogic.getProgressPercent() * 100);\n textList.add(Component.translatable(\"gtceu.multiblock.progress\", currentProgress));\n } else {\n textList.add(Component.translatable(\"gtceu.multiblock.idling\"));\n }\n if (recipeLogic.isWaiting()) {\n textList.add(Component.translatable(\"gtceu.multiblock.waiting\").setStyle(Style.EMPTY.withColor(ChatFormatting.RED)));\n }\n textList.add(Component.translatable(\"gtceu.multiblock.neutronactivator.ev\", processNumber(eV)));\n textList.add(Component.translatable(\"gtceu.multiblock.neutronactivator.height\", FormattingUtil.formatNumbers(height)));\n textList.add(Component.translatable(\"gtceu.multiblock.neutronactivator.efficiency\", FormattingUtil.formatNumbers(efficiency * 100)));\n }\n getDefinition().getAdditionalDisplay().accept(this, textList);\n }\n private String processNumber(int num) {\n float num2;\n num2 = ((float) num) / 1000F;\n if (num2 <= 0) {\n return String.format(\"%d\", num);\n }\n if (num2 < 1000.0) {\n return String.format(\"%.1fK\", num2);\n }\n num2 /= 1000F;\n return String.format(\"%.1fM\", num2);\n }\n\n @Override\n public Widget createUIWidget() {\n var group = new WidgetGroup(0, 0, 170 + 8, 129 + 8);\n var container = new WidgetGroup(4, 4, 170, 129);\n container.addWidget(new DraggableScrollableWidgetGroup(4, 4, 162, 121).setBackground(getScreenTexture())\n .addWidget(new LabelWidget(4, 5, self().getBlockState().getBlock().getDescriptionId()))\n .addWidget(new ComponentPanelWidget(4, 17, this::addDisplayText)\n .setMaxWidthLimit(150)\n .clickHandler(this::handleDisplayClick)));\n container.setBackground(GuiTextures.BACKGROUND_INVERSE);\n group.addWidget(container);\n return group;\n }\n\n @Override\n public ModularUI createUI(Player entityPlayer) {\n return IFancyUIMachine.super.createUI(entityPlayer);\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public List<IFancyUIProvider> getSubTabs() {\n return getParts().stream().filter(e -> !(e instanceof HighSpeedPipeBlock)).filter(IFancyUIProvider.class::isInstance).map(IFancyUIProvider.class::cast).toList();\n }\n\n @Override\n public void attachTooltips(TooltipsPanel tooltipsPanel) {\n for (IMultiPart part : getParts()) {\n part.attachFancyTooltipsToController(this, tooltipsPanel);\n }\n }\n\n //////////////////////////////////////\n //****** NBT SAVE *******//\n //////////////////////////////////////\n\n @Override\n public @NotNull ManagedFieldHolder getFieldHolder() {\n return MANAGED_FIELD_HOLDER;\n }\n\n @Override\n public void saveCustomPersistedData(CompoundTag tag, boolean forDrop) {\n super.saveCustomPersistedData(tag, forDrop);\n CompoundTag naTag =writeToNBT(new CompoundTag());\n tag.put(\"NA\", naTag);\n }\n\n @Override\n public void loadCustomPersistedData(CompoundTag tag) {\n super.loadCustomPersistedData(tag);\n readFromNBT(tag.getCompound(\"NA\"));\n }\n\n public CompoundTag writeToNBT(CompoundTag compound) {\n compound.putInt(\"EV\", eV);\n compound.putInt(\"Height\", height);\n compound.putInt(\"Floor\", mFloor);\n compound.putInt(\"Ceil\",mCeil);\n compound.putFloat(\"Efficiency\", efficiency);\n return compound;\n }\n\n public void readFromNBT(CompoundTag compound) {\n eV = compound.getInt(\"EV\");\n height = compound.getInt(\"Height\");\n mFloor = compound.getInt(\"Floor\");\n mCeil = compound.getInt(\"Ceil\");\n efficiency = compound.getFloat(\"Efficiency\");\n }\n\n //////////////////////////////////////\n //****** RECIPE LOGIC *******//\n //////////////////////////////////////\n\n @Override\n public boolean alwaysTryModifyRecipe(){\n return true;\n }\n\n @Nullable\n public static GTRecipe neutronActivatorRecipe(MetaMachine machine, GTRecipe recipe){\n if (machine instanceof NeutronActivator neutronActivator){\n GTRecipe recipe1 = recipe.copy();\n recipe1.duration = (int) Math.max(recipe1.duration * neutronActivator.efficiency, 1);\n if (recipe1.conditions.get(0) instanceof NeutronActivatorCondition neutronActivatorCondition){\n neutronActivator.mFloor = (neutronActivatorCondition.getEvRange() % 10000) * 1000000;\n neutronActivator.mCeil = (neutronActivatorCondition.getEvRange() / 10000) * 1000000;\n if (neutronActivator.eV > neutronActivator.mCeil || neutronActivator.eV < neutronActivator.mFloor) {\n recipe1.outputs.clear();\n recipe1.outputs.put(ItemRecipeCapability.CAP, List.of(new Content(Ingredient.of(GTNNItems.RADIOACTIVE_WASTE), 1 ,0, null, null)));\n return recipe1;\n }\n return recipe1;\n }\n }\n return null;\n }\n\n public static boolean checkNeutronActivatorCondition(MetaMachine machine, GTRecipe recipe){\n if (machine instanceof NeutronActivator ) {\n return recipe.conditions.get(0) instanceof NeutronActivatorCondition;\n }\n return false;\n }\n}" }, { "identifier": "HighSpeedPipeBlock", "path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/part/HighSpeedPipeBlock.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class HighSpeedPipeBlock extends MultiblockPartMachine{\n public HighSpeedPipeBlock(IMachineBlockEntity holder) {\n super(holder);\n }\n\n @Override\n public boolean shouldOpenUI(Player player, InteractionHand hand, BlockHitResult hit) {\n return false;\n }\n\n @Override\n public void scheduleRenderUpdate() {\n }\n\n @Override\n public boolean shouldRenderGrid(Player player, ItemStack held, Set<GTToolType> toolTypes) {\n return false;\n }\n}" }, { "identifier": "NeutronAccelerator", "path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/part/NeutronAccelerator.java", "snippet": "@Getter@Setter\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class NeutronAccelerator extends EnergyHatchPartMachine {\n protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER;\n private boolean isActive;\n\n @Override\n public boolean shouldOpenUI(Player player, InteractionHand hand, BlockHitResult hit) {\n return true;\n }\n\n public NeutronAccelerator(IMachineBlockEntity holder, int tier, Object... args) {\n super(holder, tier, IO.IN, 1, args);\n }\n\n public int getMaxEUConsume() {\n return (int) (GTValues.V[tier] * 8 / 10);\n }\n\n @Override\n public ManagedFieldHolder getFieldHolder() {\n return MANAGED_FIELD_HOLDER;\n }\n\n public void energyTick(){\n if (!this.getLevel().isClientSide){\n if (this.energyContainer.getEnergyStored() >= getMaxEUConsume() && this.isWorkingEnabled()){\n this.energyContainer.setEnergyStored(this.energyContainer.getEnergyStored() - getMaxEUConsume());\n isActive = true;\n } else{\n isActive = false;\n }\n }\n }\n\n static {\n MANAGED_FIELD_HOLDER = new ManagedFieldHolder(NeutronAccelerator.class, TieredIOPartMachine.MANAGED_FIELD_HOLDER);\n }\n}" }, { "identifier": "APredicates", "path": "src/main/java/org/arbor/gtnn/api/pattern/APredicates.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class APredicates {\n public static TraceabilityPredicate plantCasings() {\n return new TraceabilityPredicate(blockWorldState -> {\n var blockState = blockWorldState.getBlockState();\n for (var entry : PlantCasingBlock.PlantCasing.values()) {\n if (blockState.is(entry.getPlantCasing().get())) {\n var stats = entry.plantCasingType();\n Object currentPlantCasing = blockWorldState.getMatchContext().getOrPut(\"PlantCasing\", stats);\n if (!currentPlantCasing.equals(stats)) {\n blockWorldState.setError(new PatternStringError(\"gtnn.multiblock.pattern.error.plant_casings\"));\n return false;\n }\n return true;\n }\n }\n return false;\n }, () -> Arrays.stream(PlantCasingBlock.PlantCasing.values()).map(plantCasing -> BlockInfo.fromBlockState(plantCasing.getPlantCasing().get().defaultBlockState())).toArray(BlockInfo[]::new))\n .addTooltips(Component.translatable(\"gtnn.multiblock.pattern.error.plant_casings\"));\n }\n\n public static TraceabilityPredicate pipeBlock() {\n return new TraceabilityPredicate(blockWorldState -> {\n var blockState = blockWorldState.getBlockState();\n for (var entry : PipeBlock.Pipe.values()) {\n if (blockState.is(entry.getPipe().get())) {\n var stats = entry.pipeType();\n Object currentPipeBlock = blockWorldState.getMatchContext().getOrPut(\"Pipe\", stats);\n if (!currentPipeBlock.equals(stats)) {\n blockWorldState.setError(new PatternStringError(\"gtnn.multiblock.pattern.error.pipe\"));\n return false;\n }\n return true;\n }\n }\n return false;\n }, () -> Arrays.stream(PipeBlock.Pipe.values()).map(pipe -> BlockInfo.fromBlockState(pipe.getPipe().get().defaultBlockState())).toArray(BlockInfo[]::new))\n .addTooltips(Component.translatable(\"gtnn.multiblock.pattern.error.pipe\"));\n }\n\n public static TraceabilityPredicate machineCasing() {\n return new TraceabilityPredicate(blockWorldState -> {\n var blockState = blockWorldState.getBlockState();\n for (var entry : MachineCasingBlock.MachineCasing.values()) {\n if (blockState.is(entry.getMachineCasing().get())) {\n var stats = entry.machineCasingType();\n Object currentMachineCasing = blockWorldState.getMatchContext().getOrPut(\"MachineCasing\", stats);\n if (!currentMachineCasing.equals(stats)) {\n blockWorldState.setError(new PatternStringError(\"gtnn.multiblock.pattern.error.machine_casing\"));\n return false;\n }\n return true;\n }\n }\n return false;\n }, () -> Arrays.stream(MachineCasingBlock.MachineCasing.values()).map(machineCasing -> BlockInfo.fromBlockState(machineCasing.getMachineCasing().get().defaultBlockState())).toArray(BlockInfo[]::new))\n .addTooltips(Component.translatable(\"gtnn.multiblock.pattern.error.machine_casing\"));\n }\n\n public static TraceabilityPredicate ability(PartAbility ability) {\n int[] tiers = Stream.of(ULV, LV, MV, HV, EV, IV, LuV, ZPM, UV).filter(t -> t <= 1).mapToInt(Integer::intValue).toArray();\n return Predicates.blocks((tiers.length == 0 ? ability.getAllBlocks() : ability.getBlocks(tiers)).toArray(Block[]::new));\n }\n}" }, { "identifier": "BlockTier", "path": "src/main/java/org/arbor/gtnn/block/BlockTier.java", "snippet": "public enum BlockTier implements ITier {\n TIER0(0),\n TIER1(1),\n TIER2(2),\n TIER3(3),\n TIER4(4),\n TIER5(5),\n TIER6(6),\n TIER7(7);\n\n private final int tier;\n\n BlockTier(int tier) {\n this.tier = tier;\n }\n\n @Override\n public int tier() {\n return tier;\n }\n}" }, { "identifier": "MachineCasingBlock", "path": "src/main/java/org/arbor/gtnn/block/MachineCasingBlock.java", "snippet": "public class MachineCasingBlock extends Block {\n public MachineCasingBlock(Properties properties) {\n super(properties);\n }\n\n public enum MachineCasing implements MachineCasingType {\n LV(TIER0, MACHINE_CASING_LV, \"§7LV§r\"),\n MV(TIER1, MACHINE_CASING_MV, \"§bMV§r\"),\n HV(TIER2, MACHINE_CASING_HV, \"§6HV§r\"),\n EV(TIER3, MACHINE_CASING_EV, \"§5EV§r\"),\n IV(TIER4, MACHINE_CASING_IV, \"§1IV§r\"),\n LuV(TIER5, MACHINE_CASING_LuV, \"§dLuV§r\"),\n ZPM(TIER6, MACHINE_CASING_ZPM, \"§cZPM§r\"),\n UV(TIER7, MACHINE_CASING_UV, \"§3UV§r\");\n\n private final ITier tier;\n private final BlockEntry<Block> machineCasing;\n @Getter\n private final String energyHatchLevel;\n\n MachineCasing(ITier tier, BlockEntry<Block> machineCasing, String energyHatchLevel) {\n this.tier = tier;\n this.machineCasing = machineCasing;\n this.energyHatchLevel = energyHatchLevel;\n }\n\n public MachineCasingType machineCasingType() {\n return this;\n }\n\n @Override\n public int getTier() {\n return tier.tier();\n }\n\n @Override\n public BlockEntry<Block> getMachineCasing() {\n return machineCasing;\n }\n\n public BlockEntry<Block> getMachineCasing(int tier) {\n return MachineCasing.values()[tier].getMachineCasing();\n }\n }\n}" }, { "identifier": "PipeBlock", "path": "src/main/java/org/arbor/gtnn/block/PipeBlock.java", "snippet": "public class PipeBlock extends Block {\n public PipeBlock(Properties properties) {\n super(properties);\n }\n\n public enum Pipe implements PipeType {\n BRONZE(TIER0, CASING_BRONZE_PIPE),\n STEEL(TIER1, CASING_STEEL_PIPE),\n TITANIUM(TIER2, CASING_TITANIUM_PIPE),\n TUNGSTENSTEEL(TIER3, CASING_TUNGSTENSTEEL_PIPE),\n CHROME(TIER4, CASING_TUNGSTENSTEEL_PIPE),\n IRIDIUM(TIER5, CASING_TUNGSTENSTEEL_PIPE),\n OSMIUM(TIER6, CASING_TUNGSTENSTEEL_PIPE),\n NEUTRONIUM(TIER7, CASING_TUNGSTENSTEEL_PIPE);\n\n private final ITier tier;\n private final BlockEntry<Block> casingBlock;\n\n\n Pipe(ITier tier, BlockEntry<Block> casingBlock) {\n this.tier = tier;\n this.casingBlock = casingBlock;\n }\n\n public PipeType pipeType() {\n return this;\n }\n\n @Override\n public int getTier() {\n return tier.tier();\n }\n\n @Override\n public BlockEntry<Block> getPipe() {\n return casingBlock;\n }\n\n public BlockEntry<Block> getPipe(int tier) {\n return Pipe.values()[tier].getPipe();\n }\n }\n}" }, { "identifier": "PlantCasingBlock", "path": "src/main/java/org/arbor/gtnn/block/PlantCasingBlock.java", "snippet": "public class PlantCasingBlock extends Block {\n private static final Map<String, PlantCasing> All_PlantCasing = new Object2ObjectOpenHashMap<>();\n private static final Map<Integer, PlantCasing> All_PlantCasing_Tier = new Object2ObjectOpenHashMap<>();\n\n public PlantCasingBlock(Properties properties) {\n super(properties);\n }\n\n public enum PlantCasing implements PlantCasingType {\n BRONZE(TIER0, CASING_BRONZE_BRICKS, \"Bronze\", GTCEu.id(\"block/casings/solid/machine_casing_bronze_plated_bricks\")),\n STEEL(TIER1, CASING_STEEL_SOLID, \"Steel\", GTCEu.id(\"block/casings/solid/machine_casing_solid_steel\")),\n ALUMINIUM(TIER2, CASING_ALUMINIUM_FROSTPROOF, \"Aluminium\", GTCEu.id(\"block/casings/solid/machine_casing_frost_proof\")),\n STAINLESS(TIER3, CASING_STAINLESS_CLEAN, \"Stainless\", GTCEu.id(\"block/casings/solid/machine_casing_clean_stainless_steel\")),\n TITANIUM(TIER4, CASING_TITANIUM_STABLE, \"Titanium\", GTCEu.id(\"block/casings/solid/machine_casing_stable_titanium\")),\n TUNGSTENSTEEL(TIER5, CASING_TUNGSTENSTEEL_ROBUST, \"Tungstensteel\", GTCEu.id(\"block/casings/solid/machine_casing_robust_tungstensteel\")),\n CHROME(TIER6, CASING_TUNGSTENSTEEL_ROBUST, \"Chrome\", GTCEu.id(\"block/casings/solid/machine_casing_robust_tungstensteel\")),\n IRIDIUM(TIER7, CASING_TUNGSTENSTEEL_ROBUST, \"Iridium\", GTCEu.id(\"block/casings/solid/machine_casing_robust_tungstensteel\"));\n\n private final ITier tier;\n private final BlockEntry<Block> plantCasing;\n private final String name;\n private final ResourceLocation resourceLocation;\n\n PlantCasing(ITier tier, BlockEntry<Block> plantCasing, String name, ResourceLocation resourceLocation) {\n this.tier = tier;\n this.plantCasing = plantCasing;\n this.name = name;\n this.resourceLocation = resourceLocation;\n All_PlantCasing.put(name, this);\n All_PlantCasing_Tier.put(tier.tier(), this);\n }\n public static PlantCasing getByTier(int tier){\n return All_PlantCasing_Tier.get(tier);\n }\n\n @Nullable\n public static PlantCasing getByName(@Nullable String name) {\n return All_PlantCasing.get(name);\n }\n\n @Nonnull\n public static PlantCasing getByNameOrDefault(@Nullable String name) {\n var type = getByName(name);\n if (type == null) {\n return BRONZE;\n }\n return type;\n }\n\n public PlantCasingType plantCasingType() {\n return this;\n }\n\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public int getTier() {\n return tier.tier();\n }\n\n @Override\n public BlockEntry<Block> getPlantCasing() {\n return plantCasing;\n }\n\n public BlockEntry<Block> getPlantCasing(int tier) {\n return PlantCasing.values()[tier].getPlantCasing();\n }\n\n @Override\n public ResourceLocation getResourceLocation() {\n return resourceLocation;\n }\n }\n}" }, { "identifier": "BlockMachineRenderer", "path": "src/main/java/org/arbor/gtnn/client/renderer/machine/BlockMachineRenderer.java", "snippet": "public class BlockMachineRenderer extends MachineRenderer implements IPartRenderer {\n public BlockMachineRenderer(ResourceLocation modelLocation) {\n super(modelLocation);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void renderMachine(List<BakedQuad> quads, MachineDefinition definition, @javax.annotation.Nullable MetaMachine machine, Direction frontFacing, @javax.annotation.Nullable Direction side, RandomSource rand, @javax.annotation.Nullable Direction modelFacing, ModelState modelState) {\n this.renderBaseModel(quads, definition, machine, frontFacing, side, rand);\n }\n}" }, { "identifier": "GTPPMachineRenderer", "path": "src/main/java/org/arbor/gtnn/client/renderer/machine/GTPPMachineRenderer.java", "snippet": "public class GTPPMachineRenderer extends MachineRenderer implements IControllerRenderer {\n protected final WorkableOverlayModel overlayModel;\n @OnlyIn(Dist.CLIENT)\n private void render(List<BakedQuad> quads, MetaMachine machine, ModelState modelState){\n var sprite = ModelFactory.getBlockSprite(PlantCasingBlock.PlantCasing.getByTier(((IGTPPMachine)machine).getTier()).getResourceLocation());\n quads.add(FaceQuad.bakeFace(Direction.DOWN, sprite, modelState));\n quads.add(FaceQuad.bakeFace(Direction.UP, sprite, modelState));\n quads.add(FaceQuad.bakeFace(Direction.NORTH, sprite, modelState));\n quads.add(FaceQuad.bakeFace(Direction.SOUTH, sprite, modelState));\n quads.add(FaceQuad.bakeFace(Direction.WEST, sprite, modelState));\n quads.add(FaceQuad.bakeFace(Direction.EAST, sprite, modelState));\n BlockEntry<Block> casing = PlantCasingBlock.PlantCasing.getByTier(((IGTPPMachine)machine).getTier()).getPlantCasing();\n machine.self().getDefinition().setAppearance(casing::getDefaultState);\n }\n\n public GTPPMachineRenderer(ResourceLocation baseCasing,ResourceLocation workableModel, boolean tint) {\n super(tint ? GTCEu.id(\"block/tinted_cube_all\") : GTCEu.id(\"block/cube_all\"));\n this.overlayModel = new WorkableOverlayModel(workableModel);\n this.setTextureOverride(Map.of(\"all\", baseCasing));\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void renderMachine(List<BakedQuad> quads, MachineDefinition definition, @Nullable MetaMachine machine,\n Direction frontFacing, @Nullable Direction side, RandomSource rand, Direction modelFacing, ModelState modelState) {\n super.renderMachine(quads, definition, machine, frontFacing, side, rand, modelFacing, modelState);\n if (machine instanceof IGTPPMachine igtppMachine && machine instanceof MultiblockControllerMachine multiblockControllerMachine) {\n if (multiblockControllerMachine.isFormed() && igtppMachine.getTier() != 0){\n quads.clear();\n render(quads, machine, modelState);\n }\n }\n if (machine instanceof IWorkable workable) {\n quads.addAll(this.overlayModel.bakeQuads(side, frontFacing, workable.isActive(), workable.isWorkingEnabled()));\n } else {\n quads.addAll(this.overlayModel.bakeQuads(side, frontFacing, false, false));\n }\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void renderPartModel(List<BakedQuad> quads, IMultiController machine, IMultiPart part, Direction frontFacing,\n @org.jetbrains.annotations.Nullable Direction side, RandomSource rand, Direction modelFacing, ModelState modelState) {\n render(quads, machine.self(), modelState);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer<ResourceLocation> register) {\n super.onPrepareTextureAtlas(atlasName, register);\n if (atlasName.equals(InventoryMenu.BLOCK_ATLAS)) {\n this.overlayModel.registerTextureAtlas(register);\n }\n }\n\n @Override\n public boolean isConnected(BlockAndTintGetter level, BlockState state, BlockPos pos, BlockState sourceState, BlockPos sourcePos, Direction side) {\n BlockState stateAppearance = FacadeBlockAndTintGetter.getAppearance(state, level, pos, side, sourceState, sourcePos);\n BlockState sourceStateAppearance = FacadeBlockAndTintGetter.getAppearance(sourceState, level, sourcePos, side, state, pos);\n return stateAppearance == sourceStateAppearance;\n }\n}" }, { "identifier": "REGISTRATE", "path": "src/main/java/org/arbor/gtnn/api/registry/GTNNRegistries.java", "snippet": "public static final GTNNRegistrate REGISTRATE = GTNNRegistrate.create(GTNN.MODID);" } ]
import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.block.ICoilType; import com.gregtechceu.gtceu.api.data.RotationState; import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MachineDefinition; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.MultiblockMachineDefinition; import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.pattern.FactoryBlockPattern; import com.gregtechceu.gtceu.api.pattern.MultiblockShapeInfo; import com.gregtechceu.gtceu.api.pattern.Predicates; import com.gregtechceu.gtceu.api.registry.registrate.MachineBuilder; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.GTMaterials; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import org.arbor.gtnn.GTNN; import org.arbor.gtnn.api.machine.multiblock.APartAbility; import org.arbor.gtnn.api.machine.multiblock.ChemicalPlant; import org.arbor.gtnn.api.machine.multiblock.NeutronActivator; import org.arbor.gtnn.api.machine.multiblock.part.HighSpeedPipeBlock; import org.arbor.gtnn.api.machine.multiblock.part.NeutronAccelerator; import org.arbor.gtnn.api.pattern.APredicates; import org.arbor.gtnn.block.BlockTier; import org.arbor.gtnn.block.MachineCasingBlock; import org.arbor.gtnn.block.PipeBlock; import org.arbor.gtnn.block.PlantCasingBlock; import org.arbor.gtnn.client.renderer.machine.BlockMachineRenderer; import org.arbor.gtnn.client.renderer.machine.GTPPMachineRenderer; import java.util.*; import java.util.function.BiFunction; import static com.gregtechceu.gtceu.api.GTValues.V; import static com.gregtechceu.gtceu.api.GTValues.VNF; import static com.gregtechceu.gtceu.api.pattern.Predicates.abilities; import static com.gregtechceu.gtceu.api.pattern.Predicates.autoAbilities; import static com.gregtechceu.gtceu.api.pattern.util.RelativeDirection.*; import static org.arbor.gtnn.api.registry.GTNNRegistries.REGISTRATE;
9,136
package org.arbor.gtnn.data; @SuppressWarnings("unused") public class GTNNMachines { public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8); static { REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB); } ////////////////////////////////////// //********** Part **********// ////////////////////////////////////// public static final MachineDefinition[] NEUTRON_ACCELERATOR = registerTieredMachines("neutron_accelerator", NeutronAccelerator::new, (tier, builder) ->builder .langValue(VNF[tier] + "Neutron Accelerator") .rotationState(RotationState.ALL) .abilities(APartAbility.NEUTRON_ACCELERATOR) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip1")) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip2", V[tier])) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip3", V[tier] * 8 / 10)) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip4")) .overlayTieredHullRenderer("neutron_accelerator") .compassNode("neutron_accelerator") .register(), NA_TIERS); public static final MachineDefinition HIGH_SPEED_PIPE_BLOCK = REGISTRATE.machine("high_speed_pipe_block", HighSpeedPipeBlock::new)
package org.arbor.gtnn.data; @SuppressWarnings("unused") public class GTNNMachines { public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8); static { REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB); } ////////////////////////////////////// //********** Part **********// ////////////////////////////////////// public static final MachineDefinition[] NEUTRON_ACCELERATOR = registerTieredMachines("neutron_accelerator", NeutronAccelerator::new, (tier, builder) ->builder .langValue(VNF[tier] + "Neutron Accelerator") .rotationState(RotationState.ALL) .abilities(APartAbility.NEUTRON_ACCELERATOR) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip1")) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip2", V[tier])) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip3", V[tier] * 8 / 10)) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip4")) .overlayTieredHullRenderer("neutron_accelerator") .compassNode("neutron_accelerator") .register(), NA_TIERS); public static final MachineDefinition HIGH_SPEED_PIPE_BLOCK = REGISTRATE.machine("high_speed_pipe_block", HighSpeedPipeBlock::new)
.renderer(() -> new BlockMachineRenderer(GTNN.id("block/machine/part/high_speed_pipe_block")))
11
2023-11-04 07:59:02+00:00
12k
satisfyu/HerbalBrews
common/src/main/java/satisfyu/herbalbrews/compat/jei/HerbalBrewsJEIPlugin.java
[ { "identifier": "CauldronGuiHandler", "path": "common/src/main/java/satisfyu/herbalbrews/client/gui/handler/CauldronGuiHandler.java", "snippet": "public class CauldronGuiHandler extends AbstractRecipeBookGUIScreenHandler {\n\n public CauldronGuiHandler(int syncId, Inventory playerInventory) {\n this(syncId, playerInventory, new SimpleContainer(6), new SimpleContainerData(2));\n }\n public CauldronGuiHandler(int syncId, Inventory playerInventory, Container inventory, ContainerData propertyDelegate) {\n super(ScreenHandlerTypeRegistry.CAULDRON_SCREEN_HANDLER.get(), syncId, 5, playerInventory, inventory, propertyDelegate);\n buildBlockEntityContainer(playerInventory, inventory);\n buildPlayerContainer(playerInventory);\n }\n\n\n private void buildBlockEntityContainer(Inventory playerInventory, Container inventory) {\n this.addSlot(new ExtendedSlot(inventory, 0, 79, 51, stack -> stack.is(Items.GLASS_BOTTLE)));\n this.addSlot(new ExtendedSlot(inventory, 1, 33, 26, this::isIngredient));\n this.addSlot(new ExtendedSlot(inventory, 2, 51, 26, this::isIngredient));\n this.addSlot(new ExtendedSlot(inventory, 3, 33, 44, this::isIngredient));\n this.addSlot(new ExtendedSlot(inventory, 4, 51, 44, this::isIngredient));\n this.addSlot(new OutputSlot(playerInventory.player, inventory, 5, 128, 35));\n }\n\n private void buildPlayerContainer(Inventory playerInventory) {\n int i;\n for (i = 0; i < 3; ++i) {\n for (int j = 0; j < 9; ++j) {\n this.addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));\n }\n }\n for (i = 0; i < 9; ++i) {\n this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142));\n }\n }\n\n private boolean isIngredient(ItemStack stack) {\n return this.world.getRecipeManager().getAllRecipesFor(RecipeTypeRegistry.CAULDRON_RECIPE_TYPE.get()).stream().anyMatch(recipe -> recipe.getIngredients().stream().anyMatch(x -> x.test(stack)));\n }\n\n public int getScaledProgress(int arrowWidth) {\n final int progress = this.propertyDelegate.get(0);\n final int totalProgress = this.propertyDelegate.get(1);\n if (progress == 0) {\n return 0;\n }\n return progress * arrowWidth/ totalProgress + 1;\n }\n\n @Override\n public List<IRecipeBookGroup> getGroups() {\n return CauldronRecipeBookGroup.CAULDRON_GROUPS;\n }\n\n @Override\n public boolean hasIngredient(Recipe<?> recipe) {\n if (recipe instanceof CauldronRecipe cauldronRecipe) {\n for (Ingredient ingredient : cauldronRecipe.getIngredients()) {\n boolean found = false;\n for (Slot slot : this.slots) {\n if (ingredient.test(slot.getItem())) {\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n for (Slot slot : this.slots) {\n if (slot.getItem().getItem() == Items.GLASS_BOTTLE.asItem()) {\n return true;\n }\n }\n }\n return false;\n }\n\n @Override\n public int getCraftingSlotCount() {\n return 5;\n }\n}" }, { "identifier": "TeaKettleGuiHandler", "path": "common/src/main/java/satisfyu/herbalbrews/client/gui/handler/TeaKettleGuiHandler.java", "snippet": "public class TeaKettleGuiHandler extends AbstractRecipeBookGUIScreenHandler {\n public TeaKettleGuiHandler(int syncId, Inventory playerInventory) {\n this(syncId, playerInventory, new SimpleContainer(7), new SimpleContainerData(2));\n }\n\n public TeaKettleGuiHandler(int syncId, Inventory playerInventory, Container inventory, ContainerData propertyDelegate) {\n super(ScreenHandlerTypeRegistry.TEA_KETTLE_SCREEN_HANDLER.get(), syncId, 6, playerInventory, inventory, propertyDelegate);\n buildBlockEntityContainer(playerInventory, inventory);\n buildPlayerContainer(playerInventory);\n }\n\n private void buildBlockEntityContainer(Inventory playerInventory, Container inventory) {\n this.addSlot(new FurnaceResultSlot(playerInventory.player, inventory, 0, 124, 26));\n for (int row = 0; row < 2; row++) {\n for (int slot = 0; slot < 3; slot++) {\n this.addSlot(new Slot(inventory, 1 + slot + row + (row * 2), 30 + (slot * 18), 17 + (row * 18)));\n }\n }\n }\n\n private void buildPlayerContainer(Inventory playerInventory) {\n int i;\n for (i = 0; i < 3; ++i) {\n for (int j = 0; j < 9; ++j) {\n this.addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));\n }\n }\n for (i = 0; i < 9; ++i) {\n this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142));\n }\n }\n\n @Override\n public boolean stillValid(Player player) {\n return true;\n }\n\n public boolean isBeingBurned() {\n return propertyDelegate.get(1) != 0;\n }\n\n\n private boolean isItemIngredient(ItemStack stack) {\n return recipeStream().anyMatch(teaKettleRecipe -> teaKettleRecipe.getIngredients().stream().anyMatch(ingredient -> ingredient.test(stack)));\n }\n\n private Stream<TeaKettleRecipe> recipeStream() {\n return this.world.getRecipeManager().getAllRecipesFor(RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get()).stream();\n }\n\n public int getScaledProgress(int arrowWidth) {\n final int progress = this.propertyDelegate.get(0);\n final int totalProgress = TeaKettleBlockEntity.MAX_COOKING_TIME;\n if (progress == 0) {\n return 0;\n }\n return progress * arrowWidth/ totalProgress + 1;\n }\n\n\n @Override\n public List<IRecipeBookGroup> getGroups() {\n return TeaKettleRecipeBookGroup.TEAKETTLE_GROUPS;\n }\n\n @Override\n public boolean hasIngredient(Recipe<?> recipe) {\n if (recipe instanceof TeaKettleRecipe potRecipe) {\n for (Ingredient ingredient : potRecipe.getIngredients()) {\n boolean found = false;\n for (Slot slot : this.slots) {\n if (ingredient.test(slot.getItem())) {\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n @Override\n public int getCraftingSlotCount() {\n return 6;\n }\n}" }, { "identifier": "CauldronCategory", "path": "common/src/main/java/satisfyu/herbalbrews/compat/jei/category/CauldronCategory.java", "snippet": "public class CauldronCategory implements IRecipeCategory<CauldronRecipe> {\n public static final RecipeType<CauldronRecipe> CAULDRON = RecipeType.create(HerbalBrews.MOD_ID, \"cauldron_brewing\", CauldronRecipe.class);\n public static final int WIDTH = 124;\n public static final int HEIGHT = 60;\n public static final int WIDTH_OF = 26;\n public static final int HEIGHT_OF = 13;\n private final IDrawable background;\n private final IDrawable icon;\n private final IDrawableAnimated arrow;\n private final Component localizedName;\n\n public CauldronCategory(IGuiHelper helper) {\n this.background = helper.createDrawable(CauldronGui.BACKGROUND, WIDTH_OF, HEIGHT_OF, WIDTH, HEIGHT);\n this.arrow = helper.drawableBuilder(CauldronGui.BACKGROUND, 177, 17, 23, 10)\n .buildAnimated(50, IDrawableAnimated.StartDirection.LEFT, false);\n this.icon = helper.createDrawableIngredient(VanillaTypes.ITEM_STACK, ObjectRegistry.CAULDRON.get().asItem().getDefaultInstance());\n this.localizedName = Component.translatable(\"rei.herbalbrews.cauldron_category\");\n }\n\n @Override\n public void setRecipe(IRecipeLayoutBuilder builder, CauldronRecipe recipe, IFocusGroup focuses) {\n // Wine input\n NonNullList<Ingredient> ingredients = recipe.getIngredients();\n int s = ingredients.size();\n\n builder.addSlot(RecipeIngredientRole.INPUT, 79 - WIDTH_OF, 51 - HEIGHT_OF).addItemStack(Items.GLASS_BOTTLE.getDefaultInstance());\n if(s > 0) HerbalBrewsJEIPlugin.addSlot(builder, 33 - WIDTH_OF, 26 - HEIGHT_OF, ingredients.get(0));\n if(s > 1) HerbalBrewsJEIPlugin.addSlot(builder, 51 - WIDTH_OF, 26 - HEIGHT_OF, ingredients.get(1));\n if(s > 2) HerbalBrewsJEIPlugin.addSlot(builder, 33 - WIDTH_OF, 44 - HEIGHT_OF, ingredients.get(2));\n if(s > 3) HerbalBrewsJEIPlugin.addSlot(builder, 51 - WIDTH_OF, 44 - HEIGHT_OF, ingredients.get(3));\n\n // Output\n builder.addSlot(RecipeIngredientRole.OUTPUT, 128 - WIDTH_OF, 35 - HEIGHT_OF).addItemStack(recipe.getResultItem(Minecraft.getInstance().level.registryAccess()));\n }\n\n @Override\n public void draw(CauldronRecipe recipe, IRecipeSlotsView recipeSlotsView, GuiGraphics guiGraphics, double mouseX, double mouseY) {\n arrow.draw(guiGraphics, CauldronGui.ARROW_X - WIDTH_OF, CauldronGui.ARROW_Y - HEIGHT_OF);\n }\n\n @Override\n public RecipeType<CauldronRecipe> getRecipeType() {\n return CAULDRON;\n }\n\n @Override\n public Component getTitle() {\n return this.localizedName;\n }\n\n @Override\n public IDrawable getBackground() {\n return this.background;\n }\n\n @Override\n public IDrawable getIcon() {\n return this.icon;\n }\n}" }, { "identifier": "TeaKettleCategory", "path": "common/src/main/java/satisfyu/herbalbrews/compat/jei/category/TeaKettleCategory.java", "snippet": "public class TeaKettleCategory implements IRecipeCategory<TeaKettleRecipe> {\n public static final RecipeType<TeaKettleRecipe> TEA_KETTLE = RecipeType.create(HerbalBrews.MOD_ID, \"cooking\", TeaKettleRecipe.class);\n public static final int WIDTH = 124;\n public static final int HEIGHT = 55;\n public static final int WIDTH_OF = 26;\n public static final int HEIGHT_OF = 10;\n private final IDrawable background;\n private final IDrawable icon;\n private final IDrawable burnicon;\n private final IDrawableAnimated arrow;\n private final Component localizedName;\n\n public TeaKettleCategory(IGuiHelper helper) {\n this.background = helper.createDrawable(TeaKettleGui.BACKGROUND, WIDTH_OF, HEIGHT_OF, WIDTH, HEIGHT);\n this.arrow = helper.drawableBuilder(TeaKettleGui.BACKGROUND, 178, 16, 17, 29)\n .buildAnimated(TeaKettleBlockEntity.MAX_COOKING_TIME, IDrawableAnimated.StartDirection.LEFT, false);\n this.icon = helper.createDrawableIngredient(VanillaTypes.ITEM_STACK, ObjectRegistry.TEA_KETTLE.get().asItem().getDefaultInstance());\n this.burnicon = helper.createDrawable(TeaKettleGui.BACKGROUND, 176, 0, 17, 15);\n this.localizedName = Component.translatable(\"rei.herbalbrews.tea_kettle_category\");\n }\n\n\n @Override\n public void setRecipe(IRecipeLayoutBuilder builder, TeaKettleRecipe recipe, IFocusGroup focuses) {\n NonNullList<Ingredient> ingredients = recipe.getIngredients();\n int s = ingredients.size();\n\n for (int row = 0; row < 2; row++) {\n for (int slot = 0; slot < 3; slot++) {\n int current = slot + row + (row * 2);\n if(s - 1 < current) break;\n HerbalBrewsJEIPlugin.addSlot(builder,30 + (slot * 18) - WIDTH_OF, 17 + (row * 18) - HEIGHT_OF, ingredients.get(current));\n }\n }\n\n // Output\n builder.addSlot(RecipeIngredientRole.OUTPUT, 124 - WIDTH_OF, 26 - HEIGHT_OF).addItemStack(recipe.getResultItem());\n }\n\n @Override\n public void draw(TeaKettleRecipe recipe, IRecipeSlotsView recipeSlotsView, GuiGraphics guiGraphics, double mouseX, double mouseY) {\n arrow.draw(guiGraphics, TeaKettleGui.ARROW_X - WIDTH_OF, TeaKettleGui.ARROW_Y - HEIGHT_OF);\n burnicon.draw(guiGraphics, 124 - WIDTH_OF, 51 - HEIGHT_OF);\n }\n\n @Override\n public RecipeType<TeaKettleRecipe> getRecipeType() {\n return TEA_KETTLE;\n }\n\n @Override\n public Component getTitle() {\n return this.localizedName;\n }\n\n @Override\n public IDrawable getBackground() {\n return this.background;\n }\n\n @Override\n public IDrawable getIcon() {\n return this.icon;\n }\n}" }, { "identifier": "CauldronRecipe", "path": "common/src/main/java/satisfyu/herbalbrews/recipe/CauldronRecipe.java", "snippet": "public class CauldronRecipe implements Recipe<Container> {\n\n private final ResourceLocation identifier;\n private final NonNullList<Ingredient> inputs;\n private final ItemStack output;\n\n public CauldronRecipe(ResourceLocation identifier, NonNullList<Ingredient> inputs, ItemStack output) {\n this.identifier = identifier;\n this.inputs = inputs;\n this.output = output;\n }\n\n @Override\n public boolean matches(Container inventory, Level world) {\n StackedContents recipeMatcher = new StackedContents();\n int matchingStacks = 0;\n\n for(int i = 1; i < 5; ++i) {\n ItemStack itemStack = inventory.getItem(i);\n if (!itemStack.isEmpty()) {\n ++matchingStacks;\n recipeMatcher.accountStack(itemStack, 1);\n }\n }\n\n return matchingStacks == this.inputs.size() && recipeMatcher.canCraft(this, null);\n }\n\n @Override\n public ItemStack assemble(Container container, RegistryAccess registryAccess) {\n return ItemStack.EMPTY;\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return this.inputs;\n }\n\n\n @Override\n public boolean canCraftInDimensions(int width, int height) {\n return true;\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess registryAccess) {\n return this.output.copy();\n }\n\n @Override\n public ResourceLocation getId() {\n return this.identifier;\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return RecipeTypeRegistry.CAULDRON_RECIPE_SERIALIZER.get();\n }\n\n @Override\n public RecipeType<?> getType() {\n return RecipeTypeRegistry.CAULDRON_RECIPE_TYPE.get();\n }\n\n @Override\n public boolean isSpecial() {\n return true;\n }\n public static class Serializer implements RecipeSerializer<CauldronRecipe> {\n\n @Override\n public CauldronRecipe fromJson(ResourceLocation id, JsonObject json) {\n final var ingredients = GeneralUtil.deserializeIngredients(GsonHelper.getAsJsonArray(json, \"ingredients\"));\n if (ingredients.isEmpty()) {\n throw new JsonParseException(\"No ingredients for Brewing Cauldron\");\n } else if (ingredients.size() > 4) {\n throw new JsonParseException(\"Too many ingredients for Brewing Cauldron\");\n } else {\n return new CauldronRecipe(id, ingredients, ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(json, \"result\")));\n }\n }\n\n @Override\n public CauldronRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf) {\n final var ingredients = NonNullList.withSize(buf.readVarInt(), Ingredient.EMPTY);\n ingredients.replaceAll(ignored -> Ingredient.fromNetwork(buf));\n return new CauldronRecipe(id, ingredients, buf.readItem());\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, CauldronRecipe recipe) {\n buf.writeVarInt(recipe.inputs.size());\n for (Ingredient ingredient : recipe.inputs) {\n ingredient.toNetwork(buf);\n }\n\n buf.writeItem(recipe.output);\n }\n }\n}" }, { "identifier": "TeaKettleRecipe", "path": "common/src/main/java/satisfyu/herbalbrews/recipe/TeaKettleRecipe.java", "snippet": "public class TeaKettleRecipe implements Recipe<Container> {\n\n final ResourceLocation id;\n private final NonNullList<Ingredient> inputs;\n private final ItemStack output;\n\n public TeaKettleRecipe(ResourceLocation id, NonNullList<Ingredient> inputs, ItemStack output) {\n this.id = id;\n this.inputs = inputs;\n this.output = output;\n }\n\n @Override\n public boolean matches(Container inventory, Level world) {\n return GeneralUtil.matchesRecipe(inventory, inputs, 0, 6);\n }\n\n public ItemStack assemble() {\n return assemble(null, null);\n }\n\n @Override\n public ItemStack assemble(Container inventory, RegistryAccess registryManager) {\n return this.output.copy();\n }\n\n @Override\n public boolean canCraftInDimensions(int width, int height) {\n return false;\n }\n\n public ItemStack getResultItem() {\n return getResultItem(null);\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess registryManager) {\n return this.output;\n }\n\n @Override\n public ResourceLocation getId() {\n return id;\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return RecipeTypeRegistry.TEAK_KETTLE_RECIPE_SERIALIZER.get();\n }\n\n @Override\n public RecipeType<?> getType() {\n return RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get();\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return this.inputs;\n }\n\n @Override\n public boolean isSpecial() {\n return true;\n }\n\n public static class Serializer implements RecipeSerializer<TeaKettleRecipe> {\n\n @Override\n public TeaKettleRecipe fromJson(ResourceLocation id, JsonObject json) {\n final var ingredients = GeneralUtil.deserializeIngredients(GsonHelper.getAsJsonArray(json, \"ingredients\"));\n if (ingredients.isEmpty()) {\n throw new JsonParseException(\"No ingredients for Tea Kettle Recipe\");\n } else if (ingredients.size() > 6) {\n throw new JsonParseException(\"Too many ingredients for Tea Kettle Recipe\");\n } else {\n return new TeaKettleRecipe(id, ingredients, ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(json, \"result\")));\n }\n }\n\n @Override\n public TeaKettleRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf) {\n final var ingredients = NonNullList.withSize(buf.readVarInt(), Ingredient.EMPTY);\n ingredients.replaceAll(ignored -> Ingredient.fromNetwork(buf));\n return new TeaKettleRecipe(id, ingredients, buf.readItem());\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, TeaKettleRecipe recipe) {\n buf.writeVarInt(recipe.inputs.size());\n recipe.inputs.forEach(entry -> entry.toNetwork(buf));\n buf.writeItem(recipe.output);\n }\n }\n\n public static class Type implements RecipeType<TeaKettleRecipe> {\n private Type() {\n }\n\n public static final Type INSTANCE = new Type();\n\n public static final String ID = \"cooking\";\n }\n}" }, { "identifier": "ObjectRegistry", "path": "common/src/main/java/satisfyu/herbalbrews/registry/ObjectRegistry.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class ObjectRegistry {\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.ITEM);\n public static final Registrar<Item> ITEM_REGISTRAR = ITEMS.getRegistrar();\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.BLOCK);\n public static final Registrar<Block> BLOCK_REGISTRAR = BLOCKS.getRegistrar();\n\n public static final RegistrySupplier<Block> STOVE = registerWithItem(\"stove\", () -> new StoveBlock(BlockBehaviour.Properties.copy(Blocks.BRICKS).lightLevel(state -> state.getValue(StoveBlock.LIT) ? 13 : 0).randomTicks()));\n public static final RegistrySupplier<Block> TEA_LEAF_CRATE = registerWithItem(\"tea_leaf_crate\", () -> new Block(BlockBehaviour.Properties.copy(Blocks.RED_WOOL)));\n public static final RegistrySupplier<Block> GREEN_TEA_LEAF_BLOCK = registerWithItem(\"green_tea_leaf_block\", () -> new TeaLeafBlock(BlockBehaviour.Properties.copy(Blocks.ACACIA_LEAVES)));\n public static final RegistrySupplier<Block> DRIED_GREEN_TEA_LEAF_BLOCK = registerWithItem(\"dried_green_tea_leaf_block\", () -> new TeaLeafBlock(BlockBehaviour.Properties.copy(Blocks.ACACIA_LEAVES)));\n public static final RegistrySupplier<Block> DRIED_OUT_GREEN_TEA_LEAF_BLOCK = registerWithItem(\"dried_out_green_tea_leaf_block\", () -> new Block(BlockBehaviour.Properties.copy(Blocks.ACACIA_LEAVES)));\n public static final RegistrySupplier<Block> BLACK_TEA_LEAF_BLOCK = registerWithItem(\"black_tea_leaf_block\", () -> new Block(BlockBehaviour.Properties.copy(Blocks.ACACIA_LEAVES)));\n public static final RegistrySupplier<Block> MIXED_TEA_LEAF_BLOCK = registerWithItem(\"mixed_tea_leaf_block\", () -> new TeaLeafBlock(BlockBehaviour.Properties.copy(Blocks.ACACIA_LEAVES)));\n public static final RegistrySupplier<Block> OOLONG_TEA_LEAF_BLOCK = registerWithItem(\"oolong_tea_leaf_block\", () -> new Block(BlockBehaviour.Properties.copy(Blocks.ACACIA_LEAVES)));\n public static final RegistrySupplier<Block> WILD_COFFEE_PLANT = registerWithItem(\"wild_coffee_plant\", () -> new FlowerBlock(MobEffects.HEAL, 1, BlockBehaviour.Properties.copy(Blocks.DANDELION)));\n public static final RegistrySupplier<Block> COFFEE_PLANT = registerWithoutItem(\"coffee_plant\", () -> new CoffeeCropBlock(BlockBehaviour.Properties.copy(Blocks.SWEET_BERRY_BUSH)));\n public static final RegistrySupplier<Block> WILD_ROOIBOS_PLANT = registerWithItem(\"wild_rooibos_plant\", () -> new FlowerBlock(MobEffects.HEAL, 1, BlockBehaviour.Properties.copy(Blocks.DANDELION)));\n public static final RegistrySupplier<Block> ROOIBOS_PLANT = registerWithoutItem(\"rooibos_plant\", () -> new RooibosCropBlock(BlockBehaviour.Properties.copy(Blocks.SWEET_BERRY_BUSH)));\n public static final RegistrySupplier<Block> WILD_YERBA_MATE_PLANT = registerWithItem(\"wild_yerba_mate_plant\", () -> new FlowerBlock(MobEffects.HEAL, 1, BlockBehaviour.Properties.copy(Blocks.DANDELION)));\n public static final RegistrySupplier<Block> YERBA_MATE_PLANT = registerWithoutItem(\"yerba_mate_plant\", () -> new YerbaMateCropBlock(BlockBehaviour.Properties.copy(Blocks.SWEET_BERRY_BUSH)));\n public static final RegistrySupplier<Block> TEA_PLANT = registerWithoutItem(\"tea_plant\", () -> new TeaCropBlock(BlockBehaviour.Properties.copy(Blocks.SWEET_BERRY_BUSH)));\n public static final RegistrySupplier<Block> HIBISCUS = registerWithItem(\"hibiscus\", () -> new BonemealableFlower(MobEffects.HEAL, 1, BlockBehaviour.Properties.copy(Blocks.DANDELION)));\n public static final RegistrySupplier<Block> LAVENDER = registerWithItem(\"lavender\", () -> new BonemealableFlower(MobEffects.HEAL, 1, BlockBehaviour.Properties.copy(Blocks.DANDELION)));\n public static final RegistrySupplier<Block> JUG = registerWithoutItem(\"jug\", () -> new JugBlock(BlockBehaviour.Properties.copy(Blocks.GLASS)));\n public static final RegistrySupplier<Item> JUG_ITEM = registerItem(\"jug\", () -> new JugItem(JUG.get(), getSettings()));\n public static final RegistrySupplier<Block> COPPER_TEA_KETTLE = registerWithItem(\"copper_tea_kettle\", () -> new TeaKettleBlock(BlockBehaviour.Properties.copy(Blocks.IRON_BLOCK)));\n public static final RegistrySupplier<Block> TEA_KETTLE = registerWithItem(\"tea_kettle\", () -> new TeaKettleBlock(BlockBehaviour.Properties.copy(Blocks.IRON_BLOCK)));\n public static final RegistrySupplier<Block> CAULDRON = registerWithItem(\"cauldron\", () -> new CauldronBlock(BlockBehaviour.Properties.copy(Blocks.IRON_BLOCK).lightLevel((blockState) -> 11)));\n public static final RegistrySupplier<Item> ARMOR_FLASK = registerItem(\"armor_flask\", () -> new DrinkItem(getFoodItemSettings(4, 0.8f, EffectRegistry.ARMOR.get(), 6000)));\n public static final RegistrySupplier<Item> ARMOR_FLASK_BIG = registerItem(\"armor_flask_big\", () -> new DrinkItem(getFoodItemSettings(4, 0.8f, EffectRegistry.ARMOR.get(), 12000)));\n public static final RegistrySupplier<Item> DAMAGE_FLASK = registerItem(\"damage_flask\", () -> new DrinkItem(getFoodItemSettings(4, 0.8f, EffectRegistry.DAMAGE.get(), 6000)));\n public static final RegistrySupplier<Item> DAMAGE_FLASK_BIG = registerItem(\"damage_flask_big\", () -> new DrinkItem(getFoodItemSettings(4, 0.8f, EffectRegistry.DAMAGE.get(), 12000)));\n public static final RegistrySupplier<Item> FERAL_FLASK = registerItem(\"feral_flask\", () -> new DrinkItem(getFoodItemSettings(4, 0.8f, EffectRegistry.FERAL.get(), 6000)));\n public static final RegistrySupplier<Item> FERAL_FLASK_BIG = registerItem(\"feral_flask_big\", () -> new DrinkItem(getFoodItemSettings(4, 0.8f, EffectRegistry.FERAL.get(), 12000)));\n public static final RegistrySupplier<Item> TEA_BLOSSOM = registerItem(\"tea_blossom\", () -> new SeedItem(TEA_PLANT.get(), getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> GREEN_TEA_LEAF = registerItem(\"green_tea_leaf\", () -> new TooltipItem(getSettings()));\n public static final RegistrySupplier<Item> YERBA_MATE_LEAF = registerItem(\"yerba_mate_leaf\", () -> new SeedItem(YERBA_MATE_PLANT.get(), getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> ROOIBOS_LEAF = registerItem(\"rooibos_leaf\", () -> new SeedItem(ROOIBOS_PLANT.get(), getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> LAVENDER_BLOSSOM = registerItem(\"lavender_blossom\", () -> new TooltipItem(getSettings()));\n public static final RegistrySupplier<Item> DRIED_GREEN_TEA = registerItem(\"dried_green_tea\", () -> new TooltipItem(getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> DRIED_BLACK_TEA = registerItem(\"dried_black_tea\", () -> new TooltipItem(getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> DRIED_OOLONG_TEA = registerItem(\"dried_oolong_tea\", () -> new TooltipItem(getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> COFFEE_BEANS = registerItem(\"coffee_beans\", () -> new SeedItem(COFFEE_PLANT.get(), getSettings().food(new FoodProperties.Builder().nutrition(1).saturationMod(0.1f).fast().alwaysEat().build())));\n public static final RegistrySupplier<Item> GREEN_TEA = registerItem(\"green_tea\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.BALANCED.get(), 60 * 15)));\n public static final RegistrySupplier<Item> BLACK_TEA = registerItem(\"black_tea\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.REVITALIZING.get(), 60 * 15)));\n public static final RegistrySupplier<Item> LAVENDER_TEA = registerItem(\"lavender_tea\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.FORTUNE.get(), 60 * 15)));\n public static final RegistrySupplier<Item> YERBA_MATE_TEA = registerItem(\"yerba_mate_tea\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.POISONOUSBREATH.get(), 60 * 15)));\n public static final RegistrySupplier<Item> OOLONG_TEA = registerItem(\"oolong_tea\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.RENEWAL.get(), 60 * 15)));\n public static final RegistrySupplier<Item> ROOIBOS_TEA = registerItem(\"rooibos_tea\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.EXCAVATION.get(), 60 * 15)));\n public static final RegistrySupplier<Block> HIBISCUS_TEA = registerTea(\"hibiscus_tea\", () -> new TeaCupBlock(getTeaSettings()),EffectRegistry.FERAL);\n public static final RegistrySupplier<Block> MILK_COFFEE = registerTea(\"milk_coffee\", () -> new TeaCupBlock(getTeaSettings()),(EffectRegistry.TOUGH));\n public static final RegistrySupplier<Item> COFFEE = registerItem(\"coffee\", () -> new DrinkItem(getFoodItemSettings(4, 0.7f, EffectRegistry.TOUGH.get(), 60 * 15)));\n\n public static final RegistrySupplier<Item> WITCH_HAT = registerItem(\"witch_hat\", () -> new WitchHatItem(getSettings().rarity(Rarity.UNCOMMON)));\n public static final RegistrySupplier<Item> TOP_HAT = registerItem(\"top_hat\", () -> new TopHatItem(getSettings().rarity(Rarity.UNCOMMON)));\n\n public static final RegistrySupplier<Item> HERBALBREWS_STANDARD = registerItem(\"herbalbrews_standard\", () -> new HerbalbrewsStandardItem(new Item.Properties().stacksTo(16).rarity(Rarity.UNCOMMON)));\n\n\n public static final RegistrySupplier<Block> POTTED_LAVENDER = registerWithoutItem(\"potted_lavender\", () -> new FlowerPotBlock(LAVENDER.get(), BlockBehaviour.Properties.copy(Blocks.FLOWER_POT)));\n public static final RegistrySupplier<Block> POTTED_HIBISCUS = registerWithoutItem(\"potted_hibiscus\", () -> new FlowerPotBlock(HIBISCUS.get(), BlockBehaviour.Properties.copy(Blocks.FLOWER_POT)));\n public static final RegistrySupplier<Block> POTTED_WILD_ROOIBOS = registerWithoutItem(\"potted_wild_rooibos\", () -> new FlowerPotBlock(WILD_ROOIBOS_PLANT.get(), BlockBehaviour.Properties.copy(Blocks.FLOWER_POT)));\n public static final RegistrySupplier<Block> POTTED_WILD_COFFEE = registerWithoutItem(\"potted_wild_coffee\", () -> new FlowerPotBlock(WILD_COFFEE_PLANT.get(), BlockBehaviour.Properties.copy(Blocks.FLOWER_POT)));\n public static final RegistrySupplier<Block> POTTED_WILD_YERBA_MATE = registerWithoutItem(\"potted_wild_yerba_mate\", () -> new FlowerPotBlock(WILD_YERBA_MATE_PLANT.get(), BlockBehaviour.Properties.copy(Blocks.FLOWER_POT)));\n\n\n\n\n public static void init() {\n ITEMS.register();\n BLOCKS.register();\n }\n\n public static void registerCompostable() {\n registerCompostableItem(ObjectRegistry.GREEN_TEA_LEAF_BLOCK, 0.8f);\n registerCompostableItem(ObjectRegistry.BLACK_TEA_LEAF_BLOCK, 0.8f);\n registerCompostableItem(ObjectRegistry.MIXED_TEA_LEAF_BLOCK, 0.8f);\n registerCompostableItem(ObjectRegistry.OOLONG_TEA_LEAF_BLOCK, 0.8f);\n registerCompostableItem(ObjectRegistry.GREEN_TEA_LEAF, 0.2f);\n registerCompostableItem(ObjectRegistry.YERBA_MATE_LEAF, 0.3f);\n registerCompostableItem(ObjectRegistry.COFFEE_BEANS, 0.3f);\n registerCompostableItem(ObjectRegistry.TEA_BLOSSOM, 0.3f);\n registerCompostableItem(ObjectRegistry.WILD_COFFEE_PLANT, 0.3f);\n registerCompostableItem(ObjectRegistry.WILD_ROOIBOS_PLANT, 0.3f);\n registerCompostableItem(ObjectRegistry.WILD_YERBA_MATE_PLANT, 0.3f);\n registerCompostableItem(ObjectRegistry.HIBISCUS, 0.3f);\n registerCompostableItem(ObjectRegistry.LAVENDER, 0.3f);\n registerCompostableItem(ObjectRegistry.DRIED_OOLONG_TEA, 0.5f);\n registerCompostableItem(ObjectRegistry.DRIED_BLACK_TEA, 0.5f);\n }\n\n public static <T extends ItemLike> void registerCompostableItem(RegistrySupplier<T> item, float chance) {\n if (item.get().asItem() != Items.AIR) {\n ComposterBlock.COMPOSTABLES.put(item.get(), chance);\n }\n }\n \n private static Item.Properties getSettings(Consumer<Item.Properties> consumer) {\n Item.Properties settings = new Item.Properties();\n consumer.accept(settings);\n return settings;\n }\n\n private static Item.Properties getSettingsWithoutTab(Consumer<Item.Properties> consumer) {\n Item.Properties settings = new Item.Properties();\n consumer.accept(settings);\n return settings;\n }\n\n static Item.Properties getSettings() {\n return getSettings(settings -> {\n });\n }\n\n private static Item.Properties getFoodItemSettings(int nutrition, float saturationMod, MobEffect effect, int duration) {\n return getFoodItemSettings(nutrition, saturationMod, effect, duration, true, true);\n }\n\n private static Item.Properties getFoodItemSettings(int nutrition, float saturationMod, MobEffect effect, int duration, boolean alwaysEat, boolean fast) {\n return getSettings().food(createFood(nutrition, saturationMod, effect, duration, alwaysEat, fast));\n }\n\n private static FoodProperties createFood(int nutrition, float saturationMod, MobEffect effect, int duration, boolean alwaysEat, boolean fast) {\n FoodProperties.Builder food = new FoodProperties.Builder().nutrition(nutrition).saturationMod(saturationMod);\n if (alwaysEat) food.alwaysEat();\n if (fast) food.fast();\n if (effect != null) food.effect(new MobEffectInstance(effect, duration), 1.0f);\n return food.build();\n }\n\n\n private static Item.Properties getSettingsWithoutTab() {\n return getSettingsWithoutTab(settings -> {\n });\n }\n\n public static <T extends Block> RegistrySupplier<T> registerWithItem(String name, Supplier<T> block) {\n return Util.registerWithItem(BLOCKS, BLOCK_REGISTRAR, ITEMS, ITEM_REGISTRAR, new HerbalBrewsIdentifier(name), block);\n }\n\n\n public static <T extends Block> RegistrySupplier<T> registerWithoutItem(String path, Supplier<T> block) {\n return Util.registerWithoutItem(BLOCKS, BLOCK_REGISTRAR, new HerbalBrewsIdentifier(path), block);\n }\n\n public static <T extends Item> RegistrySupplier<T> registerItem(String path, Supplier<T> itemSupplier) {\n return Util.registerItem(ITEMS, ITEM_REGISTRAR, new HerbalBrewsIdentifier(path), itemSupplier);\n }\n\n\n private static ButtonBlock createWoodenButtonBlock(BlockSetType blockSetType, FeatureFlag... requiredFeatures) {\n BlockBehaviour.Properties settings = BlockBehaviour.Properties.of().noCollission().strength(0.5F).pushReaction(PushReaction.DESTROY);\n if (requiredFeatures.length > 0) {\n settings = settings.requiredFeatures(requiredFeatures);\n }\n\n return new ButtonBlock(settings, blockSetType, 30, true);\n }\n\n private static FoodProperties teaFoodComponent(MobEffect effect) {\n FoodProperties.Builder component = new FoodProperties.Builder().nutrition(2).saturationMod(2);\n if (effect != null) component.effect(new MobEffectInstance(effect, 90 * 20), 1.0f);\n return component.build();\n }\n\n private static BlockBehaviour.Properties getTeaSettings() {\n return BlockBehaviour.Properties.copy(Blocks.GLASS).noOcclusion().instabreak();\n }\n\n private static <T extends Block> RegistrySupplier<T> registerTea(String name, Supplier<T> block, RegistrySupplier<MobEffect> effect) {\n RegistrySupplier<T> toReturn = registerWithoutItem(name, block);\n registerItem(name, () -> new DrinkBlockItem(toReturn.get(), getSettings(settings -> settings.food(teaFoodComponent(effect.get())))));\n return toReturn;\n }\n\n}" }, { "identifier": "RecipeTypeRegistry", "path": "common/src/main/java/satisfyu/herbalbrews/registry/RecipeTypeRegistry.java", "snippet": "public class RecipeTypeRegistry {\n\n private static final DeferredRegister<RecipeSerializer<?>> RECIPE_SERIALIZERS = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.RECIPE_SERIALIZER);\n private static final DeferredRegister<RecipeType<?>> RECIPE_TYPES = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.RECIPE_TYPE);\n\n public static final RegistrySupplier<RecipeType<TeaKettleRecipe>> TEA_KETTLE_RECIPE_TYPE = create(\"kettle_brewing\");\n public static final RegistrySupplier<RecipeSerializer<TeaKettleRecipe>> TEAK_KETTLE_RECIPE_SERIALIZER = create(\"kettle_brewing\", TeaKettleRecipe.Serializer::new);\n public static final RegistrySupplier<RecipeType<CauldronRecipe>> CAULDRON_RECIPE_TYPE = create(\"cauldron_brewing\");\n public static final RegistrySupplier<RecipeSerializer<CauldronRecipe>> CAULDRON_RECIPE_SERIALIZER = create(\"cauldron_brewing\", CauldronRecipe.Serializer::new);\n\n private static <T extends Recipe<?>> RegistrySupplier<RecipeSerializer<T>> create(String name, Supplier<RecipeSerializer<T>> serializer) {\n return RECIPE_SERIALIZERS.register(name, serializer);\n }\n\n private static <T extends Recipe<?>> RegistrySupplier<RecipeType<T>> create(String name) {\n Supplier<RecipeType<T>> type = () -> new RecipeType<>() {\n @Override\n public String toString() {\n return name;\n }\n };\n return RECIPE_TYPES.register(name, type);\n }\n\n public static void init() {\n RECIPE_SERIALIZERS.register();\n RECIPE_TYPES.register();\n }\n\n\n}" }, { "identifier": "ScreenHandlerTypeRegistry", "path": "common/src/main/java/satisfyu/herbalbrews/registry/ScreenHandlerTypeRegistry.java", "snippet": "public class ScreenHandlerTypeRegistry {\n\n public static final DeferredRegister<MenuType<?>> MENU_TYPES = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.MENU);\n\n public static final RegistrySupplier<MenuType<TeaKettleGuiHandler>> TEA_KETTLE_SCREEN_HANDLER = create(\"tea_kettle_gui_handler\", () -> new MenuType<>(TeaKettleGuiHandler::new, FeatureFlags.VANILLA_SET));\n public static final RegistrySupplier<MenuType<CauldronGuiHandler>> CAULDRON_SCREEN_HANDLER = create(\"cauldron_gui_handler\", () -> new MenuType<>(CauldronGuiHandler::new, FeatureFlags.VANILLA_SET));\n\n\n public static void init() {\n MENU_TYPES.register();\n }\n\n private static <T extends MenuType<?>> RegistrySupplier<T> create(String name, Supplier<T> type) {\n return MENU_TYPES.register(name, type);\n }\n}" }, { "identifier": "HerbalBrewsIdentifier", "path": "common/src/main/java/satisfyu/herbalbrews/util/HerbalBrewsIdentifier.java", "snippet": "public class HerbalBrewsIdentifier extends ResourceLocation {\n\n public HerbalBrewsIdentifier(String path) {\n super(HerbalBrews.MOD_ID, path);\n }\n\n public static String asString(String path) {\n return (HerbalBrews.MOD_ID + \":\" + path);\n }\n}" } ]
import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.registration.IRecipeCatalystRegistration; import mezz.jei.api.registration.IRecipeCategoryRegistration; import mezz.jei.api.registration.IRecipeRegistration; import mezz.jei.api.registration.IRecipeTransferRegistration; import net.minecraft.client.Minecraft; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeManager; import satisfyu.herbalbrews.client.gui.handler.CauldronGuiHandler; import satisfyu.herbalbrews.client.gui.handler.TeaKettleGuiHandler; import satisfyu.herbalbrews.compat.jei.category.CauldronCategory; import satisfyu.herbalbrews.compat.jei.category.TeaKettleCategory; import satisfyu.herbalbrews.recipe.CauldronRecipe; import satisfyu.herbalbrews.recipe.TeaKettleRecipe; import satisfyu.herbalbrews.registry.ObjectRegistry; import satisfyu.herbalbrews.registry.RecipeTypeRegistry; import satisfyu.herbalbrews.registry.ScreenHandlerTypeRegistry; import satisfyu.herbalbrews.util.HerbalBrewsIdentifier; import java.util.List; import java.util.Objects;
10,527
package satisfyu.herbalbrews.compat.jei; @JeiPlugin public class HerbalBrewsJEIPlugin implements IModPlugin { @Override public void registerCategories(IRecipeCategoryRegistration registration) { registration.addRecipeCategories(new TeaKettleCategory(registration.getJeiHelpers().getGuiHelper())); registration.addRecipeCategories(new CauldronCategory(registration.getJeiHelpers().getGuiHelper())); } @Override public void registerRecipes(IRecipeRegistration registration) { RecipeManager rm = Objects.requireNonNull(Minecraft.getInstance().level).getRecipeManager(); List<TeaKettleRecipe> cookingCauldronRecipes = rm.getAllRecipesFor(RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get()); registration.addRecipes(TeaKettleCategory.TEA_KETTLE, cookingCauldronRecipes); List<CauldronRecipe> cauldronRecipes = rm.getAllRecipesFor(RecipeTypeRegistry.CAULDRON_RECIPE_TYPE.get()); registration.addRecipes(CauldronCategory.CAULDRON, cauldronRecipes); } @Override public ResourceLocation getPluginUid() { return new HerbalBrewsIdentifier("jei_plugin"); } @Override public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) { registration.addRecipeTransferHandler(TeaKettleGuiHandler.class, ScreenHandlerTypeRegistry.TEA_KETTLE_SCREEN_HANDLER.get(), TeaKettleCategory.TEA_KETTLE, 1, 6, 7, 36); registration.addRecipeTransferHandler(CauldronGuiHandler.class, ScreenHandlerTypeRegistry.CAULDRON_SCREEN_HANDLER.get(), CauldronCategory.CAULDRON, 1, 3, 5, 36); } @Override public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
package satisfyu.herbalbrews.compat.jei; @JeiPlugin public class HerbalBrewsJEIPlugin implements IModPlugin { @Override public void registerCategories(IRecipeCategoryRegistration registration) { registration.addRecipeCategories(new TeaKettleCategory(registration.getJeiHelpers().getGuiHelper())); registration.addRecipeCategories(new CauldronCategory(registration.getJeiHelpers().getGuiHelper())); } @Override public void registerRecipes(IRecipeRegistration registration) { RecipeManager rm = Objects.requireNonNull(Minecraft.getInstance().level).getRecipeManager(); List<TeaKettleRecipe> cookingCauldronRecipes = rm.getAllRecipesFor(RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get()); registration.addRecipes(TeaKettleCategory.TEA_KETTLE, cookingCauldronRecipes); List<CauldronRecipe> cauldronRecipes = rm.getAllRecipesFor(RecipeTypeRegistry.CAULDRON_RECIPE_TYPE.get()); registration.addRecipes(CauldronCategory.CAULDRON, cauldronRecipes); } @Override public ResourceLocation getPluginUid() { return new HerbalBrewsIdentifier("jei_plugin"); } @Override public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) { registration.addRecipeTransferHandler(TeaKettleGuiHandler.class, ScreenHandlerTypeRegistry.TEA_KETTLE_SCREEN_HANDLER.get(), TeaKettleCategory.TEA_KETTLE, 1, 6, 7, 36); registration.addRecipeTransferHandler(CauldronGuiHandler.class, ScreenHandlerTypeRegistry.CAULDRON_SCREEN_HANDLER.get(), CauldronCategory.CAULDRON, 1, 3, 5, 36); } @Override public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
registration.addRecipeCatalyst(ObjectRegistry.CAULDRON.get().asItem().getDefaultInstance(), CauldronCategory.CAULDRON);
6
2023-11-05 16:46:52+00:00
12k
AnhyDev/AnhyLingo
src/main/java/ink/anh/lingo/command/LingoCommand.java
[ { "identifier": "AnhyLingo", "path": "src/main/java/ink/anh/lingo/AnhyLingo.java", "snippet": "public class AnhyLingo extends JavaPlugin {\n\n private static AnhyLingo instance;\n \n private boolean isSpigot;\n private boolean isPaper;\n private boolean isFolia;\n private boolean hasPaperComponent;\n \n private GlobalManager globalManager;\n\n /**\n * Called when the plugin is loaded by the Bukkit system.\n * Sets the static instance for global access.\n */\n @Override\n public void onLoad() {\n instance = this;\n }\n\n /**\n * Called when the plugin is enabled.\n * Performs initial setup such as checking dependencies, determining server type,\n * initializing managers, and setting up commands and listeners.\n */\n @Override\n public void onEnable() {\n checkDepends(\"ProtocolLib\");\n checkServer();\n \n globalManager = GlobalManager.getManager(this);\n new PacketListenerManager().addListeners();\n new ListenerManager(this);\n this.getCommand(\"lingo\").setExecutor(new LingoCommand(this));\n }\n\n /**\n * Called when the plugin is disabled.\n * Currently, this method does not perform any specific actions.\n */\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n \n /**\n * Checks if the current server version is equal to or newer than a specified version.\n * \n * @param minorVersionToCheck The minor version to compare against.\n * @return true if the current server version is equal or newer than the specified version.\n */\n public static boolean isVersionOrNewer(int minorVersionToCheck) {\n String version = Bukkit.getBukkitVersion();\n String[] splitVersion = version.split(\"-\")[0].split(\"\\\\.\");\n\n int major = Integer.parseInt(splitVersion[0]);\n int minor = 0;\n\n if (splitVersion.length > 1) {\n minor = Integer.parseInt(splitVersion[1]);\n }\n\n return major == 1 && minor >= minorVersionToCheck;\n }\n\n /**\n * Checks the server for specific implementations like Spigot, Paper, or Folia.\n * Updates the respective boolean fields based on the server type.\n */\n private void checkServer() {\n try {\n Class.forName(\"org.bukkit.entity.Player$Spigot\");\n isSpigot = true;\n } catch (Throwable tr) {\n isSpigot = false;\n Logger.error(this, \"Console-Sender.Messages.Initialize.Require-Spigot\");\n return;\n }\n try {\n Class.forName(\"com.destroystokyo.paper.VersionHistoryManager$VersionData\");\n isPaper = true;\n try {\n Class.forName(\"io.papermc.paper.text.PaperComponents\");\n hasPaperComponent = true;\n } catch (Throwable tr) {\n hasPaperComponent = false;\n }\n } catch (Throwable tr) {\n isPaper = false;\n }\n try {\n Class.forName(\"io.papermc.paper.threadedregions.RegionizedServer\");\n isFolia = true;\n } catch (ClassNotFoundException e) {\n isFolia = false;\n }\n }\n\n /**\n * Checks for the presence of specified dependencies.\n * If any dependency is missing, the plugin is disabled.\n * \n * @param depends An array of plugin names to check for.\n * @return true if any dependency is missing.\n */\n private boolean checkDepends(String... depends) {\n boolean missingDepend = false;\n PluginManager pluginManager = Bukkit.getPluginManager();\n for (String depend : depends) {\n if (pluginManager.getPlugin(depend) == null) {\n Logger.error(this, \"Console-Sender.Messages.Initialize.Missing-Dependency \" + depend);\n missingDepend = true;\n }\n }\n if (missingDepend) {\n pluginManager.disablePlugin(instance);\n }\n return missingDepend;\n }\n\n /**\n * Gets the singleton instance of this plugin.\n * \n * @return The singleton instance of AnhyLingo.\n */\n public static AnhyLingo getInstance() {\n return instance;\n }\n\n /**\n * Gets the GlobalManager instance associated with this plugin.\n * \n * @return The GlobalManager instance.\n */\n public GlobalManager getGlobalManager() {\n return globalManager;\n }\n\n /**\n * Checks if the server is running Spigot.\n * \n * @return true if the server is Spigot.\n */\n public boolean isSpigot() {\n return isSpigot;\n }\n\n /**\n * Checks if the server is running Paper.\n * \n * @return true if the server is Paper.\n */\n public boolean isPaper() {\n return isPaper;\n }\n\n /**\n * Checks if the server is running Folia.\n * \n * @return true if the server is Folia.\n */\n public boolean isFolia() {\n return isFolia;\n }\n\n /**\n * Checks if the server has the PaperComponents feature.\n * \n * @return true if the server has PaperComponents.\n */\n public boolean hasPaperComponent() {\n return hasPaperComponent;\n }\n}" }, { "identifier": "GlobalManager", "path": "src/main/java/ink/anh/lingo/GlobalManager.java", "snippet": "public class GlobalManager extends LibraryManager {\n\n private static GlobalManager instance;\n\tprivate AnhyLingo lingoPlugin;\n \n private String pluginName;\n private String defaultLang;\n\t\n\tprivate LanguageManager langManager;\n private LanguageItemStack languageItemStack;\n \n private boolean debug;\n private boolean debugPacketShat;\n\n private boolean allowBrowsing;\n private boolean itemLingo;\n private boolean packetLingo;\n private boolean allowUpload;\n private boolean allowRemoval;\n\n private List<String> allowedDirectories;\n private List<String> allowedDirectoriesForDeletion;\n \n \n \t/**\n * Private constructor for singleton pattern.\n * Initializes the plugin and loads configuration.\n *\n * @param lingoPlugin The instance of AnhyLingo plugin.\n */\n\tprivate GlobalManager(AnhyLingo lingoPlugin) {\n\t\tsuper(lingoPlugin);\n\t\tthis.lingoPlugin = lingoPlugin;\n\t\tthis.saveDefaultConfig();\n\t\tthis.loadFields(lingoPlugin);\n\t}\n\n /**\n * Provides a synchronized method to get or create an instance of GlobalManager.\n * Ensures that only one instance of this class is created (singleton pattern).\n *\n * @param lingoPlugin The instance of AnhyLingo plugin.\n * @return The singleton instance of GlobalManager.\n */\n public static synchronized GlobalManager getManager(AnhyLingo lingoPlugin) {\n if (instance == null) {\n instance = new GlobalManager(lingoPlugin);\n }\n return instance;\n }\n \n /**\n * Gets the plugin instance associated with this GlobalManager.\n * This method is part of the implementation of the LibraryManager interface.\n *\n * @return The instance of the AnhyLingo plugin.\n */\n @Override\n public Plugin getPlugin() {\n return lingoPlugin;\n }\n\n /**\n * Gets the name of the plugin.\n * This method is part of the implementation of the LibraryManager interface.\n * The name is typically set in the plugin's configuration file and may include color codes.\n *\n * @return The name of the plugin.\n */\n @Override\n public String getPluginName() {\n return pluginName;\n }\n\n /**\n * Gets the LanguageManager instance for this plugin.\n * LanguageManager is responsible for handling language-specific functionalities.\n * This method is part of the implementation of the LibraryManager interface.\n *\n * @return The LanguageManager instance.\n */\n @Override\n public LanguageManager getLanguageManager() {\n return this.langManager;\n }\n\n /**\n * Gets the default language setting for the plugin.\n * This method is part of the implementation of the LibraryManager interface.\n * The default language is typically set in the plugin's configuration file.\n *\n * @return The default language code, e.g., \"en\" for English.\n */\n @Override\n public String getDefaultLang() {\n return defaultLang;\n }\n\n /**\n * Checks if the plugin is in debug mode.\n * When in debug mode, additional information might be logged for troubleshooting purposes.\n * This method is part of the implementation of the LibraryManager interface.\n *\n * @return true if the plugin is in debug mode, false otherwise.\n */\n @Override\n public boolean isDebug() {\n return debug;\n }\n\n /**\n * Gets the LanguageItemStack instance.\n *\n * @return The instance of LanguageItemStack.\n */\n public LanguageItemStack getLanguageItemStack() {\n \treturn languageItemStack;\n }\n\n /**\n * Checks if browsing is allowed within the plugin.\n * This setting determines whether users can browse through certain directories or files.\n *\n * @return true if browsing is allowed, false otherwise.\n */\n public boolean isAllowBrowsing() {\n return allowBrowsing;\n }\n\n /**\n * Checks if item lingo (language translation for items) is enabled.\n * When enabled, item names and descriptions will be translated based on the player's language setting.\n *\n * @return true if item lingo is enabled, false otherwise.\n */\n public boolean isItemLingo() {\n return itemLingo;\n }\n\n /**\n * Checks if packet lingo (language translation for packets) is enabled.\n * When enabled, certain packet-based texts (like chat) will be translated based on the player's language setting.\n *\n * @return true if packet lingo is enabled, false otherwise.\n */\n public boolean isPacketLingo() {\n return packetLingo;\n }\n\n /**\n * Checks if uploading files through the plugin is allowed.\n * This setting allows users to upload certain types of files to the server.\n *\n * @return true if file uploading is allowed, false otherwise.\n */\n public boolean isAllowUpload() {\n return allowUpload;\n }\n\n /**\n * Checks if removal of files or directories through the plugin is allowed.\n * This setting allows users to delete certain files or directories from the server.\n *\n * @return true if file or directory removal is allowed, false otherwise.\n */\n public boolean isAllowRemoval() {\n return allowRemoval;\n }\n\n /**\n * Checks if a given path is allowed based on the configured directories.\n *\n * @param path The path to check.\n * @return true if the path is within the allowed directories.\n */\n public boolean isPathAllowed(String path) {\n for (String allowedPath : allowedDirectories) {\n if (path.contains(allowedPath)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the list of allowed directories.\n *\n * @return A list of strings representing allowed directories.\n */\n public List<String> getAllowedDirectories() {\n return allowedDirectories;\n }\n\n /**\n * Checks if a path is allowed for deletion.\n *\n * @param path The path to check.\n * @return true if the path is within the allowed directories for deletion.\n */\n public boolean isPathDeleteAllowed(String path) {\n for (String allowedPath : allowedDirectoriesForDeletion) {\n if (path.contains(allowedPath)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the list of allowed directories for deletion.\n *\n * @return A list of strings representing allowed directories for deletion.\n */\n\tpublic List<String> getAllowedDirectoriesForDeletion() {\n\t\treturn allowedDirectoriesForDeletion;\n\t}\n \n /**\n * Loads plugin configuration fields from the config file.\n * Initializes the language and item stack managers.\n *\n * @param lingoPlugin The instance of AnhyLingo plugin.\n */\n private void loadFields(AnhyLingo lingoPlugin) {\n defaultLang = lingoPlugin.getConfig().getString(\"language\", \"en\");\n pluginName = StringUtils.colorize(lingoPlugin.getConfig().getString(\"plugin_name\", \"AnhyLingo\"));\n debug = lingoPlugin.getConfig().getBoolean(\"debug\", false);\n setLanguageManagers();\n\n allowBrowsing = lingoPlugin.getConfig().getBoolean(\"allow_browsing\", false);\n itemLingo = lingoPlugin.getConfig().getBoolean(\"item_lingo\", false);\n packetLingo = lingoPlugin.getConfig().getBoolean(\"packet_lingo\", false);\n allowUpload = lingoPlugin.getConfig().getBoolean(\"allow_upload\", false);\n debugPacketShat = lingoPlugin.getConfig().getBoolean(\"debug_packet_chat\", false);\n allowedDirectories = lingoPlugin.getConfig().getStringList(\"allowed_directories\");\n allowRemoval = lingoPlugin.getConfig().getBoolean(\"allow_removal\", false);\n allowedDirectoriesForDeletion = lingoPlugin.getConfig().getStringList(\"allowed_del_directories\");\n \n }\n\n /**\n * Ensures the default configuration file is saved.\n */\n private void saveDefaultConfig() {\n \tFile configFile = new File(lingoPlugin.getDataFolder(), \"config.yml\");\n if (!configFile.exists()) {\n \tlingoPlugin.getConfig().options().copyDefaults(true);\n \tlingoPlugin.saveDefaultConfig();\n }\n }\n\n /**\n * Sets or reloads language managers.\n */\n private void setLanguageManagers() {\n \t\n if (this.langManager == null) {\n this.langManager = LanguageSystemChat.getInstance(this);;\n } else {\n \tthis.langManager.reloadLanguages();\n }\n \n if (this.languageItemStack == null) {\n this.languageItemStack = LanguageItemStack.getInstance(this);;\n } else {\n \tthis.languageItemStack.reloadLanguages();\n }\n }\n\n /**\n * Reloads the plugin configuration and updates internal fields accordingly.\n *\n * @return true if the reload is successful.\n */\n\tpublic boolean reload() {\n\t\tBukkit.getScheduler().runTaskAsynchronously(lingoPlugin, () -> {\n\t try {\n\t \tsaveDefaultConfig();\n\t lingoPlugin.reloadConfig();\n\t loadFields(lingoPlugin);\n\t Logger.info(lingoPlugin, Translator.translateKyeWorld(instance, \"lingo_configuration_reloaded\" , new String[] {defaultLang}));\n\t } catch (Exception e) {\n\t e.printStackTrace();\n\t Logger.error(lingoPlugin, Translator.translateKyeWorld(instance, \"lingo_err_reloading_configuration \", new String[] {defaultLang}));\n\t }\n\t\t});\n return true;\n }\n\n /**\n * Provides a logo for the plugin in ASCII art form.\n *\n * @return A list of strings representing the ASCII art logo.\n */\n public static List<String> logo() {\n List<String> asciiArt = new ArrayList<>();\n\n // ASCII art logo creation logic\n asciiArt.add(\"\");\n asciiArt.add(\" ░█████╗░███╗░░██╗██╗░░██╗██╗░░░██╗██╗░░░░░██╗███╗░░██╗░██████╗░░█████╗░\");\n asciiArt.add(\" ██╔══██╗████╗░██║██║░░██║╚██╗░██╔╝██║░░░░░██║████╗░██║██╔════╝░██╔══██╗\");\n asciiArt.add(\" ███████║██╔██╗██║███████║░╚████╔╝░██║░░░░░██║██╔██╗██║██║░░██╗░██║░░██║\");\n asciiArt.add(\" ██╔══██║██║╚████║██╔══██║░░╚██╔╝░░██║░░░░░██║██║╚████║██║░░╚██╗██║░░██║\");\n asciiArt.add(\" ██║░░██║██║░╚███║██║░░██║░░░██║░░░███████╗██║██║░╚███║╚██████╔╝╚█████╔╝\");\n asciiArt.add(\" ╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░░╚═╝░░░╚═╝░░░╚══════╝╚═╝╚═╝░░╚══╝░╚═════╝░░╚════╝░\");\n asciiArt.add(\"\");\n\n return asciiArt;\n }\n\n /**\n * Checks if packet chat debugging is enabled.\n *\n * @return true if debug for packet chat is enabled.\n */\n public boolean isDebugPacketShat() {\n return debugPacketShat;\n }\n}" }, { "identifier": "Permissions", "path": "src/main/java/ink/anh/lingo/Permissions.java", "snippet": "public class Permissions {\n\n /**\n * Permission to access Lingo files \"anhylingo.file.lingo\".\n */\n public static final String FILE_LINGO = \"anhylingo.file.lingo\";\n\n /**\n * Permission to access other files \"anhylingo.file.other\".\n */\n public static final String FILE_OTHER = \"anhylingo.file.other\";\n\n /**\n * Permission to delete files \"anhylingo.file.delete\".\n */\n public static final String FILE_DELETE = \"anhylingo.file.delete\";\n\n /**\n * Permission to view directories \"anhylingo.file.view\".\n */\n public static final String DIR_VIEW = \"anhylingo.file.view\";\n\n /**\n * Permission to access information about items \"anhylingo.items.info\".\n */\n public static final String ITEMS_INFO = \"anhylingo.items.info\";\n\n /**\n * Permission to reload the plugin or its components \"anhylingo.reload\".\n */\n public static final String RELOAD = \"anhylingo.reload\";\n\n /**\n * Permission to set NBT (Named Binary Tag) data \"anhylingo.nbt.set\".\n */\n public static final String NBT_SET = \"anhylingo.nbt.set\";\n\n /**\n * Permission to list NBT data \"anhylingo.nbt.list\".\n */\n public static final String NBT_LIST = \"anhylingo.nbt.list\";\n\n /**\n * Permission to view information about NBT data \"anhylingo.nbt.info\".\n */\n public static final String NBT_INFO = \"anhylingo.nbt.info\";\n}" }, { "identifier": "DirectoryContents", "path": "src/main/java/ink/anh/lingo/file/DirectoryContents.java", "snippet": "public class DirectoryContents {\n\n\tprivate static GlobalManager globalManager;\n\t\n // Static initializer to obtain the GlobalManager instance from the AnhyLingo plugin.\n static {\n globalManager = AnhyLingo.getInstance().getGlobalManager();\n }\n\n /**\n * Lists the contents of a specified directory and sends the list to the CommandSender.\n * This method handles both files and directories, sorting them and presenting them in a user-friendly format.\n *\n * @param sender The CommandSender to whom the directory contents will be sent.\n * @param directoryPath The path to the directory whose contents are to be listed.\n */\n public static void listDirectoryContents(CommandSender sender, String directoryPath) {\n \tif (directoryPath.equals(\"0\")) directoryPath = \"\";\n \tString[] langs = (sender instanceof Player) ? LangUtils.getPlayerLanguage((Player) sender) : null;\n \tString pluginName = AnhyLingo.getInstance().getGlobalManager().getPluginName() + \": \";\n\n File directory = new File(AnhyLingo.getInstance().getServer().getWorldContainer(), \"plugins\" + File.separator + directoryPath);\n\n if (directory.exists() && directory.isDirectory()) {\n File[] fileList = directory.listFiles();\n\n if (fileList != null) {\n \tString iconFolder = \"📁 \";\n \tString iconFile = \"📄 \";\n // Сортування файлів та папок\n Arrays.sort(fileList, Comparator.comparing(File::isFile)\n .thenComparing(File::getName, String.CASE_INSENSITIVE_ORDER));\n\n \n Messenger.sendMessage(globalManager, sender, \"lingo_file_folder_contents \" + iconFolder + directoryPath, MessageType.IMPORTANT);\n for (File file : fileList) {\n if (file.isDirectory()) {\n \tMessenger.sendShowFolder(globalManager, sender, directoryPath, file.getName(), iconFolder, MessageType.IMPORTANT, langs);\n } else {\n \tMessenger.sendMessageSimple(globalManager, sender, file.getName(), iconFile, MessageType.ESPECIALLY);\n }\n }\n } else {\n \tsender.sendMessage(pluginName + Translator.translateKyeWorld(globalManager, \"lingo_err_folder_is_empty\", langs));\n }\n } else {\n \tsender.sendMessage(pluginName + Translator.translateKyeWorld(globalManager, \"lingo_err_folder_is_notexist \", langs));\n }\n }\n}" }, { "identifier": "FileProcessType", "path": "src/main/java/ink/anh/lingo/file/FileProcessType.java", "snippet": "public enum FileProcessType {\n /**\n * Represents a file operation that loads YAML files.\n */\n YAML_LOADER,\n\n /**\n * Represents a file operation that loads files in a simple format (not specifically YAML).\n */\n SIMPLE_LOADER,\n\n /**\n * Represents a file operation for deleting files.\n */\n FILE_DELETER\n}" }, { "identifier": "ItemLang", "path": "src/main/java/ink/anh/lingo/item/ItemLang.java", "snippet": "public class ItemLang {\n\n\tprivate String lang;\n\tprivate String name;\n\tprivate String[] lore;\n\n /**\n * Constructs an ItemLang with the specified name.\n *\n * @param name The name of the item.\n */\n\tpublic ItemLang(String name) {\n\t\tthis.name = name;\n\t}\n\n /**\n * Constructs an ItemLang with the specified name and lore.\n *\n * @param name The name of the item.\n * @param lore The lore (description) of the item.\n */\n\tpublic ItemLang(String name, String[] lore) {\n\t\tthis.name = name;\n\t\tthis.lore = lore;\n\t}\n\n // Getters and setters for name, lore, and language\n\n /**\n * Gets the name of the item.\n *\n * @return The name of the item.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets the lore (description) of the item.\n *\n * @return An array of strings representing the lore of the item. Each string is a line of lore.\n */\n public String[] getLore() {\n return lore;\n }\n\n /**\n * Sets the name of the item.\n *\n * @param name The new name to be set for the item.\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Sets the lore (description) of the item.\n *\n * @param lore An array of strings representing the new lore to be set for the item. Each string is a line of lore.\n */\n public void setLore(String[] lore) {\n this.lore = lore;\n }\n\n /**\n * Gets the language code associated with this item.\n *\n * @return The language code. For example, 'en' for English.\n */\n public String getLang() {\n return lang;\n }\n\n /**\n * Sets the language code for this item.\n *\n * @param lang The language code to be set. For example, 'en' for English.\n */\n public void setLang(String lang) {\n this.lang = lang;\n }\n\n /**\n * Generates a hash code for the ItemLang instance.\n *\n * @return The hash code.\n */\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + Arrays.hashCode(lore);\n\t\tresult = prime * result + Objects.hash(name);\n\t\treturn result;\n\t}\n\n /**\n * Compares this ItemLang instance with another object for equality.\n *\n * @param obj The object to compare with.\n * @return true if the specified object is equal to this ItemLang instance.\n */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tItemLang other = (ItemLang) obj;\n\t\treturn Arrays.equals(lore, other.lore) && Objects.equals(name, other.name);\n\t}\n\n /**\n * Returns a string representation of this ItemLang instance.\n * The string includes the item name and lore (if any), each on a new line.\n *\n * @return A string representation of the ItemLang instance.\n */\n\t@Override\n\tpublic String toString() {\n\t StringBuilder sb = new StringBuilder();\n\n\t // Додаємо ім'я\n\t sb.append(name).append(\"\\n\");\n\n\t // Додаємо кожен елемент лору з нового рядка і з відступом\n\t if (lore != null) {\n\t for (String line : lore) {\n\t sb.append(\" \").append(line).append(\"\\n\"); // два пробіли в якості відступу\n\t }\n\t }\n\n\t return sb.toString().trim(); // використовуємо trim(), щоб видалити зайвий рядок на кінці, якщо він є\n\t}\n}" }, { "identifier": "FileCommandProcessor", "path": "src/main/java/ink/anh/lingo/file/FileCommandProcessor.java", "snippet": "public class FileCommandProcessor {\n \n private AnhyLingo lingoPlugin;\n\n /**\n * Constructor for FileCommandProcessor.\n *\n * @param plugin The instance of AnhyLingo plugin.\n */\n public FileCommandProcessor(AnhyLingo plugin) {\n this.lingoPlugin = plugin;\n }\n\n /**\n * Processes file-related commands based on the specified FileProcessType.\n *\n * @param sender The command sender.\n * @param args Arguments of the command.\n * @param fileProcessType The type of file processing to perform.\n * @return true if the command was processed successfully, otherwise false.\n */\n public boolean processFile(CommandSender sender, String[] args, FileProcessType fileProcessType) {\n\n \tif (!isCommandAlloved(args[0])) {\n sendMessage(sender, \"lingo_err_not_alloved_config \", MessageType.WARNING);\n \t\treturn true;\n \t}\n \t\n String permission = getPermissionForFileType(fileProcessType);\n if (!sender.hasPermission(permission)) {\n sendMessage(sender, \"lingo_err_not_have_permission: \", MessageType.WARNING);\n return true;\n }\n\n if (args.length >= 3) {\n String url = args[1];\n String directoryPath = args[2];\n boolean isReplace = args.length >= 4 && Boolean.parseBoolean(args[3]);\n\n AbstractFileManager fileLoader = getFileManagerForType(fileProcessType);\n fileLoader.processingFile(sender, url, directoryPath, isReplace);\n sendMessage(sender, \"lingo_file_operation_initiated \" + directoryPath, MessageType.WARNING);\n } else {\n \tswitch (args[0].toLowerCase()) {\n case \"fl\":\n sendMessage(sender, \"lingo_err_command_format /lingo fl <url> <folder> [is_replaced]\", MessageType.WARNING);\n return true;\n case \"fo\":\n sendMessage(sender, \"lingo_err_command_format /lingo fo <url> <path> [is_replaced]\", MessageType.WARNING);\n return true;\n case \"fd\":\n sendMessage(sender, \"lingo_err_command_format /lingo fd <path> <file_name>\", MessageType.WARNING);\n return true;\n }\n }\n return true;\n }\n\n private String getPermissionForFileType(FileProcessType fileProcessType) {\n switch (fileProcessType) {\n case YAML_LOADER:\n return Permissions.FILE_LINGO;\n case SIMPLE_LOADER:\n return Permissions.FILE_OTHER;\n case FILE_DELETER:\n return Permissions.FILE_DELETE;\n default:\n return \"\";\n }\n }\n\n private void sendMessage(CommandSender sender, String message, MessageType type) {\n \tMessenger.sendMessage(lingoPlugin.getGlobalManager(), sender, message, type);\n }\n\n private AbstractFileManager getFileManagerForType(FileProcessType fileProcessType) {\n switch (fileProcessType) {\n case YAML_LOADER:\n return new YamlFileLoader(lingoPlugin);\n case SIMPLE_LOADER:\n return new SimpleFileLoader(lingoPlugin);\n case FILE_DELETER:\n return new SimpleFileDeleter(lingoPlugin);\n default:\n return null;\n }\n }\n\n private boolean isCommandAlloved(String arg0) {\n \tswitch (arg0.toLowerCase()) {\n case \"fl\":\n return lingoPlugin.getGlobalManager().isAllowUpload();\n case \"fo\":\n return lingoPlugin.getGlobalManager().isAllowUpload();\n case \"fd\":\n return lingoPlugin.getGlobalManager().isAllowRemoval();\n }\n\t\treturn false;\n }\n}" } ]
import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Map; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import ink.anh.api.lingo.Translator; import ink.anh.api.messages.MessageType; import ink.anh.api.messages.Messenger; import ink.anh.api.utils.LangUtils; import ink.anh.lingo.AnhyLingo; import ink.anh.lingo.GlobalManager; import ink.anh.lingo.Permissions; import ink.anh.lingo.file.DirectoryContents; import ink.anh.lingo.file.FileProcessType; import ink.anh.lingo.item.ItemLang; import net.md_5.bungee.api.ChatColor; import ink.anh.lingo.file.FileCommandProcessor;
7,904
package ink.anh.lingo.command; /** * Command executor for the 'lingo' command in the AnhyLingo plugin. * This class processes and executes various subcommands related to language settings and file management. */ public class LingoCommand implements CommandExecutor { private AnhyLingo lingoPlugin; private GlobalManager globalManager; /** * Constructor for the LingoCommand class. * * @param lingoPlugin The instance of AnhyLingo plugin. */ public LingoCommand(AnhyLingo lingoPlugin) { this.lingoPlugin = lingoPlugin; this.globalManager = lingoPlugin.getGlobalManager(); } /** * Executes the given command, returning its success. * * @param sender Source of the command. * @param cmd The command which was executed. * @param label Alias of the command which was used. * @param args Passed command arguments. * @return true if a valid command, otherwise false. */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { switch (args[0].toLowerCase()) { case "nbt": return new NBTSubCommand(lingoPlugin).execNBT(sender, args); case "items": return itemLang(sender, args); case "reload": return reload(sender); case "set": return setLang(sender, args); case "get": return getLang(sender); case "reset": return resetLang(sender); case "dir": return directory(sender, args); case "flingo": case "fl": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.YAML_LOADER); case "fother": case "fo": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.SIMPLE_LOADER); case "fdel": case "fd": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.FILE_DELETER); default: return false; } } return false; } private boolean directory(CommandSender sender, String[] args) { if (!lingoPlugin.getGlobalManager().isAllowBrowsing()) { sendMessage(sender, "lingo_err_not_alloved_config ", MessageType.WARNING); return true; }
package ink.anh.lingo.command; /** * Command executor for the 'lingo' command in the AnhyLingo plugin. * This class processes and executes various subcommands related to language settings and file management. */ public class LingoCommand implements CommandExecutor { private AnhyLingo lingoPlugin; private GlobalManager globalManager; /** * Constructor for the LingoCommand class. * * @param lingoPlugin The instance of AnhyLingo plugin. */ public LingoCommand(AnhyLingo lingoPlugin) { this.lingoPlugin = lingoPlugin; this.globalManager = lingoPlugin.getGlobalManager(); } /** * Executes the given command, returning its success. * * @param sender Source of the command. * @param cmd The command which was executed. * @param label Alias of the command which was used. * @param args Passed command arguments. * @return true if a valid command, otherwise false. */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { switch (args[0].toLowerCase()) { case "nbt": return new NBTSubCommand(lingoPlugin).execNBT(sender, args); case "items": return itemLang(sender, args); case "reload": return reload(sender); case "set": return setLang(sender, args); case "get": return getLang(sender); case "reset": return resetLang(sender); case "dir": return directory(sender, args); case "flingo": case "fl": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.YAML_LOADER); case "fother": case "fo": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.SIMPLE_LOADER); case "fdel": case "fd": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.FILE_DELETER); default: return false; } } return false; } private boolean directory(CommandSender sender, String[] args) { if (!lingoPlugin.getGlobalManager().isAllowBrowsing()) { sendMessage(sender, "lingo_err_not_alloved_config ", MessageType.WARNING); return true; }
int perm = checkPlayerPermissions(sender, Permissions.DIR_VIEW);
2
2023-11-10 00:35:39+00:00
12k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/modconfig/gui/DeviceConfigGUI.java
[ { "identifier": "MMM", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final Logger LOGGER = LogUtils.getLogger();\n // Set file path\n public static final String MMM_ROOT_PATH = Minecraft.getInstance().gameDirectory.getPath() + \"/mmm_data/\";\n\n // Create Device Controller object\n public static final DeviceController DEVICE_CONTROLLER = new DeviceController();\n // Create Survey Controller object\n public static final SurveyController SURVEY_CONTROLLER = new SurveyController();\n\n // Always start with the device config gui\n public static ConfigGUIType latestConfigGUI = ConfigGUIType.DEVICE;\n public static enum ConfigGUIType {\n SURVEY,\n DEVICE\n };\n\n public MMM() {\n // Register Config\n ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.SPEC, \"mmm-client-config.toml\");\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n\n // Create directory for data\n try {\n System.out.println(\"Creating directory: \" + MMM_ROOT_PATH);\n Files.createDirectories(Paths.get(MMM_ROOT_PATH));\n } catch (Exception e) {\n System.out.println(\"Error creating directory: \" + e.getMessage());\n }\n }\n\n @SubscribeEvent\n public void entityJoinLevelEvent(EntityJoinLevelEvent event) {\n // Initialize devices\n DEVICE_CONTROLLER.initDevices();\n }\n\n}" }, { "identifier": "Config", "path": "src/main/java/io/github/mmm/modconfig/Config.java", "snippet": "public class Config {\n\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static final ForgeConfigSpec.ConfigValue<Boolean> LIDAR1_SWITCH;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_HORIZONTAL_SCANS_PER_RADIUS;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_VERTICAL_SCANS_PER_RADIUS;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR1_MEASUREMENT_FREQUENCY_IN_HZ;\n\n public static final ForgeConfigSpec.ConfigValue<Boolean> LIDAR2_SWITCH;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_HORIZONTAL_SCANS_PER_RADIUS;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_VERTICAL_SCANS_PER_RADIUS;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR2_MEASUREMENT_FREQUENCY_IN_HZ;\n\n public static final ForgeConfigSpec.ConfigValue<Boolean> LIDAR3_SWITCH;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_HORIZONTAL_SCANS_PER_RADIUS;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_VERTICAL_SCANS_PER_RADIUS;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_MAXIMUM_MEASUREMENT_DISTANCE;\n public static final ForgeConfigSpec.ConfigValue<Integer> LIDAR3_MEASUREMENT_FREQUENCY_IN_HZ;\n\n public static final ForgeConfigSpec.ConfigValue<Boolean> IMU1_SWITCH;\n public static final ForgeConfigSpec.ConfigValue<Boolean> IMU1_CONSIDER_GRAVITY;\n public static final ForgeConfigSpec.ConfigValue<Integer> IMU1_YAW_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> IMU1_PITCH_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> IMU1_ROLL_OFFSET_FROM_POV_IN_DEG;\n public static final ForgeConfigSpec.ConfigValue<Integer> IMU1_MEAUREMENT_FREQUENCY_IN_HZ;\n\n public static final ForgeConfigSpec.ConfigValue<Boolean> MULTITHREAD_SWITCH;\n public static final ForgeConfigSpec.ConfigValue<Integer> THREAD_COUNT_MULTIPLIER;\n public static final ForgeConfigSpec.ConfigValue<Integer> SAVE_INTERVAL;\n public static final ForgeConfigSpec.ConfigValue<Boolean> TICK_TIME_WARNING;\n public static final ForgeConfigSpec.ConfigValue<Integer> TICK_TIME_WARNING_TOLERANCE;\n\n static {\n BUILDER.push(\"mmm_config\");\n MULTITHREAD_SWITCH = BUILDER.comment(\"Activate/Deactivate Multithreading (active = true, inactive = false)\")\n .define(\"multithread_switch\", true);\n THREAD_COUNT_MULTIPLIER = BUILDER.comment(\"Multiplier for the amount of Threads. Default is 1, resulting in 1*LOGICAL_CORES_AMOUNT Threads\")\n .define(\"thread_count_multiplier\", 4);\n SAVE_INTERVAL = BUILDER.comment(\"Interval in ticks (1 tick usually takes 50ms) in which the data is saved to the file\")\n .define(\"save_interval\", 20*60*5); // 20 ticks * 60 seconds * 5 minutes = 5 minutes\n TICK_TIME_WARNING = BUILDER.comment(\"Activate/Deactivate Tick Time Warning (active = true, inactive = false)\")\n .define(\"tick_time_warning\", false);\n TICK_TIME_WARNING_TOLERANCE = BUILDER.comment(\"Tolerance for the Tick Time Warning in MS. Default Tick Time is 50ms, this means a warning will appear when the Tick Time is longer than 50ms + tolerance.\")\n .define(\"tick_time_warning_tolerance\", 5);\n\n BUILDER.push(\"lidar1\");\n LIDAR1_SWITCH = BUILDER.comment(\"Activate/Deactivate LIDAR Sensor lidar1 (active = true, inactive = false)\")\n .define(\"lidar1_switch\", true);\n LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG = BUILDER.comment(\"Horizontal Scanning Radius in Degrees for LIDAR Sensor lidar1\")\n .define(\"lidar1_horizontal_scanning_radius_in_deg\", 180);\n LIDAR1_HORIZONTAL_SCANS_PER_RADIUS = BUILDER.comment(\"Horizontal Scans per Radius for LIDAR Sensor lidar1\")\n .define(\"lidar1_horizontal_scans_per_radius\", 180);\n LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG = BUILDER.comment(\"Vertical Scanning Radius in Degrees for LIDAR Sensor lidar1 (set it to 0 if Lidar should be 2D)\")\n .define(\"lidar1_vertical_scanning_radius_in_deg\", 60);\n LIDAR1_VERTICAL_SCANS_PER_RADIUS = BUILDER.comment(\"Vertical Scans per Radius for LIDAR Sensor lidar1 (set it to 0 if Lidar should be 2D)\")\n .define(\"lidar1_vertical_scans_per_radius\", 60);\n LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Yaw Offset from POV in Degrees for LIDAR Sensor lidar1\")\n .define(\"lidar1_yaw_offset_from_pov_in_deg\", 0);\n LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Pitch Offset from POV in Degrees for LIDAR Sensor lidar1\")\n .define(\"lidar1_pitch_offset_from_pov_in_deg\", 0);\n LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Roll Offset from POV in Degrees for LIDAR Sensor lidar1\")\n .define(\"lidar1_roll_offset_from_pov_in_deg\", 0);\n LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE = BUILDER.comment(\"Maximum Measurement Distance in Meters for LIDAR Sensor lidar1\")\n .define(\"lidar1_maximum_measurement_distance\", 10);\n LIDAR1_MEASUREMENT_FREQUENCY_IN_HZ = BUILDER.comment(\"Measurement Frequency in Hz for LIDAR Sensor lidar1 (allowed are: 1, 2, 4, 5, 10, 20)\")\n .define(\"lidar1_measurement_frequency_in_hz\", 10);\n BUILDER.pop();\n\n BUILDER.push(\"lidar2\");\n LIDAR2_SWITCH = BUILDER.comment(\"Activate/Deactivate LIDAR Sensor lidar2 (active = true, inactive = false)\")\n .define(\"lidar2_switch\", true);\n LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG = BUILDER.comment(\"Horizontal Scanning Radius in Degrees for LIDAR Sensor lidar2\")\n .define(\"lidar2_horizontal_scanning_radius_in_deg\", 360);\n LIDAR2_HORIZONTAL_SCANS_PER_RADIUS = BUILDER.comment(\"Horizontal Scans per Radius for LIDAR Sensor lidar2\")\n .define(\"lidar2_horizontal_scans_per_radius\", 45);\n LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG = BUILDER.comment(\"Vertical Scanning Radius in Degrees for LIDAR Sensor lidar2 (set it to 0 if Lidar should be 2D)\")\n .define(\"lidar2_vertical_scanning_radius_in_deg\", 0);\n LIDAR2_VERTICAL_SCANS_PER_RADIUS = BUILDER.comment(\"Vertical Scans per Radius for LIDAR Sensor lidar2 (set it to 0 if Lidar should be 2D)\")\n .define(\"lidar2_vertical_scans_per_radius\", 0);\n LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Yaw Offset from POV in Degrees for LIDAR Sensor lidar2\")\n .define(\"lidar2_yaw_offset_from_pov_in_deg\", 0);\n LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Pitch Offset from POV in Degrees for LIDAR Sensor lidar2\")\n .define(\"lidar2_pitch_offset_from_pov_in_deg\", 0);\n LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Roll Offset from POV in Degrees for LIDAR Sensor lidar2\")\n .define(\"lidar2_roll_offset_from_pov_in_deg\", 0);\n LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE = BUILDER.comment(\"Maximum Measurement Distance in Meters for LIDAR Sensor lidar2\")\n .define(\"lidar2_maximum_measurement_distance\", 10);\n LIDAR2_MEASUREMENT_FREQUENCY_IN_HZ = BUILDER.comment(\"Measurement Frequency in Hz for LIDAR Sensor lidar2 (allowed are: 1, 2, 4, 5, 10, 20)\")\n .define(\"lidar2_measurement_frequency_in_hz\", 10);\n BUILDER.pop();\n\n BUILDER.push(\"lidar3\");\n LIDAR3_SWITCH = BUILDER.comment(\"Activate/Deactivate LIDAR Sensor lidar3 (active = true, inactive = false)\")\n .define(\"lidar3_switch\", true);\n LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG = BUILDER.comment(\"Horizontal Scanning Radius in Degrees for LIDAR Sensor lidar3\")\n .define(\"lidar3_horizontal_scanning_radius_in_deg\", 360);\n LIDAR3_HORIZONTAL_SCANS_PER_RADIUS = BUILDER.comment(\"Horizontal Scans per Radius for LIDAR Sensor lidar3\")\n .define(\"lidar3_horizontal_scans_per_radius\", 180);\n LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG = BUILDER.comment(\"Vertical Scanning Radius in Degrees for LIDAR Sensor lidar3 (set it to 0 if Lidar should be 2D)\")\n .define(\"lidar3_vertical_scanning_radius_in_deg\", 0);\n LIDAR3_VERTICAL_SCANS_PER_RADIUS = BUILDER.comment(\"Vertical Scans per Radius for LIDAR Sensor lidar3 (set it to 0 if Lidar should be 2D)\")\n .define(\"lidar3_vertical_scans_per_radius\", 0);\n LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Yaw Offset from POV in Degrees for LIDAR Sensor lidar3\")\n .define(\"lidar3_yaw_offset_from_pov_in_deg\", 0);\n LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Pitch Offset from POV in Degrees for LIDAR Sensor lidar3\")\n .define(\"lidar3_pitch_offset_from_pov_in_deg\", 0);\n LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Roll Offset from POV in Degrees for LIDAR Sensor lidar3\")\n .define(\"lidar3_roll_offset_from_pov_in_deg\", 0);\n LIDAR3_MAXIMUM_MEASUREMENT_DISTANCE = BUILDER.comment(\"Maximum Measurement Distance in Meters for LIDAR Sensor lidar3\")\n .define(\"lidar3_maximum_measurement_distance\", 10);\n LIDAR3_MEASUREMENT_FREQUENCY_IN_HZ = BUILDER.comment(\"Measurement Frequency in Hz for LIDAR Sensor lidar3 (allowed are: 1, 2, 4, 5, 10, 20)\")\n .define(\"lidar3_measurement_frequency_in_hz\", 10);\n BUILDER.pop();\n\n BUILDER.push(\"imu1\");\n IMU1_SWITCH = BUILDER.comment(\"Activate/Deactivate IMU Sensor imu1 (active = true, inactive = false)\")\n .define(\"imu1_switch\", true);\n IMU1_CONSIDER_GRAVITY = BUILDER.comment(\"Consider Gravity for IMU Sensor imu1 (true = consider, false = do not consider)\")\n .define(\"imu1_consider_gravity\", true);\n IMU1_YAW_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Yaw Offset from POV in Degrees for IMU Sensor imu1\")\n .define(\"imu1_yaw_offset_from_pov_in_deg\", 0);\n IMU1_PITCH_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Pitch Offset from POV in Degrees for IMU Sensor imu1\")\n .define(\"imu1_pitch_offset_from_pov_in_deg\", 0);\n IMU1_ROLL_OFFSET_FROM_POV_IN_DEG = BUILDER.comment(\"Roll Offset from POV in Degrees for IMU Sensor imu1\")\n .define(\"imu1_roll_offset_from_pov_in_deg\", 0);\n IMU1_MEAUREMENT_FREQUENCY_IN_HZ = BUILDER.comment(\"Measurement Frequency in Hz for IMU Sensor imu1 (allowed are: 1, 2, 4, 5, 10, 20)\")\n .define(\"imu1_measurement_frequency_in_hz\", 10);\n BUILDER.pop();\n\n BUILDER.pop();\n SPEC = BUILDER.build();\n }\n\n}" }, { "identifier": "LOGGER", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "public static final Logger LOGGER = LogUtils.getLogger();" }, { "identifier": "DEVICE_CONTROLLER", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "public static final DeviceController DEVICE_CONTROLLER = new DeviceController();" } ]
import io.github.mmm.MMM; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.Tooltip; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.FormattedText; import net.minecraftforge.common.ForgeConfigSpec; import static io.github.mmm.MMM.LOGGER; import static io.github.mmm.MMM.DEVICE_CONTROLLER; import static net.minecraft.util.CommonColors.GRAY; import static net.minecraft.util.CommonColors.WHITE;
7,985
null); Lidar3YawOffsetEditBox.setMaxLength(3); Lidar3YawOffsetEditBox.setValue(String.valueOf(Config.LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar3YawOffsetEditBox); Lidar3PitchOffsetEditBox = new EditBox( this.font, 350, lidar3Y, 30, 20, null); Lidar3PitchOffsetEditBox.setMaxLength(3); Lidar3PitchOffsetEditBox.setValue(String.valueOf(Config.LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar3PitchOffsetEditBox); Lidar3RollOffsetEditBox = new EditBox( this.font, 380, lidar3Y, 30, 20, null); Lidar3RollOffsetEditBox.setMaxLength(3); Lidar3RollOffsetEditBox.setValue(String.valueOf(Config.LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar3RollOffsetEditBox); Lidar3MaxMeasurementDistanceEditBox = new EditBox( this.font, 420, lidar3Y, 40, 20, null); Lidar3MaxMeasurementDistanceEditBox.setMaxLength(4); Lidar3MaxMeasurementDistanceEditBox.setValue(String.valueOf(Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE.get())); addRenderableWidget(Lidar3MaxMeasurementDistanceEditBox); // imu1 int imu1Y = 180; IMU1SwitchButton = Button.builder(getSwitchState(Config.IMU1_SWITCH.get()), this::handleImu1SwitchButtonPress) .bounds(50, imu1Y, 50, 20) .tooltip(Tooltip.create(getSwitchTooltip(Config.IMU1_SWITCH.get()))) .build(); addRenderableWidget(IMU1SwitchButton); IMU1FrequencyButton = Button.builder(Component.literal(Config.IMU1_MEAUREMENT_FREQUENCY_IN_HZ.get()+" Hz"), this::handleImu1FrequencyButtonPress) .bounds(110, imu1Y, 40, 20) .build(); addRenderableWidget(IMU1FrequencyButton); } private void handleSurveyButtonPress(Button button) { this.onClose(); Minecraft.getInstance().setScreen(new SurveyConfigGUI()); } private Component getSwitchState(boolean state) { return state ? SWITCH_ACTIVE : SWITCH_INACTIVE; } private Component getSwitchTooltip(boolean state) { return state ? SWITCH_TOOLTIP_DEACTIVATE : SWITCH_TOOLTIP_ACTIVATE; } @Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { this.renderDirtBackground(graphics); super.render(graphics, mouseX, mouseY, partialTick); // title graphics.drawCenteredString(this.font, TITLE, this.width/2, 17, WHITE); // lidar graphics.drawString(this.font, LIDAR, 10, 45, WHITE); graphics.drawString(this.font, STATUS, 60, 60, GRAY); graphics.drawString(this.font, FREQUENCY, 117, 60, GRAY); graphics.drawWordWrap(this.font, HORIZONTAL, 160, 55, 120, GRAY); graphics.drawWordWrap(this.font, VERTICAL, 240, 55, 120, GRAY); graphics.drawString(this.font, YAW_PITCH_ROLL, 320, 60, GRAY); graphics.drawString(this.font, RANGE, 420, 60, GRAY); graphics.drawString(this.font, LIDAR1_NAME, 10, 80, GRAY); graphics.drawString(this.font, LIDAR2_NAME, 10, 110, GRAY); graphics.drawString(this.font, LIDAR3_NAME, 10, 140, GRAY); // imu graphics.drawString(this.font, IMU, 10, 165, WHITE); graphics.drawString(this.font, IMU1NAME, 10, 185, GRAY); // bottom hints graphics.drawCenteredString(this.font, SAVEPATH, this.width/2, this.height-25, GRAY); } @Override public boolean isPauseScreen() { return true; } @Override public void onClose() { Minecraft.getInstance().player.displayClientMessage( Component.translatable("chat." + MMM.MODID + ".gui.save.success"), false ); // save config saveRadius(Config.LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG, Lidar1HorizontalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR1_HORIZONTAL_SCANS_PER_RADIUS, Lidar1HorizontalScansPerRadiusEditBox); saveRadius(Config.LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG, Lidar1VerticalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR1_VERTICAL_SCANS_PER_RADIUS, Lidar1VerticalScansPerRadiusEditBox); saveRadius(Config.LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG, Lidar1YawOffsetEditBox); saveRadius(Config.LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG, Lidar1PitchOffsetEditBox); saveRadius(Config.LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG, Lidar1RollOffsetEditBox); saveDistanceOrDensity(Config.LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE, Lidar1MaxMeasurementDistanceEditBox); saveRadius(Config.LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG, Lidar2HorizontalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR2_HORIZONTAL_SCANS_PER_RADIUS, Lidar2HorizontalScansPerRadiusEditBox); saveRadius(Config.LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG, Lidar2VerticalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR2_VERTICAL_SCANS_PER_RADIUS, Lidar2VerticalScansPerRadiusEditBox); saveRadius(Config.LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG, Lidar2YawOffsetEditBox); saveRadius(Config.LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG, Lidar2PitchOffsetEditBox); saveRadius(Config.LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG, Lidar2RollOffsetEditBox); saveDistanceOrDensity(Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE, Lidar2MaxMeasurementDistanceEditBox); saveRadius(Config.LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG, Lidar3HorizontalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR3_HORIZONTAL_SCANS_PER_RADIUS, Lidar3HorizontalScansPerRadiusEditBox); saveRadius(Config.LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG, Lidar3VerticalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR3_VERTICAL_SCANS_PER_RADIUS, Lidar3VerticalScansPerRadiusEditBox); saveRadius(Config.LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG, Lidar3YawOffsetEditBox); saveRadius(Config.LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG, Lidar3PitchOffsetEditBox); saveRadius(Config.LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG, Lidar3RollOffsetEditBox); saveDistanceOrDensity(Config.LIDAR3_MAXIMUM_MEASUREMENT_DISTANCE, Lidar3MaxMeasurementDistanceEditBox);
package io.github.mmm.modconfig.gui; public class DeviceConfigGUI extends Screen { private static final int[] validFrequencies = new int[]{1, 2, 4, 5, 10, 20}; // title private static final Component TITLE = Component.translatable("gui." + MMM.MODID + ".settings.device.title"); // save private static final Component EXIT = Component.translatable("gui." + MMM.MODID + ".settings.exit.name"); private static Button ExitButton; private static final Component EXIT_BUTTON_TOOLTIP = Component.translatable("gui." + MMM.MODID + ".settings.exit.tooltip"); // open different survey config private static final Component SURVEY = Component.translatable("gui." + MMM.MODID + ".settings.survey.name"); private static Button SurveyButton; private static final Component SURVEY_BUTTON_TOOLTIP = Component.translatable("gui." + MMM.MODID + ".settings.survey.tooltip"); // switch button private static final Component SWITCH_ACTIVE = Component.translatable("gui." + MMM.MODID + ".settings.switch.active"); private static final Component SWITCH_INACTIVE = Component.translatable("gui." + MMM.MODID + ".settings.switch.inactive"); private static final Component SWITCH_TOOLTIP_DEACTIVATE = Component.translatable("gui." + MMM.MODID + ".settings.switch.tooltip.deactivate"); private static final Component SWITCH_TOOLTIP_ACTIVATE = Component.translatable("gui." + MMM.MODID + ".settings.switch.tooltip.activate"); // lidar private static final Component LIDAR = Component.translatable("gui." + MMM.MODID + ".settings.lidar.title"); private static final Component STATUS = Component.translatable("gui." + MMM.MODID + ".settings.lidar.status"); private static final Component FREQUENCY = Component.translatable("gui." + MMM.MODID + ".settings.lidar.frequency"); private static final FormattedText HORIZONTAL = Component.translatable("gui." + MMM.MODID + ".settings.lidar.horizontal"); private static final FormattedText VERTICAL = Component.translatable("gui." + MMM.MODID + ".settings.lidar.vertical"); private static final Component YAW_PITCH_ROLL = Component.translatable("gui." + MMM.MODID + ".settings.lidar.offset"); private static final Component RANGE = Component.translatable("gui." + MMM.MODID + ".settings.lidar.range"); private static final Component LIDAR1_NAME = Component.translatable("gui." + MMM.MODID + ".settings.lidar.lidar1.name"); private static Button Lidar1SwitchButton; private static Button Lidar1FrequencyButton; private static EditBox Lidar1HorizontalScanRadiusEditBox; private static EditBox Lidar1HorizontalScansPerRadiusEditBox; private static EditBox Lidar1VerticalScanRadiusEditBox; private static EditBox Lidar1VerticalScansPerRadiusEditBox; private static EditBox Lidar1YawOffsetEditBox; private static EditBox Lidar1PitchOffsetEditBox; private static EditBox Lidar1RollOffsetEditBox; private static EditBox Lidar1MaxMeasurementDistanceEditBox; private static final Component LIDAR2_NAME = Component.translatable("gui." + MMM.MODID + ".settings.lidar.lidar2.name"); private static Button Lidar2SwitchButton; private static Button Lidar2FrequencyButton; private static EditBox Lidar2HorizontalScanRadiusEditBox; private static EditBox Lidar2HorizontalScansPerRadiusEditBox; private static EditBox Lidar2VerticalScanRadiusEditBox; private static EditBox Lidar2VerticalScansPerRadiusEditBox; private static EditBox Lidar2YawOffsetEditBox; private static EditBox Lidar2PitchOffsetEditBox; private static EditBox Lidar2RollOffsetEditBox; private static EditBox Lidar2MaxMeasurementDistanceEditBox; private static final Component LIDAR3_NAME = Component.translatable("gui." + MMM.MODID + ".settings.lidar.lidar3.name"); private static Button Lidar3SwitchButton; private static Button Lidar3FrequencyButton; private static EditBox Lidar3HorizontalScanRadiusEditBox; private static EditBox Lidar3HorizontalScansPerRadiusEditBox; private static EditBox Lidar3VerticalScanRadiusEditBox; private static EditBox Lidar3VerticalScansPerRadiusEditBox; private static EditBox Lidar3YawOffsetEditBox; private static EditBox Lidar3PitchOffsetEditBox; private static EditBox Lidar3RollOffsetEditBox; private static EditBox Lidar3MaxMeasurementDistanceEditBox; // imu private static final Component IMU = Component.translatable("gui." + MMM.MODID + ".settings.imu.title"); private static Button IMU1SwitchButton; private static Button IMU1FrequencyButton; private static final Component IMU1NAME = Component.translatable("gui." + MMM.MODID + ".settings.imu.imu1.name"); // bottom hints private static final Component SAVEPATH = Component.translatable("gui." + MMM.MODID + ".settings.savepath"); public DeviceConfigGUI() { // Use the super class' constructor to set the screen's title super(TITLE); } @Override protected void init() { super.init(); // survey SurveyButton = Button.builder(SURVEY, this::handleSurveyButtonPress) .bounds(10, 10, 140, 20) .tooltip(Tooltip.create(SURVEY_BUTTON_TOOLTIP)) .build(); addRenderableWidget(SurveyButton); // exit ExitButton = Button.builder(EXIT, this::handleExitButtonPress) .bounds(this.width-140-10, 10, 140, 20) .tooltip(Tooltip.create(EXIT_BUTTON_TOOLTIP)) .build(); addRenderableWidget(ExitButton); // lidar1 int lidar1Y = 75; Lidar1SwitchButton = Button.builder(getSwitchState(Config.LIDAR1_SWITCH.get()), this::handleLidar1SwitchButtonPress) .bounds(50, lidar1Y, 50, 20) .tooltip(Tooltip.create(getSwitchTooltip(Config.LIDAR1_SWITCH.get()))) .build(); addRenderableWidget(Lidar1SwitchButton); Lidar1FrequencyButton = Button.builder(Component.literal(Config.LIDAR1_MEASUREMENT_FREQUENCY_IN_HZ.get()+" Hz"), this::handleLidar1FrequencyButtonPress) .bounds(110, lidar1Y, 40, 20) .build(); addRenderableWidget(Lidar1FrequencyButton); Lidar1HorizontalScanRadiusEditBox = new EditBox( this.font, 160, lidar1Y, 30, 20, null); Lidar1HorizontalScanRadiusEditBox.setMaxLength(3); Lidar1HorizontalScanRadiusEditBox.setValue(String.valueOf(Config.LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get())); addRenderableWidget(Lidar1HorizontalScanRadiusEditBox); Lidar1HorizontalScansPerRadiusEditBox = new EditBox( this.font, 190, lidar1Y, 40, 20, null); Lidar1HorizontalScansPerRadiusEditBox.setMaxLength(4); Lidar1HorizontalScansPerRadiusEditBox.setValue(String.valueOf(Config.LIDAR1_HORIZONTAL_SCANS_PER_RADIUS.get())); addRenderableWidget(Lidar1HorizontalScansPerRadiusEditBox); Lidar1VerticalScanRadiusEditBox = new EditBox( this.font, 240, lidar1Y, 30, 20, null); Lidar1VerticalScanRadiusEditBox.setMaxLength(3); Lidar1VerticalScanRadiusEditBox.setValue(String.valueOf(Config.LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG.get())); addRenderableWidget(Lidar1VerticalScanRadiusEditBox); Lidar1VerticalScansPerRadiusEditBox = new EditBox( this.font, 270, lidar1Y, 40, 20, null); Lidar1VerticalScansPerRadiusEditBox.setMaxLength(4); Lidar1VerticalScansPerRadiusEditBox.setValue(String.valueOf(Config.LIDAR1_VERTICAL_SCANS_PER_RADIUS.get())); addRenderableWidget(Lidar1VerticalScansPerRadiusEditBox); Lidar1YawOffsetEditBox = new EditBox( this.font, 320, lidar1Y, 30, 20, null); Lidar1YawOffsetEditBox.setMaxLength(3); Lidar1YawOffsetEditBox.setValue(String.valueOf(Config.LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar1YawOffsetEditBox); Lidar1PitchOffsetEditBox = new EditBox( this.font, 350, lidar1Y, 30, 20, null); Lidar1PitchOffsetEditBox.setMaxLength(3); Lidar1PitchOffsetEditBox.setValue(String.valueOf(Config.LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar1PitchOffsetEditBox); Lidar1RollOffsetEditBox = new EditBox( this.font, 380, lidar1Y, 30, 20, null); Lidar1RollOffsetEditBox.setMaxLength(3); Lidar1RollOffsetEditBox.setValue(String.valueOf(Config.LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar1RollOffsetEditBox); Lidar1MaxMeasurementDistanceEditBox = new EditBox( this.font, 420, lidar1Y, 40, 20, null); Lidar1MaxMeasurementDistanceEditBox.setMaxLength(4); Lidar1MaxMeasurementDistanceEditBox.setValue(String.valueOf(Config.LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE.get())); addRenderableWidget(Lidar1MaxMeasurementDistanceEditBox); // lidar2 int lidar2Y = lidar1Y+30; Lidar2SwitchButton = Button.builder(getSwitchState(Config.LIDAR2_SWITCH.get()), this::handleLidar2SwitchButtonPress) .bounds(50, lidar2Y, 50, 20) .tooltip(Tooltip.create(getSwitchTooltip(Config.LIDAR2_SWITCH.get()))) .build(); addRenderableWidget(Lidar2SwitchButton); Lidar2FrequencyButton = Button.builder(Component.literal(Config.LIDAR2_MEASUREMENT_FREQUENCY_IN_HZ.get()+" Hz"), this::handleLidar2FrequencyButtonPress) .bounds(110, lidar2Y, 40, 20) .build(); addRenderableWidget(Lidar2FrequencyButton); Lidar2HorizontalScanRadiusEditBox = new EditBox( this.font, 160, lidar2Y, 30, 20, null); Lidar2HorizontalScanRadiusEditBox.setMaxLength(3); Lidar2HorizontalScanRadiusEditBox.setValue(String.valueOf(Config.LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get())); addRenderableWidget(Lidar2HorizontalScanRadiusEditBox); Lidar2HorizontalScansPerRadiusEditBox = new EditBox( this.font, 190, lidar2Y, 40, 20, null); Lidar2HorizontalScansPerRadiusEditBox.setMaxLength(4); Lidar2HorizontalScansPerRadiusEditBox.setValue(String.valueOf(Config.LIDAR2_HORIZONTAL_SCANS_PER_RADIUS.get())); addRenderableWidget(Lidar2HorizontalScansPerRadiusEditBox); Lidar2VerticalScanRadiusEditBox = new EditBox( this.font, 240, lidar2Y, 30, 20, null); Lidar2VerticalScanRadiusEditBox.setMaxLength(3); Lidar2VerticalScanRadiusEditBox.setValue(String.valueOf(Config.LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG.get())); addRenderableWidget(Lidar2VerticalScanRadiusEditBox); Lidar2VerticalScansPerRadiusEditBox = new EditBox( this.font, 270, lidar2Y, 40, 20, null); Lidar2VerticalScansPerRadiusEditBox.setMaxLength(4); Lidar2VerticalScansPerRadiusEditBox.setValue(String.valueOf(Config.LIDAR2_VERTICAL_SCANS_PER_RADIUS.get())); addRenderableWidget(Lidar2VerticalScansPerRadiusEditBox); Lidar2YawOffsetEditBox = new EditBox( this.font, 320, lidar2Y, 30, 20, null); Lidar2YawOffsetEditBox.setMaxLength(3); Lidar2YawOffsetEditBox.setValue(String.valueOf(Config.LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar2YawOffsetEditBox); Lidar2PitchOffsetEditBox = new EditBox( this.font, 350, lidar2Y, 30, 20, null); Lidar2PitchOffsetEditBox.setMaxLength(3); Lidar2PitchOffsetEditBox.setValue(String.valueOf(Config.LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar2PitchOffsetEditBox); Lidar2RollOffsetEditBox = new EditBox( this.font, 380, lidar2Y, 30, 20, null); Lidar2RollOffsetEditBox.setMaxLength(3); Lidar2RollOffsetEditBox.setValue(String.valueOf(Config.LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar2RollOffsetEditBox); Lidar2MaxMeasurementDistanceEditBox = new EditBox( this.font, 420, lidar2Y, 40, 20, null); Lidar2MaxMeasurementDistanceEditBox.setMaxLength(4); Lidar2MaxMeasurementDistanceEditBox.setValue(String.valueOf(Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE.get())); addRenderableWidget(Lidar2MaxMeasurementDistanceEditBox); // lidar3 int lidar3Y = lidar2Y+30; Lidar3SwitchButton = Button.builder(getSwitchState(Config.LIDAR3_SWITCH.get()), this::handleLidar3SwitchButtonPress) .bounds(50, lidar3Y, 50, 20) .tooltip(Tooltip.create(getSwitchTooltip(Config.LIDAR3_SWITCH.get()))) .build(); addRenderableWidget(Lidar3SwitchButton); Lidar3FrequencyButton = Button.builder(Component.literal(Config.LIDAR3_MEASUREMENT_FREQUENCY_IN_HZ.get()+" Hz"), this::handleLidar3FrequencyButtonPress) .bounds(110, lidar3Y, 40, 20) .build(); addRenderableWidget(Lidar3FrequencyButton); Lidar3HorizontalScanRadiusEditBox = new EditBox( this.font, 160, lidar3Y, 30, 20, null); Lidar3HorizontalScanRadiusEditBox.setMaxLength(3); Lidar3HorizontalScanRadiusEditBox.setValue(String.valueOf(Config.LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get())); addRenderableWidget(Lidar3HorizontalScanRadiusEditBox); Lidar3HorizontalScansPerRadiusEditBox = new EditBox( this.font, 190, lidar3Y, 40, 20, null); Lidar3HorizontalScansPerRadiusEditBox.setMaxLength(4); Lidar3HorizontalScansPerRadiusEditBox.setValue(String.valueOf(Config.LIDAR3_HORIZONTAL_SCANS_PER_RADIUS.get())); addRenderableWidget(Lidar3HorizontalScansPerRadiusEditBox); Lidar3VerticalScanRadiusEditBox = new EditBox( this.font, 240, lidar3Y, 30, 20, null); Lidar3VerticalScanRadiusEditBox.setMaxLength(3); Lidar3VerticalScanRadiusEditBox.setValue(String.valueOf(Config.LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG.get())); addRenderableWidget(Lidar3VerticalScanRadiusEditBox); Lidar3VerticalScansPerRadiusEditBox = new EditBox( this.font, 270, lidar3Y, 40, 20, null); Lidar3VerticalScansPerRadiusEditBox.setMaxLength(4); Lidar3VerticalScansPerRadiusEditBox.setValue(String.valueOf(Config.LIDAR3_VERTICAL_SCANS_PER_RADIUS.get())); addRenderableWidget(Lidar3VerticalScansPerRadiusEditBox); Lidar3YawOffsetEditBox = new EditBox( this.font, 320, lidar3Y, 30, 20, null); Lidar3YawOffsetEditBox.setMaxLength(3); Lidar3YawOffsetEditBox.setValue(String.valueOf(Config.LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar3YawOffsetEditBox); Lidar3PitchOffsetEditBox = new EditBox( this.font, 350, lidar3Y, 30, 20, null); Lidar3PitchOffsetEditBox.setMaxLength(3); Lidar3PitchOffsetEditBox.setValue(String.valueOf(Config.LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar3PitchOffsetEditBox); Lidar3RollOffsetEditBox = new EditBox( this.font, 380, lidar3Y, 30, 20, null); Lidar3RollOffsetEditBox.setMaxLength(3); Lidar3RollOffsetEditBox.setValue(String.valueOf(Config.LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG.get())); addRenderableWidget(Lidar3RollOffsetEditBox); Lidar3MaxMeasurementDistanceEditBox = new EditBox( this.font, 420, lidar3Y, 40, 20, null); Lidar3MaxMeasurementDistanceEditBox.setMaxLength(4); Lidar3MaxMeasurementDistanceEditBox.setValue(String.valueOf(Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE.get())); addRenderableWidget(Lidar3MaxMeasurementDistanceEditBox); // imu1 int imu1Y = 180; IMU1SwitchButton = Button.builder(getSwitchState(Config.IMU1_SWITCH.get()), this::handleImu1SwitchButtonPress) .bounds(50, imu1Y, 50, 20) .tooltip(Tooltip.create(getSwitchTooltip(Config.IMU1_SWITCH.get()))) .build(); addRenderableWidget(IMU1SwitchButton); IMU1FrequencyButton = Button.builder(Component.literal(Config.IMU1_MEAUREMENT_FREQUENCY_IN_HZ.get()+" Hz"), this::handleImu1FrequencyButtonPress) .bounds(110, imu1Y, 40, 20) .build(); addRenderableWidget(IMU1FrequencyButton); } private void handleSurveyButtonPress(Button button) { this.onClose(); Minecraft.getInstance().setScreen(new SurveyConfigGUI()); } private Component getSwitchState(boolean state) { return state ? SWITCH_ACTIVE : SWITCH_INACTIVE; } private Component getSwitchTooltip(boolean state) { return state ? SWITCH_TOOLTIP_DEACTIVATE : SWITCH_TOOLTIP_ACTIVATE; } @Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { this.renderDirtBackground(graphics); super.render(graphics, mouseX, mouseY, partialTick); // title graphics.drawCenteredString(this.font, TITLE, this.width/2, 17, WHITE); // lidar graphics.drawString(this.font, LIDAR, 10, 45, WHITE); graphics.drawString(this.font, STATUS, 60, 60, GRAY); graphics.drawString(this.font, FREQUENCY, 117, 60, GRAY); graphics.drawWordWrap(this.font, HORIZONTAL, 160, 55, 120, GRAY); graphics.drawWordWrap(this.font, VERTICAL, 240, 55, 120, GRAY); graphics.drawString(this.font, YAW_PITCH_ROLL, 320, 60, GRAY); graphics.drawString(this.font, RANGE, 420, 60, GRAY); graphics.drawString(this.font, LIDAR1_NAME, 10, 80, GRAY); graphics.drawString(this.font, LIDAR2_NAME, 10, 110, GRAY); graphics.drawString(this.font, LIDAR3_NAME, 10, 140, GRAY); // imu graphics.drawString(this.font, IMU, 10, 165, WHITE); graphics.drawString(this.font, IMU1NAME, 10, 185, GRAY); // bottom hints graphics.drawCenteredString(this.font, SAVEPATH, this.width/2, this.height-25, GRAY); } @Override public boolean isPauseScreen() { return true; } @Override public void onClose() { Minecraft.getInstance().player.displayClientMessage( Component.translatable("chat." + MMM.MODID + ".gui.save.success"), false ); // save config saveRadius(Config.LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG, Lidar1HorizontalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR1_HORIZONTAL_SCANS_PER_RADIUS, Lidar1HorizontalScansPerRadiusEditBox); saveRadius(Config.LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG, Lidar1VerticalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR1_VERTICAL_SCANS_PER_RADIUS, Lidar1VerticalScansPerRadiusEditBox); saveRadius(Config.LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG, Lidar1YawOffsetEditBox); saveRadius(Config.LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG, Lidar1PitchOffsetEditBox); saveRadius(Config.LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG, Lidar1RollOffsetEditBox); saveDistanceOrDensity(Config.LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE, Lidar1MaxMeasurementDistanceEditBox); saveRadius(Config.LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG, Lidar2HorizontalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR2_HORIZONTAL_SCANS_PER_RADIUS, Lidar2HorizontalScansPerRadiusEditBox); saveRadius(Config.LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG, Lidar2VerticalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR2_VERTICAL_SCANS_PER_RADIUS, Lidar2VerticalScansPerRadiusEditBox); saveRadius(Config.LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG, Lidar2YawOffsetEditBox); saveRadius(Config.LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG, Lidar2PitchOffsetEditBox); saveRadius(Config.LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG, Lidar2RollOffsetEditBox); saveDistanceOrDensity(Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE, Lidar2MaxMeasurementDistanceEditBox); saveRadius(Config.LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG, Lidar3HorizontalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR3_HORIZONTAL_SCANS_PER_RADIUS, Lidar3HorizontalScansPerRadiusEditBox); saveRadius(Config.LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG, Lidar3VerticalScanRadiusEditBox); saveDistanceOrDensity(Config.LIDAR3_VERTICAL_SCANS_PER_RADIUS, Lidar3VerticalScansPerRadiusEditBox); saveRadius(Config.LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG, Lidar3YawOffsetEditBox); saveRadius(Config.LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG, Lidar3PitchOffsetEditBox); saveRadius(Config.LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG, Lidar3RollOffsetEditBox); saveDistanceOrDensity(Config.LIDAR3_MAXIMUM_MEASUREMENT_DISTANCE, Lidar3MaxMeasurementDistanceEditBox);
DEVICE_CONTROLLER.initDevices();
3
2023-11-06 16:56:46+00:00
12k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleTankDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 73.17330064499293;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ANG_ACCEL = Math.toRadians(232.91784999999996);" }, { "identifier": "MAX_ANG_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ANG_VEL = Math.toRadians(232.91784999999996);" }, { "identifier": "MAX_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_VEL = 73.17330064499293;" }, { "identifier": "MOTOR_VELO_PID", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static PIDFCoefficients MOTOR_VELO_PID = new PIDFCoefficients(0, 0, 0,\n getMotorVelocityF(MAX_RPM / 60 * TICKS_PER_REV));" }, { "identifier": "RUN_USING_ENCODER", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static final boolean RUN_USING_ENCODER = false;" }, { "identifier": "TRACK_WIDTH", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double TRACK_WIDTH = 16.75; // in" }, { "identifier": "encoderTicksToInches", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double encoderTicksToInches(double ticks) {\n return WHEEL_RADIUS * 2 * Math.PI * GEAR_RATIO * ticks / TICKS_PER_REV;\n}" }, { "identifier": "kA", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double kA = 0;" }, { "identifier": "kStatic", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double kStatic = 0;" }, { "identifier": "kV", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double kV = 1.0 / rpmToVelocity(MAX_RPM);" }, { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> sequenceList) {\n if (sequenceList.size() == 0) throw new EmptySequenceException();\n\n this.sequenceList = Collections.unmodifiableList(sequenceList);\n }\n\n public Pose2d start() {\n return sequenceList.get(0).getStartPose();\n }\n\n public Pose2d end() {\n return sequenceList.get(sequenceList.size() - 1).getEndPose();\n }\n\n public double duration() {\n double total = 0.0;\n\n for (SequenceSegment segment : sequenceList) {\n total += segment.getDuration();\n }\n\n return total;\n }\n\n public SequenceSegment get(int i) {\n return sequenceList.get(i);\n }\n\n public int size() {\n return sequenceList.size();\n }\n}" }, { "identifier": "TrajectorySequenceBuilder", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequenceBuilder.java", "snippet": "public class TrajectorySequenceBuilder {\n private final double resolution = 0.25;\n\n private final TrajectoryVelocityConstraint baseVelConstraint;\n private final TrajectoryAccelerationConstraint baseAccelConstraint;\n\n private TrajectoryVelocityConstraint currentVelConstraint;\n private TrajectoryAccelerationConstraint currentAccelConstraint;\n\n private final double baseTurnConstraintMaxAngVel;\n private final double baseTurnConstraintMaxAngAccel;\n\n private double currentTurnConstraintMaxAngVel;\n private double currentTurnConstraintMaxAngAccel;\n\n private final List<SequenceSegment> sequenceSegments;\n\n private final List<TemporalMarker> temporalMarkers;\n private final List<DisplacementMarker> displacementMarkers;\n private final List<SpatialMarker> spatialMarkers;\n\n private Pose2d lastPose;\n\n private double tangentOffset;\n\n private boolean setAbsoluteTangent;\n private double absoluteTangent;\n\n private TrajectoryBuilder currentTrajectoryBuilder;\n\n private double currentDuration;\n private double currentDisplacement;\n\n private double lastDurationTraj;\n private double lastDisplacementTraj;\n\n public TrajectorySequenceBuilder(\n Pose2d startPose,\n Double startTangent,\n TrajectoryVelocityConstraint baseVelConstraint,\n TrajectoryAccelerationConstraint baseAccelConstraint,\n double baseTurnConstraintMaxAngVel,\n double baseTurnConstraintMaxAngAccel\n ) {\n this.baseVelConstraint = baseVelConstraint;\n this.baseAccelConstraint = baseAccelConstraint;\n\n this.currentVelConstraint = baseVelConstraint;\n this.currentAccelConstraint = baseAccelConstraint;\n\n this.baseTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.baseTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n sequenceSegments = new ArrayList<>();\n\n temporalMarkers = new ArrayList<>();\n displacementMarkers = new ArrayList<>();\n spatialMarkers = new ArrayList<>();\n\n lastPose = startPose;\n\n tangentOffset = 0.0;\n\n setAbsoluteTangent = (startTangent != null);\n absoluteTangent = startTangent != null ? startTangent : 0.0;\n\n currentTrajectoryBuilder = null;\n\n currentDuration = 0.0;\n currentDisplacement = 0.0;\n\n lastDurationTraj = 0.0;\n lastDisplacementTraj = 0.0;\n }\n\n public TrajectorySequenceBuilder(\n Pose2d startPose,\n TrajectoryVelocityConstraint baseVelConstraint,\n TrajectoryAccelerationConstraint baseAccelConstraint,\n double baseTurnConstraintMaxAngVel,\n double baseTurnConstraintMaxAngAccel\n ) {\n this(\n startPose, null,\n baseVelConstraint, baseAccelConstraint,\n baseTurnConstraintMaxAngVel, baseTurnConstraintMaxAngAccel\n );\n }\n\n public TrajectorySequenceBuilder lineTo(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineTo(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToConstantHeading(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToConstantHeading(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToLinearHeading(Pose2d endPose) {\n return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToLinearHeading(\n Pose2d endPose,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToSplineHeading(Pose2d endPose) {\n return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder lineToSplineHeading(\n Pose2d endPose,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeTo(Vector2d endPosition) {\n return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeTo(\n Vector2d endPosition,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder forward(double distance) {\n return addPath(() -> currentTrajectoryBuilder.forward(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder forward(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.forward(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder back(double distance) {\n return addPath(() -> currentTrajectoryBuilder.back(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder back(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.back(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeLeft(double distance) {\n return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeLeft(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeRight(double distance) {\n return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder strafeRight(\n double distance,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineTo(Vector2d endPosition, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineTo(\n Vector2d endPosition,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToConstantHeading(Vector2d endPosition, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToConstantHeading(\n Vector2d endPosition,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToLinearHeading(Pose2d endPose, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToLinearHeading(\n Pose2d endPose,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, velConstraint, accelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToSplineHeading(Pose2d endPose, double endHeading) {\n return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint));\n }\n\n public TrajectorySequenceBuilder splineToSplineHeading(\n Pose2d endPose,\n double endHeading,\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, velConstraint, accelConstraint));\n }\n\n private TrajectorySequenceBuilder addPath(AddPathCallback callback) {\n if (currentTrajectoryBuilder == null) newPath();\n\n try {\n callback.run();\n } catch (PathContinuityViolationException e) {\n newPath();\n callback.run();\n }\n\n Trajectory builtTraj = currentTrajectoryBuilder.build();\n\n double durationDifference = builtTraj.duration() - lastDurationTraj;\n double displacementDifference = builtTraj.getPath().length() - lastDisplacementTraj;\n\n lastPose = builtTraj.end();\n currentDuration += durationDifference;\n currentDisplacement += displacementDifference;\n\n lastDurationTraj = builtTraj.duration();\n lastDisplacementTraj = builtTraj.getPath().length();\n\n return this;\n }\n\n public TrajectorySequenceBuilder setTangent(double tangent) {\n setAbsoluteTangent = true;\n absoluteTangent = tangent;\n\n pushPath();\n\n return this;\n }\n\n private TrajectorySequenceBuilder setTangentOffset(double offset) {\n setAbsoluteTangent = false;\n\n this.tangentOffset = offset;\n this.pushPath();\n\n return this;\n }\n\n public TrajectorySequenceBuilder setReversed(boolean reversed) {\n return reversed ? this.setTangentOffset(Math.toRadians(180.0)) : this.setTangentOffset(0.0);\n }\n\n public TrajectorySequenceBuilder setConstraints(\n TrajectoryVelocityConstraint velConstraint,\n TrajectoryAccelerationConstraint accelConstraint\n ) {\n this.currentVelConstraint = velConstraint;\n this.currentAccelConstraint = accelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetConstraints() {\n this.currentVelConstraint = this.baseVelConstraint;\n this.currentAccelConstraint = this.baseAccelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) {\n this.currentVelConstraint = velConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetVelConstraint() {\n this.currentVelConstraint = this.baseVelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) {\n this.currentAccelConstraint = accelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetAccelConstraint() {\n this.currentAccelConstraint = this.baseAccelConstraint;\n\n return this;\n }\n\n public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) {\n this.currentTurnConstraintMaxAngVel = maxAngVel;\n this.currentTurnConstraintMaxAngAccel = maxAngAccel;\n\n return this;\n }\n\n public TrajectorySequenceBuilder resetTurnConstraint() {\n this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel;\n this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel;\n\n return this;\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) {\n return this.addTemporalMarker(currentDuration, callback);\n }\n\n public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) {\n return this.addTemporalMarker(currentDuration + offset, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) {\n return this.addTemporalMarker(0.0, time, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) {\n return this.addTemporalMarker(time -> scale * time + offset, callback);\n }\n\n public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) {\n this.temporalMarkers.add(new TemporalMarker(time, callback));\n return this;\n }\n\n public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) {\n this.spatialMarkers.add(new SpatialMarker(point, callback));\n return this;\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) {\n return this.addDisplacementMarker(currentDisplacement, callback);\n }\n\n public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) {\n return this.addDisplacementMarker(currentDisplacement + offset, callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) {\n return this.addDisplacementMarker(0.0, displacement, callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) {\n return addDisplacementMarker((displacement -> scale * displacement + offset), callback);\n }\n\n public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) {\n displacementMarkers.add(new DisplacementMarker(displacement, callback));\n\n return this;\n }\n\n public TrajectorySequenceBuilder turn(double angle) {\n return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel);\n }\n\n public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) {\n pushPath();\n\n MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile(\n new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0),\n new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0),\n maxAngVel,\n maxAngAccel\n );\n\n sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList()));\n\n lastPose = new Pose2d(\n lastPose.getX(), lastPose.getY(),\n Angle.norm(lastPose.getHeading() + angle)\n );\n\n currentDuration += turnProfile.duration();\n\n return this;\n }\n\n public TrajectorySequenceBuilder waitSeconds(double seconds) {\n pushPath();\n sequenceSegments.add(new WaitSegment(lastPose, seconds, Collections.emptyList()));\n\n currentDuration += seconds;\n return this;\n }\n\n public TrajectorySequenceBuilder addTrajectory(Trajectory trajectory) {\n pushPath();\n\n sequenceSegments.add(new TrajectorySegment(trajectory));\n return this;\n }\n\n private void pushPath() {\n if (currentTrajectoryBuilder != null) {\n Trajectory builtTraj = currentTrajectoryBuilder.build();\n sequenceSegments.add(new TrajectorySegment(builtTraj));\n }\n\n currentTrajectoryBuilder = null;\n }\n\n private void newPath() {\n if (currentTrajectoryBuilder != null)\n pushPath();\n\n lastDurationTraj = 0.0;\n lastDisplacementTraj = 0.0;\n\n double tangent = setAbsoluteTangent ? absoluteTangent : Angle.norm(lastPose.getHeading() + tangentOffset);\n\n currentTrajectoryBuilder = new TrajectoryBuilder(lastPose, tangent, currentVelConstraint, currentAccelConstraint, resolution);\n }\n\n public TrajectorySequence build() {\n pushPath();\n\n List<TrajectoryMarker> globalMarkers = convertMarkersToGlobal(\n sequenceSegments,\n temporalMarkers, displacementMarkers, spatialMarkers\n );\n\n return new TrajectorySequence(projectGlobalMarkersToLocalSegments(globalMarkers, sequenceSegments));\n }\n\n private List<TrajectoryMarker> convertMarkersToGlobal(\n List<SequenceSegment> sequenceSegments,\n List<TemporalMarker> temporalMarkers,\n List<DisplacementMarker> displacementMarkers,\n List<SpatialMarker> spatialMarkers\n ) {\n ArrayList<TrajectoryMarker> trajectoryMarkers = new ArrayList<>();\n\n // Convert temporal markers\n for (TemporalMarker marker : temporalMarkers) {\n trajectoryMarkers.add(\n new TrajectoryMarker(marker.getProducer().produce(currentDuration), marker.getCallback())\n );\n }\n\n // Convert displacement markers\n for (DisplacementMarker marker : displacementMarkers) {\n double time = displacementToTime(\n sequenceSegments,\n marker.getProducer().produce(currentDisplacement)\n );\n\n trajectoryMarkers.add(\n new TrajectoryMarker(\n time,\n marker.getCallback()\n )\n );\n }\n\n // Convert spatial markers\n for (SpatialMarker marker : spatialMarkers) {\n trajectoryMarkers.add(\n new TrajectoryMarker(\n pointToTime(sequenceSegments, marker.getPoint()),\n marker.getCallback()\n )\n );\n }\n\n return trajectoryMarkers;\n }\n\n private List<SequenceSegment> projectGlobalMarkersToLocalSegments(List<TrajectoryMarker> markers, List<SequenceSegment> sequenceSegments) {\n if (sequenceSegments.isEmpty()) return Collections.emptyList();\n\n markers.sort(Comparator.comparingDouble(TrajectoryMarker::getTime));\n\n int segmentIndex = 0;\n double currentTime = 0;\n\n for (TrajectoryMarker marker : markers) {\n SequenceSegment segment = null;\n\n double markerTime = marker.getTime();\n double segmentOffsetTime = 0;\n\n while (segmentIndex < sequenceSegments.size()) {\n SequenceSegment seg = sequenceSegments.get(segmentIndex);\n\n if (currentTime + seg.getDuration() >= markerTime) {\n segment = seg;\n segmentOffsetTime = markerTime - currentTime;\n break;\n } else {\n currentTime += seg.getDuration();\n segmentIndex++;\n }\n }\n if (segmentIndex >= sequenceSegments.size()) {\n segment = sequenceSegments.get(sequenceSegments.size()-1);\n segmentOffsetTime = segment.getDuration();\n }\n\n SequenceSegment newSegment = null;\n\n if (segment instanceof WaitSegment) {\n WaitSegment thisSegment = (WaitSegment) segment;\n \n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new WaitSegment(thisSegment.getStartPose(), thisSegment.getDuration(), newMarkers);\n } else if (segment instanceof TurnSegment) {\n TurnSegment thisSegment = (TurnSegment) segment;\n \n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new TurnSegment(thisSegment.getStartPose(), thisSegment.getTotalRotation(), thisSegment.getMotionProfile(), newMarkers);\n } else if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n List<TrajectoryMarker> newMarkers = new ArrayList<>(thisSegment.getTrajectory().getMarkers());\n newMarkers.add(new TrajectoryMarker(segmentOffsetTime, marker.getCallback()));\n\n newSegment = new TrajectorySegment(new Trajectory(thisSegment.getTrajectory().getPath(), thisSegment.getTrajectory().getProfile(), newMarkers));\n }\n\n sequenceSegments.set(segmentIndex, newSegment);\n }\n\n return sequenceSegments;\n }\n\n // Taken from Road Runner's TrajectoryGenerator.displacementToTime() since it's private\n // note: this assumes that the profile position is monotonic increasing\n private Double motionProfileDisplacementToTime(MotionProfile profile, double s) {\n double tLo = 0.0;\n double tHi = profile.duration();\n while (!(Math.abs(tLo - tHi) < 1e-6)) {\n double tMid = 0.5 * (tLo + tHi);\n if (profile.get(tMid).getX() > s) {\n tHi = tMid;\n } else {\n tLo = tMid;\n }\n }\n return 0.5 * (tLo + tHi);\n }\n\n private Double displacementToTime(List<SequenceSegment> sequenceSegments, double s) {\n double currentTime = 0.0;\n double currentDisplacement = 0.0;\n\n for (SequenceSegment segment : sequenceSegments) {\n if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n double segmentLength = thisSegment.getTrajectory().getPath().length();\n\n if (currentDisplacement + segmentLength > s) {\n double target = s - currentDisplacement;\n double timeInSegment = motionProfileDisplacementToTime(\n thisSegment.getTrajectory().getProfile(),\n target\n );\n\n return currentTime + timeInSegment;\n } else {\n currentDisplacement += segmentLength;\n currentTime += thisSegment.getTrajectory().duration();\n }\n } else {\n currentTime += segment.getDuration();\n }\n }\n\n return 0.0;\n }\n\n private Double pointToTime(List<SequenceSegment> sequenceSegments, Vector2d point) {\n class ComparingPoints {\n private final double distanceToPoint;\n private final double totalDisplacement;\n private final double thisPathDisplacement;\n\n public ComparingPoints(double distanceToPoint, double totalDisplacement, double thisPathDisplacement) {\n this.distanceToPoint = distanceToPoint;\n this.totalDisplacement = totalDisplacement;\n this.thisPathDisplacement = thisPathDisplacement;\n }\n }\n\n List<ComparingPoints> projectedPoints = new ArrayList<>();\n\n for (SequenceSegment segment : sequenceSegments) {\n if (segment instanceof TrajectorySegment) {\n TrajectorySegment thisSegment = (TrajectorySegment) segment;\n\n double displacement = thisSegment.getTrajectory().getPath().project(point, 0.25);\n Vector2d projectedPoint = thisSegment.getTrajectory().getPath().get(displacement).vec();\n double distanceToPoint = point.minus(projectedPoint).norm();\n\n double totalDisplacement = 0.0;\n\n for (ComparingPoints comparingPoint : projectedPoints) {\n totalDisplacement += comparingPoint.totalDisplacement;\n }\n\n totalDisplacement += displacement;\n\n projectedPoints.add(new ComparingPoints(distanceToPoint, displacement, totalDisplacement));\n }\n }\n\n ComparingPoints closestPoint = null;\n\n for (ComparingPoints comparingPoint : projectedPoints) {\n if (closestPoint == null) {\n closestPoint = comparingPoint;\n continue;\n }\n\n if (comparingPoint.distanceToPoint < closestPoint.distanceToPoint)\n closestPoint = comparingPoint;\n }\n\n return displacementToTime(sequenceSegments, closestPoint.thisPathDisplacement);\n }\n\n private interface AddPathCallback {\n void run();\n }\n}" }, { "identifier": "TrajectorySequenceRunner", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequenceRunner.java", "snippet": "@Config\npublic class TrajectorySequenceRunner {\n public static String COLOR_INACTIVE_TRAJECTORY = \"#4caf507a\";\n public static String COLOR_INACTIVE_TURN = \"#7c4dff7a\";\n public static String COLOR_INACTIVE_WAIT = \"#dd2c007a\";\n\n public static String COLOR_ACTIVE_TRAJECTORY = \"#4CAF50\";\n public static String COLOR_ACTIVE_TURN = \"#7c4dff\";\n public static String COLOR_ACTIVE_WAIT = \"#dd2c00\";\n\n public static int POSE_HISTORY_LIMIT = 100;\n\n private final TrajectoryFollower follower;\n\n private final PIDFController turnController;\n\n private final NanoClock clock;\n\n private TrajectorySequence currentTrajectorySequence;\n private double currentSegmentStartTime;\n private int currentSegmentIndex;\n private int lastSegmentIndex;\n\n private Pose2d lastPoseError = new Pose2d();\n\n List<TrajectoryMarker> remainingMarkers = new ArrayList<>();\n\n private final FtcDashboard dashboard;\n private final LinkedList<Pose2d> poseHistory = new LinkedList<>();\n\n private VoltageSensor voltageSensor;\n\n private List<Integer> lastDriveEncPositions, lastDriveEncVels, lastTrackingEncPositions, lastTrackingEncVels;\n\n public TrajectorySequenceRunner(\n TrajectoryFollower follower, PIDCoefficients headingPIDCoefficients, VoltageSensor voltageSensor,\n List<Integer> lastDriveEncPositions, List<Integer> lastDriveEncVels, List<Integer> lastTrackingEncPositions, List<Integer> lastTrackingEncVels\n ) {\n this.follower = follower;\n\n turnController = new PIDFController(headingPIDCoefficients);\n turnController.setInputBounds(0, 2 * Math.PI);\n\n this.voltageSensor = voltageSensor;\n\n this.lastDriveEncPositions = lastDriveEncPositions;\n this.lastDriveEncVels = lastDriveEncVels;\n this.lastTrackingEncPositions = lastTrackingEncPositions;\n this.lastTrackingEncVels = lastTrackingEncVels;\n\n clock = NanoClock.system();\n\n dashboard = FtcDashboard.getInstance();\n dashboard.setTelemetryTransmissionInterval(25);\n }\n\n public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {\n currentTrajectorySequence = trajectorySequence;\n currentSegmentStartTime = clock.seconds();\n currentSegmentIndex = 0;\n lastSegmentIndex = -1;\n }\n\n public @Nullable\n DriveSignal update(Pose2d poseEstimate, Pose2d poseVelocity) {\n Pose2d targetPose = null;\n DriveSignal driveSignal = null;\n\n TelemetryPacket packet = new TelemetryPacket();\n Canvas fieldOverlay = packet.fieldOverlay();\n\n SequenceSegment currentSegment = null;\n\n if (currentTrajectorySequence != null) {\n if (currentSegmentIndex >= currentTrajectorySequence.size()) {\n for (TrajectoryMarker marker : remainingMarkers) {\n marker.getCallback().onMarkerReached();\n }\n\n remainingMarkers.clear();\n\n currentTrajectorySequence = null;\n }\n\n if (currentTrajectorySequence == null)\n return new DriveSignal();\n\n double now = clock.seconds();\n boolean isNewTransition = currentSegmentIndex != lastSegmentIndex;\n\n currentSegment = currentTrajectorySequence.get(currentSegmentIndex);\n\n if (isNewTransition) {\n currentSegmentStartTime = now;\n lastSegmentIndex = currentSegmentIndex;\n\n for (TrajectoryMarker marker : remainingMarkers) {\n marker.getCallback().onMarkerReached();\n }\n\n remainingMarkers.clear();\n\n remainingMarkers.addAll(currentSegment.getMarkers());\n Collections.sort(remainingMarkers, (t1, t2) -> Double.compare(t1.getTime(), t2.getTime()));\n }\n\n double deltaTime = now - currentSegmentStartTime;\n\n if (currentSegment instanceof TrajectorySegment) {\n Trajectory currentTrajectory = ((TrajectorySegment) currentSegment).getTrajectory();\n\n if (isNewTransition)\n follower.followTrajectory(currentTrajectory);\n\n if (!follower.isFollowing()) {\n currentSegmentIndex++;\n\n driveSignal = new DriveSignal();\n } else {\n driveSignal = follower.update(poseEstimate, poseVelocity);\n lastPoseError = follower.getLastError();\n }\n\n targetPose = currentTrajectory.get(deltaTime);\n } else if (currentSegment instanceof TurnSegment) {\n MotionState targetState = ((TurnSegment) currentSegment).getMotionProfile().get(deltaTime);\n\n turnController.setTargetPosition(targetState.getX());\n\n double correction = turnController.update(poseEstimate.getHeading());\n\n double targetOmega = targetState.getV();\n double targetAlpha = targetState.getA();\n\n lastPoseError = new Pose2d(0, 0, turnController.getLastError());\n\n Pose2d startPose = currentSegment.getStartPose();\n targetPose = startPose.copy(startPose.getX(), startPose.getY(), targetState.getX());\n\n driveSignal = new DriveSignal(\n new Pose2d(0, 0, targetOmega + correction),\n new Pose2d(0, 0, targetAlpha)\n );\n\n if (deltaTime >= currentSegment.getDuration()) {\n currentSegmentIndex++;\n driveSignal = new DriveSignal();\n }\n } else if (currentSegment instanceof WaitSegment) {\n lastPoseError = new Pose2d();\n\n targetPose = currentSegment.getStartPose();\n driveSignal = new DriveSignal();\n\n if (deltaTime >= currentSegment.getDuration()) {\n currentSegmentIndex++;\n }\n }\n\n while (remainingMarkers.size() > 0 && deltaTime > remainingMarkers.get(0).getTime()) {\n remainingMarkers.get(0).getCallback().onMarkerReached();\n remainingMarkers.remove(0);\n }\n }\n\n poseHistory.add(poseEstimate);\n\n if (POSE_HISTORY_LIMIT > -1 && poseHistory.size() > POSE_HISTORY_LIMIT) {\n poseHistory.removeFirst();\n }\n\n final double NOMINAL_VOLTAGE = 12.0;\n double voltage = voltageSensor.getVoltage();\n if (driveSignal != null && !DriveConstants.RUN_USING_ENCODER) {\n driveSignal = new DriveSignal(\n driveSignal.getVel().times(NOMINAL_VOLTAGE / voltage),\n driveSignal.getAccel().times(NOMINAL_VOLTAGE / voltage)\n );\n }\n\n if (targetPose != null) {\n LogFiles.record(\n targetPose, poseEstimate, voltage,\n lastDriveEncPositions, lastDriveEncVels, lastTrackingEncPositions, lastTrackingEncVels\n );\n }\n\n packet.put(\"x\", poseEstimate.getX());\n packet.put(\"y\", poseEstimate.getY());\n packet.put(\"heading (deg)\", Math.toDegrees(poseEstimate.getHeading()));\n\n packet.put(\"xError\", getLastPoseError().getX());\n packet.put(\"yError\", getLastPoseError().getY());\n packet.put(\"headingError (deg)\", Math.toDegrees(getLastPoseError().getHeading()));\n\n draw(fieldOverlay, currentTrajectorySequence, currentSegment, targetPose, poseEstimate);\n\n dashboard.sendTelemetryPacket(packet);\n\n return driveSignal;\n }\n\n private void draw(\n Canvas fieldOverlay,\n TrajectorySequence sequence, SequenceSegment currentSegment,\n Pose2d targetPose, Pose2d poseEstimate\n ) {\n if (sequence != null) {\n for (int i = 0; i < sequence.size(); i++) {\n SequenceSegment segment = sequence.get(i);\n\n if (segment instanceof TrajectorySegment) {\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_INACTIVE_TRAJECTORY);\n\n DashboardUtil.drawSampledPath(fieldOverlay, ((TrajectorySegment) segment).getTrajectory().getPath());\n } else if (segment instanceof TurnSegment) {\n Pose2d pose = segment.getStartPose();\n\n fieldOverlay.setFill(COLOR_INACTIVE_TURN);\n fieldOverlay.fillCircle(pose.getX(), pose.getY(), 2);\n } else if (segment instanceof WaitSegment) {\n Pose2d pose = segment.getStartPose();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_INACTIVE_WAIT);\n fieldOverlay.strokeCircle(pose.getX(), pose.getY(), 3);\n }\n }\n }\n\n if (currentSegment != null) {\n if (currentSegment instanceof TrajectorySegment) {\n Trajectory currentTrajectory = ((TrajectorySegment) currentSegment).getTrajectory();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_ACTIVE_TRAJECTORY);\n\n DashboardUtil.drawSampledPath(fieldOverlay, currentTrajectory.getPath());\n } else if (currentSegment instanceof TurnSegment) {\n Pose2d pose = currentSegment.getStartPose();\n\n fieldOverlay.setFill(COLOR_ACTIVE_TURN);\n fieldOverlay.fillCircle(pose.getX(), pose.getY(), 3);\n } else if (currentSegment instanceof WaitSegment) {\n Pose2d pose = currentSegment.getStartPose();\n\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(COLOR_ACTIVE_WAIT);\n fieldOverlay.strokeCircle(pose.getX(), pose.getY(), 3);\n }\n }\n\n if (targetPose != null) {\n fieldOverlay.setStrokeWidth(1);\n fieldOverlay.setStroke(\"#4CAF50\");\n DashboardUtil.drawRobot(fieldOverlay, targetPose);\n }\n\n fieldOverlay.setStroke(\"#3F51B5\");\n DashboardUtil.drawPoseHistory(fieldOverlay, poseHistory);\n\n fieldOverlay.setStroke(\"#3F51B5\");\n DashboardUtil.drawRobot(fieldOverlay, poseEstimate);\n }\n\n public Pose2d getLastPoseError() {\n return lastPoseError;\n }\n\n public boolean isBusy() {\n return currentTrajectorySequence != null;\n }\n}" }, { "identifier": "LynxModuleUtil", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/LynxModuleUtil.java", "snippet": "public class LynxModuleUtil {\n\n private static final LynxFirmwareVersion MIN_VERSION = new LynxFirmwareVersion(1, 8, 2);\n\n /**\n * Parsed representation of a Lynx module firmware version.\n */\n public static class LynxFirmwareVersion implements Comparable<LynxFirmwareVersion> {\n public final int major;\n public final int minor;\n public final int eng;\n\n public LynxFirmwareVersion(int major, int minor, int eng) {\n this.major = major;\n this.minor = minor;\n this.eng = eng;\n }\n\n @Override\n public boolean equals(Object other) {\n if (other instanceof LynxFirmwareVersion) {\n LynxFirmwareVersion otherVersion = (LynxFirmwareVersion) other;\n return major == otherVersion.major && minor == otherVersion.minor &&\n eng == otherVersion.eng;\n } else {\n return false;\n }\n }\n\n @Override\n public int compareTo(LynxFirmwareVersion other) {\n int majorComp = Integer.compare(major, other.major);\n if (majorComp == 0) {\n int minorComp = Integer.compare(minor, other.minor);\n if (minorComp == 0) {\n return Integer.compare(eng, other.eng);\n } else {\n return minorComp;\n }\n } else {\n return majorComp;\n }\n }\n\n @Override\n public String toString() {\n return Misc.formatInvariant(\"%d.%d.%d\", major, minor, eng);\n }\n }\n\n /**\n * Retrieve and parse Lynx module firmware version.\n * @param module Lynx module\n * @return parsed firmware version\n */\n public static LynxFirmwareVersion getFirmwareVersion(LynxModule module) {\n String versionString = module.getNullableFirmwareVersionString();\n if (versionString == null) {\n return null;\n }\n\n String[] parts = versionString.split(\"[ :,]+\");\n try {\n // note: for now, we ignore the hardware entry\n return new LynxFirmwareVersion(\n Integer.parseInt(parts[3]),\n Integer.parseInt(parts[5]),\n Integer.parseInt(parts[7])\n );\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n /**\n * Exception indicating an outdated Lynx firmware version.\n */\n public static class LynxFirmwareVersionException extends RuntimeException {\n public LynxFirmwareVersionException(String detailMessage) {\n super(detailMessage);\n }\n }\n\n /**\n * Ensure all of the Lynx modules attached to the robot satisfy the minimum requirement.\n * @param hardwareMap hardware map containing Lynx modules\n */\n public static void ensureMinimumFirmwareVersion(HardwareMap hardwareMap) {\n Map<String, LynxFirmwareVersion> outdatedModules = new HashMap<>();\n for (LynxModule module : hardwareMap.getAll(LynxModule.class)) {\n LynxFirmwareVersion version = getFirmwareVersion(module);\n if (version == null || version.compareTo(MIN_VERSION) < 0) {\n for (String name : hardwareMap.getNamesOf(module)) {\n outdatedModules.put(name, version);\n }\n }\n }\n if (outdatedModules.size() > 0) {\n StringBuilder msgBuilder = new StringBuilder();\n msgBuilder.append(\"One or more of the attached Lynx modules has outdated firmware\\n\");\n msgBuilder.append(Misc.formatInvariant(\"Mandatory minimum firmware version for Road Runner: %s\\n\",\n MIN_VERSION.toString()));\n for (Map.Entry<String, LynxFirmwareVersion> entry : outdatedModules.entrySet()) {\n msgBuilder.append(Misc.formatInvariant(\n \"\\t%s: %s\\n\", entry.getKey(),\n entry.getValue() == null ? \"Unknown\" : entry.getValue().toString()));\n }\n throw new LynxFirmwareVersionException(msgBuilder.toString());\n }\n }\n}" } ]
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import static org.openftc.apriltag.ApriltagDetectionJNI.getPoseEstimate; import com.acmerobotics.roadrunner.drive.TankDrive; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,738
package org.firstinspires.ftc.teamcode.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner;
package org.firstinspires.ftc.teamcode.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner;
private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
6
2023-11-04 04:11:26+00:00
12k
InfantinoAndrea00/polimi-software-engineering-project-2022
src/main/java/it/polimi/ingsw/server/controller/ViewObserver.java
[ { "identifier": "ActionPhase1Move", "path": "src/main/java/it/polimi/ingsw/resources/ActionPhase1Move.java", "snippet": "public class ActionPhase1Move implements Serializable {\n private Color student;\n private Destination destination;\n private int islandId;\n\n private ActionPhase1Move(Color student, Destination destination, int islandId) {\n this.student = student;\n this.destination = destination;\n this.islandId = islandId;\n }\n\n public Destination getDestination() {\n return destination;\n }\n\n public Color getStudent() {\n return student;\n }\n\n public int getIslandId() {\n return islandId;\n }\n\n public static ActionPhase1Move onIsland(Color student, int islandId) {\n return new ActionPhase1Move(student, Destination.ISLAND, islandId);\n }\n public static ActionPhase1Move inDiningRoom(Color student) {\n return new ActionPhase1Move(student, Destination.DINING_ROOM, -1);\n }\n\n}" }, { "identifier": "GameState", "path": "src/main/java/it/polimi/ingsw/resources/GameState.java", "snippet": "public class GameState implements Serializable {\n private List<Player> players;\n private Board board;\n private Map<Integer, AssistantCard> cardsPlayed;\n\n private CharacterCard[] characterCards;\n private int remainingCoins;\n\n public GameState(Game game) {\n players = new ArrayList<>();\n board = new Board(game.getBoard());\n for(it.polimi.ingsw.server.model.Player p : game.getPlayers())\n players.add(new Player(p));\n\n for(Team t : game.getTeams()) {\n for(Player p : players)\n if(t.getPlayers().get(0) == p.id)\n p.school.towers = t.towers;\n }\n\n cardsPlayed = new HashMap<>();\n cardsPlayed.putAll(game.currentRound.getAssistantCardsPlayed());\n\n if(game.isExpertMode()) {\n characterCards = new CharacterCard[3];\n for(int i=0; i<3; i++)\n characterCards[i] = new CharacterCard(((ExpertGame) game).getCharacterCards()[i]);\n remainingCoins = ((ExpertGame) game).leftCoins;\n for(Player p : players)\n p.coins = ((ExpertPlayer) game.getPlayerById(p.id)).getCoins();\n }\n }\n\n public List<Player> getPlayers() {\n return players;\n }\n\n public Player getPlayerById(int id) {\n for(Player p : players)\n if (id == p.getId())\n return p;\n return null;\n }\n\n public Board getBoard() {\n return board;\n }\n\n public Map<Integer, AssistantCard> getCardsPlayed() {\n return cardsPlayed;\n }\n\n public CharacterCard[] getCharacterCards() {\n return characterCards;\n }\n\n public int getRemainingCoins() {\n return remainingCoins;\n }\n\n public class CharacterCard implements Serializable {\n int id;\n int cost;\n int remainingNoEntryTiles;\n List<Color> students;\n\n CharacterCard(it.polimi.ingsw.server.model.expert.CharacterCard c) {\n this.id = c.getId();\n this.cost = c.getCost();\n this.remainingNoEntryTiles = c.remainingNoEntryTiles;\n this.students = new ArrayList<>();\n this.students.addAll(c.getStudents());\n }\n\n public int getId() {\n return id;\n }\n\n public int getCost() {\n return cost;\n }\n\n public int getRemainingNoEntryTiles() {\n return remainingNoEntryTiles;\n }\n\n public List<Color> getStudents() {\n return students;\n }\n }\n public class Board implements Serializable {\n List<Island> islands;\n List<Cloud> clouds;\n Map<Color, Boolean> professors;\n\n Board (it.polimi.ingsw.server.model.Board board) {\n islands = new ArrayList<>();\n for(it.polimi.ingsw.server.model.IslandGroup i : board.getIslandGroups())\n islands.add(new Island(i));\n clouds = new ArrayList<>();\n for(it.polimi.ingsw.server.model.Cloud c : board.getClouds())\n clouds.add(new Cloud(c));\n professors = new HashMap<>();\n professors.putAll(board.professors);\n }\n\n public List<Island> getIslands() {\n return islands;\n }\n\n public List<Cloud> getClouds() {\n return clouds;\n }\n\n public Map<Color, Boolean> getProfessors() {\n return professors;\n }\n\n public class Cloud implements Serializable {\n int id;\n List<Color> students;\n\n Cloud(it.polimi.ingsw.server.model.Cloud c) {\n id = c.getId();\n students = new ArrayList<>(c.getStudents());\n }\n\n public int getId(){\n return id;\n }\n\n public List<Color> getStudents() {\n return students;\n }\n }\n public class Island implements Serializable {\n int id;\n int islandNumber;\n List<Color> students;\n boolean hasMotherNature;\n boolean hasNoEntryTile;\n TowerColor controlledBy;\n\n Island (it.polimi.ingsw.server.model.IslandGroup island) {\n id = island.getId();\n islandNumber = island.islandsNumber;\n students = new ArrayList<>(island.getStudents());\n hasMotherNature = island.hasMotherNature;\n hasNoEntryTile = island.hasNoEntryTile;\n controlledBy = island.controlledBy;\n }\n\n public int getId() {\n return id;\n }\n\n public int getIslandNumber() {\n return islandNumber;\n }\n\n public List<Color> getStudents() {\n return students;\n }\n\n public boolean isHasMotherNature() {\n return hasMotherNature;\n }\n\n public boolean isHasNoEntryTile() {\n return hasNoEntryTile;\n }\n\n public TowerColor getControlledBy() {\n return controlledBy;\n }\n }\n\n }\n public class Player implements Serializable {\n int id;\n School school;\n List<AssistantCard> deck;\n\n int coins;\n\n Player(it.polimi.ingsw.server.model.Player player) {\n id = player.getId();\n deck = new ArrayList<>(player.getDeck());\n school = new School(player.getSchool());\n }\n\n public int getId() {\n return id;\n }\n\n public School getSchool() {\n return school;\n }\n\n public List<AssistantCard> getDeck() {\n return deck;\n }\n\n public int getCoins() {\n return coins;\n }\n\n public class School implements Serializable {\n Map<Color, Integer> diningRoom;\n Map<Color, Boolean> professors;\n List<Color> entrance;\n int towers;\n\n School(it.polimi.ingsw.server.model.School school) {\n diningRoom = new HashMap<>(school.getDiningRoom());\n professors = new HashMap<>(school.professor);\n entrance = new ArrayList<>(school.getStudents());\n }\n\n public Map<Color, Boolean> getProfessors() {\n return professors;\n }\n\n public Map<Color, Integer> getDiningRoom() {\n return diningRoom;\n }\n\n public List<Color> getEntrance() {\n return entrance;\n }\n\n public int getTowers() {\n return towers;\n }\n }\n }\n}" }, { "identifier": "Message", "path": "src/main/java/it/polimi/ingsw/resources/Message.java", "snippet": "public class Message implements Serializable {\n private MessageCode message;\n private Object param1, param2;\n\n public Message(MessageCode message, Object param1, Object param2) {\n this.message = message;\n this.param1 = param1;\n this.param2 = param2;\n }\n\n public MessageCode getMessage() {\n return message;\n }\n\n public Object getParam1() {\n return param1;\n }\n\n public Object getParam2() {\n return param2;\n }\n}" }, { "identifier": "TowerColor", "path": "src/main/java/it/polimi/ingsw/resources/enumerators/TowerColor.java", "snippet": "public enum TowerColor {\n WHITE,\n BLACK,\n GREY\n}" }, { "identifier": "ClientHandler", "path": "src/main/java/it/polimi/ingsw/server/ClientHandler.java", "snippet": "public class ClientHandler implements Runnable\n{\n private Socket client;\n private ObjectOutputStream output;\n private ObjectInputStream input;\n\n ClientHandler(Socket client)\n {\n this.client = client;\n }\n\n public Socket getClient() { return client; }\n\n @Override\n public void run()\n {\n try {\n output = new ObjectOutputStream(client.getOutputStream());\n input = new ObjectInputStream(client.getInputStream());\n } catch (IOException e) {\n System.out.println(\"could not open connection to \" + client.getInetAddress());\n return;\n }\n\n System.out.println(\"Connected to \" + client.getInetAddress());\n\n try {\n handleClientConnection();\n } catch (IOException e) {\n System.out.println(\"client \" + client.getInetAddress() + \" connection dropped\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n try {\n client.close();\n } catch (IOException ignored) { }\n }\n\n private void handleClientConnection() throws IOException {\n try {\n while (true) {\n Object next = input.readObject();\n Message message = (Message) next;\n handleMessage(message);\n }\n } catch (ClassNotFoundException | ClassCastException e) {\n e.printStackTrace();\n }\n }\n\n public void sendResponseMessage(Message message) throws IOException\n {\n System.out.println(\"sending message: \" + message.getMessage());\n output.writeObject(message);\n }\n\n private void handleMessage(Message message) throws IOException {\n switch (message.getMessage()) {\n case START: {\n if(Server.creatingGame.get()) {\n sendResponseMessage(new Message(ADMIN_CLIENT, null, null));\n Server.creatingGame.set(false);\n }\n else\n sendResponseMessage(new Message(GUEST_CLIENT, null, null));\n break;\n }\n case EXPERT_MODE_AND_PLAYER_NUMBER: {\n Message response = Server.viewObserver.expertModeAndPlayerNumber((Boolean) message.getParam1(), (Integer) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case ADD_NEW_PLAYER: {\n Message response = Server.viewObserver.addNewPlayer((String) message.getParam1(), this);\n sendResponseMessage(response);\n break;\n }\n case ADD_PLAYER_IN_TEAM: {\n Message response = Server.viewObserver.addPlayerInTeam((Integer) message.getParam1(), (Integer) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case PLAY_ASSISTANT_CARD: {\n Message response = Server.viewObserver.playAssistantCard((Integer) message.getParam1(), (Integer) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case MOVE_STUDENTS: {\n System.out.println(\"message received\");\n Message response = Server.viewObserver.moveStudents((Integer) message.getParam1(), (List<ActionPhase1Move>) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case MOVE_MOTHER_NATURE: {\n Message response = Server.viewObserver.moveMotherNature((Integer) message.getParam1(), (Integer) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case CHOOSE_CLOUD_TILE: {\n Message response = Server.viewObserver.chooseCloudTile((Integer) message.getParam1(), (Integer) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case EXIT: {\n sendResponseMessage(new Message(ACK, null, null));\n break;\n }\n case PLAY_A_CHARACTER_CARD: {\n Message response = Server.viewObserver.playACharacterCard((Integer) message.getParam1(), (Integer) message.getParam2());\n sendResponseMessage(response);\n break;\n }\n case ACTIVATE_CHARACTER_CARD_EFFECT: {\n Message response = Server.viewObserver.activateCharacterCardEffect(message.getParam1(), message.getParam2());\n sendResponseMessage(response);\n break;\n }\n }\n }\n\n}" }, { "identifier": "Server", "path": "src/main/java/it/polimi/ingsw/server/Server.java", "snippet": "public class Server {\n public static final int PORT = 5555;\n public static ViewObserver viewObserver;\n public static AtomicBoolean creatingGame;\n public static Game game;\n\n public static void main(String[] args) {\n ServerSocket socket;\n creatingGame = new AtomicBoolean(true);\n viewObserver = new ViewObserver();\n try {\n socket = new ServerSocket(PORT);\n } catch (IOException e) {\n System.out.println(\"cannot open server socket\");\n System.exit(1);\n return;\n }\n\n while (true) {\n try {\n Socket client = socket.accept();\n ClientHandler clientHandler = new ClientHandler(client);\n Thread thread = new Thread(clientHandler, \"Eryantis_Server - \" + client.getInetAddress());\n thread.start();\n } catch (IOException e) {\n System.out.println(\"connection dropped\");\n }\n }\n }\n}" }, { "identifier": "ChooseCloudTile", "path": "src/main/java/it/polimi/ingsw/server/controller/states/ChooseCloudTile.java", "snippet": "public class ChooseCloudTile implements GameControllerState {\n public boolean mustEndRound;\n\n @Override\n public void nextState(GameController g) {\n if (mustEndRound)\n g.setState(new NextRoundOrEndGame());\n else\n g.setState(new MoveStudents());\n }\n\n /**\n * Class ChooseCloudTile constructor\n */\n public ChooseCloudTile() {\n mustEndRound = false;\n }\n\n @Override\n public void Action(Object o_playerId, Object o_cloudId) {\n List<Color> studentsInCloudChosen = new ArrayList<>(Server.game.getBoard().getCloudById((Integer)o_cloudId).getStudents());\n Server.game.getBoard().getCloudById((Integer)o_cloudId).removeStudents(studentsInCloudChosen);\n Server.game.getPlayerById((Integer) o_playerId).getSchool().addStudents(studentsInCloudChosen);\n }\n}" }, { "identifier": "MoveMotherNature", "path": "src/main/java/it/polimi/ingsw/server/controller/states/MoveMotherNature.java", "snippet": "public class MoveMotherNature implements GameControllerState {\n\n @Override\n public void nextState(GameController g) {\n if (checkEndConditions())\n g.setState(new EndGame());\n else\n g.setState(new ChooseCloudTile());\n }\n\n @Override\n public void Action(Object o_choice, Object null_o) {\n int islandWithMN = (Integer) o_choice;\n Server.game.getBoard().setMotherNatureIsland(islandWithMN);\n islandConquer(islandWithMN);\n }\n\n /**\n * method that change the owner of the island if possible\n * @param islandId island's identifier of the one in which mother nature has been moved to\n */\n public static void islandConquer(int islandId) {\n if(Server.game.getBoard().getIslandGroupById(islandId).hasNoEntryTile) {\n Server.game.getBoard().getIslandGroupById(islandId).hasNoEntryTile = false;\n for(CharacterCard c : ((ExpertGame) Server.game).getCharacterCards())\n if(c.getId() == 4)\n c.remainingNoEntryTiles++;\n }\n else {\n for (Team t : Server.game.getTeams()) {\n Server.game.getBoard().getIslandGroupById(islandId).setInfluence(t.towerColor, calculateInfluence(islandId, t));\n }\n int maxInfluence = 0;\n TowerColor strongestTeam = null;\n for (Team t : Server.game.getTeams()) {\n if (Server.game.getBoard().getIslandGroupById(islandId).getInfluence().get(t.towerColor) > maxInfluence) {\n maxInfluence = Server.game.getBoard().getIslandGroupById(islandId).getInfluence().get(t.towerColor);\n strongestTeam = t.towerColor;\n }\n }\n if(strongestTeam != null) {\n changeTowers(islandId, strongestTeam);\n mergeIsland(islandId);\n }\n }\n }\n\n /**\n * method that calculate influence on the island in which mother nature has been moved to\n * @param islandId identifier of the island(s) where mother nature is\n * @param team team that is calculating influence\n * @return the value of influence for the team\n */\n private static int calculateInfluence(int islandId, Team team){\n int influence = 0;\n if (team.towerColor == Server.game.getBoard().getIslandGroupById(islandId).controlledBy && !Server.game.currentRound.currentTurn.card6Played)\n influence += Server.game.getBoard().getIslandGroupById(islandId).islandsNumber;\n for (Color c : Color.values())\n for (Integer p: team.getPlayers())\n if (Server.game.getPlayerById(p).getSchool().professor.get(c) && Server.game.currentRound.currentTurn.card9Played != c)\n influence += Server.game.getBoard().getIslandGroupById(islandId).getStudentsByColor(c);\n if (team.getPlayers().contains(Server.game.currentRound.currentTurn.getPlayerId()) && Server.game.currentRound.currentTurn.card8Played)\n influence += 2;\n return influence;\n }\n\n /**\n * method that changes the towers after a conquest of the group of islands\n * @param islandId identifier of the conquered island\n * @param towerColor color of the player's tower that conquered the island(s)\n */\n private static void changeTowers(int islandId, TowerColor towerColor){\n if (Server.game.getBoard().getIslandGroupById(islandId).controlledBy != null) {\n Server.game.getTeamByTowerColor(Server.game.getBoard().getIslandGroupById(islandId).controlledBy).towers += Server.game.getBoard().getMotherNatureIsland().islandsNumber;\n }\n Server.game.getTeamByTowerColor(towerColor).towers -= Server.game.getBoard().getIslandGroupById(islandId).islandsNumber;\n Server.game.getBoard().getIslandGroupById(islandId).controlledBy = towerColor;\n }\n\n /**\n * method that checks if is the case and then joins two groups of island\n * @param islandId identifier of the conquered island(s)\n */\n private static void mergeIsland(int islandId){\n int previous, next;\n if (islandId == 0)\n previous = Server.game.getBoard().getIslandGroups().size() - 1;\n else\n previous = islandId - 1;\n if (islandId == Server.game.getBoard().getIslandGroups().size() - 1)\n next = 0;\n else\n next = islandId + 1;\n\n if (Server.game.getBoard().getIslandGroupById(islandId).controlledBy == Server.game.getBoard().getIslandGroupById(next).controlledBy)\n Server.game.getBoard().Join(islandId, next);\n\n if (islandId == 0)\n previous = Server.game.getBoard().getIslandGroups().size() - 1;\n if (Server.game.getBoard().getIslandGroupById(islandId).controlledBy == Server.game.getBoard().getIslandGroupById(previous).controlledBy)\n Server.game.getBoard().Join(previous, islandId);\n }\n\n /**\n * check if the end conditions are reached\n * @return true if the game is in end conditions, false otherwise\n */\n public boolean checkEndConditions(){\n for (Team p : Server.game.getTeams()){\n if (p.towers == 0)\n return true;\n }\n return Server.game.getBoard().threeIslandGroups();\n }\n\n}" }, { "identifier": "NextRoundOrEndGame", "path": "src/main/java/it/polimi/ingsw/server/controller/states/NextRoundOrEndGame.java", "snippet": "public class NextRoundOrEndGame implements GameControllerState {\n @Override\n public void nextState(GameController g) {\n if (checkEndConditions())\n g.setState(new EndGame());\n else\n g.setState(new RefillCloudTiles());\n }\n\n @Override\n public void Action(Object o1, Object o2) {\n Server.game.currentRound.roundCounter++;\n for(Cloud c : Server.game.getBoard().getClouds())\n System.out.println(\"Cloud: \" + c.getStudents() + \"\\n\");\n }\n\n /**\n * check if the end conditions are reached\n * @return true if the game is in end conditions, false otherwise\n */\n public boolean checkEndConditions(){\n if (Server.game.getBoard().getBag().isEmpty())\n return true;\n for (Player p : Server.game.getPlayers()){\n if (p.emptyDeck())\n return true;\n }\n return false;\n }\n\n}" }, { "identifier": "Cloud", "path": "src/main/java/it/polimi/ingsw/server/model/Cloud.java", "snippet": "public class Cloud extends StudentPosition implements Serializable {\n private int id;\n\n /**\n * constructor\n * @param playerNumber is the number of players playing the game\n * @param id is the single cloud's unique identifier\n */\n public Cloud(int playerNumber, int id) {\n super.init();\n this.id = id;\n if(playerNumber == 2 || playerNumber == 4)\n super.setMaxNumber(3);\n if(playerNumber == 3)\n super.setMaxNumber(4);\n }\n\n /**\n * request for the cloud's id\n * @return the cloud's id\n */\n public int getId() { return id; }\n}" }, { "identifier": "Player", "path": "src/main/java/it/polimi/ingsw/server/model/Player.java", "snippet": "public class Player {\n private String name;\n private int id;\n private List<AssistantCard> deck;\n private School school;\n\n /**\n * Check if the deck of a particular player is empty\n * @return true if the deck is empty\n */\n public boolean emptyDeck(){\n return deck.isEmpty();\n }\n\n /**\n * Class Player constructor\n * @param id player Id\n * @param name player nickname\n */\n public Player(int id, String name){\n this.id = id;\n this.name = name;\n deck = new ArrayList<>();\n for (int i = 1; i < 11; i++)\n deck.add(new AssistantCard(i));\n school = new School(id);\n }\n\n /**\n * Request for the player name (nickname)\n * @return player nickname\n */\n public String getName(){\n return name;\n }\n\n /**\n * Request for the player Id\n * @return player Id\n */\n public int getId(){\n return id;\n }\n\n /**\n * Request for the assistant cards list\n * @return deck made of assistant cards\n */\n public List<AssistantCard> getDeck(){\n return deck;\n }\n\n /**\n * Request for a particular assistant card by its speed value\n * @param speedValue related to a particular assistant card\n * @return Assistant card corresponding to that speed value\n */\n public AssistantCard getAssistantCardBySpeedValue(int speedValue){\n for(AssistantCard ac : deck)\n if (ac.getSpeedValue() == speedValue)\n return ac;\n return null;\n }\n\n /**\n * Request for remove an assistant card\n * @param speedValue the value on the top of the assistant card\n */\n public void removeAssistantCard(int speedValue) {\n deck.removeIf(a -> a.getSpeedValue() == speedValue);\n }\n\n /**\n * Request for the current player school\n * @return current player school\n */\n public School getSchool(){\n return school;\n }\n}" }, { "identifier": "PlayerTurn", "path": "src/main/java/it/polimi/ingsw/server/model/PlayerTurn.java", "snippet": "public class PlayerTurn {\n private int playerId;\n public boolean card2Played;\n public boolean card4Played;\n public boolean card6Played;\n public boolean card8Played;\n public Color card9Played;\n\n public boolean hasAlreadyPlayedACharacterCard;\n\n /**\n * Class PlayerTurn constructor\n * @param playerId that is playing the current turn\n */\n public PlayerTurn(int playerId){\n this.playerId = playerId;\n card2Played = false;\n card4Played = false;\n card6Played = false;\n card8Played = false;\n card9Played = null;\n hasAlreadyPlayedACharacterCard = false;\n }\n\n /**\n * Request for the current player Id\n * @return current player Id\n */\n public int getPlayerId(){\n return playerId;\n }\n\n}" }, { "identifier": "Team", "path": "src/main/java/it/polimi/ingsw/server/model/Team.java", "snippet": "public class Team {\n private List<Integer> players;\n private int id;\n public TowerColor towerColor;\n public int towers;\n\n /**\n * Class Team first constructor (2 or 3 players mode)\n * @param playerId player Id of a player who is part of that team\n * @param id that is the team identifier\n * @param playerNumber player numbers is playing in that game\n */\n public Team(int playerId, int id, int playerNumber){\n this.id = id;\n players = new ArrayList<>();\n towerColor = TowerColor.values()[id];\n players.add(playerId);\n if (playerNumber == 2 || playerNumber == 4)\n this.towers = 8;\n else\n this.towers = 6;\n }\n\n /**\n * Class Team second constructor (4 players mode)\n * @param id that is the team identifier\n */\n public Team(int id){\n this.id = id;\n players = new ArrayList<>();\n towerColor = TowerColor.values()[id];\n this.towers = 8;\n }\n\n /**\n * Request for add a palyer in that team\n * @param playerId of the new player to add\n */\n public void addPlayer(int playerId){\n players.add(playerId);\n }\n\n /**\n * Request for the list of the players in that team\n * @return players of that team\n */\n public List<Integer> getPlayers(){\n return players;\n }\n\n /**\n * Request for the team id\n * @return team id\n */\n public int getId(){\n return id;\n }\n\n /**\n * Check if all towers are placed\n * @return true if all towers of that team have been placed\n */\n public boolean allTowersPlaced(){\n return this.towers == 0;\n }\n}" }, { "identifier": "ExpertGame", "path": "src/main/java/it/polimi/ingsw/server/model/expert/ExpertGame.java", "snippet": "public class ExpertGame extends Game {\n public int leftCoins;\n private CharacterCard[] characterCards;\n\n /**\n * constructor\n * @param expertMode a boolean representing whether the game is in expert mode or not\n * @param playerNumber the number of players playing in the game\n */\n public ExpertGame (boolean expertMode, int playerNumber){\n super(expertMode, playerNumber);\n this.leftCoins = 20 - playerNumber;\n this.characterCards = new CharacterCard[3];\n List<Integer> cardPick = new ArrayList<>();\n for (int i = 0; i < 12 ; i++){\n cardPick.add(i);\n }\n for (int i = 0; i < 3 ; i++){\n int randPick = (int) (Math.random() * cardPick.size());\n int randId = cardPick.get(randPick);\n cardPick.remove(randPick);\n characterCards[i] = new CharacterCard(randId);\n }\n\n }\n\n /**\n * method that represents the fact that a player plays a character card\n * @param expertPlayer the player that wants to play a character card\n * @param characterCardNumber the id of the character card that the player wants to play\n */\n public void playCharacterCard(ExpertPlayer expertPlayer, int characterCardNumber){\n if (expertPlayer.getCoins() >= characterCards[characterCardNumber].getCost()) {\n expertPlayer.removeCoins(characterCards[characterCardNumber].getCost());\n leftCoins += characterCards[characterCardNumber].getCost();\n characterCards[characterCardNumber].increaseCost();\n }\n }\n\n /**\n * request for the 3 character cards in the game\n * @return the 3 character cards in the game\n */\n public CharacterCard[] getCharacterCards() {\n return characterCards;\n }\n}" }, { "identifier": "ExpertPlayer", "path": "src/main/java/it/polimi/ingsw/server/model/expert/ExpertPlayer.java", "snippet": "public class ExpertPlayer extends Player {\n private int coins;\n\n /**\n * Request for the coins held by that expert player\n * @return coins held by that player\n */\n public int getCoins(){\n return coins;\n }\n\n /**\n * Request to add a coin to that expert player\n */\n public void addCoin(){\n this.coins++;\n }\n\n /**\n * Request to remove coins from that expert player\n * @param numberOfCoins that represent coins held by that player\n */\n public void removeCoins(int numberOfCoins){\n this.coins -= numberOfCoins;\n }\n\n /**\n * Class ExpertPlayer constructor\n * @param id that is the expert player Id\n * @param name that is the expert player nickname\n */\n public ExpertPlayer(int id, String name){\n super(id, name);\n coins = 1;\n }\n}" }, { "identifier": "MessageCode", "path": "src/main/java/it/polimi/ingsw/resources/enumerators/MessageCode.java", "snippet": "public enum MessageCode {\n\n //Messages from client to server\n START,\n EXPERT_MODE_AND_PLAYER_NUMBER,\n ADD_NEW_PLAYER,\n ADD_PLAYER_IN_TEAM,\n PLAY_ASSISTANT_CARD,\n MOVE_STUDENTS,\n MOVE_MOTHER_NATURE,\n CHOOSE_CLOUD_TILE,\n\n //Messages from server to client\n PLAYERS_AND_MODE,\n START_GAME_SESSION,\n START_PLANNING_PHASE,\n START_ACTION_PHASE_1,\n START_ACTION_PHASE_2,\n START_ACTION_PHASE_3,\n MODEL_CHANGED,\n NEW_TURN,\n END_GAME,\n\n //Response Messages\n ACK,\n ADMIN_CLIENT,\n GUEST_CLIENT,\n CREATING_GAME,\n GAME_CREATED,\n PLAYER_ADDED,\n MAX_PLAYER_NUMBER_REACHED,\n FULL_TEAM,\n UNPLAYABLE_ASSISTANT_CARD,\n INVALID_MOVE,\n NOT_YOUR_TURN,\n EXIT,\n\n //Character cards\n PLAY_A_CHARACTER_CARD,\n ACTIVATE_CHARACTER_CARD_EFFECT,\n PLAYER_USED_CHARACTER_CARD,\n NOT_ENOUGH_COINS,\n ALREADY_PLAYED_A_CHARACTER_CARD,\n WAIT_FOR_CHARACTER_CARD_PARAMETERS,\n\n PING\n\n}" } ]
import it.polimi.ingsw.resources.ActionPhase1Move; import it.polimi.ingsw.resources.GameState; import it.polimi.ingsw.resources.Message; import it.polimi.ingsw.resources.enumerators.TowerColor; import it.polimi.ingsw.server.ClientHandler; import it.polimi.ingsw.server.Server; import it.polimi.ingsw.server.controller.states.ChooseCloudTile; import it.polimi.ingsw.server.controller.states.MoveMotherNature; import it.polimi.ingsw.server.controller.states.NextRoundOrEndGame; import it.polimi.ingsw.server.model.Cloud; import it.polimi.ingsw.server.model.Player; import it.polimi.ingsw.server.model.PlayerTurn; import it.polimi.ingsw.server.model.Team; import it.polimi.ingsw.server.model.expert.ExpertGame; import it.polimi.ingsw.server.model.expert.ExpertPlayer; import java.io.IOException; import java.net.Socket; import java.util.*; import static it.polimi.ingsw.resources.enumerators.MessageCode.*;
9,985
} return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param moves * @return */ public Message moveStudents(int playerId, List<ActionPhase1Move> moves) { System.out.println("Students movement\n" + Server.game.currentRound.getAssistantCardsPlayed()); if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, moves); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); c.sendResponseMessage(new Message(START_ACTION_PHASE_2, null, null)); } } catch (IOException e) { e.printStackTrace(); } gameController.nextState(); return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param islandId * @return */ public Message moveMotherNature(int playerId, int islandId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { int maxPossibleMoves = Server.game.currentRound.getAssistantCardsPlayed().get(playerId).getMoveValue(); if(Server.game.currentRound.currentTurn.card4Played) maxPossibleMoves += 2; int islandCounter = Server.game.getBoard().getMotherNatureIsland().getId(); for (int i = 0; i < maxPossibleMoves; i++) { if (islandCounter < Server.game.getBoard().getIslandGroups().size() - 1) islandCounter++; else islandCounter = 0; if(islandCounter == islandId) { System.out.println("Teams:" + Server.game.getTeamById(0).towerColor + " " + Server.game.getTeamById(1).towerColor); gameController.changeModel(islandId, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } if(!((MoveMotherNature) gameController.getState()).checkEndConditions()) { gameController.nextState(); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_3, null, null)); } } catch (IOException e) { e.printStackTrace(); } } else { gameController.nextState(); gameController.changeModel(null, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(END_GAME, Server.game.getTeamById(Server.game.winnerTeamId).towerColor, null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } } return new Message(INVALID_MOVE, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param cloudId * @return */ public Message chooseCloudTile(int playerId, int cloudId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, cloudId); try { for (ClientHandler c : clients) { if(counter == Server.game.getPlayerNumber()-1) Server.game.currentRound.resetCardsPlayed(); c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } counter++; if(counter < Server.game.getPlayerNumber()) { gameController.nextState(); Server.game.currentRound.currentTurn = new PlayerTurn(Server.game.currentRound.getOrder().get(counter)); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_1, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.currentTurn.getPlayerId(), null)); } } catch (IOException e) { e.printStackTrace(); } } else {
package it.polimi.ingsw.server.controller; /** * class that observe the view */ public class ViewObserver { private GameController gameController; private int counter; private boolean canAddPlayer; private CharacterCardHandler characterCardHandler; private Map<Integer, Socket> playersSockets; private List<ClientHandler> clients; public ViewObserver () { clients = new ArrayList<>(); playersSockets = new HashMap<>(); gameController = new GameController(); counter = 0; canAddPlayer = false; } /** * * @param expertMode true if the game is in expert mode, false otherwise * @param playerNumber number of players in the game * @return an acknowledgement message */ public Message expertModeAndPlayerNumber(boolean expertMode, int playerNumber) { gameController.changeModel(expertMode, playerNumber); gameController.nextState(); canAddPlayer = true; return new Message(GAME_CREATED, null, null); } /** * * @param playerName * @param client * @return */ public Message addNewPlayer(String playerName, ClientHandler client) { if(canAddPlayer) { if (Server.game.getPlayerNumber() > Server.game.getPlayers().size()) { gameController.changeModel(playerName, counter); playersSockets.put(counter, client.getClient()); clients.add(client); try { client.sendResponseMessage(new Message(PLAYER_ADDED, counter, Server.game.getPlayerNumber())); } catch (IOException e) { e.printStackTrace(); } counter++; if (Server.game.getPlayerNumber() == counter) { gameController.nextState(); counter = 0; Map<Integer, String> playerNames = new HashMap<>(); for(Player p : Server.game.getPlayers()) playerNames.put(p.getId(), p.getName()); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(PLAYERS_AND_MODE, playerNames, Server.game.isExpertMode())); } } catch (IOException e) { e.printStackTrace(); } if (Server.game.getPlayerNumber() != 4) { gameController.changeModel(null, null); System.out.println("Initialized game"); gameController.nextState(); gameController.changeModel(null, null); System.out.println("Refilled cloud tiles"); gameController.nextState(); Map<Integer, TowerColor> playersAssociation = new HashMap<>(); for (Player p : Server.game.getPlayers()) playersAssociation.put(p.getId(), Server.game.getTeamById(p.getId()).towerColor); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_GAME_SESSION, playersAssociation, new GameState(Server.game))); c.sendResponseMessage(new Message(START_PLANNING_PHASE, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.getOrder().get(0), null)); } } catch (IOException e) { e.printStackTrace(); } } } return new Message(ACK, null, null); } return new Message(MAX_PLAYER_NUMBER_REACHED, null, null); } return new Message(CREATING_GAME, null, null); } /** * * @param playerId * @param teamId * @return */ public Message addPlayerInTeam(int playerId, int teamId) { if(Server.game.getTeamById(teamId).getPlayers().size() < 2) { gameController.changeModel(playerId, teamId); counter++; if(counter == 4) { gameController.nextState(); counter = 0; gameController.changeModel(null, null); gameController.nextState(); gameController.changeModel(null, null); gameController.nextState(); Map<Integer, TowerColor> teamsAssociation = new HashMap<>(); for (Team t : Server.game.getTeams()) for (int id : t.getPlayers()) teamsAssociation.put(id, t.towerColor); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_GAME_SESSION, teamsAssociation, new GameState(Server.game))); c.sendResponseMessage(new Message(START_PLANNING_PHASE, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.getOrder().get(0), null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } return new Message(FULL_TEAM, null, null); } /** * * @param playerId * @param assistantCardSpeedValue * @return */ public Message playAssistantCard(int playerId, int assistantCardSpeedValue) { if(Server.game.currentRound.getOrder().get(counter) == playerId) { if(Server.game.currentRound.playableCards(Server.game.getPlayerById(playerId)).contains(assistantCardSpeedValue)) { gameController.changeModel(playerId, assistantCardSpeedValue); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } counter++; if(counter < Server.game.getPlayerNumber()) try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.getOrder().get(counter), null)); } } catch (IOException e) { e.printStackTrace(); } } else return new Message(UNPLAYABLE_ASSISTANT_CARD, null, null); if(counter == Server.game.getPlayerNumber()) { counter = 0; gameController.nextState(); gameController.changeModel(null, null); System.out.println("Establish round order\n" + Server.game.currentRound.getAssistantCardsPlayed()); gameController.nextState(); Server.game.currentRound.currentTurn = new PlayerTurn(Server.game.currentRound.getOrder().get(counter)); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_1, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.currentTurn.getPlayerId(), null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param moves * @return */ public Message moveStudents(int playerId, List<ActionPhase1Move> moves) { System.out.println("Students movement\n" + Server.game.currentRound.getAssistantCardsPlayed()); if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, moves); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); c.sendResponseMessage(new Message(START_ACTION_PHASE_2, null, null)); } } catch (IOException e) { e.printStackTrace(); } gameController.nextState(); return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param islandId * @return */ public Message moveMotherNature(int playerId, int islandId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { int maxPossibleMoves = Server.game.currentRound.getAssistantCardsPlayed().get(playerId).getMoveValue(); if(Server.game.currentRound.currentTurn.card4Played) maxPossibleMoves += 2; int islandCounter = Server.game.getBoard().getMotherNatureIsland().getId(); for (int i = 0; i < maxPossibleMoves; i++) { if (islandCounter < Server.game.getBoard().getIslandGroups().size() - 1) islandCounter++; else islandCounter = 0; if(islandCounter == islandId) { System.out.println("Teams:" + Server.game.getTeamById(0).towerColor + " " + Server.game.getTeamById(1).towerColor); gameController.changeModel(islandId, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } if(!((MoveMotherNature) gameController.getState()).checkEndConditions()) { gameController.nextState(); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_3, null, null)); } } catch (IOException e) { e.printStackTrace(); } } else { gameController.nextState(); gameController.changeModel(null, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(END_GAME, Server.game.getTeamById(Server.game.winnerTeamId).towerColor, null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } } return new Message(INVALID_MOVE, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param cloudId * @return */ public Message chooseCloudTile(int playerId, int cloudId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, cloudId); try { for (ClientHandler c : clients) { if(counter == Server.game.getPlayerNumber()-1) Server.game.currentRound.resetCardsPlayed(); c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } counter++; if(counter < Server.game.getPlayerNumber()) { gameController.nextState(); Server.game.currentRound.currentTurn = new PlayerTurn(Server.game.currentRound.getOrder().get(counter)); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_1, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.currentTurn.getPlayerId(), null)); } } catch (IOException e) { e.printStackTrace(); } } else {
((ChooseCloudTile) gameController.getState()).mustEndRound = true;
6
2023-11-06 00:50:18+00:00
12k
conductor-oss/conductor
amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java
[ { "identifier": "AMQPEventQueueProperties", "path": "amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/config/AMQPEventQueueProperties.java", "snippet": "@ConfigurationProperties(\"conductor.event-queues.amqp\")\npublic class AMQPEventQueueProperties {\n\n private int batchSize = 1;\n\n private Duration pollTimeDuration = Duration.ofMillis(100);\n\n private String hosts = ConnectionFactory.DEFAULT_HOST;\n\n private String username = ConnectionFactory.DEFAULT_USER;\n\n private String password = ConnectionFactory.DEFAULT_PASS;\n\n private String virtualHost = ConnectionFactory.DEFAULT_VHOST;\n\n private int port = PROTOCOL.PORT;\n\n private int connectionTimeoutInMilliSecs = 180000;\n private int networkRecoveryIntervalInMilliSecs = 5000;\n private int requestHeartbeatTimeoutInSecs = 30;\n private int handshakeTimeoutInMilliSecs = 180000;\n private int maxChannelCount = 5000;\n private int limit = 50;\n private int duration = 1000;\n private RetryType retryType = RetryType.REGULARINTERVALS;\n\n public int getLimit() {\n return limit;\n }\n\n public void setLimit(int limit) {\n this.limit = limit;\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n public RetryType getType() {\n return retryType;\n }\n\n public void setType(RetryType type) {\n this.retryType = type;\n }\n\n public int getConnectionTimeoutInMilliSecs() {\n return connectionTimeoutInMilliSecs;\n }\n\n public void setConnectionTimeoutInMilliSecs(int connectionTimeoutInMilliSecs) {\n this.connectionTimeoutInMilliSecs = connectionTimeoutInMilliSecs;\n }\n\n public int getHandshakeTimeoutInMilliSecs() {\n return handshakeTimeoutInMilliSecs;\n }\n\n public void setHandshakeTimeoutInMilliSecs(int handshakeTimeoutInMilliSecs) {\n this.handshakeTimeoutInMilliSecs = handshakeTimeoutInMilliSecs;\n }\n\n public int getMaxChannelCount() {\n return maxChannelCount;\n }\n\n public void setMaxChannelCount(int maxChannelCount) {\n this.maxChannelCount = maxChannelCount;\n }\n\n private boolean useNio = false;\n\n private boolean durable = true;\n\n private boolean exclusive = false;\n\n private boolean autoDelete = false;\n\n private String contentType = \"application/json\";\n\n private String contentEncoding = \"UTF-8\";\n\n private String exchangeType = \"topic\";\n\n private String queueType = \"classic\";\n\n private boolean sequentialMsgProcessing = true;\n\n private int deliveryMode = 2;\n\n private boolean useExchange = true;\n\n private String listenerQueuePrefix = \"\";\n\n private boolean useSslProtocol = false;\n\n public int getBatchSize() {\n return batchSize;\n }\n\n public void setBatchSize(int batchSize) {\n this.batchSize = batchSize;\n }\n\n public Duration getPollTimeDuration() {\n return pollTimeDuration;\n }\n\n public void setPollTimeDuration(Duration pollTimeDuration) {\n this.pollTimeDuration = pollTimeDuration;\n }\n\n public String getHosts() {\n return hosts;\n }\n\n public void setHosts(String hosts) {\n this.hosts = hosts;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getVirtualHost() {\n return virtualHost;\n }\n\n public void setVirtualHost(String virtualHost) {\n this.virtualHost = virtualHost;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public boolean isUseNio() {\n return useNio;\n }\n\n public void setUseNio(boolean useNio) {\n this.useNio = useNio;\n }\n\n public boolean isDurable() {\n return durable;\n }\n\n public void setDurable(boolean durable) {\n this.durable = durable;\n }\n\n public boolean isExclusive() {\n return exclusive;\n }\n\n public void setExclusive(boolean exclusive) {\n this.exclusive = exclusive;\n }\n\n public boolean isAutoDelete() {\n return autoDelete;\n }\n\n public void setAutoDelete(boolean autoDelete) {\n this.autoDelete = autoDelete;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public void setContentType(String contentType) {\n this.contentType = contentType;\n }\n\n public String getContentEncoding() {\n return contentEncoding;\n }\n\n public void setContentEncoding(String contentEncoding) {\n this.contentEncoding = contentEncoding;\n }\n\n public String getExchangeType() {\n return exchangeType;\n }\n\n public void setExchangeType(String exchangeType) {\n this.exchangeType = exchangeType;\n }\n\n public int getDeliveryMode() {\n return deliveryMode;\n }\n\n public void setDeliveryMode(int deliveryMode) {\n this.deliveryMode = deliveryMode;\n }\n\n public boolean isUseExchange() {\n return useExchange;\n }\n\n public void setUseExchange(boolean useExchange) {\n this.useExchange = useExchange;\n }\n\n public String getListenerQueuePrefix() {\n return listenerQueuePrefix;\n }\n\n public void setListenerQueuePrefix(String listenerQueuePrefix) {\n this.listenerQueuePrefix = listenerQueuePrefix;\n }\n\n public String getQueueType() {\n return queueType;\n }\n\n public boolean isUseSslProtocol() {\n return useSslProtocol;\n }\n\n public void setUseSslProtocol(boolean useSslProtocol) {\n this.useSslProtocol = useSslProtocol;\n }\n\n /**\n * @param queueType Supports two queue types, 'classic' and 'quorum'. Classic will be be\n * deprecated in 2022 and its usage discouraged from RabbitMQ community. So not using enum\n * type here to hold different values.\n */\n public void setQueueType(String queueType) {\n this.queueType = queueType;\n }\n\n /**\n * @return the sequentialMsgProcessing\n */\n public boolean isSequentialMsgProcessing() {\n return sequentialMsgProcessing;\n }\n\n /**\n * @param sequentialMsgProcessing the sequentialMsgProcessing to set Supports sequential and\n * parallel message processing capabilities. In parallel message processing, number of\n * threads are controlled by batch size. No thread control or execution framework required\n * here as threads are limited and short-lived.\n */\n public void setSequentialMsgProcessing(boolean sequentialMsgProcessing) {\n this.sequentialMsgProcessing = sequentialMsgProcessing;\n }\n\n public int getNetworkRecoveryIntervalInMilliSecs() {\n return networkRecoveryIntervalInMilliSecs;\n }\n\n public void setNetworkRecoveryIntervalInMilliSecs(int networkRecoveryIntervalInMilliSecs) {\n this.networkRecoveryIntervalInMilliSecs = networkRecoveryIntervalInMilliSecs;\n }\n\n public int getRequestHeartbeatTimeoutInSecs() {\n return requestHeartbeatTimeoutInSecs;\n }\n\n public void setRequestHeartbeatTimeoutInSecs(int requestHeartbeatTimeoutInSecs) {\n this.requestHeartbeatTimeoutInSecs = requestHeartbeatTimeoutInSecs;\n }\n}" }, { "identifier": "AMQPRetryPattern", "path": "amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/config/AMQPRetryPattern.java", "snippet": "public class AMQPRetryPattern {\n\n private int limit = 50;\n private int duration = 1000;\n private RetryType type = RetryType.REGULARINTERVALS;\n\n public AMQPRetryPattern() {}\n\n public AMQPRetryPattern(int limit, int duration, RetryType type) {\n this.limit = limit;\n this.duration = duration;\n this.type = type;\n }\n\n /**\n * This gets executed if the retry index is within the allowed limits, otherwise exception will\n * be thrown.\n *\n * @throws Exception\n */\n public void continueOrPropogate(Exception ex, int retryIndex) throws Exception {\n if (retryIndex > limit) {\n throw ex;\n }\n // Regular Intervals is the default\n long waitDuration = duration;\n if (type == RetryType.INCREMENTALINTERVALS) {\n waitDuration = duration * retryIndex;\n } else if (type == RetryType.EXPONENTIALBACKOFF) {\n waitDuration = (long) Math.pow(2, retryIndex) * duration;\n }\n try {\n Thread.sleep(waitDuration);\n } catch (InterruptedException ignored) {\n Thread.currentThread().interrupt();\n }\n }\n}" }, { "identifier": "AMQPConstants", "path": "amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/util/AMQPConstants.java", "snippet": "public class AMQPConstants {\n\n /** this when set will create a rabbitmq queue */\n public static String AMQP_QUEUE_TYPE = \"amqp_queue\";\n\n /** this when set will create a rabbitmq exchange */\n public static String AMQP_EXCHANGE_TYPE = \"amqp_exchange\";\n\n public static String PROPERTY_KEY_TEMPLATE = \"conductor.event-queues.amqp.%s\";\n\n /** default content type for the message read from rabbitmq */\n public static String DEFAULT_CONTENT_TYPE = \"application/json\";\n\n /** default encoding for the message read from rabbitmq */\n public static String DEFAULT_CONTENT_ENCODING = \"UTF-8\";\n\n /** default rabbitmq exchange type */\n public static String DEFAULT_EXCHANGE_TYPE = \"topic\";\n\n /**\n * default rabbitmq durability When set to true the queues are persisted to the disk.\n *\n * <p>{@see <a href=\"https://www.rabbitmq.com/queues.html\">RabbitMQ</a>}.\n */\n public static boolean DEFAULT_DURABLE = true;\n\n /**\n * default rabbitmq exclusivity When set to true the queues can be only used by one connection.\n *\n * <p>{@see <a href=\"https://www.rabbitmq.com/queues.html\">RabbitMQ</a>}.\n */\n public static boolean DEFAULT_EXCLUSIVE = false;\n\n /**\n * default rabbitmq auto delete When set to true the queues will be deleted when the last\n * consumer is cancelled\n *\n * <p>{@see <a href=\"https://www.rabbitmq.com/queues.html\">RabbitMQ</a>}.\n */\n public static boolean DEFAULT_AUTO_DELETE = false;\n\n /**\n * default rabbitmq delivery mode This is a property of the message When set to 1 the will be\n * non persistent and 2 will be persistent {@see <a\n * href=\"https://www.rabbitmq.com/releases/rabbitmq-java-client/v3.5.4/rabbitmq-java-client-javadoc-3.5.4/com/rabbitmq/client/MessageProperties.html>\n * Message Properties</a>}.\n */\n public static int DEFAULT_DELIVERY_MODE = 2;\n\n /**\n * default rabbitmq delivery mode This is a property of the channel limit to get the number of\n * unacknowledged messages. {@see <a\n * href=\"https://www.rabbitmq.com/consumer-prefetch.html>Consumer Prefetch</a>}.\n */\n public static int DEFAULT_BATCH_SIZE = 1;\n\n /**\n * default rabbitmq delivery mode This is a property of the amqp implementation which sets teh\n * polling time to drain the in-memory queue.\n */\n public static int DEFAULT_POLL_TIME_MS = 100;\n\n // info channel messages.\n public static final String INFO_CHANNEL_BORROW_SUCCESS =\n \"Borrowed the channel object from the channel pool for \" + \"the connection type [%s]\";\n public static final String INFO_CHANNEL_RETURN_SUCCESS =\n \"Returned the borrowed channel object to the pool for \" + \"the connection type [%s]\";\n public static final String INFO_CHANNEL_CREATION_SUCCESS =\n \"Channels are not available in the pool. Created a\"\n + \" channel for the connection type [%s]\";\n public static final String INFO_CHANNEL_RESET_SUCCESS =\n \"No proper channels available in the pool. Created a \"\n + \"channel for the connection type [%s]\";\n}" }, { "identifier": "AMQPSettings", "path": "amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/util/AMQPSettings.java", "snippet": "public class AMQPSettings {\n\n private static final Pattern URI_PATTERN =\n Pattern.compile(\n \"^(?:amqp\\\\_(queue|exchange))?\\\\:?(?<name>[^\\\\?]+)\\\\??(?<params>.*)$\",\n Pattern.CASE_INSENSITIVE);\n\n private String queueOrExchangeName;\n private String eventName;\n private String exchangeType;\n private String exchangeBoundQueueName;\n private String queueType;\n private String routingKey;\n private final String contentEncoding;\n private final String contentType;\n private boolean durable;\n private boolean exclusive;\n private boolean autoDelete;\n private boolean sequentialProcessing;\n private int deliveryMode;\n\n private final Map<String, Object> arguments = new HashMap<>();\n private static final Logger LOGGER = LoggerFactory.getLogger(AMQPSettings.class);\n\n public AMQPSettings(final AMQPEventQueueProperties properties) {\n // Initialize with a default values\n durable = properties.isDurable();\n exclusive = properties.isExclusive();\n autoDelete = properties.isAutoDelete();\n contentType = properties.getContentType();\n contentEncoding = properties.getContentEncoding();\n exchangeType = properties.getExchangeType();\n routingKey = StringUtils.EMPTY;\n queueType = properties.getQueueType();\n sequentialProcessing = properties.isSequentialMsgProcessing();\n // Set common settings for publishing and consuming\n setDeliveryMode(properties.getDeliveryMode());\n }\n\n public final boolean isDurable() {\n return durable;\n }\n\n public final boolean isExclusive() {\n return exclusive;\n }\n\n public final boolean autoDelete() {\n return autoDelete;\n }\n\n public final Map<String, Object> getArguments() {\n return arguments;\n }\n\n public final String getContentEncoding() {\n return contentEncoding;\n }\n\n /**\n * Use queue for publishing\n *\n * @param queueName the name of queue\n */\n public void setQueue(String queueName) {\n if (StringUtils.isEmpty(queueName)) {\n throw new IllegalArgumentException(\"Queue name for publishing is undefined\");\n }\n this.queueOrExchangeName = queueName;\n }\n\n public String getQueueOrExchangeName() {\n return queueOrExchangeName;\n }\n\n public String getExchangeBoundQueueName() {\n if (StringUtils.isEmpty(exchangeBoundQueueName)) {\n return String.format(\"bound_to_%s\", queueOrExchangeName);\n }\n return exchangeBoundQueueName;\n }\n\n public String getExchangeType() {\n return exchangeType;\n }\n\n public String getRoutingKey() {\n return routingKey;\n }\n\n public int getDeliveryMode() {\n return deliveryMode;\n }\n\n public AMQPSettings setDeliveryMode(int deliveryMode) {\n if (deliveryMode != 1 && deliveryMode != 2) {\n throw new IllegalArgumentException(\"Delivery mode must be 1 or 2\");\n }\n this.deliveryMode = deliveryMode;\n return this;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n /**\n * Complete settings from the queue URI.\n *\n * <p><u>Example for queue:</u>\n *\n * <pre>\n * amqp_queue:myQueue?deliveryMode=1&autoDelete=true&exclusive=true\n * </pre>\n *\n * <u>Example for exchange:</u>\n *\n * <pre>\n * amqp_exchange:myExchange?bindQueueName=myQueue&exchangeType=topic&routingKey=myRoutingKey&exclusive=true\n * </pre>\n *\n * @param queueURI\n * @return\n */\n public final AMQPSettings fromURI(final String queueURI) {\n final Matcher matcher = URI_PATTERN.matcher(queueURI);\n if (!matcher.matches()) {\n throw new IllegalArgumentException(\"Queue URI doesn't matches the expected regexp\");\n }\n\n // Set name of queue or exchange from group \"name\"\n LOGGER.info(\"Queue URI:{}\", queueURI);\n queueOrExchangeName = matcher.group(\"name\");\n eventName = queueURI;\n if (matcher.groupCount() > 1) {\n final String queryParams = matcher.group(\"params\");\n if (StringUtils.isNotEmpty(queryParams)) {\n // Handle parameters\n Arrays.stream(queryParams.split(\"\\\\s*\\\\&\\\\s*\"))\n .forEach(\n param -> {\n final String[] kv = param.split(\"\\\\s*=\\\\s*\");\n if (kv.length == 2) {\n if (kv[0].equalsIgnoreCase(\n String.valueOf(PARAM_EXCHANGE_TYPE))) {\n String value = kv[1];\n if (StringUtils.isEmpty(value)) {\n throw new IllegalArgumentException(\n \"The provided exchange type is empty\");\n }\n exchangeType = value;\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_QUEUE_NAME)))) {\n exchangeBoundQueueName = kv[1];\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_ROUTING_KEY)))) {\n String value = kv[1];\n if (StringUtils.isEmpty(value)) {\n throw new IllegalArgumentException(\n \"The provided routing key is empty\");\n }\n routingKey = value;\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_DURABLE)))) {\n durable = Boolean.parseBoolean(kv[1]);\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_EXCLUSIVE)))) {\n exclusive = Boolean.parseBoolean(kv[1]);\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_AUTO_DELETE)))) {\n autoDelete = Boolean.parseBoolean(kv[1]);\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_DELIVERY_MODE)))) {\n setDeliveryMode(Integer.parseInt(kv[1]));\n }\n if (kv[0].equalsIgnoreCase(\n (String.valueOf(PARAM_MAX_PRIORITY)))) {\n arguments.put(\"x-max-priority\", Integer.valueOf(kv[1]));\n }\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (!(obj instanceof AMQPSettings)) return false;\n AMQPSettings other = (AMQPSettings) obj;\n return Objects.equals(arguments, other.arguments)\n && autoDelete == other.autoDelete\n && Objects.equals(contentEncoding, other.contentEncoding)\n && Objects.equals(contentType, other.contentType)\n && deliveryMode == other.deliveryMode\n && durable == other.durable\n && Objects.equals(eventName, other.eventName)\n && Objects.equals(exchangeType, other.exchangeType)\n && exclusive == other.exclusive\n && Objects.equals(queueOrExchangeName, other.queueOrExchangeName)\n && Objects.equals(exchangeBoundQueueName, other.exchangeBoundQueueName)\n && Objects.equals(queueType, other.queueType)\n && Objects.equals(routingKey, other.routingKey)\n && sequentialProcessing == other.sequentialProcessing;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n arguments,\n autoDelete,\n contentEncoding,\n contentType,\n deliveryMode,\n durable,\n eventName,\n exchangeType,\n exclusive,\n queueOrExchangeName,\n exchangeBoundQueueName,\n queueType,\n routingKey,\n sequentialProcessing);\n }\n\n @Override\n public String toString() {\n return \"AMQPSettings [queueOrExchangeName=\"\n + queueOrExchangeName\n + \", eventName=\"\n + eventName\n + \", exchangeType=\"\n + exchangeType\n + \", exchangeQueueName=\"\n + exchangeBoundQueueName\n + \", queueType=\"\n + queueType\n + \", routingKey=\"\n + routingKey\n + \", contentEncoding=\"\n + contentEncoding\n + \", contentType=\"\n + contentType\n + \", durable=\"\n + durable\n + \", exclusive=\"\n + exclusive\n + \", autoDelete=\"\n + autoDelete\n + \", sequentialProcessing=\"\n + sequentialProcessing\n + \", deliveryMode=\"\n + deliveryMode\n + \", arguments=\"\n + arguments\n + \"]\";\n }\n\n public String getEventName() {\n return eventName;\n }\n\n /**\n * @return the queueType\n */\n public String getQueueType() {\n return queueType;\n }\n\n /**\n * @return the sequentialProcessing\n */\n public boolean isSequentialProcessing() {\n return sequentialProcessing;\n }\n}" }, { "identifier": "RetryType", "path": "amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/util/RetryType.java", "snippet": "public enum RetryType {\n REGULARINTERVALS,\n EXPONENTIALBACKOFF,\n INCREMENTALINTERVALS\n}" }, { "identifier": "Message", "path": "core/src/main/java/com/netflix/conductor/core/events/queue/Message.java", "snippet": "public class Message {\n\n private String payload;\n private String id;\n private String receipt;\n private int priority;\n\n public Message() {}\n\n public Message(String id, String payload, String receipt) {\n this.payload = payload;\n this.id = id;\n this.receipt = receipt;\n }\n\n public Message(String id, String payload, String receipt, int priority) {\n this.payload = payload;\n this.id = id;\n this.receipt = receipt;\n this.priority = priority;\n }\n\n /**\n * @return the payload\n */\n public String getPayload() {\n return payload;\n }\n\n /**\n * @param payload the payload to set\n */\n public void setPayload(String payload) {\n this.payload = payload;\n }\n\n /**\n * @return the id\n */\n public String getId() {\n return id;\n }\n\n /**\n * @param id the id to set\n */\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * @return Receipt attached to the message\n */\n public String getReceipt() {\n return receipt;\n }\n\n /**\n * @param receipt Receipt attached to the message\n */\n public void setReceipt(String receipt) {\n this.receipt = receipt;\n }\n\n /**\n * Gets the message priority\n *\n * @return priority of message.\n */\n public int getPriority() {\n return priority;\n }\n\n /**\n * Sets the message priority (between 0 and 99). Higher priority message is retrieved ahead of\n * lower priority ones.\n *\n * @param priority the priority of message (between 0 and 99)\n */\n public void setPriority(int priority) {\n this.priority = priority;\n }\n\n @Override\n public String toString() {\n return id;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Message message = (Message) o;\n return Objects.equals(payload, message.payload)\n && Objects.equals(id, message.id)\n && Objects.equals(priority, message.priority)\n && Objects.equals(receipt, message.receipt);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(payload, id, receipt, priority);\n }\n}" } ]
import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.internal.stubbing.answers.DoesNothing; import org.mockito.stubbing.OngoingStubbing; import com.netflix.conductor.contribs.queue.amqp.config.AMQPEventQueueProperties; import com.netflix.conductor.contribs.queue.amqp.config.AMQPRetryPattern; import com.netflix.conductor.contribs.queue.amqp.util.AMQPConstants; import com.netflix.conductor.contribs.queue.amqp.util.AMQPSettings; import com.netflix.conductor.contribs.queue.amqp.util.RetryType; import com.netflix.conductor.core.events.queue.Message; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AMQP.PROTOCOL; import com.rabbitmq.client.AMQP.Queue.DeclareOk; import com.rabbitmq.client.Address; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.impl.AMQImpl; import rx.Observable; import rx.observers.Subscribers; import rx.observers.TestSubscriber; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
8,571
public void testGetMessagesFromExistingExchangeWithDurableExclusiveAutoDeleteQueueConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndCustomConfigurationFromURI( channel, connection, true, true, true, true, true); } @Test public void testGetMessagesFromExistingExchangeWithDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndDefaultConfiguration(channel, connection, true, true); } @Test public void testPublishMessagesToNotExistingExchangeAndDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testPublishMessagesToExchangeAndDefaultConfiguration(channel, connection, false, true); } @Test public void testAck() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); final Random random = new Random(); final String name = RandomStringUtils.randomAlphabetic(30), type = "topic", routingKey = RandomStringUtils.randomAlphabetic(30); AMQPRetryPattern retrySettings = null; final AMQPSettings settings = new AMQPSettings(properties) .fromURI( "amqp_exchange:" + name + "?exchangeType=" + type + "&routingKey=" + routingKey); AMQPObservableQueue observableQueue = new AMQPObservableQueue( mockConnectionFactory(connection), addresses, true, settings, retrySettings, batchSize, pollTimeMs); List<Message> messages = new LinkedList<>(); Message msg = new Message(); msg.setId("0e3eef8f-ebb1-4244-9665-759ab5bdf433"); msg.setPayload("Payload"); msg.setReceipt("1"); messages.add(msg); List<String> failedMessages = observableQueue.ack(messages); assertNotNull(failedMessages); assertTrue(failedMessages.isEmpty()); } private void testGetMessagesFromExchangeAndDefaultConfiguration( Channel channel, Connection connection, boolean exists, boolean useWorkingChannel) throws IOException, TimeoutException { final Random random = new Random(); final String name = RandomStringUtils.randomAlphabetic(30), type = "topic", routingKey = RandomStringUtils.randomAlphabetic(30); final String queueName = String.format("bound_to_%s", name); final AMQPSettings settings = new AMQPSettings(properties) .fromURI( "amqp_exchange:" + name + "?exchangeType=" + type + "&routingKey=" + routingKey); assertTrue(settings.isDurable()); assertFalse(settings.isExclusive()); assertFalse(settings.autoDelete()); assertEquals(2, settings.getDeliveryMode()); assertEquals(name, settings.getQueueOrExchangeName()); assertEquals(type, settings.getExchangeType()); assertEquals(routingKey, settings.getRoutingKey()); assertEquals(queueName, settings.getExchangeBoundQueueName()); List<GetResponse> queue = buildQueue(random, batchSize); channel = mockChannelForExchange( channel, useWorkingChannel, exists, queueName, name, type, routingKey, queue); AMQPRetryPattern retrySettings = null; AMQPObservableQueue observableQueue = new AMQPObservableQueue( mockConnectionFactory(connection), addresses, true, settings, retrySettings, batchSize, pollTimeMs); assertArrayEquals(addresses, observableQueue.getAddresses());
/* * Copyright 2023 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.queue.amqp; @SuppressWarnings({"rawtypes", "unchecked"}) public class AMQPObservableQueueTest { final int batchSize = 10; final int pollTimeMs = 500; Address[] addresses; AMQPEventQueueProperties properties; @Before public void setUp() { properties = mock(AMQPEventQueueProperties.class); when(properties.getBatchSize()).thenReturn(1); when(properties.getPollTimeDuration()).thenReturn(Duration.ofMillis(100)); when(properties.getHosts()).thenReturn(ConnectionFactory.DEFAULT_HOST); when(properties.getUsername()).thenReturn(ConnectionFactory.DEFAULT_USER); when(properties.getPassword()).thenReturn(ConnectionFactory.DEFAULT_PASS); when(properties.getVirtualHost()).thenReturn(ConnectionFactory.DEFAULT_VHOST); when(properties.getPort()).thenReturn(PROTOCOL.PORT); when(properties.getConnectionTimeoutInMilliSecs()).thenReturn(60000); when(properties.isUseNio()).thenReturn(false); when(properties.isDurable()).thenReturn(true); when(properties.isExclusive()).thenReturn(false); when(properties.isAutoDelete()).thenReturn(false); when(properties.getContentType()).thenReturn("application/json"); when(properties.getContentEncoding()).thenReturn("UTF-8"); when(properties.getExchangeType()).thenReturn("topic"); when(properties.getDeliveryMode()).thenReturn(2); when(properties.isUseExchange()).thenReturn(true); addresses = new Address[] {new Address("localhost", PROTOCOL.PORT)}; AMQPConnection.setAMQPConnection(null); } List<GetResponse> buildQueue(final Random random, final int bound) { final LinkedList<GetResponse> queue = new LinkedList(); for (int i = 0; i < bound; i++) { AMQP.BasicProperties props = mock(AMQP.BasicProperties.class); when(props.getMessageId()).thenReturn(UUID.randomUUID().toString()); Envelope envelope = mock(Envelope.class); when(envelope.getDeliveryTag()).thenReturn(random.nextLong()); GetResponse response = mock(GetResponse.class); when(response.getProps()).thenReturn(props); when(response.getEnvelope()).thenReturn(envelope); when(response.getBody()).thenReturn("{}".getBytes()); when(response.getMessageCount()).thenReturn(bound - i); queue.add(response); } return queue; } Channel mockBaseChannel() throws IOException, TimeoutException { Channel channel = mock(Channel.class); when(channel.isOpen()).thenReturn(Boolean.TRUE); /* * doAnswer(invocation -> { when(channel.isOpen()).thenReturn(Boolean.FALSE); * return DoesNothing.doesNothing(); }).when(channel).close(); */ return channel; } Channel mockChannelForQueue( Channel channel, boolean isWorking, boolean exists, String name, List<GetResponse> queue) throws IOException { // queueDeclarePassive final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(name, queue.size(), 1); if (exists) { when(channel.queueDeclarePassive(eq(name))).thenReturn(queueDeclareOK); } else { when(channel.queueDeclarePassive(eq(name))) .thenThrow(new IOException("Queue " + name + " exists")); } // queueDeclare OngoingStubbing<DeclareOk> declareOkOngoingStubbing = when(channel.queueDeclare( eq(name), anyBoolean(), anyBoolean(), anyBoolean(), anyMap())) .thenReturn(queueDeclareOK); if (!isWorking) { declareOkOngoingStubbing.thenThrow( new IOException("Cannot declare queue " + name), new RuntimeException("Not working")); } // messageCount when(channel.messageCount(eq(name))).thenReturn((long) queue.size()); // basicGet OngoingStubbing<String> getResponseOngoingStubbing = Mockito.when(channel.basicConsume(eq(name), anyBoolean(), any(Consumer.class))) .thenReturn(name); if (!isWorking) { getResponseOngoingStubbing.thenThrow( new IOException("Not working"), new RuntimeException("Not working")); } // basicPublish if (isWorking) { doNothing() .when(channel) .basicPublish( eq(StringUtils.EMPTY), eq(name), any(AMQP.BasicProperties.class), any(byte[].class)); } else { doThrow(new IOException("Not working")) .when(channel) .basicPublish( eq(StringUtils.EMPTY), eq(name), any(AMQP.BasicProperties.class), any(byte[].class)); } return channel; } Channel mockChannelForExchange( Channel channel, boolean isWorking, boolean exists, String queueName, String name, String type, String routingKey, List<GetResponse> queue) throws IOException { // exchangeDeclarePassive final AMQImpl.Exchange.DeclareOk exchangeDeclareOK = new AMQImpl.Exchange.DeclareOk(); if (exists) { when(channel.exchangeDeclarePassive(eq(name))).thenReturn(exchangeDeclareOK); } else { when(channel.exchangeDeclarePassive(eq(name))) .thenThrow(new IOException("Exchange " + name + " exists")); } // exchangeDeclare OngoingStubbing<AMQP.Exchange.DeclareOk> declareOkOngoingStubbing = when(channel.exchangeDeclare( eq(name), eq(type), anyBoolean(), anyBoolean(), anyMap())) .thenReturn(exchangeDeclareOK); if (!isWorking) { declareOkOngoingStubbing.thenThrow( new IOException("Cannot declare exchange " + name + " of type " + type), new RuntimeException("Not working")); } // queueDeclarePassive final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(queueName, queue.size(), 1); if (exists) { when(channel.queueDeclarePassive(eq(queueName))).thenReturn(queueDeclareOK); } else { when(channel.queueDeclarePassive(eq(queueName))) .thenThrow(new IOException("Queue " + queueName + " exists")); } // queueDeclare when(channel.queueDeclare( eq(queueName), anyBoolean(), anyBoolean(), anyBoolean(), anyMap())) .thenReturn(queueDeclareOK); // queueBind when(channel.queueBind(eq(queueName), eq(name), eq(routingKey))) .thenReturn(new AMQImpl.Queue.BindOk()); // messageCount when(channel.messageCount(eq(name))).thenReturn((long) queue.size()); // basicGet OngoingStubbing<String> getResponseOngoingStubbing = Mockito.when(channel.basicConsume(eq(queueName), anyBoolean(), any(Consumer.class))) .thenReturn(queueName); if (!isWorking) { getResponseOngoingStubbing.thenThrow( new IOException("Not working"), new RuntimeException("Not working")); } // basicPublish if (isWorking) { doNothing() .when(channel) .basicPublish( eq(name), eq(routingKey), any(AMQP.BasicProperties.class), any(byte[].class)); } else { doThrow(new IOException("Not working")) .when(channel) .basicPublish( eq(name), eq(routingKey), any(AMQP.BasicProperties.class), any(byte[].class)); } return channel; } Connection mockGoodConnection(Channel channel) throws IOException { Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); when(connection.isOpen()).thenReturn(Boolean.TRUE); /* * doAnswer(invocation -> { when(connection.isOpen()).thenReturn(Boolean.FALSE); * return DoesNothing.doesNothing(); }).when(connection).close(); */ return connection; } Connection mockBadConnection() throws IOException { Connection connection = mock(Connection.class); when(connection.createChannel()).thenThrow(new IOException("Can't create channel")); when(connection.isOpen()).thenReturn(Boolean.TRUE); doThrow(new IOException("Can't close connection")).when(connection).close(); return connection; } ConnectionFactory mockConnectionFactory(Connection connection) throws IOException, TimeoutException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection(eq(addresses), Mockito.anyString())) .thenReturn(connection); return connectionFactory; } void runObserve( Channel channel, AMQPObservableQueue observableQueue, String queueName, boolean useWorkingChannel, int batchSize) throws IOException { final List<Message> found = new ArrayList<>(batchSize); TestSubscriber<Message> subscriber = TestSubscriber.create(Subscribers.create(found::add)); rx.Observable<Message> observable = observableQueue.observe().take(pollTimeMs * 2, TimeUnit.MILLISECONDS); assertNotNull(observable); observable.subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); subscriber.assertCompleted(); if (useWorkingChannel) { verify(channel, atLeast(1)) .basicConsume(eq(queueName), anyBoolean(), any(Consumer.class)); doNothing().when(channel).basicAck(anyLong(), eq(false)); doAnswer(DoesNothing.doesNothing()).when(channel).basicAck(anyLong(), eq(false)); observableQueue.ack(Collections.synchronizedList(found)); } else { assertNotNull(found); assertTrue(found.isEmpty()); } observableQueue.close(); } @Test public void testGetMessagesFromExistingExchangeWithDurableExclusiveAutoDeleteQueueConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndCustomConfigurationFromURI( channel, connection, true, true, true, true, true); } @Test public void testGetMessagesFromExistingExchangeWithDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndDefaultConfiguration(channel, connection, true, true); } @Test public void testPublishMessagesToNotExistingExchangeAndDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testPublishMessagesToExchangeAndDefaultConfiguration(channel, connection, false, true); } @Test public void testAck() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); final Random random = new Random(); final String name = RandomStringUtils.randomAlphabetic(30), type = "topic", routingKey = RandomStringUtils.randomAlphabetic(30); AMQPRetryPattern retrySettings = null; final AMQPSettings settings = new AMQPSettings(properties) .fromURI( "amqp_exchange:" + name + "?exchangeType=" + type + "&routingKey=" + routingKey); AMQPObservableQueue observableQueue = new AMQPObservableQueue( mockConnectionFactory(connection), addresses, true, settings, retrySettings, batchSize, pollTimeMs); List<Message> messages = new LinkedList<>(); Message msg = new Message(); msg.setId("0e3eef8f-ebb1-4244-9665-759ab5bdf433"); msg.setPayload("Payload"); msg.setReceipt("1"); messages.add(msg); List<String> failedMessages = observableQueue.ack(messages); assertNotNull(failedMessages); assertTrue(failedMessages.isEmpty()); } private void testGetMessagesFromExchangeAndDefaultConfiguration( Channel channel, Connection connection, boolean exists, boolean useWorkingChannel) throws IOException, TimeoutException { final Random random = new Random(); final String name = RandomStringUtils.randomAlphabetic(30), type = "topic", routingKey = RandomStringUtils.randomAlphabetic(30); final String queueName = String.format("bound_to_%s", name); final AMQPSettings settings = new AMQPSettings(properties) .fromURI( "amqp_exchange:" + name + "?exchangeType=" + type + "&routingKey=" + routingKey); assertTrue(settings.isDurable()); assertFalse(settings.isExclusive()); assertFalse(settings.autoDelete()); assertEquals(2, settings.getDeliveryMode()); assertEquals(name, settings.getQueueOrExchangeName()); assertEquals(type, settings.getExchangeType()); assertEquals(routingKey, settings.getRoutingKey()); assertEquals(queueName, settings.getExchangeBoundQueueName()); List<GetResponse> queue = buildQueue(random, batchSize); channel = mockChannelForExchange( channel, useWorkingChannel, exists, queueName, name, type, routingKey, queue); AMQPRetryPattern retrySettings = null; AMQPObservableQueue observableQueue = new AMQPObservableQueue( mockConnectionFactory(connection), addresses, true, settings, retrySettings, batchSize, pollTimeMs); assertArrayEquals(addresses, observableQueue.getAddresses());
assertEquals(AMQPConstants.AMQP_EXCHANGE_TYPE, observableQueue.getType());
2
2023-12-08 06:06:09+00:00
12k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/widgets/StylePreviewWidget.java
[ { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_ACCENT_SATURATION = \"monetAccentSaturationValue\";" }, { "identifier": "MONET_ACCURATE_SHADES", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_ACCURATE_SHADES = \"monetAccurateShades\";" }, { "identifier": "MONET_BACKGROUND_LIGHTNESS", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_BACKGROUND_LIGHTNESS = \"monetBackgroundLightnessValue\";" }, { "identifier": "MONET_BACKGROUND_SATURATION", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_BACKGROUND_SATURATION = \"monetBackgroundSaturationValue\";" }, { "identifier": "MONET_PITCH_BLACK_THEME", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_PITCH_BLACK_THEME = \"monetPitchBlackTheme\";" }, { "identifier": "MONET_STYLE", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_STYLE = \"customMonetStyle\";" }, { "identifier": "RPrefs", "path": "app/src/main/java/com/drdisagree/colorblendr/config/RPrefs.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class RPrefs {\n\n private static final String TAG = RPrefs.class.getSimpleName();\n\n public static SharedPreferences prefs = ColorBlendr.getAppContext().createDeviceProtectedStorageContext().getSharedPreferences(Const.SharedPrefs, MODE_PRIVATE);\n static SharedPreferences.Editor editor = prefs.edit();\n\n public static void putBoolean(String key, boolean val) {\n editor.putBoolean(key, val).apply();\n }\n\n public static void putInt(String key, int val) {\n editor.putInt(key, val).apply();\n }\n\n public static void putLong(String key, long val) {\n editor.putLong(key, val).apply();\n }\n\n public static void putFloat(String key, float val) {\n editor.putFloat(key, val).apply();\n }\n\n public static void putString(String key, String val) {\n editor.putString(key, val).apply();\n }\n\n public static boolean getBoolean(String key) {\n return prefs.getBoolean(key, false);\n }\n\n public static boolean getBoolean(String key, Boolean defValue) {\n return prefs.getBoolean(key, defValue);\n }\n\n public static int getInt(String key) {\n return prefs.getInt(key, 0);\n }\n\n public static int getInt(String key, int defValue) {\n return prefs.getInt(key, defValue);\n }\n\n public static long getLong(String key) {\n return prefs.getLong(key, 0);\n }\n\n public static long getLong(String key, long defValue) {\n return prefs.getLong(key, defValue);\n }\n\n public static float getFloat(String key) {\n return prefs.getFloat(key, 0);\n }\n\n public static float getFloat(String key, float defValue) {\n return prefs.getFloat(key, defValue);\n }\n\n public static String getString(String key) {\n return prefs.getString(key, null);\n }\n\n public static String getString(String key, String defValue) {\n return prefs.getString(key, defValue);\n }\n\n public static void clearPref(String key) {\n editor.remove(key).apply();\n }\n\n public static void clearPrefs(String... keys) {\n for (String key : keys) {\n editor.remove(key).apply();\n }\n }\n\n public static void clearAllPrefs() {\n editor.clear().apply();\n }\n\n public static void backupPrefs(final @NonNull OutputStream outputStream) {\n try (outputStream; ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {\n objectOutputStream.writeObject(prefs.getAll());\n } catch (IOException e) {\n Log.e(TAG, \"Error serializing preferences\", e);\n }\n\n try (outputStream; ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {\n Map<String, ?> allPrefs = prefs.getAll();\n\n for (String excludedPref : EXCLUDED_PREFS_FROM_BACKUP) {\n allPrefs.remove(excludedPref);\n }\n\n objectOutputStream.writeObject(allPrefs);\n } catch (IOException e) {\n Log.e(TAG, \"Error serializing preferences\", e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static void restorePrefs(final @NonNull InputStream inputStream) {\n Map<String, Object> map;\n try (inputStream; ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {\n map = (Map<String, Object>) objectInputStream.readObject();\n } catch (ClassNotFoundException | IOException e) {\n Log.e(TAG, \"Error deserializing preferences\", e);\n return;\n }\n\n // Retrieve excluded prefs from current prefs\n Map<String, Object> excludedPrefs = new HashMap<>();\n for (String excludedPref : EXCLUDED_PREFS_FROM_BACKUP) {\n Object prefValue = prefs.getAll().get(excludedPref);\n if (prefValue != null) {\n excludedPrefs.put(excludedPref, prefValue);\n }\n }\n\n editor.clear();\n\n // Restore excluded prefs\n for (Map.Entry<String, Object> entry : excludedPrefs.entrySet()) {\n putObject(entry.getKey(), entry.getValue());\n }\n\n // Restore non-excluded prefs\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n if (EXCLUDED_PREFS_FROM_BACKUP.contains(entry.getKey())) {\n continue;\n }\n\n putObject(entry.getKey(), entry.getValue());\n }\n\n editor.apply();\n }\n\n private static void putObject(String key, Object value) {\n if (value instanceof Boolean) {\n editor.putBoolean(key, (Boolean) value);\n } else if (value instanceof String) {\n editor.putString(key, (String) value);\n } else if (value instanceof Integer) {\n editor.putInt(key, (Integer) value);\n } else if (value instanceof Float) {\n editor.putFloat(key, (Float) value);\n } else if (value instanceof Long) {\n editor.putLong(key, (Long) value);\n } else {\n throw new IllegalArgumentException(\"Type \" + value.getClass().getName() + \" is unknown\");\n }\n }\n}" }, { "identifier": "ColorPreview", "path": "app/src/main/java/com/drdisagree/colorblendr/ui/views/ColorPreview.java", "snippet": "public class ColorPreview extends View {\n\n private Paint squarePaint, secondQuarterCirclePaint, firstQuarterCirclePaint, halfCirclePaint;\n private RectF squareRect, circleRect;\n private float padding;\n\n public ColorPreview(Context context) {\n super(context);\n init(context);\n }\n\n public ColorPreview(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context);\n }\n\n public ColorPreview(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context);\n }\n\n private void init(Context context) {\n boolean isDarkMode = (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_YES) == Configuration.UI_MODE_NIGHT_YES;\n\n padding = 10 * getResources().getDisplayMetrics().density;\n\n squareRect = new RectF();\n circleRect = new RectF();\n\n squarePaint = new Paint();\n squarePaint.setColor(ContextCompat.getColor(context,\n !isDarkMode ?\n com.google.android.material.R.color.material_dynamic_neutral99 :\n com.google.android.material.R.color.material_dynamic_neutral10\n ));\n squarePaint.setStyle(Paint.Style.FILL);\n\n halfCirclePaint = new Paint();\n halfCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_primary90));\n halfCirclePaint.setStyle(Paint.Style.FILL);\n\n firstQuarterCirclePaint = new Paint();\n firstQuarterCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_secondary90));\n firstQuarterCirclePaint.setStyle(Paint.Style.FILL);\n\n secondQuarterCirclePaint = new Paint();\n secondQuarterCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_tertiary90));\n secondQuarterCirclePaint.setStyle(Paint.Style.FILL);\n }\n\n @Override\n protected void onDraw(@NonNull Canvas canvas) {\n super.onDraw(canvas);\n\n int width = getWidth();\n int height = getHeight();\n\n float cornerRadius = 12 * getResources().getDisplayMetrics().density;\n squareRect.set(0, 0, width, height);\n canvas.drawRoundRect(squareRect, cornerRadius, cornerRadius, squarePaint);\n\n float margin = 0 * getResources().getDisplayMetrics().density;\n\n circleRect.set(padding, padding, width - padding, height - padding - margin);\n canvas.drawArc(circleRect, 180, 180, true, halfCirclePaint);\n\n circleRect.set(padding, padding + margin, width - padding - margin, height - padding);\n canvas.drawArc(circleRect, 90, 90, true, firstQuarterCirclePaint);\n\n circleRect.set(padding + margin, padding + margin, width - padding, height - padding);\n canvas.drawArc(circleRect, 0, 90, true, secondQuarterCirclePaint);\n }\n\n public void setSquareColor(@ColorInt int color) {\n squarePaint.setColor(color);\n }\n\n public void setFirstQuarterCircleColor(@ColorInt int color) {\n firstQuarterCirclePaint.setColor(color);\n }\n\n public void setSecondQuarterCircleColor(@ColorInt int color) {\n secondQuarterCirclePaint.setColor(color);\n }\n\n public void setHalfCircleColor(@ColorInt int color) {\n halfCirclePaint.setColor(color);\n }\n\n public void invalidateColors() {\n invalidate();\n }\n\n public void setPadding(float padding) {\n this.padding = padding * getResources().getDisplayMetrics().density;\n }\n}" }, { "identifier": "ColorSchemeUtil", "path": "app/src/main/java/com/drdisagree/colorblendr/utils/ColorSchemeUtil.java", "snippet": "public class ColorSchemeUtil {\n\n public enum MONET {\n SPRITZ,\n MONOCHROMATIC,\n TONAL_SPOT,\n VIBRANT,\n RAINBOW,\n EXPRESSIVE,\n FIDELITY,\n CONTENT,\n FRUIT_SALAD\n }\n\n public static final int[] tones = {100, 99, 95, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0};\n\n public static ArrayList<ArrayList<Integer>> generateColorPalette(MONET style, @ColorInt int color) {\n return generateColorPalette(style, color, SystemUtil.isDarkMode(), 5);\n }\n\n public static ArrayList<ArrayList<Integer>> generateColorPalette(MONET style, @ColorInt int color, boolean isDark) {\n return generateColorPalette(style, color, isDark, 5);\n }\n\n public static ArrayList<ArrayList<Integer>> generateColorPalette(MONET style, @ColorInt int color, boolean isDark, int contrast) {\n ArrayList<ArrayList<Integer>> palette = new ArrayList<>();\n\n DynamicScheme dynamicScheme = getDynamicScheme(style, color, isDark, contrast);\n\n TonalPalette[] tonalPalettes = {\n dynamicScheme.primaryPalette,\n dynamicScheme.secondaryPalette,\n dynamicScheme.tertiaryPalette,\n dynamicScheme.neutralPalette,\n dynamicScheme.neutralVariantPalette\n };\n\n for (TonalPalette tonalPalette : tonalPalettes) {\n palette.add(createToneList(tonalPalette));\n }\n\n return palette;\n }\n\n public static DynamicScheme getDynamicScheme(MONET style, @ColorInt int color, boolean isDark, int contrast) {\n return switch (style) {\n case SPRITZ -> new SchemeNeutral(Hct.fromInt(color), isDark, contrast);\n case MONOCHROMATIC -> new SchemeMonochrome(Hct.fromInt(color), isDark, contrast);\n case TONAL_SPOT -> new SchemeTonalSpot(Hct.fromInt(color), isDark, contrast);\n case VIBRANT -> new SchemeVibrant(Hct.fromInt(color), isDark, contrast);\n case RAINBOW -> new SchemeRainbow(Hct.fromInt(color), isDark, contrast);\n case EXPRESSIVE -> new SchemeExpressive(Hct.fromInt(color), isDark, contrast);\n case FIDELITY -> new SchemeFidelity(Hct.fromInt(color), isDark, contrast);\n case CONTENT -> new SchemeContent(Hct.fromInt(color), isDark, contrast);\n case FRUIT_SALAD -> new SchemeFruitSalad(Hct.fromInt(color), isDark, contrast);\n };\n }\n\n private static ArrayList<Integer> createToneList(TonalPalette palette) {\n ArrayList<Integer> toneList = new ArrayList<>();\n for (int tone : ColorSchemeUtil.tones) {\n toneList.add(palette.tone(tone));\n }\n return toneList;\n }\n\n public static MONET stringToEnumMonetStyle(Context context, String enumString) {\n if (enumString.equals(context.getString(R.string.monet_neutral))) {\n return MONET.SPRITZ;\n } else if (enumString.equals(context.getString(R.string.monet_monochrome))) {\n return MONET.MONOCHROMATIC;\n } else if (enumString.equals(context.getString(R.string.monet_tonalspot))) {\n return MONET.TONAL_SPOT;\n } else if (enumString.equals(context.getString(R.string.monet_vibrant))) {\n return MONET.VIBRANT;\n } else if (enumString.equals(context.getString(R.string.monet_rainbow))) {\n return MONET.RAINBOW;\n } else if (enumString.equals(context.getString(R.string.monet_expressive))) {\n return MONET.EXPRESSIVE;\n } else if (enumString.equals(context.getString(R.string.monet_fidelity))) {\n return MONET.FIDELITY;\n } else if (enumString.equals(context.getString(R.string.monet_content))) {\n return MONET.CONTENT;\n } else if (enumString.equals(context.getString(R.string.monet_fruitsalad))) {\n return MONET.FRUIT_SALAD;\n } else {\n return MONET.TONAL_SPOT;\n }\n }\n}" }, { "identifier": "ColorUtil", "path": "app/src/main/java/com/drdisagree/colorblendr/utils/ColorUtil.java", "snippet": "public class ColorUtil {\n\n public static @ColorInt int getColorFromAttribute(Context context, int attr) {\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(attr, typedValue, true);\n return typedValue.data;\n }\n\n public static ArrayList<ArrayList<Integer>> generateModifiedColors(\n Context context,\n ColorSchemeUtil.MONET style,\n int accentSaturation,\n int backgroundSaturation,\n int backgroundLightness,\n boolean pitchBlackTheme,\n boolean accurateShades\n ) {\n return generateModifiedColors(\n context,\n style,\n accentSaturation,\n backgroundSaturation,\n backgroundLightness,\n pitchBlackTheme,\n accurateShades,\n true\n );\n }\n\n public static ArrayList<ArrayList<Integer>> generateModifiedColors(\n Context context,\n ColorSchemeUtil.MONET style,\n int accentSaturation,\n int backgroundSaturation,\n int backgroundLightness,\n boolean pitchBlackTheme,\n boolean accurateShades,\n boolean modifyPitchBlack\n ) {\n return generateModifiedColors(\n context,\n style,\n accentSaturation,\n backgroundSaturation,\n backgroundLightness,\n pitchBlackTheme,\n accurateShades,\n modifyPitchBlack,\n SystemUtil.isDarkMode()\n );\n }\n\n public static ArrayList<ArrayList<Integer>> generateModifiedColors(\n Context context,\n ColorSchemeUtil.MONET style,\n int accentSaturation,\n int backgroundSaturation,\n int backgroundLightness,\n boolean pitchBlackTheme,\n boolean accurateShades,\n boolean modifyPitchBlack,\n boolean isDark\n ) {\n String wallpaperColors = RPrefs.getString(WALLPAPER_COLOR_LIST, null);\n ArrayList<Integer> wallpaperColorList;\n\n if (wallpaperColors != null) {\n wallpaperColorList = Const.GSON.fromJson(\n wallpaperColors,\n new TypeToken<ArrayList<Integer>>() {\n }.getType()\n );\n } else {\n wallpaperColorList = WallpaperUtil.getWallpaperColors(context);\n }\n\n return generateModifiedColors(\n style,\n RPrefs.getInt(\n MONET_SEED_COLOR,\n wallpaperColorList.get(0)\n ),\n accentSaturation,\n backgroundSaturation,\n backgroundLightness,\n pitchBlackTheme,\n accurateShades,\n modifyPitchBlack,\n isDark\n );\n }\n\n public static ArrayList<ArrayList<Integer>> generateModifiedColors(\n ColorSchemeUtil.MONET style,\n @ColorInt int seedColor,\n int accentSaturation,\n int backgroundSaturation,\n int backgroundLightness,\n boolean pitchBlackTheme,\n boolean accurateShades,\n boolean modifyPitchBlack,\n boolean isDark\n ) {\n ArrayList<ArrayList<Integer>> palette = ColorSchemeUtil.generateColorPalette(\n style,\n seedColor,\n isDark\n );\n\n // Modify colors\n for (int i = 0; i < palette.size(); i++) {\n ArrayList<Integer> modifiedShades = ColorModifiers.modifyColors(\n new ArrayList<>(palette.get(i).subList(1, palette.get(i).size())),\n new AtomicInteger(i),\n style,\n accentSaturation,\n backgroundSaturation,\n backgroundLightness,\n pitchBlackTheme,\n accurateShades,\n modifyPitchBlack\n );\n for (int j = 1; j < palette.get(i).size(); j++) {\n palette.get(i).set(j, modifiedShades.get(j - 1));\n }\n }\n\n return palette;\n }\n\n public static @ColorInt int getAccentColor(Context context) {\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue, true);\n return typedValue.data;\n }\n\n public static int modifySaturation(int color, int saturation) {\n float saturationFloat = (saturation - 100) / 100f;\n\n float[] hsl = new float[3];\n ColorUtils.colorToHSL(color, hsl);\n\n if (saturationFloat > 0) {\n hsl[1] += ((1 - hsl[1]) * saturationFloat);\n } else if (saturationFloat < 0) {\n hsl[1] += (hsl[1] * saturationFloat);\n }\n\n return ColorUtils.HSLToColor(hsl);\n }\n\n public static int modifyLightness(int color, int lightness, int idx) {\n float lightnessFloat = (lightness - 100) / 1000f;\n float shade = getSystemTintList()[idx];\n\n if (idx == 0 || idx == 12) {\n lightnessFloat = 0;\n } else if (idx == 1) {\n lightnessFloat /= 10;\n } else if (idx == 2) {\n lightnessFloat /= 2;\n }\n\n float[] hsl = new float[3];\n ColorUtils.colorToHSL(color, hsl);\n\n hsl[2] = shade + lightnessFloat;\n\n return ColorUtils.HSLToColor(hsl);\n }\n\n public static float getHue(int color) {\n float[] hsl = new float[3];\n ColorUtils.colorToHSL(color, hsl);\n\n return hsl[0];\n }\n\n public static float[] getSystemTintList() {\n return new float[]{1.0f, 0.99f, 0.95f, 0.9f, 0.8f, 0.7f, 0.6f, 0.496f, 0.4f, 0.3f, 0.2f, 0.1f, 0.0f};\n }\n\n public static String[][] getColorNames() {\n String[] accentTypes = {\"system_accent1\", \"system_accent2\", \"system_accent3\", \"system_neutral1\", \"system_neutral2\"};\n String[] values = {\"0\", \"10\", \"50\", \"100\", \"200\", \"300\", \"400\", \"500\", \"600\", \"700\", \"800\", \"900\", \"1000\"};\n\n String[][] colorNames = new String[accentTypes.length][values.length];\n\n for (int i = 0; i < accentTypes.length; i++) {\n for (int j = 0; j < values.length; j++) {\n colorNames[i][j] = accentTypes[i] + \"_\" + values[j];\n }\n }\n\n return colorNames;\n }\n\n public static String[][] getColorNamesM3(boolean isDynamic, boolean prefixG) {\n String prefix = \"m3_ref_palette_\";\n String dynamic = \"dynamic_\";\n\n String[] accentTypes = {\"primary\", \"secondary\", \"tertiary\", \"neutral\", \"neutral_variant\"};\n String[] values = {\"100\", \"99\", \"95\", \"90\", \"80\", \"70\", \"60\", \"50\", \"40\", \"30\", \"20\", \"10\", \"0\"};\n\n String[][] colorNames = new String[accentTypes.length][values.length];\n\n for (int i = 0; i < accentTypes.length; i++) {\n for (int j = 0; j < values.length; j++) {\n colorNames[i][j] = (prefixG ? \"g\" : \"\") + prefix + (isDynamic ? dynamic : \"\") + accentTypes[i] + values[j];\n }\n }\n\n return colorNames;\n }\n\n public static String intToHexColor(int colorInt) {\n return String.format(\"#%06X\", (0xFFFFFF & colorInt));\n }\n\n public static int[][] getSystemColors(Context context) {\n return new int[][]{\n new int[]{\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary100, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary99, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary95, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary90, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary80, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary70, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary60, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary50, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary40, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary30, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary20, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary10, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary0, context.getTheme())\n },\n\n new int[]{\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary100, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary99, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary95, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary90, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary80, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary70, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary60, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary50, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary40, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary30, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary20, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary10, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary0, context.getTheme())\n },\n\n new int[]{\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary100, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary99, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary95, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary90, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary80, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary70, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary60, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary50, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary40, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary30, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary20, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary10, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary0, context.getTheme())\n },\n\n new int[]{\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral100, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral99, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral95, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral90, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral70, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral60, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral50, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral40, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral30, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral20, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral10, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral0, context.getTheme())\n },\n\n new int[]{\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant100, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant99, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant95, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant90, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant80, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant70, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant60, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant50, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant40, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant30, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant20, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant10, context.getTheme()),\n context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant0, context.getTheme())\n }};\n }\n\n public static int calculateTextColor(@ColorInt int color) {\n double darkness = 1 - (0.299 * Color.red(color) +\n 0.587 * Color.green(color) +\n 0.114 * Color.blue(color)) / 255;\n\n return darkness < 0.5 ? Color.BLACK : Color.WHITE;\n }\n\n /**\n * Convert a color appearance model representation to an ARGB color.\n * <p>\n * Note: the returned color may have a lower chroma than requested. Whether a chroma is\n * available depends on luminance. For example, there's no such thing as a high chroma light\n * red, due to the limitations of our eyes and/or physics. If the requested chroma is\n * unavailable, the highest possible chroma at the requested luminance is returned.\n *\n * @param hue hue, in degrees, in CAM coordinates\n * @param chroma chroma in CAM coordinates.\n * @param lstar perceptual luminance, L* in L*a*b*\n */\n @ColorInt\n public static int CAMToColor(float hue, float chroma, float lstar) {\n return Cam.getInt(hue, chroma, lstar);\n }\n\n private static final double XYZ_WHITE_REFERENCE_X = 95.047;\n private static final double XYZ_WHITE_REFERENCE_Y = 100;\n private static final double XYZ_WHITE_REFERENCE_Z = 108.883;\n\n /**\n * Converts a color from CIE XYZ to its RGB representation.\n *\n * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE\n * 2° Standard Observer (1931).</p>\n *\n * @param x X component value [0...95.047)\n * @param y Y component value [0...100)\n * @param z Z component value [0...108.883)\n * @return int containing the RGB representation\n */\n @ColorInt\n public static int XYZToColor(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x,\n @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y,\n @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z) {\n double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100;\n double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100;\n double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100;\n\n r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r;\n g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g;\n b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b;\n\n return Color.rgb(\n constrain((int) Math.round(r * 255), 0, 255),\n constrain((int) Math.round(g * 255), 0, 255),\n constrain((int) Math.round(b * 255), 0, 255));\n }\n\n private static float constrain(float amount, float low, float high) {\n return amount < low ? low : Math.min(amount, high);\n }\n\n @SuppressWarnings(\"SameParameterValue\")\n private static int constrain(int amount, int low, int high) {\n return amount < low ? low : Math.min(amount, high);\n }\n\n public static ArrayList<Integer> getMonetAccentColors() {\n ArrayList<Integer> colors = new ArrayList<>();\n colors.add(ContextCompat.getColor(ColorBlendr.getAppContext(), android.R.color.system_accent1_400));\n colors.add(ContextCompat.getColor(ColorBlendr.getAppContext(), android.R.color.system_accent2_400));\n colors.add(ContextCompat.getColor(ColorBlendr.getAppContext(), android.R.color.system_accent3_400));\n return colors;\n }\n}" }, { "identifier": "OverlayManager", "path": "app/src/main/java/com/drdisagree/colorblendr/utils/OverlayManager.java", "snippet": "public class OverlayManager {\n\n private static final String TAG = OverlayManager.class.getSimpleName();\n private static final IRootService mRootService = ColorBlendr.getRootService();\n private static final String[][] colorNames = ColorUtil.getColorNames();\n\n public static void enableOverlay(String packageName) {\n try {\n mRootService.enableOverlay(Collections.singletonList(packageName));\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to enable overlay: \" + packageName, e);\n }\n }\n\n public static void disableOverlay(String packageName) {\n try {\n mRootService.disableOverlay(Collections.singletonList(packageName));\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to disable overlay: \" + packageName, e);\n }\n }\n\n public static boolean isOverlayInstalled(String packageName) {\n try {\n return mRootService.isOverlayInstalled(packageName);\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to check if overlay is installed: \" + packageName, e);\n return false;\n }\n }\n\n public static boolean isOverlayEnabled(String packageName) {\n try {\n return mRootService.isOverlayEnabled(packageName);\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to check if overlay is enabled: \" + packageName, e);\n return false;\n }\n }\n\n public static void uninstallOverlayUpdates(String packageName) {\n try {\n mRootService.uninstallOverlayUpdates(packageName);\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to uninstall overlay updates: \" + packageName, e);\n }\n }\n\n public static void registerFabricatedOverlay(FabricatedOverlayResource fabricatedOverlay) {\n try {\n mRootService.registerFabricatedOverlay(fabricatedOverlay);\n mRootService.enableOverlayWithIdentifier(Collections.singletonList(fabricatedOverlay.overlayName));\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to register fabricated overlay: \" + fabricatedOverlay.overlayName, e);\n }\n }\n\n public static void unregisterFabricatedOverlay(String packageName) {\n try {\n mRootService.unregisterFabricatedOverlay(packageName);\n } catch (RemoteException e) {\n Log.e(TAG, \"Failed to unregister fabricated overlay: \" + packageName, e);\n }\n }\n\n public static void applyFabricatedColors(Context context) {\n if (!RPrefs.getBoolean(THEMING_ENABLED, true)) {\n return;\n }\n\n ColorSchemeUtil.MONET style = ColorSchemeUtil.stringToEnumMonetStyle(\n context,\n RPrefs.getString(MONET_STYLE, context.getString(R.string.monet_tonalspot))\n );\n int monetAccentSaturation = RPrefs.getInt(MONET_ACCENT_SATURATION, 100);\n int monetBackgroundSaturation = RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100);\n int monetBackgroundLightness = RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100);\n boolean pitchBlackTheme = RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false);\n boolean accurateShades = RPrefs.getBoolean(MONET_ACCURATE_SHADES, true);\n\n ArrayList<ArrayList<Integer>> paletteLight = ColorUtil.generateModifiedColors(\n context,\n style,\n monetAccentSaturation,\n monetBackgroundSaturation,\n monetBackgroundLightness,\n pitchBlackTheme,\n accurateShades,\n false,\n false\n );\n\n ArrayList<ArrayList<Integer>> paletteDark = ColorUtil.generateModifiedColors(\n context,\n style,\n monetAccentSaturation,\n monetBackgroundSaturation,\n monetBackgroundLightness,\n pitchBlackTheme,\n accurateShades,\n false,\n true\n );\n\n ArrayList<FabricatedOverlayResource> fabricatedOverlays = new ArrayList<>();\n fabricatedOverlays.add(new FabricatedOverlayResource(\n FABRICATED_OVERLAY_NAME_SYSTEM,\n FRAMEWORK_PACKAGE\n ));\n\n for (int i = 0; i < 5; i++) {\n for (int j = 0; j < 13; j++) {\n fabricatedOverlays.get(0).setColor(colorNames[i][j], paletteDark.get(i).get(j));\n }\n }\n\n FabricatedUtil.createDynamicOverlay(\n fabricatedOverlays.get(0),\n paletteLight,\n paletteDark\n );\n\n HashMap<String, Boolean> selectedApps = Const.getSelectedFabricatedApps();\n\n for (String packageName : selectedApps.keySet()) {\n if (Boolean.TRUE.equals(selectedApps.get(packageName)) &&\n SystemUtil.isAppInstalled(packageName)) {\n FabricatedOverlayResource fabricatedOverlayPerApp = getFabricatedColorsPerApp(\n context,\n packageName,\n SystemUtil.isDarkMode() ?\n paletteDark :\n paletteLight\n );\n\n fabricatedOverlays.add(fabricatedOverlayPerApp);\n }\n }\n\n if (pitchBlackTheme) {\n fabricatedOverlays.get(0).setColor(\"surface_header_dark_sysui\", Color.BLACK);\n fabricatedOverlays.get(0).setColor(colorNames[3][11], Color.BLACK);\n fabricatedOverlays.get(0).setColor(colorNames[4][11], Color.BLACK);\n }\n\n if (!RPrefs.getBoolean(TINT_TEXT_COLOR, true)) {\n fabricatedOverlays.get(0).setColor(\"text_color_primary_device_default_dark\", Color.WHITE);\n fabricatedOverlays.get(0).setColor(\"text_color_secondary_device_default_dark\", 0xB3FFFFFF);\n fabricatedOverlays.get(0).setColor(\"text_color_primary_device_default_light\", Color.BLACK);\n fabricatedOverlays.get(0).setColor(\"text_color_secondary_device_default_light\", 0xB3000000);\n }\n\n for (FabricatedOverlayResource fabricatedOverlay : fabricatedOverlays) {\n registerFabricatedOverlay(fabricatedOverlay);\n }\n }\n\n public static void applyFabricatedColorsPerApp(Context context, String packageName, ArrayList<ArrayList<Integer>> palette) {\n registerFabricatedOverlay(\n getFabricatedColorsPerApp(\n context,\n packageName,\n palette\n )\n );\n }\n\n public static void removeFabricatedColors() {\n ArrayList<String> fabricatedOverlays = new ArrayList<>();\n HashMap<String, Boolean> selectedApps = Const.getSelectedFabricatedApps();\n\n for (String packageName : selectedApps.keySet()) {\n if (Boolean.TRUE.equals(selectedApps.get(packageName))) {\n fabricatedOverlays.add(String.format(FABRICATED_OVERLAY_NAME_APPS, packageName));\n }\n }\n\n fabricatedOverlays.add(FABRICATED_OVERLAY_NAME_SYSTEM);\n\n for (String packageName : fabricatedOverlays) {\n unregisterFabricatedOverlay(packageName);\n }\n }\n\n private static FabricatedOverlayResource getFabricatedColorsPerApp(Context context, String packageName, ArrayList<ArrayList<Integer>> palette) {\n if (palette == null) {\n palette = ColorUtil.generateModifiedColors(\n context,\n ColorSchemeUtil.stringToEnumMonetStyle(\n context,\n RPrefs.getString(MONET_STYLE, context.getString(R.string.monet_tonalspot))\n ),\n RPrefs.getInt(MONET_ACCENT_SATURATION, 100),\n RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100),\n RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100),\n RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false),\n RPrefs.getBoolean(MONET_ACCURATE_SHADES, true),\n false\n );\n }\n\n FabricatedOverlayResource fabricatedOverlay = new FabricatedOverlayResource(\n String.format(FABRICATED_OVERLAY_NAME_APPS, packageName),\n packageName\n );\n\n FabricatedUtil.assignPerAppColorsToOverlay(fabricatedOverlay, palette);\n\n return fabricatedOverlay;\n }\n}" }, { "identifier": "SystemUtil", "path": "app/src/main/java/com/drdisagree/colorblendr/utils/SystemUtil.java", "snippet": "public class SystemUtil {\n\n public static boolean isDarkMode() {\n return (ColorBlendr.getAppContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_YES) == Configuration.UI_MODE_NIGHT_YES;\n }\n\n public static boolean isAppInstalled(String package_name) {\n try {\n ColorBlendr.getAppContext()\n .getPackageManager()\n .getPackageInfo(package_name, PackageManager.GET_META_DATA);\n return true;\n } catch (PackageManager.NameNotFoundException ignored) {\n return false;\n }\n }\n\n public static int getScreenRotation(Context context) {\n\n final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();\n\n return switch (display.getRotation()) {\n case Surface.ROTATION_0 -> 0;\n case Surface.ROTATION_90 -> 90;\n case Surface.ROTATION_180 -> 180;\n case Surface.ROTATION_270 -> 270;\n default -> -1;\n };\n }\n}" } ]
import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import android.content.Context; import android.content.res.TypedArray; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.Nullable; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.ui.views.ColorPreview; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.OverlayManager; import com.drdisagree.colorblendr.utils.SystemUtil; import com.google.android.material.card.MaterialCardView; import java.util.ArrayList;
10,744
package com.drdisagree.colorblendr.ui.widgets; public class StylePreviewWidget extends RelativeLayout { private Context context; private MaterialCardView container; private TextView titleTextView; private TextView descriptionTextView; private ColorPreview colorContainer; private boolean isSelected = false; private OnClickListener onClickListener; private String styleName; private ColorSchemeUtil.MONET monetStyle; private ArrayList<ArrayList<Integer>> colorPalette; public StylePreviewWidget(Context context) { super(context); init(context, null); } public StylePreviewWidget(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public StylePreviewWidget(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { this.context = context; inflate(context, R.layout.view_widget_style_preview, this); initializeId(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StylePreviewWidget); styleName = typedArray.getString(R.styleable.StylePreviewWidget_titleText); setTitle(styleName); setDescription(typedArray.getString(R.styleable.StylePreviewWidget_descriptionText)); typedArray.recycle(); setColorPreview(); container.setOnClickListener(v -> { if (onClickListener != null && !isSelected()) { setSelected(true); onClickListener.onClick(v); } }); } public void setTitle(int titleResId) { titleTextView.setText(titleResId); } public void setTitle(String title) { titleTextView.setText(title); } public void setDescription(int summaryResId) { descriptionTextView.setText(summaryResId); } public void setDescription(String summary) { descriptionTextView.setText(summary); } public boolean isSelected() { return isSelected; } public void setSelected(boolean isSelected) { this.isSelected = isSelected; container.setCardBackgroundColor(getCardBackgroundColor()); container.setStrokeWidth(isSelected ? 2 : 0); titleTextView.setTextColor(getTextColor(isSelected)); descriptionTextView.setTextColor(getTextColor(isSelected)); } public void applyColorScheme() { RPrefs.putString(MONET_STYLE, styleName); OverlayManager.applyFabricatedColors(context); } private void setColorPreview() { new Thread(() -> { try { if (styleName == null) { styleName = context.getString(R.string.monet_tonalspot); } monetStyle = ColorSchemeUtil.stringToEnumMonetStyle( context, styleName ); colorPalette = ColorUtil.generateModifiedColors( context, monetStyle, RPrefs.getInt(MONET_ACCENT_SATURATION, 100), RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100),
package com.drdisagree.colorblendr.ui.widgets; public class StylePreviewWidget extends RelativeLayout { private Context context; private MaterialCardView container; private TextView titleTextView; private TextView descriptionTextView; private ColorPreview colorContainer; private boolean isSelected = false; private OnClickListener onClickListener; private String styleName; private ColorSchemeUtil.MONET monetStyle; private ArrayList<ArrayList<Integer>> colorPalette; public StylePreviewWidget(Context context) { super(context); init(context, null); } public StylePreviewWidget(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public StylePreviewWidget(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { this.context = context; inflate(context, R.layout.view_widget_style_preview, this); initializeId(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StylePreviewWidget); styleName = typedArray.getString(R.styleable.StylePreviewWidget_titleText); setTitle(styleName); setDescription(typedArray.getString(R.styleable.StylePreviewWidget_descriptionText)); typedArray.recycle(); setColorPreview(); container.setOnClickListener(v -> { if (onClickListener != null && !isSelected()) { setSelected(true); onClickListener.onClick(v); } }); } public void setTitle(int titleResId) { titleTextView.setText(titleResId); } public void setTitle(String title) { titleTextView.setText(title); } public void setDescription(int summaryResId) { descriptionTextView.setText(summaryResId); } public void setDescription(String summary) { descriptionTextView.setText(summary); } public boolean isSelected() { return isSelected; } public void setSelected(boolean isSelected) { this.isSelected = isSelected; container.setCardBackgroundColor(getCardBackgroundColor()); container.setStrokeWidth(isSelected ? 2 : 0); titleTextView.setTextColor(getTextColor(isSelected)); descriptionTextView.setTextColor(getTextColor(isSelected)); } public void applyColorScheme() { RPrefs.putString(MONET_STYLE, styleName); OverlayManager.applyFabricatedColors(context); } private void setColorPreview() { new Thread(() -> { try { if (styleName == null) { styleName = context.getString(R.string.monet_tonalspot); } monetStyle = ColorSchemeUtil.stringToEnumMonetStyle( context, styleName ); colorPalette = ColorUtil.generateModifiedColors( context, monetStyle, RPrefs.getInt(MONET_ACCENT_SATURATION, 100), RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100),
RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100),
2
2023-12-06 13:20:16+00:00
12k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/menu/MenuItem.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMap(Enum::name, Function.identity()));\r\n private static DeluxeMenus instance;\r\n private static DebugLevel debugLevel = DebugLevel.LOWEST;\r\n private DeluxeMenusConfig menuConfig;\r\n private Map<String, ItemHook> itemHooks;\r\n private VaultHook vaultHook;\r\n private boolean checkUpdates;\r\n private ItemStack head;\r\n private PersistentMetaHandler persistentMetaHandler;\r\n private MenuItemMarker menuItemMarker;\r\n private DupeFixer dupeFixer;\r\n private BukkitAudiences adventure;\r\n\r\n @Override\r\n public void onLoad() {\r\n instance = this;\r\n\r\n this.persistentMetaHandler = new PersistentMetaHandler();\r\n \r\n if (NbtProvider.isAvailable()) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"NMS hook has been setup successfully!\"\r\n );\r\n return;\r\n }\r\n\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Could not setup a NMS hook for your server version!\"\r\n );\r\n }\r\n\r\n @SuppressWarnings(\"deprecation\")\r\n @Override\r\n public void onEnable() {\r\n if (!hookPlaceholderAPI()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.SEVERE,\r\n \"Could not hook into PlaceholderAPI!\",\r\n \"DeluxeMenus will now disable!\"\r\n );\r\n Bukkit.getPluginManager().disablePlugin(this);\r\n return;\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"Successfully hooked into PlaceholderAPI!\"\r\n );\r\n }\r\n\r\n menuItemMarker = new MenuItemMarker(this);\r\n dupeFixer = new DupeFixer(this, menuItemMarker);\r\n\r\n this.adventure = BukkitAudiences.create(this);\r\n\r\n setupItemHooks();\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"Vault\")) {\r\n vaultHook = new VaultHook();\r\n\r\n if (vaultHook.hooked()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"Successfully hooked into Vault!\"\r\n );\r\n }\r\n }\r\n\r\n if (!VersionHelper.IS_ITEM_LEGACY) {\r\n head = new ItemStack(Material.PLAYER_HEAD, 1);\r\n } else {\r\n head = new ItemStack(Material.valueOf(\"SKULL_ITEM\"), 1, (short) 3);\r\n }\r\n\r\n menuConfig = new DeluxeMenusConfig(this);\r\n if (menuConfig.loadDefConfig()) {\r\n debugLevel(menuConfig.debugLevel());\r\n checkUpdates = getConfig().getBoolean(\"check_updates\");\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n menuConfig.loadGUIMenus() + \" GUI menus loaded!\"\r\n );\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Failed to load from config.yml. Use /dm reload after fixing your errors.\"\r\n );\r\n }\r\n\r\n new PlayerListener(this);\r\n new DeluxeMenusCommands(this);\r\n Bukkit.getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\r\n\r\n if (checkUpdates) {\r\n UpdateChecker updateChecker = new UpdateChecker(this);\r\n\r\n if (updateChecker.updateAvailable()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"An update for DeluxeMenus (DeluxeMenus v\" + updateChecker.getLatestVersion() + \")\",\r\n \"is available at https://www.spigotmc.org/resources/deluxemenus.11734/\"\r\n );\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"You are running the latest version of DeluxeMenus!\"\r\n );\r\n }\r\n }\r\n\r\n startMetrics();\r\n\r\n new Expansion(this).register();\r\n }\r\n\r\n @Override\r\n public void onDisable() {\r\n Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, \"BungeeCord\");\r\n\r\n Bukkit.getScheduler().cancelTasks(this);\r\n\r\n if (this.adventure != null) {\r\n this.adventure.close();\r\n this.adventure = null;\r\n }\r\n\r\n Menu.unloadForShutdown();\r\n\r\n itemHooks.clear();\r\n\r\n instance = null;\r\n }\r\n\r\n private void setupItemHooks() {\r\n itemHooks = new HashMap<>();\r\n\r\n if (PlaceholderAPIPlugin.getServerVersion().isSpigot()) {\r\n itemHooks.put(HeadType.NAMED.getHookName(), new NamedHeadHook(this));\r\n itemHooks.put(HeadType.BASE64.getHookName(), new BaseHeadHook());\r\n itemHooks.put(HeadType.TEXTURE.getHookName(), new TextureHeadHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"HeadDatabase\")) {\r\n try {\r\n Class.forName(\"me.arcaniax.hdb.api.HeadDatabaseAPI\");\r\n itemHooks.put(HeadType.HDB.getHookName(), new HeadDatabaseHook());\r\n } catch (ClassNotFoundException ignored) {}\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"ItemsAdder\")) {\r\n itemHooks.put(\"itemsadder\", new ItemsAdderHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"Oraxen\")) {\r\n itemHooks.put(\"oraxen\", new OraxenHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"MMOItems\")) {\r\n itemHooks.put(\"mmoitems\", new MMOItemsHook());\r\n }\r\n }\r\n\r\n public Optional<ItemHook> getItemHook(String id) {\r\n return Optional.ofNullable(itemHooks.get(id));\r\n }\r\n\r\n public Map<String, ItemHook> getItemHooks() {\r\n return itemHooks;\r\n }\r\n\r\n public ItemStack getHead() {\r\n return head != null ? head : new ItemStack(Material.DIRT, 1);\r\n }\r\n\r\n public static DeluxeMenus getInstance() {\r\n return instance;\r\n }\r\n\r\n public static DebugLevel debugLevel() {\r\n return debugLevel;\r\n }\r\n\r\n public static void debugLevel(final DebugLevel level) {\r\n debugLevel = level;\r\n }\r\n\r\n public static DebugLevel printStacktraceLevel() {\r\n return DebugLevel.MEDIUM;\r\n }\r\n\r\n public static boolean shouldPrintStackTrace() {\r\n return debugLevel().getPriority() <= printStacktraceLevel().getPriority();\r\n }\r\n\r\n public static void printStacktrace(final String message, final Throwable throwable) {\r\n if (!shouldPrintStackTrace()) return;\r\n\r\n getInstance().getLogger().log(Level.SEVERE, message, throwable);\r\n }\r\n\r\n private void startMetrics() {\r\n Metrics metrics = new Metrics(this, 445);\r\n metrics.addCustomChart(new Metrics.SingleLineChart(\"menus\", Menu::getLoadedMenuSize));\r\n }\r\n\r\n public void connect(Player p, String server) {\r\n ByteArrayDataOutput out = ByteStreams.newDataOutput();\r\n\r\n try {\r\n out.writeUTF(\"Connect\");\r\n out.writeUTF(server);\r\n } catch (Exception e) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.SEVERE,\r\n \"There was a problem attempting to send \" + p.getName() + \" to server \" + server + \"!\"\r\n );\r\n\r\n printStacktrace(\r\n \"There was a problem attempting to send \" + p.getName() + \" to server \" + server + \"!\",\r\n e\r\n );\r\n }\r\n\r\n p.sendPluginMessage(this, \"BungeeCord\", out.toByteArray());\r\n }\r\n\r\n public void sms(CommandSender s, Component msg) {\r\n adventure().sender(s).sendMessage(msg);\r\n }\r\n\r\n public void sms(CommandSender s, Messages msg) {\r\n adventure().sender(s).sendMessage(msg.message());\r\n }\r\n\r\n public static void debug(@NotNull final DebugLevel debugLevel, @NotNull final Level level, @NotNull final String... messages) {\r\n if (debugLevel().getPriority() > debugLevel.getPriority()) return;\r\n\r\n getInstance().getLogger().log(\r\n level,\r\n String.join(System.lineSeparator(), messages)\r\n );\r\n }\r\n\r\n private boolean hookPlaceholderAPI() {\r\n return Bukkit.getPluginManager().getPlugin(\"PlaceholderAPI\") != null;\r\n }\r\n\r\n public MenuItemMarker getMenuItemMarker() {\r\n return menuItemMarker;\r\n }\r\n\r\n public DeluxeMenusConfig getConfiguration() {\r\n return menuConfig;\r\n }\r\n\r\n public VaultHook getVault() {\r\n return vaultHook;\r\n }\r\n\r\n public PersistentMetaHandler getPersistentMetaHandler() {\r\n return persistentMetaHandler;\r\n }\r\n\r\n public BukkitAudiences adventure() {\r\n if (this.adventure == null) {\r\n throw new IllegalStateException(\"Tried to access Adventure when the plugin was disabled!\");\r\n }\r\n return this.adventure;\r\n }\r\n\r\n public void clearCaches() {\r\n itemHooks.values().stream()\r\n .filter(Objects::nonNull)\r\n .filter(hook -> hook instanceof SimpleCache)\r\n .map(hook -> (SimpleCache) hook)\r\n .forEach(SimpleCache::clearCache);\r\n }\r\n}\r" }, { "identifier": "ItemHook", "path": "src/main/java/com/extendedclip/deluxemenus/hooks/ItemHook.java", "snippet": "public interface ItemHook {\r\n\r\n ItemStack getItem(@NotNull final String... arguments);\r\n\r\n String getPrefix();\r\n\r\n}\r" }, { "identifier": "NbtProvider", "path": "src/main/java/com/extendedclip/deluxemenus/nbt/NbtProvider.java", "snippet": "public final class NbtProvider {\r\n\r\n private static boolean NBT_HOOKED;\r\n\r\n private static Method getStringMethod;\r\n private static Method setStringMethod;\r\n private static Method setBooleanMethod;\r\n private static Method setIntMethod;\r\n private static Method removeTagMethod;\r\n private static Method hasTagMethod;\r\n private static Method getTagMethod;\r\n private static Method setTagMethod;\r\n private static Method containsMethod;\r\n private static Method asNMSCopyMethod;\r\n private static Method asBukkitCopyMethod;\r\n\r\n private static Constructor<?> nbtCompoundConstructor;\r\n\r\n static {\r\n try {\r\n final Class<?> compoundClass = VersionHelper.getNMSClass(\"nbt\", \"NBTTagCompound\");\r\n final Class<?> itemStackClass = VersionHelper.getNMSClass(\"world.item\", \"ItemStack\");\r\n final Class<?> inventoryClass = VersionHelper.getCraftClass(\"inventory.CraftItemStack\");\r\n\r\n containsMethod = compoundClass.getMethod(VersionConstants.CONTAINS_METHOD_NAME, String.class);\r\n getStringMethod = compoundClass.getMethod(VersionConstants.GET_STRING_METHOD_NAME, String.class);\r\n setStringMethod = compoundClass.getMethod(VersionConstants.SET_STRING_METHOD_NAME, String.class, String.class);\r\n setBooleanMethod = compoundClass.getMethod(VersionConstants.SET_BOOLEAN_METHOD_NAME, String.class, boolean.class);\r\n setIntMethod = compoundClass.getMethod(VersionConstants.SET_INTEGER_METHOD_NAME, String.class, int.class);\r\n removeTagMethod = compoundClass.getMethod(VersionConstants.REMOVE_TAG_METHOD_NAME, String.class);\r\n hasTagMethod = itemStackClass.getMethod(VersionConstants.HAS_TAG_METHOD_NAME);\r\n getTagMethod = itemStackClass.getMethod(VersionConstants.GET_TAG_METHOD_NAME);\r\n setTagMethod = itemStackClass.getMethod(VersionConstants.SET_TAG_METHOD_NAME, compoundClass);\r\n nbtCompoundConstructor = compoundClass.getDeclaredConstructor();\r\n\r\n asNMSCopyMethod = inventoryClass.getMethod(\"asNMSCopy\", ItemStack.class);\r\n asBukkitCopyMethod = inventoryClass.getMethod(\"asBukkitCopy\", itemStackClass);\r\n\r\n NBT_HOOKED = true;\r\n } catch (NoSuchMethodException | ClassNotFoundException e) {\r\n NBT_HOOKED = false;\r\n }\r\n }\r\n\r\n public static boolean isAvailable() {\r\n return NBT_HOOKED;\r\n }\r\n\r\n /**\r\n * Sets an NBT tag to the an {@link ItemStack}.\r\n *\r\n * @param itemStack The current {@link ItemStack} to be set.\r\n * @param key The NBT key to use.\r\n * @param value The tag value to set.\r\n * @return An {@link ItemStack} that has NBT set.\r\n */\r\n public static ItemStack setString(final ItemStack itemStack, final String key, final String value) {\r\n if (itemStack == null) return null;\r\n if (itemStack.getType() == Material.AIR) return itemStack;\r\n\r\n Object nmsItemStack = asNMSCopy(itemStack);\r\n Object itemCompound = hasTag(nmsItemStack) ? getTag(nmsItemStack) : newNBTTagCompound();\r\n\r\n setString(itemCompound, key, value);\r\n setTag(nmsItemStack, itemCompound);\r\n\r\n return asBukkitCopy(nmsItemStack);\r\n }\r\n\r\n /**\r\n * Sets a boolean to the {@link ItemStack}.\r\n * Mainly used for setting an item to be unbreakable on older versions.\r\n *\r\n * @param itemStack The {@link ItemStack} to set the boolean to.\r\n * @param key The key to use.\r\n * @param value The boolean value.\r\n * @return An {@link ItemStack} with a boolean value set.\r\n */\r\n public static ItemStack setBoolean(final ItemStack itemStack, final String key, final boolean value) {\r\n if (itemStack == null) return null;\r\n if (itemStack.getType() == Material.AIR) return itemStack;\r\n\r\n Object nmsItemStack = asNMSCopy(itemStack);\r\n Object itemCompound = hasTag(nmsItemStack) ? getTag(nmsItemStack) : newNBTTagCompound();\r\n\r\n setBoolean(itemCompound, key, value);\r\n setTag(nmsItemStack, itemCompound);\r\n\r\n return asBukkitCopy(nmsItemStack);\r\n }\r\n\r\n /**\r\n * Gets the NBT tag based on a given key.\r\n *\r\n * @param itemStack The {@link ItemStack} to get from.\r\n * @param key The key to look for.\r\n * @return The tag that was stored in the {@link ItemStack}.\r\n */\r\n public static String getString(final ItemStack itemStack, final String key) {\r\n if (itemStack == null) return null;\r\n if (itemStack.getType() == Material.AIR) return null;\r\n\r\n Object nmsItemStack = asNMSCopy(itemStack);\r\n Object itemCompound = hasTag(nmsItemStack) ? getTag(nmsItemStack) : newNBTTagCompound();\r\n\r\n return getString(itemCompound, key);\r\n }\r\n\r\n public static ItemStack setInt(final ItemStack itemStack, final String key, final int value) {\r\n if (itemStack == null) return null;\r\n if (itemStack.getType() == Material.AIR) return null;\r\n\r\n Object nmsItemStack = asNMSCopy(itemStack);\r\n Object itemCompound = hasTag(nmsItemStack) ? getTag(nmsItemStack) : newNBTTagCompound();\r\n\r\n setInt(itemCompound, key, value);\r\n setTag(nmsItemStack, itemCompound);\r\n\r\n return asBukkitCopy(nmsItemStack);\r\n }\r\n\r\n public static boolean hasKey(final ItemStack itemStack, final String key) {\r\n if (itemStack == null) return false;\r\n\r\n final Object nmsItemStack = asNMSCopy(itemStack);\r\n final Object itemCompound = hasTag(nmsItemStack) ? getTag(nmsItemStack) : newNBTTagCompound();\r\n try {\r\n return (boolean) containsMethod.invoke(itemCompound, key);\r\n } catch (IllegalAccessException | InvocationTargetException e) {\r\n return false;\r\n }\r\n }\r\n\r\n public static ItemStack removeKey(final ItemStack itemStack, final String key) {\r\n if (itemStack == null) return null;\r\n if (itemStack.getType() == Material.AIR) return null;\r\n\r\n Object nmsItemStack = asNMSCopy(itemStack);\r\n if (!hasTag(nmsItemStack)) return itemStack;\r\n Object itemCompound = hasTag(nmsItemStack) ? getTag(nmsItemStack) : newNBTTagCompound();\r\n\r\n removeTag(itemCompound, key);\r\n setTag(nmsItemStack, itemCompound);\r\n\r\n return asBukkitCopy(nmsItemStack);\r\n }\r\n\r\n /**\r\n * Mimics the itemCompound#setString method.\r\n *\r\n * @param itemCompound The ItemCompound.\r\n * @param key The key to add.\r\n * @param value The value to add.\r\n */\r\n private static void setString(final Object itemCompound, final String key, final String value) {\r\n try {\r\n setStringMethod.invoke(itemCompound, key, value);\r\n } catch (IllegalAccessException | InvocationTargetException ignored) {\r\n }\r\n }\r\n\r\n private static void setBoolean(final Object itemCompound, final String key, final boolean value) {\r\n try {\r\n setBooleanMethod.invoke(itemCompound, key, value);\r\n } catch (IllegalAccessException | InvocationTargetException ignored) {\r\n }\r\n }\r\n\r\n private static void setInt(final Object itemCompound, final String key, final int value) {\r\n try {\r\n setIntMethod.invoke(itemCompound, key, value);\r\n } catch (IllegalAccessException | InvocationTargetException ignored) {\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the itemCompound#getString method.\r\n *\r\n * @param itemCompound The ItemCompound.\r\n * @param key The key to get from.\r\n * @return A string with the value from the key.\r\n */\r\n private static String getString(final Object itemCompound, final String key) {\r\n try {\r\n return (String) getStringMethod.invoke(itemCompound, key);\r\n } catch (IllegalAccessException | InvocationTargetException e) {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the nmsItemStack#hasTag method.\r\n *\r\n * @param nmsItemStack the NMS ItemStack to check from.\r\n * @return True or false depending if it has tag or not.\r\n */\r\n private static boolean hasTag(final Object nmsItemStack) {\r\n try {\r\n return (boolean) hasTagMethod.invoke(nmsItemStack);\r\n } catch (IllegalAccessException | InvocationTargetException e) {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the nmsItemStack#getTag method.\r\n *\r\n * @param nmsItemStack The NMS ItemStack to get from.\r\n * @return The tag compound.\r\n */\r\n public static Object getTag(final Object nmsItemStack) {\r\n try {\r\n return getTagMethod.invoke(nmsItemStack);\r\n } catch (IllegalAccessException | InvocationTargetException e) {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the nmsItemStack#setTag method.\r\n *\r\n * @param nmsItemStack the NMS ItemStack to set the tag to.\r\n * @param itemCompound The item compound to set.\r\n */\r\n private static void setTag(final Object nmsItemStack, final Object itemCompound) {\r\n try {\r\n setTagMethod.invoke(nmsItemStack, itemCompound);\r\n } catch (IllegalAccessException | InvocationTargetException ignored) {\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the nmsItemStack#removeTag method.\r\n *\r\n * @param nmsItemStack the NMS ItemStack to remove the tag from.\r\n * @param itemCompound The item compound to remove.\r\n */\r\n private static void removeTag(final Object nmsItemStack, final Object itemCompound) {\r\n try {\r\n removeTagMethod.invoke(nmsItemStack, itemCompound);\r\n } catch (IllegalAccessException | InvocationTargetException ignored) {\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the new NBTTagCompound instantiation.\r\n *\r\n * @return The new NBTTagCompound.\r\n */\r\n private static Object newNBTTagCompound() {\r\n try {\r\n return nbtCompoundConstructor.newInstance();\r\n } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the CraftItemStack#asNMSCopy method.\r\n *\r\n * @param itemStack The ItemStack to make NMS copy.\r\n * @return An NMS copy of the ItemStack.\r\n */\r\n public static Object asNMSCopy(final ItemStack itemStack) {\r\n try {\r\n return asNMSCopyMethod.invoke(null, itemStack);\r\n } catch (IllegalAccessException | InvocationTargetException e) {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Mimics the CraftItemStack#asBukkitCopy method.\r\n *\r\n * @param nmsItemStack The NMS ItemStack to turn into {@link ItemStack}.\r\n * @return The new {@link ItemStack}.\r\n */\r\n public static ItemStack asBukkitCopy(final Object nmsItemStack) {\r\n try {\r\n return (ItemStack) asBukkitCopyMethod.invoke(null, nmsItemStack);\r\n } catch (IllegalAccessException | InvocationTargetException e) {\r\n return null;\r\n }\r\n }\r\n\r\n private static class VersionConstants {\r\n\r\n private final static String CONTAINS_METHOD_NAME = containsMethodName();\r\n private final static String GET_STRING_METHOD_NAME = getStringMethodName();\r\n private final static String SET_STRING_METHOD_NAME = setStringMethodName();\r\n private final static String SET_BOOLEAN_METHOD_NAME = setBooleanMethodName();\r\n private final static String SET_INTEGER_METHOD_NAME = setIntegerMethodName();\r\n private final static String REMOVE_TAG_METHOD_NAME = removeTagMethodName();\r\n private final static String HAS_TAG_METHOD_NAME = hasTagMethodName();\r\n private final static String GET_TAG_METHOD_NAME = getTagMethodName();\r\n private final static String SET_TAG_METHOD_NAME = setTagMethodName();\r\n\r\n private static String getStringMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"l\";\r\n return \"getString\";\r\n }\r\n\r\n private static String setStringMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"a\";\r\n return \"setString\";\r\n }\r\n\r\n private static String setBooleanMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"a\";\r\n return \"setBoolean\";\r\n }\r\n\r\n private static String setIntegerMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"a\";\r\n return \"setInt\";\r\n }\r\n\r\n private static String hasTagMethodName() {\r\n if (VersionHelper.CURRENT_VERSION >= 1200) return \"u\"; // 1.20 variable change\r\n if (VersionHelper.CURRENT_VERSION >= 1190) return \"t\"; // 1.19 variable change\r\n if (VersionHelper.CURRENT_VERSION == 1182) return \"s\"; // 1.18.2 variable change\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"r\"; // 1.18-1.18.1\r\n return \"hasTag\";\r\n }\r\n\r\n private static String getTagMethodName() {\r\n if (VersionHelper.CURRENT_VERSION >= 1200) return \"v\"; // 1.20 variable change\r\n if (VersionHelper.CURRENT_VERSION >= 1190) return \"u\"; // 1.19 variable change\r\n if (VersionHelper.CURRENT_VERSION == 1182) return \"t\"; // 1.18.2 variable change\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"s\"; // 1.18-1.18.1\r\n return \"getTag\";\r\n }\r\n\r\n private static String containsMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"e\";\r\n return \"hasKey\";\r\n }\r\n\r\n private static String setTagMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"c\";\r\n return \"setTag\";\r\n }\r\n\r\n private static String removeTagMethodName() {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) return \"r\";\r\n return \"remove\";\r\n }\r\n\r\n }\r\n}\r" }, { "identifier": "DebugLevel", "path": "src/main/java/com/extendedclip/deluxemenus/utils/DebugLevel.java", "snippet": "public enum DebugLevel {\r\n LOWEST(0, \"LOWEST\"),\r\n LOW(1, \"LOW\"),\r\n MEDIUM(2, \"MEDIUM\"),\r\n HIGH(3, \"HIGH\"),\r\n HIGHEST(4, \"HIGHEST\");\r\n\r\n private final String[] names;\r\n private final int priority;\r\n\r\n private DebugLevel(final int priority, @NotNull final String... names) {\r\n this.priority = priority;\r\n this.names = names;\r\n }\r\n\r\n public int getPriority() {\r\n return priority;\r\n }\r\n\r\n private static final Map<String, DebugLevel> LEVELS = Arrays.stream(values())\r\n .flatMap(level -> Arrays.stream(level.names).map(name -> Map.entry(name.toLowerCase(Locale.ROOT), level)))\r\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\r\n\r\n public static @Nullable DebugLevel getByName(@NotNull final String name) {\r\n return LEVELS.get(name.toLowerCase(Locale.ROOT));\r\n }\r\n}\r" }, { "identifier": "ItemUtils", "path": "src/main/java/com/extendedclip/deluxemenus/utils/ItemUtils.java", "snippet": "public final class ItemUtils {\n\n private ItemUtils() {\n throw new UnsupportedOperationException(\"This is a utility class and cannot be instantiated\");\n }\n\n /**\n * Checks if the string starts with the substring \"placeholder-\". The check is case-sensitive.\n *\n * @param material The string to check\n * @return true if the string starts with \"placeholder-\", false otherwise\n */\n public static boolean isPlaceholderMaterial(@NotNull final String material) {\n return material.startsWith(PLACEHOLDER_PREFIX);\n }\n\n /**\n * Checks if the string is a player item. The check is case-sensitive.\n * Player items are: \"main_hand\", \"off_hand\", \"armor_helmet\", \"armor_chestplate\", \"armor_leggings\", \"armor_boots\"\n *\n * @param material The string to check\n * @return true if the string is a player item, false otherwise\n */\n public static boolean isPlayerItem(@NotNull final String material) {\n return INVENTORY_ITEM_ACCESSORS.containsKey(material);\n }\n\n /**\n * Checks if the string is an ItemsAdder item. The check is case-sensitive.\n * ItemsAdder items are: \"itemsadder-{namespace:name}\"\n *\n * @param material The string to check\n * @return true if the string is an ItemsAdder item, false otherwise\n */\n public static boolean isItemsAdderItem(@NotNull final String material) {\n return material.startsWith(ITEMSADDER_PREFIX);\n }\n\n /**\n * Checks if the string is an Oraxen item. The check is case-sensitive.\n * Oraxen items are: \"oraxen-{namespace:name}\"\n *\n * @param material The string to check\n * @return true if the string is an Oraxen item, false otherwise\n */\n public static boolean isOraxenItem(@NotNull final String material) {\n return material.startsWith(ORAXEN_PREFIX);\n }\n\n /**\n * Checks if the string is an MMOItems item. The check is case-sensitive.\n * MMOItems items are: \"mmoitems-{namespace:name}\"\n *\n * @param material The string to check\n * @return true if the string is an MMOItem item, false otherwise\n */\n public static boolean isMMOItemsItem(@NotNull final String material) {\n return material.startsWith(MMOITEMS_PREFIX);\n }\n\n /**\n * Checks if the material is a water bottle. The check is case-insensitive.\n *\n * @param material The material to check\n * @return true if the material is a water bottle, false otherwise\n */\n public static boolean isWaterBottle(@NotNull final String material) {\n return material.equalsIgnoreCase(WATER_BOTTLE);\n }\n\n /**\n * Checks if the material is a banner.\n *\n * @param material The material to check\n * @return true if the material is a banner, false otherwise\n */\n public static boolean isBanner(@NotNull final Material material) {\n return material.name().endsWith(\"_BANNER\");\n }\n\n /**\n * Checks if the material is a shield.\n *\n * @param material The material to check\n * @return true if the material is a shield, false otherwise\n */\n public static boolean isShield(@NotNull final Material material) {\n return material == Material.SHIELD;\n }\n\n /**\n * Checks if the ItemStack is a potion or can hold potion effects.\n *\n * @param itemStack The ItemStack to check\n * @return true if the ItemStack is a potion or can hold a potion effect, false otherwise\n */\n public static boolean hasPotionMeta(@NotNull final ItemStack itemStack) {\n return itemStack.getItemMeta() instanceof PotionMeta;\n }\n\n /**\n * Creates water bottles stack\n * @param amount the amount of water bottles to put in the stack\n * @return the water bottles stack\n */\n public static @NotNull ItemStack createWaterBottles(final int amount) {\n final ItemStack itemStack = new ItemStack(Material.POTION, amount);\n final PotionMeta itemMeta = (PotionMeta) itemStack.getItemMeta();\n\n if (itemMeta != null) {\n final PotionData potionData = new PotionData(PotionType.WATER);\n itemMeta.setBasePotionData(potionData);\n itemStack.setItemMeta(itemMeta);\n }\n\n return itemStack;\n }\n}" }, { "identifier": "StringUtils", "path": "src/main/java/com/extendedclip/deluxemenus/utils/StringUtils.java", "snippet": "public class StringUtils {\r\n\r\n private final static Pattern HEX_PATTERN = Pattern\r\n .compile(\"&(#[a-f0-9]{6})\", Pattern.CASE_INSENSITIVE);\r\n\r\n /**\r\n * Translates the ampersand color codes like '&7' to their section symbol counterparts like '§7'.\r\n * <br>\r\n * It also translates hex colors like '&#aaFF00' to their section symbol counterparts like '§x§a§a§F§F§0§0'.\r\n *\r\n * @param input The string in which to translate the color codes.\r\n * @return The string with the translated colors.\r\n */\r\n @NotNull\r\n public static String color(@NotNull String input) {\r\n //Hex Support for 1.16.1+\r\n Matcher m = HEX_PATTERN.matcher(input);\r\n if (VersionHelper.IS_HEX_VERSION) {\r\n while (m.find()) {\r\n input = input.replace(m.group(), ChatColor.of(m.group(1)).toString());\r\n }\r\n }\r\n\r\n return ChatColor.translateAlternateColorCodes('&', input);\r\n }\r\n\r\n}\r" }, { "identifier": "VersionHelper", "path": "src/main/java/com/extendedclip/deluxemenus/utils/VersionHelper.java", "snippet": "public final class VersionHelper {\r\n\r\n private static final String PACKAGE_NAME = Bukkit.getServer().getClass().getPackage().getName();\r\n public static final String NMS_VERSION = PACKAGE_NAME.substring(PACKAGE_NAME.lastIndexOf('.') + 1);\r\n\r\n // PlayerProfile API\r\n private static final int V1_18_1 = 1181;\r\n // Mojang obfuscation changes\r\n private static final int V1_17 = 1170;\r\n // Material and components on items change\r\n private static final int V1_13 = 1130;\r\n // PDC and customModelData\r\n private static final int V1_14 = 1140;\r\n // Hex colors\r\n private static final int V1_16 = 1160;\r\n // Paper adventure changes\r\n private static final int V1_16_5 = 1165;\r\n // SkullMeta#setOwningPlayer was added\r\n private static final int V1_12 = 1120;\r\n\r\n public static final int CURRENT_VERSION = getCurrentVersion();\r\n\r\n private static final boolean IS_PAPER = checkPaper();\r\n\r\n\r\n /**\r\n * Checks if current version includes the PlayerProfile API\r\n */\r\n public static final boolean HAS_PLAYER_PROFILES = CURRENT_VERSION >= V1_18_1;\r\n\r\n /**\r\n * Checks if the current version was a version without versioned packages.\r\n */\r\n public static final boolean HAS_OBFUSCATED_NAMES = CURRENT_VERSION >= V1_17;\r\n\r\n /**\r\n * Checks if the version supports Components or not\r\n * Paper versions above 1.16.5 would be true\r\n * Spigot always false\r\n */\r\n public static final boolean IS_COMPONENT = IS_PAPER && CURRENT_VERSION >= V1_16_5;\r\n\r\n /**\r\n * Checks if the version is lower than 1.13 due to the item changes\r\n */\r\n public static final boolean IS_ITEM_LEGACY = CURRENT_VERSION < V1_13;\r\n\r\n /**\r\n * Checks if the version supports {@link org.bukkit.persistence.PersistentDataContainer}\r\n */\r\n public static final boolean IS_PDC_VERSION = CURRENT_VERSION >= V1_14;\r\n\r\n /**\r\n * Checks if the version doesn't have {@link org.bukkit.inventory.meta.SkullMeta#setOwningPlayer(OfflinePlayer)} and\r\n * {@link org.bukkit.inventory.meta.SkullMeta#setOwner(String)} should be used instead\r\n */\r\n public static final boolean IS_SKULL_OWNER_LEGACY = CURRENT_VERSION <= V1_12;\r\n\r\n /**\r\n * Checks if the version has {@link org.bukkit.inventory.meta.ItemMeta#setCustomModelData(Integer)}\r\n */\r\n public static final boolean IS_CUSTOM_MODEL_DATA = CURRENT_VERSION >= V1_14;\r\n\r\n public static final boolean IS_HEX_VERSION = CURRENT_VERSION >= V1_16;\r\n\r\n private static List<InventoryType> CHEST_INVENTORY_TYPES = null;\r\n\r\n private static List<InventoryType> VALID_INVENTORY_TYPES = null;\r\n\r\n private static List<InventoryType> getChestInventoryTypes() {\r\n if (CHEST_INVENTORY_TYPES != null) return CHEST_INVENTORY_TYPES;\r\n\r\n if (CURRENT_VERSION >= V1_14) {\r\n CHEST_INVENTORY_TYPES = List.of(\r\n InventoryType.BARREL,\r\n InventoryType.CHEST,\r\n InventoryType.CRAFTING,\r\n InventoryType.CREATIVE,\r\n InventoryType.ENDER_CHEST,\r\n InventoryType.LECTERN,\r\n InventoryType.MERCHANT,\r\n InventoryType.SHULKER_BOX\r\n );\r\n\r\n return CHEST_INVENTORY_TYPES;\r\n }\r\n\r\n CHEST_INVENTORY_TYPES = List.of(\r\n InventoryType.CHEST,\r\n InventoryType.CRAFTING,\r\n InventoryType.CREATIVE,\r\n InventoryType.ENDER_CHEST,\r\n InventoryType.MERCHANT,\r\n InventoryType.SHULKER_BOX\r\n );\r\n\r\n return CHEST_INVENTORY_TYPES;\r\n }\r\n\r\n public static List<InventoryType> getValidInventoryTypes() {\r\n if (VALID_INVENTORY_TYPES != null) return VALID_INVENTORY_TYPES;\r\n\r\n final List<InventoryType> chestInventoryTypes = getChestInventoryTypes();\r\n final List<InventoryType> validInventoryTypes = new ArrayList<>();\r\n\r\n for (final InventoryType inventoryType : InventoryType.values()) {\r\n if (inventoryType != InventoryType.CHEST && chestInventoryTypes.contains(inventoryType)) continue;\r\n validInventoryTypes.add(inventoryType);\r\n }\r\n\r\n VALID_INVENTORY_TYPES = validInventoryTypes;\r\n return VALID_INVENTORY_TYPES;\r\n }\r\n\r\n /**\r\n * Check if the server has access to the Paper API\r\n * Taken from <a href=\"https://github.com/PaperMC/PaperLib\">PaperLib</a>\r\n *\r\n * @return True if on Paper server (or forks), false anything else\r\n */\r\n private static boolean checkPaper() {\r\n try {\r\n Class.forName(\"com.destroystokyo.paper.PaperConfig\");\r\n return true;\r\n } catch (ClassNotFoundException ignored) {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current server version\r\n *\r\n * @return A protocol like number representing the version, for example 1.16.5 - 1165\r\n */\r\n private static int getCurrentVersion() {\r\n // No need to cache since will only run once\r\n final Matcher matcher = Pattern.compile(\"(?<version>\\\\d+\\\\.\\\\d+)(?<patch>\\\\.\\\\d+)?\").matcher(Bukkit.getBukkitVersion());\r\n\r\n final StringBuilder stringBuilder = new StringBuilder();\r\n if (matcher.find()) {\r\n stringBuilder.append(matcher.group(\"version\").replace(\".\", \"\"));\r\n final String patch = matcher.group(\"patch\");\r\n if (patch == null) stringBuilder.append(\"0\");\r\n else stringBuilder.append(patch.replace(\".\", \"\"));\r\n }\r\n\r\n //noinspection UnstableApiUsage\r\n final Integer version = Ints.tryParse(stringBuilder.toString());\r\n\r\n // Should never fail\r\n if (version == null) throw new RuntimeException(\"Could not retrieve server version!\");\r\n\r\n return version;\r\n }\r\n\r\n public static String getNmsVersion() {\r\n final String version = Bukkit.getServer().getClass().getPackage().getName();\r\n return version.substring(version.lastIndexOf('.') + 1);\r\n }\r\n\r\n /**\r\n * Gets the NMS class from class name.\r\n *\r\n * @return The NMS class.\r\n */\r\n public static Class<?> getNMSClass(final String pkg, final String className) throws ClassNotFoundException {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) {\r\n return Class.forName(\"net.minecraft.\" + pkg + \".\" + className);\r\n }\r\n return Class.forName(\"net.minecraft.server.\" + VersionHelper.NMS_VERSION + \".\" + className);\r\n }\r\n\r\n /**\r\n * Gets the craft class from class name.\r\n *\r\n * @return The craft class.\r\n */\r\n public static Class<?> getCraftClass(@NotNull final String name) throws ClassNotFoundException {\r\n return Class.forName(\"org.bukkit.craftbukkit.\" + NMS_VERSION + \".\" + name);\r\n }\r\n\r\n}\r" }, { "identifier": "INVENTORY_ITEM_ACCESSORS", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final Map<String, Function<PlayerInventory, ItemStack>> INVENTORY_ITEM_ACCESSORS = ImmutableMap.<String, Function<PlayerInventory, ItemStack>>builder()\r\n .put(MAIN_HAND, PlayerInventory::getItemInMainHand)\r\n .put(OFF_HAND, PlayerInventory::getItemInOffHand)\r\n .put(HELMET, PlayerInventory::getHelmet)\r\n .put(CHESTPLATE, PlayerInventory::getChestplate)\r\n .put(LEGGINGS, PlayerInventory::getLeggings)\r\n .put(BOOTS, PlayerInventory::getBoots)\r\n .build();\r" }, { "identifier": "ITEMSADDER_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String ITEMSADDER_PREFIX = \"itemsadder-\";\r" }, { "identifier": "MMOITEMS_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String MMOITEMS_PREFIX = \"mmoitems-\";\r" }, { "identifier": "ORAXEN_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String ORAXEN_PREFIX = \"oraxen-\";\r" }, { "identifier": "PLACEHOLDER_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String PLACEHOLDER_PREFIX = \"placeholder-\";\r" } ]
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.hooks.ItemHook; import com.extendedclip.deluxemenus.nbt.NbtProvider; import com.extendedclip.deluxemenus.utils.DebugLevel; import com.extendedclip.deluxemenus.utils.ItemUtils; import com.extendedclip.deluxemenus.utils.StringUtils; import com.extendedclip.deluxemenus.utils.VersionHelper; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.block.Banner; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BannerMeta; import org.bukkit.inventory.meta.BlockStateMeta; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.FireworkEffectMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.stream.Collectors; import static com.extendedclip.deluxemenus.utils.Constants.INVENTORY_ITEM_ACCESSORS; import static com.extendedclip.deluxemenus.utils.Constants.ITEMSADDER_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.MMOITEMS_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.ORAXEN_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.PLACEHOLDER_PREFIX;
9,720
package com.extendedclip.deluxemenus.menu; public class MenuItem { private final @NotNull MenuItemOptions options; public MenuItem(@NotNull final MenuItemOptions options) { this.options = options; } public ItemStack getItemStack(@NotNull final MenuHolder holder) { final Player viewer = holder.getViewer(); ItemStack itemStack = null; int amount = 1; String stringMaterial = this.options.material(); String lowercaseStringMaterial = stringMaterial.toLowerCase(Locale.ROOT); if (ItemUtils.isPlaceholderMaterial(lowercaseStringMaterial)) { stringMaterial = holder.setPlaceholders(stringMaterial.substring(PLACEHOLDER_PREFIX.length())); lowercaseStringMaterial = stringMaterial.toLowerCase(Locale.ENGLISH); } if (ItemUtils.isPlayerItem(lowercaseStringMaterial)) {
package com.extendedclip.deluxemenus.menu; public class MenuItem { private final @NotNull MenuItemOptions options; public MenuItem(@NotNull final MenuItemOptions options) { this.options = options; } public ItemStack getItemStack(@NotNull final MenuHolder holder) { final Player viewer = holder.getViewer(); ItemStack itemStack = null; int amount = 1; String stringMaterial = this.options.material(); String lowercaseStringMaterial = stringMaterial.toLowerCase(Locale.ROOT); if (ItemUtils.isPlaceholderMaterial(lowercaseStringMaterial)) { stringMaterial = holder.setPlaceholders(stringMaterial.substring(PLACEHOLDER_PREFIX.length())); lowercaseStringMaterial = stringMaterial.toLowerCase(Locale.ENGLISH); } if (ItemUtils.isPlayerItem(lowercaseStringMaterial)) {
final ItemStack playerItem = INVENTORY_ITEM_ACCESSORS.get(lowercaseStringMaterial).apply(viewer.getInventory());
7
2023-12-14 23:41:07+00:00
12k
lxs2601055687/contextAdminRuoYi
ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CaptchaController.java
[ { "identifier": "CacheConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java", "snippet": "public interface CacheConstants {\n\n /**\n * 登录用户 redis key\n */\n String LOGIN_TOKEN_KEY = \"Authorization:login:token:\";\n\n /**\n * 在线用户 redis key\n */\n String ONLINE_TOKEN_KEY = \"online_tokens:\";\n\n /**\n * 验证码 redis key\n */\n String CAPTCHA_CODE_KEY = \"captcha_codes:\";\n\n /**\n * 参数管理 cache key\n */\n String SYS_CONFIG_KEY = \"sys_config:\";\n\n /**\n * 字典管理 cache key\n */\n String SYS_DICT_KEY = \"sys_dict:\";\n\n /**\n * 防重提交 redis key\n */\n String REPEAT_SUBMIT_KEY = \"repeat_submit:\";\n\n /**\n * 限流 redis key\n */\n String RATE_LIMIT_KEY = \"rate_limit:\";\n\n /**\n * 登录账户密码错误次数 redis key\n */\n String PWD_ERR_CNT_KEY = \"pwd_err_cnt:\";\n}" }, { "identifier": "Constants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java", "snippet": "public interface Constants {\n\n /**\n * UTF-8 字符集\n */\n String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n String GBK = \"GBK\";\n\n /**\n * www主域\n */\n String WWW = \"www.\";\n\n /**\n * http请求\n */\n String HTTP = \"http://\";\n\n /**\n * https请求\n */\n String HTTPS = \"https://\";\n\n /**\n * 通用成功标识\n */\n String SUCCESS = \"0\";\n\n /**\n * 通用失败标识\n */\n String FAIL = \"1\";\n\n /**\n * 登录成功\n */\n String LOGIN_SUCCESS = \"Success\";\n\n /**\n * 注销\n */\n String LOGOUT = \"Logout\";\n\n /**\n * 注册\n */\n String REGISTER = \"Register\";\n\n /**\n * 登录失败\n */\n String LOGIN_FAIL = \"Error\";\n\n /**\n * 验证码有效期(分钟)\n */\n Integer CAPTCHA_EXPIRATION = 2;\n\n /**\n * 令牌\n */\n String TOKEN = \"token\";\n\n}" }, { "identifier": "R", "path": "ruoyi-common/src/main/java/com/ruoyi/common/core/domain/R.java", "snippet": "@Data\n@NoArgsConstructor\npublic class R<T> implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * 成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 失败\n */\n public static final int FAIL = 500;\n\n private int code;\n\n private String msg;\n\n private T data;\n\n public static <T> R<T> ok() {\n return restResult(null, SUCCESS, \"操作成功\");\n }\n\n public static <T> R<T> ok(T data) {\n return restResult(data, SUCCESS, \"操作成功\");\n }\n\n public static <T> R<T> ok(String msg) {\n return restResult(null, SUCCESS, msg);\n }\n\n public static <T> R<T> ok(String msg, T data) {\n return restResult(data, SUCCESS, msg);\n }\n\n public static <T> R<T> fail() {\n return restResult(null, FAIL, \"操作失败\");\n }\n\n public static <T> R<T> fail(String msg) {\n return restResult(null, FAIL, msg);\n }\n\n public static <T> R<T> fail(T data) {\n return restResult(data, FAIL, \"操作失败\");\n }\n\n public static <T> R<T> fail(String msg, T data) {\n return restResult(data, FAIL, msg);\n }\n\n public static <T> R<T> fail(int code, String msg) {\n return restResult(null, code, msg);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static <T> R<T> warn(String msg) {\n return restResult(null, HttpStatus.WARN, msg);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static <T> R<T> warn(String msg, T data) {\n return restResult(data, HttpStatus.WARN, msg);\n }\n\n private static <T> R<T> restResult(T data, int code, String msg) {\n R<T> r = new R<>();\n r.setCode(code);\n r.setData(data);\n r.setMsg(msg);\n return r;\n }\n\n public static <T> Boolean isError(R<T> ret) {\n return !isSuccess(ret);\n }\n\n public static <T> Boolean isSuccess(R<T> ret) {\n return R.SUCCESS == ret.getCode();\n }\n}" }, { "identifier": "CaptchaType", "path": "ruoyi-common/src/main/java/com/ruoyi/common/enums/CaptchaType.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CaptchaType {\n\n /**\n * 数字\n */\n MATH(UnsignedMathGenerator.class),\n\n /**\n * 字符\n */\n CHAR(RandomGenerator.class);\n\n private final Class<? extends CodeGenerator> clazz;\n}" }, { "identifier": "StringUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringUtils extends org.apache.commons.lang3.StringUtils {\n\n public static final String SEPARATOR = \",\";\n\n /**\n * 获取参数不为空值\n *\n * @param str defaultValue 要判断的value\n * @return value 返回值\n */\n public static String blankToDefault(String str, String defaultValue) {\n return StrUtil.blankToDefault(str, defaultValue);\n }\n\n /**\n * * 判断一个字符串是否为空串\n *\n * @param str String\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(String str) {\n return StrUtil.isEmpty(str);\n }\n\n /**\n * * 判断一个字符串是否为非空串\n *\n * @param str String\n * @return true:非空串 false:空串\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n\n /**\n * 去空格\n */\n public static String trim(String str) {\n return StrUtil.trim(str);\n }\n\n /**\n * 截取字符串\n *\n * @param str 字符串\n * @param start 开始\n * @return 结果\n */\n public static String substring(final String str, int start) {\n return substring(str, start, str.length());\n }\n\n /**\n * 截取字符串\n *\n * @param str 字符串\n * @param start 开始\n * @param end 结束\n * @return 结果\n */\n public static String substring(final String str, int start, int end) {\n return StrUtil.sub(str, start, end);\n }\n\n /**\n * 格式化文本, {} 表示占位符<br>\n * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>\n * 如果想输出 {} 使用 \\\\转义 { 即可,如果想输出 {} 之前的 \\ 使用双转义符 \\\\\\\\ 即可<br>\n * 例:<br>\n * 通常使用:format(\"this is {} for {}\", \"a\", \"b\") -> this is a for b<br>\n * 转义{}: format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is {} for a<br>\n * 转义\\: format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b<br>\n *\n * @param template 文本模板,被替换的部分用 {} 表示\n * @param params 参数值\n * @return 格式化后的文本\n */\n public static String format(String template, Object... params) {\n return StrUtil.format(template, params);\n }\n\n /**\n * 是否为http(s)://开头\n *\n * @param link 链接\n * @return 结果\n */\n public static boolean ishttp(String link) {\n return Validator.isUrl(link);\n }\n\n /**\n * 字符串转set\n *\n * @param str 字符串\n * @param sep 分隔符\n * @return set集合\n */\n public static Set<String> str2Set(String str, String sep) {\n return new HashSet<>(str2List(str, sep, true, false));\n }\n\n /**\n * 字符串转list\n *\n * @param str 字符串\n * @param sep 分隔符\n * @param filterBlank 过滤纯空白\n * @param trim 去掉首尾空白\n * @return list集合\n */\n public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {\n List<String> list = new ArrayList<>();\n if (isEmpty(str)) {\n return list;\n }\n\n // 过滤空白字符串\n if (filterBlank && isBlank(str)) {\n return list;\n }\n String[] split = str.split(sep);\n for (String string : split) {\n if (filterBlank && isBlank(string)) {\n continue;\n }\n if (trim) {\n string = trim(string);\n }\n list.add(string);\n }\n\n return list;\n }\n\n /**\n * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写\n *\n * @param cs 指定字符串\n * @param searchCharSequences 需要检查的字符串数组\n * @return 是否包含任意一个字符串\n */\n public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {\n return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);\n }\n\n /**\n * 驼峰转下划线命名\n */\n public static String toUnderScoreCase(String str) {\n return StrUtil.toUnderlineCase(str);\n }\n\n /**\n * 是否包含字符串\n *\n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n return StrUtil.equalsAnyIgnoreCase(str, strs);\n }\n\n /**\n * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld\n *\n * @param name 转换前的下划线大写方式命名的字符串\n * @return 转换后的驼峰式命名的字符串\n */\n public static String convertToCamelCase(String name) {\n return StrUtil.upperFirst(StrUtil.toCamelCase(name));\n }\n\n /**\n * 驼峰式命名法 例如:user_name->userName\n */\n public static String toCamelCase(String s) {\n return StrUtil.toCamelCase(s);\n }\n\n /**\n * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串\n *\n * @param str 指定字符串\n * @param strs 需要检查的字符串数组\n * @return 是否匹配\n */\n public static boolean matches(String str, List<String> strs) {\n if (isEmpty(str) || CollUtil.isEmpty(strs)) {\n return false;\n }\n for (String pattern : strs) {\n if (isMatch(pattern, str)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断url是否与规则配置:\n * ? 表示单个字符;\n * * 表示一层路径内的任意字符串,不可跨层级;\n * ** 表示任意层路径;\n *\n * @param pattern 匹配规则\n * @param url 需要匹配的url\n */\n public static boolean isMatch(String pattern, String url) {\n AntPathMatcher matcher = new AntPathMatcher();\n return matcher.match(pattern, url);\n }\n\n /**\n * 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。\n *\n * @param num 数字对象\n * @param size 字符串指定长度\n * @return 返回数字的字符串格式,该字符串为指定长度。\n */\n public static String padl(final Number num, final int size) {\n return padl(num.toString(), size, '0');\n }\n\n /**\n * 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。\n *\n * @param s 原始字符串\n * @param size 字符串指定长度\n * @param c 用于补齐的字符\n * @return 返回指定长度的字符串,由原字符串左补齐或截取得到。\n */\n public static String padl(final String s, final int size, final char c) {\n final StringBuilder sb = new StringBuilder(size);\n if (s != null) {\n final int len = s.length();\n if (s.length() <= size) {\n for (int i = size - len; i > 0; i--) {\n sb.append(c);\n }\n sb.append(s);\n } else {\n return s.substring(len - size, len);\n }\n } else {\n for (int i = size; i > 0; i--) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n /**\n * 切分字符串(分隔符默认逗号)\n *\n * @param str 被切分的字符串\n * @return 分割后的数据列表\n */\n public static List<String> splitList(String str) {\n return splitTo(str, Convert::toStr);\n }\n\n /**\n * 切分字符串\n *\n * @param str 被切分的字符串\n * @param separator 分隔符\n * @return 分割后的数据列表\n */\n public static List<String> splitList(String str, String separator) {\n return splitTo(str, separator, Convert::toStr);\n }\n\n /**\n * 切分字符串自定义转换(分隔符默认逗号)\n *\n * @param str 被切分的字符串\n * @param mapper 自定义转换\n * @return 分割后的数据列表\n */\n public static <T> List<T> splitTo(String str, Function<? super Object, T> mapper) {\n return splitTo(str, SEPARATOR, mapper);\n }\n\n /**\n * 切分字符串自定义转换\n *\n * @param str 被切分的字符串\n * @param separator 分隔符\n * @param mapper 自定义转换\n * @return 分割后的数据列表\n */\n public static <T> List<T> splitTo(String str, String separator, Function<? super Object, T> mapper) {\n if (isBlank(str)) {\n return new ArrayList<>(0);\n }\n return StrUtil.split(str, separator)\n .stream()\n .filter(Objects::nonNull)\n .map(mapper)\n .collect(Collectors.toList());\n }\n\n}" }, { "identifier": "RedisUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/redis/RedisUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@SuppressWarnings(value = {\"unchecked\", \"rawtypes\"})\npublic class RedisUtils {\n\n private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);\n\n /**\n * 限流\n *\n * @param key 限流key\n * @param rateType 限流类型\n * @param rate 速率\n * @param rateInterval 速率间隔\n * @return -1 表示失败\n */\n public static long rateLimiter(String key, RateType rateType, int rate, int rateInterval) {\n RRateLimiter rateLimiter = CLIENT.getRateLimiter(key);\n rateLimiter.trySetRate(rateType, rate, rateInterval, RateIntervalUnit.SECONDS);\n if (rateLimiter.tryAcquire()) {\n return rateLimiter.availablePermits();\n } else {\n return -1L;\n }\n }\n\n /**\n * 获取客户端实例\n */\n public static RedissonClient getClient() {\n return CLIENT;\n }\n\n /**\n * 发布通道消息\n *\n * @param channelKey 通道key\n * @param msg 发送数据\n * @param consumer 自定义处理\n */\n public static <T> void publish(String channelKey, T msg, Consumer<T> consumer) {\n RTopic topic = CLIENT.getTopic(channelKey);\n topic.publish(msg);\n consumer.accept(msg);\n }\n\n public static <T> void publish(String channelKey, T msg) {\n RTopic topic = CLIENT.getTopic(channelKey);\n topic.publish(msg);\n }\n\n /**\n * 订阅通道接收消息\n *\n * @param channelKey 通道key\n * @param clazz 消息类型\n * @param consumer 自定义处理\n */\n public static <T> void subscribe(String channelKey, Class<T> clazz, Consumer<T> consumer) {\n RTopic topic = CLIENT.getTopic(channelKey);\n topic.addListener(clazz, (channel, msg) -> consumer.accept(msg));\n }\n\n /**\n * 缓存基本的对象,Integer、String、实体类等\n *\n * @param key 缓存的键值\n * @param value 缓存的值\n */\n public static <T> void setCacheObject(final String key, final T value) {\n setCacheObject(key, value, false);\n }\n\n /**\n * 缓存基本的对象,保留当前对象 TTL 有效期\n *\n * @param key 缓存的键值\n * @param value 缓存的值\n * @param isSaveTtl 是否保留TTL有效期(例如: set之前ttl剩余90 set之后还是为90)\n * @since Redis 6.X 以上使用 setAndKeepTTL 兼容 5.X 方案\n */\n public static <T> void setCacheObject(final String key, final T value, final boolean isSaveTtl) {\n RBucket<T> bucket = CLIENT.getBucket(key);\n if (isSaveTtl) {\n try {\n bucket.setAndKeepTTL(value);\n } catch (Exception e) {\n long timeToLive = bucket.remainTimeToLive();\n setCacheObject(key, value, Duration.ofMillis(timeToLive));\n }\n } else {\n bucket.set(value);\n }\n }\n\n /**\n * 缓存基本的对象,Integer、String、实体类等\n *\n * @param key 缓存的键值\n * @param value 缓存的值\n * @param duration 时间\n */\n public static <T> void setCacheObject(final String key, final T value, final Duration duration) {\n RBatch batch = CLIENT.createBatch();\n RBucketAsync<T> bucket = batch.getBucket(key);\n bucket.setAsync(value);\n bucket.expireAsync(duration);\n batch.execute();\n }\n\n /**\n * 注册对象监听器\n * <p>\n * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置\n *\n * @param key 缓存的键值\n * @param listener 监听器配置\n */\n public static <T> void addObjectListener(final String key, final ObjectListener listener) {\n RBucket<T> result = CLIENT.getBucket(key);\n result.addListener(listener);\n }\n\n /**\n * 设置有效时间\n *\n * @param key Redis键\n * @param timeout 超时时间\n * @return true=设置成功;false=设置失败\n */\n public static boolean expire(final String key, final long timeout) {\n return expire(key, Duration.ofSeconds(timeout));\n }\n\n /**\n * 设置有效时间\n *\n * @param key Redis键\n * @param duration 超时时间\n * @return true=设置成功;false=设置失败\n */\n public static boolean expire(final String key, final Duration duration) {\n RBucket rBucket = CLIENT.getBucket(key);\n return rBucket.expire(duration);\n }\n\n /**\n * 获得缓存的基本对象。\n *\n * @param key 缓存键值\n * @return 缓存键值对应的数据\n */\n public static <T> T getCacheObject(final String key) {\n RBucket<T> rBucket = CLIENT.getBucket(key);\n return rBucket.get();\n }\n\n /**\n * 获得key剩余存活时间\n *\n * @param key 缓存键值\n * @return 剩余存活时间\n */\n public static <T> long getTimeToLive(final String key) {\n RBucket<T> rBucket = CLIENT.getBucket(key);\n return rBucket.remainTimeToLive();\n }\n\n /**\n * 删除单个对象\n *\n * @param key 缓存的键值\n */\n public static boolean deleteObject(final String key) {\n return CLIENT.getBucket(key).delete();\n }\n\n /**\n * 删除集合对象\n *\n * @param collection 多个对象\n */\n public static void deleteObject(final Collection collection) {\n RBatch batch = CLIENT.createBatch();\n collection.forEach(t -> {\n batch.getBucket(t.toString()).deleteAsync();\n });\n batch.execute();\n }\n\n /**\n * 检查缓存对象是否存在\n *\n * @param key 缓存的键值\n */\n public static boolean isExistsObject(final String key) {\n return CLIENT.getBucket(key).isExists();\n }\n\n /**\n * 缓存List数据\n *\n * @param key 缓存的键值\n * @param dataList 待缓存的List数据\n * @return 缓存的对象\n */\n public static <T> boolean setCacheList(final String key, final List<T> dataList) {\n RList<T> rList = CLIENT.getList(key);\n return rList.addAll(dataList);\n }\n\n /**\n * 注册List监听器\n * <p>\n * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置\n *\n * @param key 缓存的键值\n * @param listener 监听器配置\n */\n public static <T> void addListListener(final String key, final ObjectListener listener) {\n RList<T> rList = CLIENT.getList(key);\n rList.addListener(listener);\n }\n\n /**\n * 获得缓存的list对象\n *\n * @param key 缓存的键值\n * @return 缓存键值对应的数据\n */\n public static <T> List<T> getCacheList(final String key) {\n RList<T> rList = CLIENT.getList(key);\n return rList.readAll();\n }\n\n /**\n * 缓存Set\n *\n * @param key 缓存键值\n * @param dataSet 缓存的数据\n * @return 缓存数据的对象\n */\n public static <T> boolean setCacheSet(final String key, final Set<T> dataSet) {\n RSet<T> rSet = CLIENT.getSet(key);\n return rSet.addAll(dataSet);\n }\n\n /**\n * 注册Set监听器\n * <p>\n * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置\n *\n * @param key 缓存的键值\n * @param listener 监听器配置\n */\n public static <T> void addSetListener(final String key, final ObjectListener listener) {\n RSet<T> rSet = CLIENT.getSet(key);\n rSet.addListener(listener);\n }\n\n /**\n * 获得缓存的set\n *\n * @param key 缓存的key\n * @return set对象\n */\n public static <T> Set<T> getCacheSet(final String key) {\n RSet<T> rSet = CLIENT.getSet(key);\n return rSet.readAll();\n }\n\n /**\n * 缓存Map\n *\n * @param key 缓存的键值\n * @param dataMap 缓存的数据\n */\n public static <T> void setCacheMap(final String key, final Map<String, T> dataMap) {\n if (dataMap != null) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n rMap.putAll(dataMap);\n }\n }\n\n /**\n * 注册Map监听器\n * <p>\n * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置\n *\n * @param key 缓存的键值\n * @param listener 监听器配置\n */\n public static <T> void addMapListener(final String key, final ObjectListener listener) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n rMap.addListener(listener);\n }\n\n /**\n * 获得缓存的Map\n *\n * @param key 缓存的键值\n * @return map对象\n */\n public static <T> Map<String, T> getCacheMap(final String key) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n return rMap.getAll(rMap.keySet());\n }\n\n /**\n * 获得缓存Map的key列表\n *\n * @param key 缓存的键值\n * @return key列表\n */\n public static <T> Set<String> getCacheMapKeySet(final String key) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n return rMap.keySet();\n }\n\n /**\n * 往Hash中存入数据\n *\n * @param key Redis键\n * @param hKey Hash键\n * @param value 值\n */\n public static <T> void setCacheMapValue(final String key, final String hKey, final T value) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n rMap.put(hKey, value);\n }\n\n /**\n * 获取Hash中的数据\n *\n * @param key Redis键\n * @param hKey Hash键\n * @return Hash中的对象\n */\n public static <T> T getCacheMapValue(final String key, final String hKey) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n return rMap.get(hKey);\n }\n\n /**\n * 删除Hash中的数据\n *\n * @param key Redis键\n * @param hKey Hash键\n * @return Hash中的对象\n */\n public static <T> T delCacheMapValue(final String key, final String hKey) {\n RMap<String, T> rMap = CLIENT.getMap(key);\n return rMap.remove(hKey);\n }\n\n /**\n * 获取多个Hash中的数据\n *\n * @param key Redis键\n * @param hKeys Hash键集合\n * @return Hash对象集合\n */\n public static <K, V> Map<K, V> getMultiCacheMapValue(final String key, final Set<K> hKeys) {\n RMap<K, V> rMap = CLIENT.getMap(key);\n return rMap.getAll(hKeys);\n }\n\n /**\n * 设置原子值\n *\n * @param key Redis键\n * @param value 值\n */\n public static void setAtomicValue(String key, long value) {\n RAtomicLong atomic = CLIENT.getAtomicLong(key);\n atomic.set(value);\n }\n\n /**\n * 获取原子值\n *\n * @param key Redis键\n * @return 当前值\n */\n public static long getAtomicValue(String key) {\n RAtomicLong atomic = CLIENT.getAtomicLong(key);\n return atomic.get();\n }\n\n /**\n * 递增原子值\n *\n * @param key Redis键\n * @return 当前值\n */\n public static long incrAtomicValue(String key) {\n RAtomicLong atomic = CLIENT.getAtomicLong(key);\n return atomic.incrementAndGet();\n }\n\n /**\n * 递减原子值\n *\n * @param key Redis键\n * @return 当前值\n */\n public static long decrAtomicValue(String key) {\n RAtomicLong atomic = CLIENT.getAtomicLong(key);\n return atomic.decrementAndGet();\n }\n\n /**\n * 获得缓存的基本对象列表\n *\n * @param pattern 字符串前缀\n * @return 对象列表\n */\n public static Collection<String> keys(final String pattern) {\n Stream<String> stream = CLIENT.getKeys().getKeysStreamByPattern(pattern);\n return stream.collect(Collectors.toList());\n }\n\n /**\n * 删除缓存的基本对象列表\n *\n * @param pattern 字符串前缀\n */\n public static void deleteKeys(final String pattern) {\n CLIENT.getKeys().deleteByPattern(pattern);\n }\n\n /**\n * 检查redis中是否存在key\n *\n * @param key 键\n */\n public static Boolean hasKey(String key) {\n RKeys rKeys = CLIENT.getKeys();\n return rKeys.countExists(key) > 0;\n }\n}" }, { "identifier": "ReflectUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java", "snippet": "@SuppressWarnings(\"rawtypes\")\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ReflectUtils extends ReflectUtil {\n\n private static final String SETTER_PREFIX = \"set\";\n\n private static final String GETTER_PREFIX = \"get\";\n\n /**\n * 调用Getter方法.\n * 支持多级,如:对象名.对象名.方法\n */\n @SuppressWarnings(\"unchecked\")\n public static <E> E invokeGetter(Object obj, String propertyName) {\n Object object = obj;\n for (String name : StringUtils.split(propertyName, \".\")) {\n String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);\n object = invoke(object, getterMethodName);\n }\n return (E) object;\n }\n\n /**\n * 调用Setter方法, 仅匹配方法名。\n * 支持多级,如:对象名.对象名.方法\n */\n public static <E> void invokeSetter(Object obj, String propertyName, E value) {\n Object object = obj;\n String[] names = StringUtils.split(propertyName, \".\");\n for (int i = 0; i < names.length; i++) {\n if (i < names.length - 1) {\n String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);\n object = invoke(object, getterMethodName);\n } else {\n String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);\n Method method = getMethodByName(object.getClass(), setterMethodName);\n invoke(object, method, value);\n }\n }\n }\n\n}" }, { "identifier": "SpringUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/spring/SpringUtils.java", "snippet": "@Component\npublic final class SpringUtils extends SpringUtil {\n\n /**\n * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true\n *\n * @param name\n * @return boolean\n */\n public static boolean containsBean(String name) {\n return getBeanFactory().containsBean(name);\n }\n\n /**\n * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。\n * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)\n *\n * @param name\n * @return boolean\n */\n public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {\n return getBeanFactory().isSingleton(name);\n }\n\n /**\n * @param name\n * @return Class 注册对象的类型\n */\n public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {\n return getBeanFactory().getType(name);\n }\n\n /**\n * 如果给定的bean名字在bean定义中有别名,则返回这些别名\n *\n * @param name\n */\n public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {\n return getBeanFactory().getAliases(name);\n }\n\n /**\n * 获取aop代理对象\n *\n * @param invoker\n * @return\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getAopProxy(T invoker) {\n return (T) AopContext.currentProxy();\n }\n\n\n /**\n * 获取spring上下文\n */\n public static ApplicationContext context() {\n return getApplicationContext();\n }\n\n}" }, { "identifier": "CaptchaProperties", "path": "ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/CaptchaProperties.java", "snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"captcha\")\npublic class CaptchaProperties {\n\n /**\n * 验证码类型\n */\n private CaptchaType type;\n\n /**\n * 验证码类别\n */\n private CaptchaCategory category;\n\n /**\n * 数字验证码位数\n */\n private Integer numberLength;\n\n /**\n * 字符验证码长度\n */\n private Integer charLength;\n}" }, { "identifier": "SmsProperties", "path": "ruoyi-sms/src/main/java/com/ruoyi/sms/config/properties/SmsProperties.java", "snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"sms\")\npublic class SmsProperties {\n\n private Boolean enabled;\n\n /**\n * 配置节点\n * 阿里云 dysmsapi.aliyuncs.com\n * 腾讯云 sms.tencentcloudapi.com\n */\n private String endpoint;\n\n /**\n * key\n */\n private String accessKeyId;\n\n /**\n * 密匙\n */\n private String accessKeySecret;\n\n /*\n * 短信签名\n */\n private String signName;\n\n /**\n * 短信应用ID (腾讯专属)\n */\n private String sdkAppId;\n\n}" }, { "identifier": "SmsTemplate", "path": "ruoyi-sms/src/main/java/com/ruoyi/sms/core/SmsTemplate.java", "snippet": "public interface SmsTemplate {\n\n /**\n * 发送短信\n *\n * @param phones 电话号(多个逗号分割)\n * @param templateId 模板id\n * @param param 模板对应参数\n * 阿里 需使用 模板变量名称对应内容 例如: code=1234\n * 腾讯 需使用 模板变量顺序对应内容 例如: 1=1234, 1为模板内第一个参数\n */\n SmsResult send(String phones, String templateId, Map<String, String> param);\n\n}" }, { "identifier": "SmsResult", "path": "ruoyi-sms/src/main/java/com/ruoyi/sms/entity/SmsResult.java", "snippet": "@Data\n@Builder\npublic class SmsResult {\n\n /**\n * 是否成功\n */\n private boolean isSuccess;\n\n /**\n * 响应消息\n */\n private String message;\n\n /**\n * 实际响应体\n * <p>\n * 可自行转换为 SDK 对应的 SendSmsResponse\n */\n private String response;\n}" }, { "identifier": "ISysConfigService", "path": "ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java", "snippet": "public interface ISysConfigService {\n\n\n TableDataInfo<SysConfig> selectPageConfigList(SysConfig config, PageQuery pageQuery);\n\n /**\n * 查询参数配置信息\n *\n * @param configId 参数配置ID\n * @return 参数配置信息\n */\n SysConfig selectConfigById(Long configId);\n\n /**\n * 根据键名查询参数配置信息\n *\n * @param configKey 参数键名\n * @return 参数键值\n */\n String selectConfigByKey(String configKey);\n\n /**\n * 获取验证码开关\n *\n * @return true开启,false关闭\n */\n boolean selectCaptchaEnabled();\n\n /**\n * 查询参数配置列表\n *\n * @param config 参数配置信息\n * @return 参数配置集合\n */\n List<SysConfig> selectConfigList(SysConfig config);\n\n /**\n * 新增参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n String insertConfig(SysConfig config);\n\n /**\n * 修改参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n String updateConfig(SysConfig config);\n\n /**\n * 批量删除参数信息\n *\n * @param configIds 需要删除的参数ID\n */\n void deleteConfigByIds(Long[] configIds);\n\n /**\n * 加载参数缓存数据\n */\n void loadingConfigCache();\n\n /**\n * 清空参数缓存数据\n */\n void clearConfigCache();\n\n /**\n * 重置参数缓存数据\n */\n void resetConfigCache();\n\n /**\n * 校验参数键名是否唯一\n *\n * @param config 参数信息\n * @return 结果\n */\n boolean checkConfigKeyUnique(SysConfig config);\n\n}" } ]
import cn.dev33.satoken.annotation.SaIgnore; import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.RandomUtil; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.enums.CaptchaType; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.redis.RedisUtils; import com.ruoyi.common.utils.reflect.ReflectUtils; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.framework.config.properties.CaptchaProperties; import com.ruoyi.sms.config.properties.SmsProperties; import com.ruoyi.sms.core.SmsTemplate; import com.ruoyi.sms.entity.SmsResult; import com.ruoyi.system.service.ISysConfigService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.constraints.NotBlank; import java.time.Duration; import java.util.HashMap; import java.util.Map;
10,322
package com.ruoyi.web.controller.common; /** * 验证码操作处理 * * @author Lion Li */ @SaIgnore @Slf4j @Validated @RequiredArgsConstructor @RestController public class CaptchaController {
package com.ruoyi.web.controller.common; /** * 验证码操作处理 * * @author Lion Li */ @SaIgnore @Slf4j @Validated @RequiredArgsConstructor @RestController public class CaptchaController {
private final CaptchaProperties captchaProperties;
8
2023-12-07 12:06:21+00:00
12k
Earthcomputer/ModCompatChecker
root/src/main/java/net/earthcomputer/modcompatchecker/checker/indy/LambdaMetafactoryChecker.java
[ { "identifier": "Errors", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/checker/Errors.java", "snippet": "public enum Errors {\n CLASS_EXTENDS_REMOVED(\"Superclass %s is removed\"),\n CLASS_EXTENDS_FINAL(\"Superclass %s is final\"),\n CLASS_EXTENDS_INTERFACE(\"Superclass %s is an interface\"),\n CLASS_EXTENDS_SEALED(\"Superclass %s is sealed, and this class is not in its 'permits' clause\"),\n CLASS_EXTENDS_INACCESSIBLE(\"Superclass %s is inaccessible with %s visibility\"),\n CLASS_IMPLEMENTS_REMOVED(\"Superinterface %s is removed\"),\n CLASS_IMPLEMENTS_CLASS(\"Superinterface %s is a class\"),\n CLASS_IMPLEMENTS_SEALED(\"Superinterface %s is sealed, and this class is not in its 'permits' clause\"),\n CLASS_IMPLEMENTS_INACCESSIBLE(\"Superinterface %s is inaccessible with %s visibility\"),\n FIELD_TYPE_REMOVED(\"Field type %s is removed\"),\n FIELD_TYPE_INACCESSIBLE(\"Field type %s is inaccessible with %s visibility\"),\n METHOD_RETURN_TYPE_REMOVED(\"Method return type %s is removed\"),\n METHOD_RETURN_TYPE_INACCESSIBLE(\"Method return type %s is inaccessible with %s visibility\"),\n METHOD_PARAM_TYPE_REMOVED(\"Method parameter type %s is removed\"),\n METHOD_PARAM_TYPE_INACCESSIBLE(\"Method parameter type %s is inaccessible with %s visibility\"),\n METHOD_THROWS_TYPE_REMOVED(\"Method throws type %s is removed\"),\n METHOD_THROWS_TYPE_INACCESSIBLE(\"Method throws type %s is inaccessible with %s visibility\"),\n METHOD_OVERRIDES_FINAL(\"Method overrides final method\"),\n ABSTRACT_METHOD_UNIMPLEMENTED(\"Class does not implement the abstract method %s.%s %s\"),\n INCORRECT_INTERFACE_METHOD_LOOKUP(\"Class does not override the interface method %s.%s %s, resulting in it resolving to the %s method in %s\"),\n DIAMOND_PROBLEM(\"Class inherits multiple non-abstract implementations of method %s %s from different interfaces\"),\n CODE_REFERENCES_REMOVED_CLASS(\"Code accesses class %s which is removed\"),\n CODE_REFERENCES_INACCESSIBLE_CLASS(\"Code accesses class %s which is inaccessible with %s visibility\"),\n ACCESS_REMOVED_FIELD(\"Code accesses field %s.%s : %s which is removed\"),\n ACCESS_INACCESSIBLE_FIELD(\"Code accesses field %s.%s : %s which is inaccessible with %s visibility\"),\n NONSTATIC_ACCESS_TO_STATIC_FIELD(\"Code accesses static field %s.%s : %s in a non-static way\"),\n STATIC_ACCESS_TO_NONSTATIC_FIELD(\"Code accesses non-static field %s.%s : %s in a static way\"),\n WRITE_FINAL_FIELD(\"Code writes to final field %s.%s : %s\"),\n ACCESS_REMOVED_METHOD(\"Code accesses method %s.%s %s which is removed\"),\n ACCESS_INACCESSIBLE_METHOD(\"Code accesses method %s.%s %s which is inaccessible with %s visibility\"),\n INTERFACE_CALL_TO_NON_INTERFACE_METHOD(\"Code accesses non-interface method %s.%s %s as if it were in an interface\"),\n NON_INTERFACE_CALL_TO_INTERFACE_METHOD(\"Code accesses interface method %s.%s %s as if it were not in an interface\"),\n INTERFACE_CALL_TO_PACKAGE_OR_PROTECTED(\"Code accesses interface method %s.%s %s with %s visibility\"),\n NONSTATIC_CALL_TO_STATIC_METHOD(\"Code accesses static method %s.%s %s in a non-static way\"),\n STATIC_CALL_TO_NONSTATIC_METHOD(\"Code accesses non-static method %s.%s %s in a static way\"),\n INVOKESPECIAL_ABSTRACT_METHOD(\"Code invokes abstract method %s.%s %s\"),\n INVOKESPECIAL_DIAMOND_PROBLEM(\"Code invokes method %s.%s %s, which has multiple implementations from different interfaces\"),\n INSTANTIATING_ABSTRACT_CLASS(\"Code instantiates abstract class %s\"),\n INSTANTIATING_INTERFACE(\"Code instantiates interface %s\"),\n LAMBDA_INTERFACE_REMOVED(\"Lambda implements interface %s which is removed\"),\n LAMBDA_INTERFACE_INACCESSIBLE(\"Lambda implements interface %s which is inaccessible with %s visibility\"),\n LAMBDA_INTERFACE_NOT_AN_INTERFACE(\"Lambda implements %s which is not an interface\"),\n LAMBDA_DIAMOND_PROBLEM(\"Lambda inherits multiple non-abstract implementations of method %s %s from different interfaces\"),\n LAMBDA_ABSTRACT_METHOD_UNIMPLEMENTED(\"Lambda does not implement the abstract method %s.%s %s\"),\n LAMBDA_INCORRECT_INTERFACE_METHOD_LOOKUP(\"Lambda does not override the interface method %s.%s %s, resulting in it resolving to the %s method in %s\"),\n ENUM_SWITCH_ON_NON_ENUM(\"Enum switch on non-enum class %s\"),\n ENUM_SWITCH_REMOVED_ENUM_CONSTANT(\"Enum switch references removed enum constant %s.%s\"),\n ENUM_CONSTANT_NOT_AN_ENUM_CONSTANT(\"Code references non-enum-constant %s.%s as if it were an enum constant\"),\n STATIC_FINAL_FIELD_NOT_FINAL(\"Code attempts to retrieve value of static final field %s.%s : %s but it is not final\"),\n ;\n\n private final String description;\n\n Errors(String description) {\n this.description = description;\n }\n\n public String getDescription() {\n return description;\n }\n}" }, { "identifier": "IResolvedClass", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/indexer/IResolvedClass.java", "snippet": "public sealed interface IResolvedClass permits ClassIndex, ClasspathClass {\n AccessFlags getAccess();\n @Nullable\n String getSuperclass();\n List<String> getInterfaces();\n Collection<ClassMember> getFields();\n Collection<ClassMember> getMethods();\n Collection<String> getPermittedSubclasses();\n @Nullable\n String getNestHost();\n Collection<String> getNestMembers();\n}" }, { "identifier": "AccessFlags", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/AccessFlags.java", "snippet": "public final class AccessFlags {\n private final int flags;\n\n public AccessFlags(int flags) {\n this.flags = flags;\n }\n\n public AccessLevel accessLevel() {\n return AccessLevel.fromAsm(flags);\n }\n\n public boolean isStatic() {\n return (flags & Opcodes.ACC_STATIC) != 0;\n }\n\n public boolean isFinal() {\n return (flags & Opcodes.ACC_FINAL) != 0;\n }\n\n public boolean isAbstract() {\n return (flags & Opcodes.ACC_ABSTRACT) != 0;\n }\n\n public boolean isNative() {\n return (flags & Opcodes.ACC_NATIVE) != 0;\n }\n\n public boolean isVarArgs() {\n return (flags & Opcodes.ACC_VARARGS) != 0;\n }\n\n public boolean isInterface() {\n return (flags & Opcodes.ACC_INTERFACE) != 0;\n }\n\n public boolean isEnum() {\n return (flags & Opcodes.ACC_ENUM) != 0;\n }\n\n public int toAsm() {\n return flags;\n }\n\n public static AccessFlags fromReflectionModifiers(int modifiers) {\n return new AccessFlags(modifiers & (\n Opcodes.ACC_PUBLIC\n | Opcodes.ACC_PROTECTED\n | Opcodes.ACC_PRIVATE\n | Opcodes.ACC_STATIC\n | Opcodes.ACC_FINAL\n | Opcodes.ACC_ABSTRACT\n | Opcodes.ACC_NATIVE\n | Opcodes.ACC_INTERFACE\n ));\n }\n\n @Nullable\n public static AccessFlags parse(String str) {\n String[] parts = str.split(\"-\");\n AccessLevel accessLevel;\n try {\n accessLevel = AccessLevel.valueOf(parts[0].toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n return null;\n }\n int flags = accessLevel.toAsm();\n for (int i = 1; i < parts.length; i++) {\n switch (parts[i]) {\n case \"static\" -> flags |= Opcodes.ACC_STATIC;\n case \"final\" -> flags |= Opcodes.ACC_FINAL;\n case \"abstract\" -> flags |= Opcodes.ACC_ABSTRACT;\n case \"native\" -> flags |= Opcodes.ACC_NATIVE;\n case \"varargs\" -> flags |= Opcodes.ACC_VARARGS;\n case \"interface\" -> flags |= Opcodes.ACC_INTERFACE;\n case \"enum\" -> flags |= Opcodes.ACC_ENUM;\n default -> {\n return null;\n }\n }\n }\n return new AccessFlags(flags);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(accessLevel().getLowerName());\n if (isStatic()) {\n sb.append(\"-static\");\n }\n if (isFinal()) {\n sb.append(\"-final\");\n }\n if (isAbstract()) {\n sb.append(\"-abstract\");\n }\n if (isNative()) {\n sb.append(\"-native\");\n }\n if (isVarArgs()) {\n sb.append(\"-varargs\");\n }\n if (isInterface()) {\n sb.append(\"-interface\");\n }\n if (isEnum()) {\n sb.append(\"-enum\");\n }\n return sb.toString();\n }\n\n @Override\n public int hashCode() {\n return flags;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n AccessFlags that = (AccessFlags) o;\n return flags == that.flags;\n }\n}" }, { "identifier": "AccessLevel", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/AccessLevel.java", "snippet": "public enum AccessLevel {\n PUBLIC(\"public\", Opcodes.ACC_PUBLIC),\n PROTECTED(\"protected\", Opcodes.ACC_PROTECTED),\n PACKAGE(\"package\", 0),\n PRIVATE(\"private\", Opcodes.ACC_PRIVATE);\n\n private final String lowerName;\n private final int asm;\n\n AccessLevel(String lowerName, int asm) {\n this.lowerName = lowerName;\n this.asm = asm;\n }\n\n public String getLowerName() {\n return lowerName;\n }\n\n public int toAsm() {\n return asm;\n }\n\n public static AccessLevel fromAsm(int access) {\n if ((access & Opcodes.ACC_PUBLIC) != 0) {\n return PUBLIC;\n }\n if ((access & Opcodes.ACC_PROTECTED) != 0) {\n return PROTECTED;\n }\n if ((access & Opcodes.ACC_PRIVATE) != 0) {\n return PRIVATE;\n }\n return PACKAGE;\n }\n\n public boolean isHigherVisibility(AccessLevel other) {\n return ordinal() < other.ordinal();\n }\n}" }, { "identifier": "AsmUtil", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/AsmUtil.java", "snippet": "public final class AsmUtil {\n public static final int API = getAsmApi();\n\n public static final String OBJECT = \"java/lang/Object\";\n public static final String ENUM = \"java/lang/Enum\";\n public static final String CONSTRUCTOR_NAME = \"<init>\";\n public static final String CLASS_INITIALIZER_NAME = \"<clinit>\";\n\n private AsmUtil() {\n }\n\n private static int getAsmApi() {\n try {\n int apiVersion = Opcodes.ASM4;\n for (Field field : Opcodes.class.getFields()) {\n if (field.getName().matches(\"ASM\\\\d+\")) {\n apiVersion = Math.max(apiVersion, field.getInt(null));\n }\n }\n return apiVersion;\n } catch (Exception e) {\n throw new RuntimeException(\"Failed to determine ASM API\", e);\n }\n }\n\n public static boolean isClassAccessible(String fromClass, String targetClass, int accessFlags) {\n return isClassAccessible(fromClass, targetClass, AccessLevel.fromAsm(accessFlags));\n }\n\n public static boolean isClassAccessible(String fromClass, String targetClass, AccessLevel accessLevel) {\n // JVMS 21 §5.4.4\n return accessLevel == AccessLevel.PUBLIC || areSamePackage(fromClass, targetClass);\n }\n\n public static boolean isMemberAccessible(Index index, String fromClass, String containingClassName, AccessLevel accessLevel) {\n IResolvedClass resolvedClass = index.findClass(containingClassName);\n return resolvedClass != null && isMemberAccessible(index, fromClass, containingClassName, resolvedClass, accessLevel);\n }\n\n public static boolean isMemberAccessible(Index index, String fromClass, String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel) {\n // JVMS 21 §5.4.4\n\n switch (accessLevel) {\n case PUBLIC -> {\n return true;\n }\n case PROTECTED -> {\n if (isSubclass(index, fromClass, containingClassName) || areSamePackage(fromClass, containingClassName)) {\n return true;\n }\n }\n case PACKAGE -> {\n if (areSamePackage(fromClass, containingClassName)) {\n return true;\n }\n }\n }\n\n String nestHost = Objects.requireNonNullElse(containingClass.getNestHost(), containingClassName);\n if (nestHost.equals(fromClass)) {\n return true;\n }\n IResolvedClass resolvedNestHost = index.findClass(nestHost);\n return resolvedNestHost != null && resolvedNestHost.getNestMembers().contains(fromClass);\n }\n\n private static boolean isSubclass(Index index, String className, String superclass) {\n IResolvedClass clazz;\n while ((clazz = index.findClass(className)) != null) {\n if (superclass.equals(className)) {\n return true;\n }\n className = clazz.getSuperclass();\n }\n\n return false;\n }\n\n public static boolean areSamePackage(String a, String b) {\n int slashA = a.lastIndexOf('/');\n int slashB = b.lastIndexOf('/');\n return slashA == slashB && (slashA == -1 || a.startsWith(b.substring(0, slashB)));\n }\n\n @Nullable\n public static String getReferredClass(String typeDescriptor) {\n return getReferredClass(Type.getType(typeDescriptor));\n }\n\n @Nullable\n public static String getReferredClass(Type type) {\n if (type.getSort() == Type.ARRAY) {\n type = type.getElementType();\n }\n return type.getSort() == Type.OBJECT ? type.getInternalName() : null;\n }\n\n @Nullable\n public static Type toClassConstant(Object constant) {\n if (constant instanceof Type type) {\n return type.getSort() == Type.METHOD ? null : type;\n } else if (constant instanceof ConstantDynamic condy) {\n if (\"java/lang/invoke/ConstantBootstraps\".equals(condy.getBootstrapMethod().getOwner())\n && \"primitiveClass\".equals(condy.getBootstrapMethod().getName())\n && \"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Class;\".equals(condy.getBootstrapMethod().getDesc())\n ) {\n return Type.getType(condy.getName());\n }\n return null;\n } else {\n return null;\n }\n }\n}" }, { "identifier": "InheritanceUtil", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/InheritanceUtil.java", "snippet": "public final class InheritanceUtil {\n private InheritanceUtil() {\n }\n\n public static boolean canOverride(String subclass, String superclass, AccessFlags superMethodAccess) {\n // JVMS 21 §5.4.5, assumes no intermediate subclasses between `subclass` and `superclass` which contain methods\n // that can override the super method.\n if (superMethodAccess.isStatic()) {\n return false;\n }\n return switch (superMethodAccess.accessLevel()) {\n case PUBLIC, PROTECTED -> true;\n case PACKAGE -> AsmUtil.areSamePackage(subclass, superclass);\n case PRIVATE -> false;\n };\n }\n\n @Nullable\n public static OwnedClassMember lookupField(Index index, String owner, String name, String desc) {\n // JVMS 21 §5.4.3.2 field resolution, 1-4 (field lookup)\n for (IResolvedClass resolvedClass = index.findClass(owner); resolvedClass != null; resolvedClass = index.findClass(owner = resolvedClass.getSuperclass())) {\n for (ClassMember field : resolvedClass.getFields()) {\n if (field.name().equals(name) && field.descriptor().equals(desc)) {\n return new OwnedClassMember(owner, field);\n }\n }\n }\n return null;\n }\n\n @Nullable\n public static OwnedClassMember lookupMethod(Index index, String owner, String name, String desc) {\n List<OwnedClassMember> multiLookup = multiLookupMethod(index, owner, name, desc);\n return multiLookup.isEmpty() ? null : multiLookup.get(0);\n }\n\n public static List<OwnedClassMember> multiLookupMethod(Index index, String owner, String name, String desc) {\n return multiLookupMethod(index, owner, List.of(), name, desc);\n }\n\n public static List<OwnedClassMember> multiLookupMethod(Index index, String owner, List<String> additionalInterfaces, String name, String desc) {\n // JVMS 21 §5.4.3.3 method resolution, 1-3 (method lookup)\n // JVMS 21 §5.4.3.4 interface method resolution, 1-6 (interface method lookup)\n // the below algorithm implements §5.4.3.3 if `owner` is a class and §5.4.3.4 if `owner` is an interface.\n\n // search superclasses first\n String className = owner;\n for (IResolvedClass resolvedClass = index.findClass(className); resolvedClass != null; resolvedClass = index.findClass(className = resolvedClass.getSuperclass())) {\n for (ClassMember method : resolvedClass.getMethods()) {\n if (method.name().equals(name)) {\n if (isSignaturePolymorphic(className, method.descriptor(), method.access())) {\n return List.of(new OwnedClassMember(className, method));\n }\n if (method.descriptor().equals(desc)) {\n return List.of(new OwnedClassMember(className, method));\n }\n }\n }\n }\n\n // search for maximally specific methods\n Map<String, ClassMember> maximallySpecificMethods = new LinkedHashMap<>();\n Set<String> superinterfacesOfMaximallySpecificMethods = new HashSet<>();\n for (String additionalInterface : additionalInterfaces) {\n IResolvedClass resolvedItf = index.findClass(additionalInterface);\n if (resolvedItf != null) {\n searchForMaximallySpecificMethods(index, additionalInterface, resolvedItf, name, desc, maximallySpecificMethods, superinterfacesOfMaximallySpecificMethods);\n }\n }\n for (IResolvedClass resolvedClass = index.findClass(owner); resolvedClass != null; resolvedClass = index.findClass(resolvedClass.getSuperclass())) {\n for (String itf : resolvedClass.getInterfaces()) {\n IResolvedClass resolvedItf = index.findClass(itf);\n if (resolvedItf != null) {\n searchForMaximallySpecificMethods(index, itf, resolvedItf, name, desc, maximallySpecificMethods, superinterfacesOfMaximallySpecificMethods);\n }\n }\n }\n\n if (maximallySpecificMethods.isEmpty()) {\n return List.of();\n }\n\n // check if there is exactly one non-abstract maximally specific method\n OwnedClassMember nonAbstractMethod = null;\n for (var entry : maximallySpecificMethods.entrySet()) {\n if (!entry.getValue().access().isAbstract()) {\n if (nonAbstractMethod != null) {\n nonAbstractMethod = null;\n break;\n } else {\n nonAbstractMethod = new OwnedClassMember(entry.getKey(), entry.getValue());\n }\n }\n }\n if (nonAbstractMethod != null) {\n return List.of(nonAbstractMethod);\n }\n\n // the spec says we can return an arbitrary method here, we return all of them\n return maximallySpecificMethods.entrySet().stream().map(entry -> new OwnedClassMember(entry.getKey(), entry.getValue())).toList();\n }\n\n private static void searchForMaximallySpecificMethods(Index index, String itf, IResolvedClass resolvedInterface, String name, String desc, Map<String, ClassMember> maximallySpecificMethods, Set<String> superinterfacesOfMaximallySpecificMethods) {\n if (maximallySpecificMethods.containsKey(itf) || superinterfacesOfMaximallySpecificMethods.contains(itf)) {\n return;\n }\n\n for (ClassMember method : resolvedInterface.getMethods()) {\n if (!method.name().equals(name) || !method.descriptor().equals(desc)) {\n continue;\n }\n if (method.access().isStatic() || method.access().accessLevel() == AccessLevel.PRIVATE) {\n continue;\n }\n\n maximallySpecificMethods.put(itf, method);\n findSuperinterfacesOfMaximallySpecificMethod(index, resolvedInterface, maximallySpecificMethods, superinterfacesOfMaximallySpecificMethods);\n return;\n }\n\n for (String superinterface : resolvedInterface.getInterfaces()) {\n IResolvedClass resolvedSuperinterface = index.findClass(superinterface);\n if (resolvedSuperinterface != null) {\n searchForMaximallySpecificMethods(index, superinterface, resolvedSuperinterface, name, desc, maximallySpecificMethods, superinterfacesOfMaximallySpecificMethods);\n }\n }\n }\n\n private static void findSuperinterfacesOfMaximallySpecificMethod(Index index, IResolvedClass resolvedInterface, Map<String, ClassMember> maximallySpecificMethods, Set<String> superinterfacesOfMaximallySpecificMethods) {\n for (String superinterface : resolvedInterface.getInterfaces()) {\n if (superinterfacesOfMaximallySpecificMethods.add(superinterface)) {\n maximallySpecificMethods.remove(superinterface);\n IResolvedClass resolvedSuperinterface = index.findClass(superinterface);\n if (resolvedSuperinterface != null) {\n findSuperinterfacesOfMaximallySpecificMethod(index, resolvedSuperinterface, maximallySpecificMethods, superinterfacesOfMaximallySpecificMethods);\n }\n }\n }\n }\n\n private static boolean isSignaturePolymorphic(String owner, String desc, AccessFlags flags) {\n // JVMS 21 §2.9.3 - signature polymorphic methods\n if (!\"java/lang/invoke/MethodHandle\".equals(owner) && !\"java/lang/invoke/VarHandle\".equals(owner)) {\n return false;\n }\n if (!desc.startsWith(\"([Ljava/lang/Object;)\")) {\n return false;\n }\n return flags.isVarArgs() && flags.isNative();\n }\n}" }, { "identifier": "UnimplementedMethodChecker", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/UnimplementedMethodChecker.java", "snippet": "public abstract class UnimplementedMethodChecker {\n protected final Index index;\n protected final String superName;\n protected final String @Nullable[] interfaces;\n\n protected UnimplementedMethodChecker(Index index, String superName, String @Nullable [] interfaces) {\n this.index = index;\n this.superName = superName;\n this.interfaces = interfaces;\n }\n\n public void run() {\n Map<NameAndDesc, PossiblyUnimplementedMethod> possiblyUnimplementedMethods = new LinkedHashMap<>();\n\n searchParentsForPossiblyUnimplementedMethods(possiblyUnimplementedMethods);\n\n // remove the possibly unimplemented methods which are actually implemented and visible\n possiblyUnimplementedMethods.entrySet().removeIf(abstractMethod -> {\n List<OwnedClassMember> lookupResult = multiLookupMethod(abstractMethod.getKey().name(), abstractMethod.getKey().desc());\n List<OwnedClassMember> nonAbstractMethods = lookupResult.stream().filter(method -> !method.member().access().isAbstract()).toList();\n if (nonAbstractMethods.size() != 1) {\n return false;\n }\n OwnedClassMember concreteMethod = nonAbstractMethods.get(0);\n if (concreteMethod.member().access().isStatic()) {\n return false;\n }\n if (abstractMethod.getValue().access.accessLevel().isHigherVisibility(concreteMethod.member().access().accessLevel())) {\n return false;\n }\n return isMethodAccessible(concreteMethod.owner(), concreteMethod.member().access().accessLevel())\n && AsmUtil.isMemberAccessible(index, abstractMethod.getValue().owner(), concreteMethod.owner(), concreteMethod.member().access().accessLevel());\n });\n\n possiblyUnimplementedMethods.forEach((nameAndDesc, possiblyUnimplementedMethod) -> {\n List<OwnedClassMember> lookupResult = multiLookupMethod(nameAndDesc.name(), nameAndDesc.desc());\n List<OwnedClassMember> nonAbstractMethods = lookupResult.stream().filter(method -> !method.member().access().isAbstract()).toList();\n if (nonAbstractMethods.size() > 1) {\n onDiamondProblem(nameAndDesc.name(), nameAndDesc.desc());\n } else if (possiblyUnimplementedMethod.access.isAbstract()) {\n onAbstractMethodUnimplemented(possiblyUnimplementedMethod.owner, nameAndDesc.name(), nameAndDesc.desc());\n } else {\n String problematicAccessModifier;\n String owner;\n if (nonAbstractMethods.isEmpty()) {\n problematicAccessModifier = \"abstract\";\n owner = lookupResult.get(0).owner();\n } else {\n OwnedClassMember concreteMethod = nonAbstractMethods.get(0);\n if (concreteMethod.member().access().isStatic()) {\n problematicAccessModifier = \"static\";\n } else {\n problematicAccessModifier = concreteMethod.member().access().accessLevel().getLowerName();\n }\n owner = concreteMethod.owner();\n }\n onIncorrectInterfaceMethodLookup(possiblyUnimplementedMethod.owner, nameAndDesc.name(), nameAndDesc.desc(), owner, problematicAccessModifier);\n }\n });\n }\n\n private void searchParentsForPossiblyUnimplementedMethods(Map<NameAndDesc, PossiblyUnimplementedMethod> possiblyUnimplementedMethods) {\n IResolvedClass superClass = index.findClass(superName);\n if (superClass != null) {\n searchClassAndParentsForPossiblyUnimplementedMethods(superName, superClass, possiblyUnimplementedMethods);\n }\n if (interfaces != null) {\n for (String itf : interfaces) {\n IResolvedClass resolvedClass = index.findClass(itf);\n if (resolvedClass != null) {\n searchClassAndParentsForPossiblyUnimplementedMethods(itf, resolvedClass, possiblyUnimplementedMethods);\n }\n }\n }\n }\n\n private void searchClassAndParentsForPossiblyUnimplementedMethods(String className, IResolvedClass clazz, Map<NameAndDesc, PossiblyUnimplementedMethod> possiblyUnimplementedMethods) {\n for (ClassMember method : clazz.getMethods()) {\n NameAndDesc nameAndDesc = new NameAndDesc(method.name(), method.descriptor());\n if (method.access().isAbstract()\n || (clazz.getAccess().isInterface() && !method.access().isStatic() && isMethodAccessible(className, clazz, method.access().accessLevel()))) {\n possiblyUnimplementedMethods.merge(nameAndDesc, new PossiblyUnimplementedMethod(className, method.access()), PossiblyUnimplementedMethod::maxVisibility);\n }\n }\n\n IResolvedClass resolvedSuperClass = index.findClass(clazz.getSuperclass());\n if (resolvedSuperClass != null) {\n searchClassAndParentsForPossiblyUnimplementedMethods(clazz.getSuperclass(), resolvedSuperClass, possiblyUnimplementedMethods);\n }\n for (String itf : clazz.getInterfaces()) {\n IResolvedClass resolvedInterface = index.findClass(itf);\n if (resolvedInterface != null) {\n searchClassAndParentsForPossiblyUnimplementedMethods(itf, resolvedInterface, possiblyUnimplementedMethods);\n }\n }\n }\n\n protected boolean isMethodAccessible(String containingClassName, AccessLevel accessLevel) {\n IResolvedClass containingClass = index.findClass(containingClassName);\n return containingClass != null && isMethodAccessible(containingClassName, containingClass, accessLevel);\n }\n\n protected abstract boolean isMethodAccessible(String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel);\n\n protected abstract List<OwnedClassMember> multiLookupMethod(String name, String desc);\n\n protected abstract void onDiamondProblem(String methodName, String methodDesc);\n protected abstract void onAbstractMethodUnimplemented(String methodOwner, String methodName, String methodDesc);\n protected abstract void onIncorrectInterfaceMethodLookup(String interfaceName, String methodName, String methodDesc, String resolvedClassName, String problematicAccessModifier);\n\n private record PossiblyUnimplementedMethod(String owner, AccessFlags access) {\n static PossiblyUnimplementedMethod maxVisibility(PossiblyUnimplementedMethod a, PossiblyUnimplementedMethod b) {\n return b.access.accessLevel().isHigherVisibility(a.access().accessLevel()) ? b : a;\n }\n }\n\n public static abstract class Simple extends UnimplementedMethodChecker {\n protected final String className;\n\n protected Simple(Index index, String className, String superName, String @Nullable [] interfaces) {\n super(index, superName, interfaces);\n this.className = className;\n }\n\n @Override\n protected boolean isMethodAccessible(String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel) {\n return AsmUtil.isMemberAccessible(index, className, containingClassName, containingClass, accessLevel);\n }\n\n @Override\n protected List<OwnedClassMember> multiLookupMethod(String name, String desc) {\n return InheritanceUtil.multiLookupMethod(index, className, name, desc);\n }\n }\n}" } ]
import net.earthcomputer.modcompatchecker.checker.Errors; import net.earthcomputer.modcompatchecker.indexer.IResolvedClass; import net.earthcomputer.modcompatchecker.util.AccessFlags; import net.earthcomputer.modcompatchecker.util.AccessLevel; import net.earthcomputer.modcompatchecker.util.AsmUtil; import net.earthcomputer.modcompatchecker.util.ClassMember; import net.earthcomputer.modcompatchecker.util.InheritanceUtil; import net.earthcomputer.modcompatchecker.util.OwnedClassMember; import net.earthcomputer.modcompatchecker.util.UnimplementedMethodChecker; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import java.lang.invoke.LambdaMetafactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
7,777
package net.earthcomputer.modcompatchecker.checker.indy; public enum LambdaMetafactoryChecker implements IndyChecker { INSTANCE; @Override public void check(IndyContext context) { List<String> interfaces = new ArrayList<>(); List<String> interfaceMethodDescs = new ArrayList<>(); Type interfaceType = Type.getReturnType(context.descriptor()); if (interfaceType.getSort() != Type.OBJECT) { return; } interfaces.add(interfaceType.getInternalName()); String interfaceMethodName = context.name(); if (!(context.args()[0] instanceof Type interfaceMethodType)) { return; } interfaceMethodDescs.add(interfaceMethodType.getDescriptor()); if ("altMetafactory".equals(context.bsm().getName())) { if (!(context.args()[3] instanceof Integer flags)) { return; } int argIndex = 4; if ((flags & LambdaMetafactory.FLAG_MARKERS) != 0) { if (!(context.args()[argIndex++] instanceof Integer markerCount)) { return; } for (int i = 0; i < markerCount; i++) { if (!(context.args()[argIndex++] instanceof Type itfType)) { return; } if (itfType.getSort() != Type.OBJECT) { return; } interfaces.add(itfType.getInternalName()); } } if ((flags & LambdaMetafactory.FLAG_BRIDGES) != 0) { if (!(context.args()[argIndex++] instanceof Integer bridgeCount)) { return; } for (int i = 0; i < bridgeCount; i++) { if (!(context.args()[argIndex++] instanceof Type bridgeType)) { return; } if (bridgeType.getSort() != Type.METHOD) { return; } interfaceMethodDescs.add(bridgeType.getDescriptor()); } } } for (String interfaceName : interfaces) { IResolvedClass resolvedInterface = context.index().findClass(interfaceName); if (resolvedInterface == null) { context.addProblem(Errors.LAMBDA_INTERFACE_REMOVED, interfaceName); continue; } if (!AsmUtil.isClassAccessible(context.className(), interfaceName, resolvedInterface.getAccess().accessLevel())) { context.addProblem(Errors.LAMBDA_INTERFACE_INACCESSIBLE, interfaceName, resolvedInterface.getAccess().accessLevel().getLowerName()); } if (!resolvedInterface.getAccess().isInterface()) { context.addProblem(Errors.LAMBDA_INTERFACE_NOT_AN_INTERFACE, interfaceName); } } UnimplementedMethodChecker checker = new UnimplementedMethodChecker(context.index(), AsmUtil.OBJECT, interfaces.toArray(String[]::new)) { @Override protected boolean isMethodAccessible(String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel) { return AsmUtil.isMemberAccessible(index, context.className(), containingClassName, containingClass, accessLevel); } @Override protected List<OwnedClassMember> multiLookupMethod(String name, String desc) { if (name.equals(interfaceMethodName) && interfaceMethodDescs.contains(desc)) { return List.of(new OwnedClassMember(context.className(), new ClassMember(new AccessFlags(Opcodes.ACC_PUBLIC), name, desc))); } else { assert interfaces != null;
package net.earthcomputer.modcompatchecker.checker.indy; public enum LambdaMetafactoryChecker implements IndyChecker { INSTANCE; @Override public void check(IndyContext context) { List<String> interfaces = new ArrayList<>(); List<String> interfaceMethodDescs = new ArrayList<>(); Type interfaceType = Type.getReturnType(context.descriptor()); if (interfaceType.getSort() != Type.OBJECT) { return; } interfaces.add(interfaceType.getInternalName()); String interfaceMethodName = context.name(); if (!(context.args()[0] instanceof Type interfaceMethodType)) { return; } interfaceMethodDescs.add(interfaceMethodType.getDescriptor()); if ("altMetafactory".equals(context.bsm().getName())) { if (!(context.args()[3] instanceof Integer flags)) { return; } int argIndex = 4; if ((flags & LambdaMetafactory.FLAG_MARKERS) != 0) { if (!(context.args()[argIndex++] instanceof Integer markerCount)) { return; } for (int i = 0; i < markerCount; i++) { if (!(context.args()[argIndex++] instanceof Type itfType)) { return; } if (itfType.getSort() != Type.OBJECT) { return; } interfaces.add(itfType.getInternalName()); } } if ((flags & LambdaMetafactory.FLAG_BRIDGES) != 0) { if (!(context.args()[argIndex++] instanceof Integer bridgeCount)) { return; } for (int i = 0; i < bridgeCount; i++) { if (!(context.args()[argIndex++] instanceof Type bridgeType)) { return; } if (bridgeType.getSort() != Type.METHOD) { return; } interfaceMethodDescs.add(bridgeType.getDescriptor()); } } } for (String interfaceName : interfaces) { IResolvedClass resolvedInterface = context.index().findClass(interfaceName); if (resolvedInterface == null) { context.addProblem(Errors.LAMBDA_INTERFACE_REMOVED, interfaceName); continue; } if (!AsmUtil.isClassAccessible(context.className(), interfaceName, resolvedInterface.getAccess().accessLevel())) { context.addProblem(Errors.LAMBDA_INTERFACE_INACCESSIBLE, interfaceName, resolvedInterface.getAccess().accessLevel().getLowerName()); } if (!resolvedInterface.getAccess().isInterface()) { context.addProblem(Errors.LAMBDA_INTERFACE_NOT_AN_INTERFACE, interfaceName); } } UnimplementedMethodChecker checker = new UnimplementedMethodChecker(context.index(), AsmUtil.OBJECT, interfaces.toArray(String[]::new)) { @Override protected boolean isMethodAccessible(String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel) { return AsmUtil.isMemberAccessible(index, context.className(), containingClassName, containingClass, accessLevel); } @Override protected List<OwnedClassMember> multiLookupMethod(String name, String desc) { if (name.equals(interfaceMethodName) && interfaceMethodDescs.contains(desc)) { return List.of(new OwnedClassMember(context.className(), new ClassMember(new AccessFlags(Opcodes.ACC_PUBLIC), name, desc))); } else { assert interfaces != null;
return InheritanceUtil.multiLookupMethod(index, AsmUtil.OBJECT, Arrays.asList(interfaces), name, desc);
5
2023-12-11 00:48:12+00:00
12k
HzlGauss/bulls
src/main/java/com/bulls/qa/service/PioneerService.java
[ { "identifier": "RequestConfigs", "path": "src/main/java/com/bulls/qa/configuration/RequestConfigs.java", "snippet": "@Data\n@Configuration\n@Component\n@PropertySource(factory = YamlPropertySourceFactory.class, value = {\"testerhome.yml\"})\n//@PropertySource(factory = YamlPropertySourceFactory.class, value = {\"interface_*.yml\"})\n//@PropertySource(factory = YamlPropertySourceFactory.class, value = {\"request-copy.yml\"},name = \"b\" ,ignoreResourceNotFound = true)\n@ConfigurationProperties(prefix = \"api\", ignoreInvalidFields = true, ignoreUnknownFields = true)\n//@ConfigurationProperties(ignoreUnknownFields = false)\npublic class RequestConfigs {\n\n @Setter\n @Getter\n private List<PioneerConfig> pioneers;\n\n //@Setter\n //@Getter\n private List<RequestConfig> requests;\n @Setter(AccessLevel.PRIVATE)\n @Getter(AccessLevel.PRIVATE)\n private Map<String, Object> globalVariableMap = new HashMap<>();\n\n private List<Map<String, String>> globalVariables;\n\n @Setter(AccessLevel.PRIVATE)\n @Getter(AccessLevel.PRIVATE)\n private static Map<String, RequestConfig> requestMap = new HashMap<>();\n\n\n @Autowired\n Environment environment;\n\n private Properties properties;\n\n public Map<String, String> reLogin(String cookiesName) {\n for (PioneerConfig pioneerConfig : pioneers) {\n for (Map<String, String> map : pioneerConfig.getExtractors()) {\n System.out.println(map.keySet());\n if (map.get(\"name\").equals(cookiesName)) {\n PioneerService.handle(pioneerConfig, this);\n Map<String, String> res = (Map<String, String>) this.getGlobalVariable(cookiesName);\n System.out.println(res);\n return res;\n }\n }\n }\n return null;\n }\n\n public void setGlobalVariables(List<Map<String, String>> globalVariables) {\n //this.globalVariables = globalVariables;\n for (Map<String, String> map : globalVariables) {\n this.globalVariableMap.putAll(map);\n }\n }\n\n public void setRequests(List<RequestConfig> requests) {\n if (this.requests == null) {\n this.requests = requests;\n } else {\n this.requests.addAll(requests);\n }\n }\n\n //@Bean(name = \"envProperties\")\n public Properties getEnvProperties() {\n if (this.properties != null) {\n return this.properties;\n }\n //ApplicationContext context = new AnnotationConfigApplicationContext(SConfig.class);\n //String[] ss = context.getEnvironment().getActiveProfiles();\n String[] ss = environment.getActiveProfiles();\n if (ss.length > 0) {\n String env = ss[0];\n Resource resource = new ClassPathResource(env + \"/test.properties\");\n Properties props = null;\n try {\n props = PropertiesLoaderUtils.loadProperties(resource);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return props;\n }\n return null;\n }\n\n public void setGlobalVariable(String name, Object value) {\n this.globalVariableMap.put(name, value);\n }\n\n public Object getGlobalVariable(String name) {\n if (this.globalVariableMap.containsKey(name)) {\n return this.globalVariableMap.get(name);\n }\n Properties properties = this.getEnvProperties();\n if (properties != null) {\n return properties.getProperty(name);\n }\n return null;\n }\n\n public RequestConfig getRequest(String requestId) {\n\n if (requestMap.keySet().contains(requestId)) {\n return requestMap.get(requestId);\n }\n for (RequestConfig request : requests) {\n if (request.getId().equals(requestId)) {\n requestMap.put(requestId, request);\n return request;\n }\n }\n if (this.pioneers == null) {\n return null;\n }\n for (RequestConfig request : this.pioneers) {\n if (request.getId().equals(requestId)) {\n requestMap.put(requestId, request);\n return request;\n }\n }\n return null;\n }\n}" }, { "identifier": "Request", "path": "src/main/java/com/bulls/qa/request/Request.java", "snippet": "@Slf4j\npublic class Request {\n private RequestConfig requestConfig;\n private String method;\n private String name;\n private String path;\n private String filePath;\n private Map<String, Object> headers;\n private Map<String, String> cookies = new HashMap<>();\n private Map<String, Object> parameter;\n private Map<String, Object> tmpParameter = new HashMap<>();\n //private static final Logger logger = LoggerFactory.getLogger(RequestConfig.class);\n //private static final Logger logger= LogManager.getLogger(Request.class);\n private static final Logger logger = LoggerFactory.getLogger(Request.class);\n\n public static void setRequestConfigs(RequestConfigs requestConfigs) {\n Request.requestConfigs = requestConfigs;\n }\n\n public static RequestConfigs getRequestConfigs() {\n return requestConfigs;\n }\n\n\n private static RequestConfigs requestConfigs = null;\n\n\n private Request(RequestConfig requestConfig) {\n this.requestConfig = requestConfig;\n init();\n }\n\n public Request setCookies(Map<String, String> cookies) {\n if (this.cookies == null) {\n this.cookies = cookies;\n } else {\n this.cookies.putAll(cookies);\n }\n return this;\n }\n\n public Request clearCookies() {\n if (this.cookies != null) {\n this.cookies.clear();\n }\n return this;\n }\n\n public void addCookie(String key, String value) {\n this.cookies.put(key, value);\n }\n\n public void addCookies(Map<String, String> cookies) {\n if (cookies == null || cookies.size() == 0) {\n return;\n }\n if (this.headers != null && this.headers.containsKey(\"cookie\")) {\n Object cookie = this.headers.get(\"cookie\");\n this.cookies.putAll((Map<? extends String, ? extends String>) cookie);\n this.headers.remove(\"cookie\");\n }\n this.cookies.putAll(cookies);\n }\n\n public void setFilePath(String filePath) {\n this.filePath = filePath;\n }\n\n private void init() {\n String requestMethod = requestConfig.getMethod().trim();\n if (requestMethod.equalsIgnoreCase(\"get\")) {\n this.method = \"get\";\n } else if (requestMethod.equalsIgnoreCase(\"post\")) {\n this.method = \"post\";\n }\n this.method = requestConfig.getMethod();\n this.name = requestConfig.getName();\n this.path = requestConfig.getPath();\n this.filePath = requestConfig.getFilePath();\n try {\n initPath();\n initHeader();\n initParameter();\n } catch (IOException e) {\n e.printStackTrace();\n logger.error(e.toString());\n }\n initGlobalVariable();\n }\n\n private void initPath() {\n try {\n URL url = new URL(this.path);\n String host = url.getHost();\n if (host.startsWith(\"$\")) {\n String value = PioneerService.getProperty(host.substring(1));\n String replace = this.path.replace(host, value);\n this.path = replace;\n logger.info(\"{}\", replace);\n }\n } catch (MalformedURLException e) {\n e.printStackTrace();\n }\n }\n\n private void initHeader() throws IOException {\n ObjectMapper MAPPER = new ObjectMapper();\n String s = requestConfig.getHeaders();\n if (StringUtils.isNotEmpty(s)) {\n HashMap<String, Object> headers = MAPPER.readValue(s.replace(\"\\\\\", \"\"), HashMap.class);\n for (String key : headers.keySet()) {\n Object value = headers.get(key);\n if (value instanceof String) {\n String sv = (String) value;\n if (StringUtils.isNotEmpty(sv) && sv.startsWith(\"$\")) {\n Object o = requestConfigs.getGlobalVariable(sv.replace(\"$\", \"\"));\n if (o != null) {\n headers.put(key, o);\n }\n }\n }\n }\n //cookie\n if (headers.containsKey(\"cookie\")) {\n Object value = headers.get(\"cookie\");\n Map<String, String> cookie = null;\n if (value instanceof String) {\n cookie = string2Map((String) value);\n } else {\n cookie = (Map<String, String>) value;\n }\n if (this.cookies == null) {\n this.cookies = cookie;\n } else {\n this.cookies.putAll(cookie);\n }\n headers.remove(\"cookie\");\n }\n this.headers = headers;\n }\n }\n\n private static Map<String, String> string2Map(String str) {\n Map<String, String> map = new HashMap<String, String>();\n if (str == null || str.trim().length() == 0) {\n return map;\n }\n for (String subStr : str.split(\";\")) {\n String[] kv = subStr.split(\"=\");\n if (kv.length != 2) {\n continue;\n }\n map.put(kv[0], kv[1]);\n }\n return map;\n }\n\n private void initParameter() throws IOException {\n ObjectMapper MAPPER = new ObjectMapper();\n if (StringUtils.isNotEmpty(requestConfig.getParameters())) {\n String s = requestConfig.getParameters().replace(\"\\\\\", \"\").trim();\n HashMap<String, Object> parameters = null;\n if (s.startsWith(\"{\") && s.endsWith(\"}\")) {\n parameters = MAPPER.readValue(s, HashMap.class);\n } else {\n parameters = new HashMap<>();\n String[] ss = s.split(\"[=&]\");\n int len = ss.length;\n if ((len & 0x01) == 1) {\n len--;\n }\n for (int i = 0; i < len; i = i + 2) {\n if (ss[i + 1].contains(\",\")) {\n parameters.put(ss[i], Arrays.asList(ss[i + 1].split(\",\")));\n } else {\n parameters.put(ss[i], ss[i + 1]);\n }\n\n }\n }\n this.parameter = parameters;\n } else {\n this.parameter = new HashMap<>();\n }\n }\n\n private void initGlobalVariable() {\n //cookies\n String cookiesName = this.requestConfig.getCookies();\n if (StringUtils.isNotEmpty(cookiesName)) {\n String[] names = cookiesName.split(\";\");\n for (String name : names) {\n if (name.startsWith(\"$\")) {\n name = name.replace(\"$\", \"\");\n if (requestConfigs.getGlobalVariable(name) != null) {\n Object value = requestConfigs.getGlobalVariable(name);\n if (value instanceof Map) {\n this.cookies.putAll((Map<String, String>) value);\n } else {\n this.cookies.put(name, value.toString());\n }\n }\n }\n }\n /*if (cookiesName.startsWith(\"$\")) {\n cookiesName = cookiesName.replace(\"$\", \"\");\n if (requestConfigs.getGlobalVariable(cookiesName) != null) {\n this.cookies.putAll((Map<String, String>) requestConfigs.getGlobalVariable(cookiesName));\n }\n }*/\n }\n //host\n if (StringUtils.isEmpty(this.path)) {\n logger.error(\"{}-{}path格式错误,无法完成请求,请核对配置\", requestConfig.getName(), requestConfig.getId());\n return;\n }\n String s = this.path;\n s = s.replace(\"http://\", \"\").replace(\"https://\", \"\");//去除http和https前缀\n String[] arr = s.split(\"/\");//按‘/’分隔,取第一个\n String host = arr[0];\n if (host.startsWith(\"$\")) {\n host = host.replace(\"$\", \"\");\n host = (String) requestConfigs.getGlobalVariable(host);\n if (StringUtils.isNotEmpty(host)) {\n this.path.replace(arr[0], host);\n }\n }\n //header\n if (this.headers != null) {\n for (String key : this.headers.keySet()) {\n Object value = this.headers.get(key);\n if (value instanceof String) {\n String s1 = (String) value;\n if (StringUtils.isNotEmpty(s1) && s.startsWith(\"$\")) {\n String v = (String) requestConfigs.getGlobalVariable(s1.replace(\"$\", \"\"));\n if (StringUtils.isNotEmpty(v)) {\n this.headers.put(key, v);\n }\n }\n }\n }\n }\n //parameter\n if (this.parameter != null && this.parameter.size() > 0) {\n mapReplace(this.parameter);\n }\n }\n\n\n private void mapReplace(Map<String, Object> map) {\n for (String key : map.keySet()) {\n Object value = map.get(key);\n if (value != null) {\n if (value instanceof java.util.List) {\n List list = (List) value;\n for (int i = 0; i < list.size(); i++) {\n Object o = list.get(i);\n if (o instanceof java.util.Map) {\n mapReplace((Map<String, Object>) o);\n } else if (o instanceof String) {\n String s = (String) o;\n if (StringUtils.isNotEmpty(s) && s.startsWith(\"$\")) {\n s = s.replace(\"$\", \"\");\n if (StringUtils.isNotEmpty(s) && Request.requestConfigs.getGlobalVariable(s) != null) {\n Object o1 = Request.requestConfigs.getGlobalVariable(s);\n list.set(i, o1);\n }\n }\n }\n }\n } else if (value.getClass().isArray()) {\n int length = Array.getLength(value);\n Object[] os = new Object[length];\n for (int i = 0; i < length; i++) {\n Object o = Array.get(value, i);\n if (o instanceof java.util.Map) {\n mapReplace((Map<String, Object>) o);\n } else if (o instanceof String) {\n String s = (String) o;\n if (StringUtils.isNotEmpty(s) && s.startsWith(\"$\")) {\n s = s.replace(\"$\", \"\");\n if (StringUtils.isNotEmpty(s) && Request.requestConfigs.getGlobalVariable(s) != null) {\n Object o1 = Request.requestConfigs.getGlobalVariable(s);\n Array.set(value, i, o1);\n }\n }\n }\n }\n } else if (value instanceof java.util.Map) {\n mapReplace((Map<String, Object>) value);\n } else if (value instanceof String) {\n String s = (String) value;\n if (StringUtils.isNotEmpty(s) && s.startsWith(\"$\")) {\n s = s.replace(\"$\", \"\");\n if (StringUtils.isNotEmpty(s) && Request.requestConfigs.getGlobalVariable(s) != null) {\n Object o1 = Request.requestConfigs.getGlobalVariable(s);\n map.put(key, o1);\n }\n }\n }\n }\n }\n }\n\n private void checkHeaderAndParam() throws Exception {\n if (this.headers == null) {\n logger.warn(\"header is null!\");\n }\n for (String key : headers.keySet()) {\n Object value = this.headers.get(key);\n if (StringUtils.isNotEmpty(value.toString()) && value.toString().trim().equals(\"***\")) {\n logger.warn(\"header {} is required!\", key);\n }\n }\n if (StringUtils.isEmpty(path) || StringUtils.isEmpty(method)) {\n throw new Exception(\"request定义错误,缺少path或method字段\");\n }\n }\n\n public static Request getInstance(String configId) {\n RequestConfig requestConfig = requestConfigs.getRequest(configId);\n return new Request(requestConfig);\n }\n\n public static Request getInstance(RequestConfig requestConfig) {\n return new Request(requestConfig);\n }\n\n public void addHeader(String key, String value) {\n this.headers.put(key, value);\n }\n\n public void addHeader(Map<String, Object> headers) {\n for (Map.Entry<String, Object> entry : headers.entrySet()) {\n if (\"Set-Cookie\".equals(entry.getKey())) {\n continue;\n } else {\n this.headers.put(entry.getKey(), entry.getValue());\n }\n }\n }\n\n public void addHeaders(Headers headers) {\n Map<String, Object> myHeaders = new HashMap<String, Object>();\n List<Header> list = headers.asList();\n for (Header header : list) {\n String name = header.getName();\n String value = header.getValue();\n myHeaders.put(name, value);\n }\n if (myHeaders.size() > 0) {\n this.addHeader(myHeaders);\n }\n }\n\n private void updateCookie(RequestSpecification request) {\n if (this.cookies != null && this.cookies.size() > 0) {\n request = request.cookies(this.cookies);\n }\n }\n\n public Response doRequest() {\n Response response = null;\n try {\n checkHeaderAndParam();\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n RequestSpecification request = given();\n request = request.relaxedHTTPSValidation();\n if (this.cookies != null && this.cookies.size() > 0) {\n request = request.cookies(this.cookies);\n }\n if (this.headers != null && this.headers.size() > 0) {\n request = request.headers(this.headers);\n }\n String type = (String) this.headers.get(\"Content-Type\");\n ContentType contentType = null;\n if (StringUtils.isNotEmpty(type)) {\n if (type.contains(\"application/json\") || type.contains(\"javascript\")) {\n contentType = ContentType.JSON;\n } else if (type.contains(\"text/html\")) {\n contentType = ContentType.HTML;\n } else if (type.contains(\"application/x-www-form-urlencoded\")) {\n contentType = ContentType.URLENC;\n } else if (type.contains(\"multipart/form-data\")) {\n if (StringUtils.isEmpty(this.filePath)) {\n logger.error(\"{}文件路径不能为空!\", this.requestConfig.getId());\n } else {\n request.multiPart(new File(this.filePath));\n }\n //contentType = ContentType.BINARY;\n\n } else if (type.contains(\"text/plain\")) {\n contentType = ContentType.TEXT;\n } else if (type.contains(\"octet-stream\")) {\n contentType = ContentType.BINARY;\n } else if (type.contains(\"xml\")) {\n contentType = ContentType.XML;\n } else {\n contentType = ContentType.ANY;\n }\n //request = request.contentType(contentType);\n } else {\n contentType = ContentType.URLENC;\n\n }\n if (null != type && type.contains(\"multipart/form-data\")) {\n request = request.contentType(\"multipart/form-data\");\n } else if (null != type && type.contains(\";charSet\")) {\n request = request.contentType(contentType + \";charSet\" + type.split(\"charSet\")[1]);\n } else {\n //request = request.contentType(contentType);\n request = request.contentType(type);\n }\n\n if (this.parameter != null && this.parameter.size() > 0) {\n if (contentType.equals(ContentType.JSON)) {\n request = request.body(this.parameter);\n } else {\n request = request.params(this.parameter);\n }\n }\n String requestInfo = String.format(\"[接口请求信息] id:%s,name:%s,url:%s\", requestConfig.getId(),\n requestConfig.getName(), this.path);\n logger.info(requestInfo);\n Reporter.log(requestInfo);\n if (this.headers != null) {\n logger.info(\"请求头:{}\", this.headers);\n }\n if (this.cookies != null) {\n logger.info(\"请求cookies:{}\", this.cookies);\n }\n if (this.parameter != null && this.parameter.size() > 0) {\n logger.info(\"请求参数:{}\", this.parameter);\n Reporter.log(\"请求参数:\" + this.parameter);\n }\n if (this.tmpParameter != null && this.tmpParameter.size() > 0) {\n logger.info(\"请求参数:{}\", this.tmpParameter);\n Reporter.log(\"请求参数:\" + this.tmpParameter);\n }\n boolean isTestMethodCalled = isTestMethodCalled();\n if (isTestMethodCalled) {\n //Allure.step(requestConfig.getName() + \"-请求url:\" + this.path);\n //Allure.step(requestConfig.getName() + \"-请求参数:\" + this.parameter);\n }\n\n response = request(request);\n //重试\n if ((300 <= response.statusCode() && response.statusCode() < 400) || response.asString().contains(\"重新登录\")) {\n //重新登录\n logger.info(\"重新登录\");\n relogin();\n //重新发送请求\n updateCookie(request);\n response = request(request);\n }\n String source = response.asString();\n if (StringUtils.isNotEmpty(source) && source.contains(\"<title>登录</title>\")) {\n //重新登录\n logger.info(\"重新登录\");\n relogin();\n //重新发送请求\n updateCookie(request);\n response = request(request);\n }\n logger.info(\"name:{}, id:{},请求结果,状态码:{};内容:{}\", requestConfig.getName(), requestConfig.getId(), response.statusCode(), response.asString());\n String responseInfo = String.format(\"[接口返回信息] id:%s,name:%s, 返回状态码:%s\", requestConfig.getId(), requestConfig.getName(), response.statusCode());\n Reporter.log(responseInfo);\n if (response != null && response.getHeaders() != null) {\n log.info(\"返回头:{}\", response.getHeaders());\n }\n //Allure.addAttachment(\"log\",response.asString());\n if (isTestMethodCalled) {\n //Allure.step(requestConfig.getName() + \"-请求返回:\" + response.asString());\n }\n return response;\n }\n\n private void relogin() {\n String cookiesName = this.requestConfig.getCookies();\n if (StringUtils.isNotEmpty(cookiesName)) {\n String[] names = cookiesName.split(\";\");\n for (String name : names) {\n if (StringUtils.isNotEmpty(name) && name.startsWith(\"$\")) {\n name = name.substring(1, name.length());\n this.setCookies(requestConfigs.reLogin(name));\n }\n }\n }\n }\n\n private Response request(RequestSpecification request) {\n Response response = null;\n this.method = this.method.toLowerCase();\n switch (this.method) {\n case \"get\":\n response = request.get(this.path);\n break;\n case \"post\":\n response = request.post(this.path);\n break;\n case \"delete\":\n response = request.delete(this.path);\n break;\n }\n return response;\n }\n\n private static void writeValue(Object value, ArrayNode node) {\n String type = value.getClass().toString();\n switch (type) {\n case \"class java.lang.String\":\n node.add((String) value);\n break;\n case \"class java.lang.Byte\":\n node.add((Byte) value);\n break;\n case \"class java.lang.Short\":\n node.add((Short) value);\n break;\n case \"class java.lang.Integer\":\n node.add((Integer) value);\n break;\n case \"class java.lang.Long\":\n node.add((Long) value);\n break;\n case \"class java.lang.Float\":\n node.add((Float) value);\n break;\n case \"class java.lang.Double\":\n node.add((Double) value);\n break;\n case \"class java.lang.Boolean\":\n node.add((Boolean) value);\n break;\n case \"class java.lang.Character\":\n node.add((Character) value);\n break;\n default:\n System.out.println(\"不支持的类型:\" + type);\n }\n }\n\n public Request setPath(String path) {\n this.path = path;\n return this;\n }\n\n public Request setParameter(String name, Object value) {\n this.tmpParameter.put(name, value);\n this.setParameters(this.tmpParameter);\n return this;\n }\n\n //根据路径删除,路径按json path\n public Request removeParameterByPath(String path) {\n if (!path.trim().startsWith(\"$.\")) {\n logger.error(\"删除参数失败!参数路径格式错误!{}\", path);\n return this;\n }\n Object map = this.parameter;\n String[] ps = path.split(\"\\\\.\");\n for (int i = 1; i < ps.length; i++) {\n String key = ps[i];\n if (key.contains(\"[\") && key.endsWith(\"]\")) {\n String[] ss = key.split(\"[\\\\[,\\\\]]\");\n if (!((Map<String, Object>) map).containsKey(ss[0])) {\n logger.error(\"删除参数失败!通过该路径未能找到要删除参数!{}\", path);\n return this;\n }\n map = ((Map<String, Object>) map).get(ss[0]);\n int j = Integer.valueOf(ss[1]);\n if (map instanceof List && ((List) map).size() > j) {\n //path已经到末尾\n if (i == ps.length - 1) {\n ((List) map).remove(j);\n } else {\n map = ((List) map).get(j);\n }\n } else {\n logger.error(\"设置参数失败!通过该路径未能找到要替换参数!{}\", path);\n return this;\n }\n } else {\n if (!((Map<String, Object>) map).containsKey(key)) {\n logger.error(\"设置参数失败!通过该路径未能找到要替换参数!{}\", path);\n return this;\n }\n //path已经到末尾\n if (i == ps.length - 1) {\n ((Map<String, Object>) map).remove(key);\n } else {\n map = ((Map<String, Object>) map).get(key);\n }\n }\n }\n return this;\n }\n\n //根据路径设置,路径按json path\n private void setParameterByPath(String path, Object value) {\n if (!path.trim().startsWith(\"$.\")) {\n logger.error(\"设置参数失败!参数路径格式错误!{}\", path);\n return;\n }\n Object map = this.parameter;\n String[] ps = path.split(\"\\\\.\");\n if (ps.length == 1) {\n if (map instanceof Map && value instanceof Map) {\n ((Map) map).putAll((Map) value);\n }\n if (map instanceof List) {\n ((List) map).add(value);\n }\n }\n for (int i = 1; i < ps.length; i++) {\n String key = ps[i];\n if (key.equals(\"$\")) {\n continue;\n }\n if (key.contains(\"[\") && key.endsWith(\"]\")) {\n String[] ss = key.split(\"[\\\\[,\\\\]]\");\n if (!((Map<String, Object>) map).containsKey(ss[0])) {\n logger.error(\"设置参数失败!通过该路径未能找到要替换参数!{}\", path);\n return;\n }\n map = ((Map<String, Object>) map).get(ss[0]);\n int j = Integer.valueOf(ss[1]);\n if (map instanceof List) {\n if (((List) map).size() > j) {\n //path已经到末尾\n if (i == ps.length - 1) {\n ((List) map).set(j, value);\n } else {\n map = ((List) map).get(j);\n }\n } else {\n //添加到列表末尾\n if (i == ps.length - 1) {\n ((List) map).add(value);\n }\n }\n\n } else {\n logger.error(\"设置参数失败!通过该路径未能找到要替换参数!{}\", path);\n return;\n }\n } else {\n if (!((Map<String, Object>) map).containsKey(key)) {\n ((Map<String, Object>) map).put(key, new HashMap<String, Object>());\n //logger.error(\"设置参数失败!通过该路径未能找到要替换参数!{}\", path);\n //return;\n }\n //path已经到末尾\n if (i == ps.length - 1) {\n ((Map<String, Object>) map).put(key, value);\n } else {\n map = ((Map<String, Object>) map).get(key);\n }\n }\n }\n }\n\n public Request setParameters(Map<String, Object> parameters) {\n if (this.method.equals(\"get\") || this.method.equals(\"delete\")) {\n for (String key : parameters.keySet()) {\n this.path = replaceOrAdd(this.path, key, parameters.get(key).toString());\n }\n } else {\n if (this.parameter.size() == 0 || (!this.requestConfig.getParameters().trim().startsWith(\"{\"))) {\n this.parameter.putAll(parameters);\n } else {\n mapCrawl(this.parameter, parameters);\n }\n }\n //logger.info(this.parameter.toString());\n return this;\n }\n\n private void mapCrawl(Map<String, Object> target, Map<String, Object> replacement) {\n Set<String> keySet = replacement.keySet();\n //json path 路径的设置\n for (String key : keySet) {\n if (key.startsWith(\"$.\")) {\n this.setParameterByPath(key, replacement.get(key));\n replacement.remove(key);\n }\n }\n for (String key : target.keySet()) {\n if (keySet.contains(key)) {\n target.put(key, replacement.get(key));\n }\n Object value = target.get(key);\n if (value != null) {\n if (value instanceof java.util.List) {\n for (Object o : (List) value) {\n if (o instanceof java.util.Map) {\n mapCrawl((Map<String, Object>) o, replacement);\n }\n }\n } else if (value.getClass().isArray()) {\n int length = Array.getLength(value);\n Object[] os = new Object[length];\n for (int i = 0; i < length; i++) {\n Object o = Array.get(value, i);\n if (o instanceof java.util.Map) {\n mapCrawl((Map<String, Object>) o, replacement);\n }\n }\n } else if (value instanceof java.util.Map) {\n mapCrawl((Map<String, Object>) value, replacement);\n }\n }\n }\n }\n\n private static void modify(JsonNode root, Map<String, Object> map) {\n Set<String> keySet = map.keySet();\n if (root.isObject()) {\n Iterator<String> it = root.fieldNames();\n while (it.hasNext()) {\n String key = it.next();\n if (keySet.contains(key)) {\n Object value = map.get(key);\n ObjectNode objectNode = (ObjectNode) root;\n ObjectMapper mapper = new ObjectMapper();\n if (value instanceof java.util.List) {\n ArrayNode arrayNode = mapper.createArrayNode();\n for (Object o : (List) value) {\n writeValue(o, arrayNode);\n }\n ((ObjectNode) root).set(key, arrayNode);\n } else if (value.getClass().isArray()) {\n int length = Array.getLength(value);\n Object[] os = new Object[length];\n ArrayNode arrayNode = mapper.createArrayNode();\n for (int i = 0; i < length; i++) {\n writeValue(Array.get(value, i), arrayNode);\n }\n ((ObjectNode) root).set(key, arrayNode);\n }\n } else {\n modify(root.findValue(key), map);\n }\n }\n }\n if (root.isArray()) {\n Iterator<JsonNode> it = root.iterator();\n while (it.hasNext()) {\n modify(it.next(), map);\n }\n }\n }\n\n private static void jsonLeaf(JsonNode node, String name, Object value) throws IOException {\n if (node.isValueNode()) {\n //System.out.println(node.toString());\n return;\n }\n if (node.isObject()) {\n Iterator<String> it = node.fieldNames();\n //Iterator<Map.Entry<String, JsonNode>> it = node.fields();\n while (it.hasNext()) {\n //Map.Entry<String, JsonNode> entry = it.next();\n String key = it.next();\n if (key.equals(name)) {\n ObjectNode objectNode = (ObjectNode) node;\n //objectNode.put(key,value.toString());\n ObjectMapper mapper = new ObjectMapper();\n\n if (value instanceof java.util.List) {\n ArrayNode arrayNode = mapper.createArrayNode();\n for (Object o : (List) value) {\n writeValue(o, arrayNode);\n }\n ((ObjectNode) node).set(key, arrayNode);\n } else if (value.getClass().isArray()) {\n int length = Array.getLength(value);\n Object[] os = new Object[length];\n ArrayNode arrayNode = mapper.createArrayNode();\n for (int i = 0; i < length; i++) {\n writeValue(Array.get(value, i), arrayNode);\n //System.out.println(Array.get(value, i));\n //System.out.println(Array.get(value, i).getClass());\n //((ArrayNode)arrayNode).add(Array.get(value, i));\n }\n ((ObjectNode) node).set(key, arrayNode);\n }\n\n } else {\n jsonLeaf(node.findValue(key), name, value);\n }\n }\n }\n if (node.isArray()) {\n Iterator<JsonNode> it = node.iterator();\n while (it.hasNext()) {\n jsonLeaf(it.next(), name, value);\n }\n }\n }\n\n public static String replaceOrAdd(String url, String name, String value) {\n if (StringUtils.isNotBlank(url) && StringUtils.isNotBlank(value)) {\n if (url.contains(name + \"=\")) {\n url = url.replaceAll(\"(&\" + name + \"=[^&]*)\", \"&\" + name + \"=\" + value);\n url = url.replaceAll(\"(\\\\?\" + name + \"=[^&]*)\", \"?\" + name + \"=\" + value);\n } else {\n if (!url.contains(\"?\")) {\n url = url + \"?\";\n } else {\n url = url + \"&\";\n }\n url = url + name + \"=\" + value;\n }\n }\n return url;\n }\n\n private boolean isTestMethodCalled() {\n StackTraceElement[] sts = Thread.currentThread().getStackTrace();\n Class c = null;\n StackTraceElement ste = sts[3];\n //System.out.println(ste.getClassName() + \".\" + ste.getMethodName());\n try {\n c = Class.forName(ste.getClassName());\n for (Method method : c.getMethods()) {\n if (method.getName().equals(ste.getMethodName())) {\n Test t = method.getAnnotation(Test.class);\n if (t != null && c.getSuperclass().equals(AbstractTestNGSpringContextTests.class)) {\n return true;\n }\n }\n }\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n return false;\n }\n\n public static void main(String[] args) throws IOException {\n ObjectMapper MAPPER = new ObjectMapper();\n String s = \"{'code':'0','desc':'查询保证金记录成功','data':{'dataSnapshot':{'totalAmount':109279050,'rechargeAmount':0,'deductAmount':0,'refundAmount':0},'list':[],'totalCount':0}}\";\n //System.out.println(MAPPER.readValue(s.replace(\"'\",\"\\\"\"), HashMap.class));\n JsonNode root = MAPPER.readTree(s.replace(\"'\", \"\\\"\"));\n List<String> list = new ArrayList<>();\n list.add(\"abc\");\n list.add(\"123\");\n Object o = new Object();\n jsonLeaf(root, \"totalAmount\", list);\n logger.info(root.toString());\n System.out.println(root);\n String s1 = \"http://manager.tuia.cn/homePage/queryAdvertData?pageSize=15&currentPage=1&startDate=2020-05-26&endDate=2020-05-26\";\n s1 = replaceOrAdd(s1, \"currentPage\", \"999\");\n System.out.println(s1);\n Map<String, String> map = new HashMap<>();\n String s2 = \"pageSize=50&currentPage=1&name=&checkStatus=&advertId=&companyName=&aeName=&sellName=&tradeId=&tableHeight=0&otherheight=12\";\n String[] ss = s2.split(\"[=,&]\");\n int len = ss.length;\n if ((len & 0x01) == 1) {\n len--;\n }\n for (int i = 0; i < len; i = i + 2) {\n map.put(ss[i], ss[i + 1]);\n }\n Map<String, String> map1 = new HashMap<>();\n map1.put(\"a\", \"1\");\n map1.put(\"pageSize\", \"49\");\n System.out.println(map);\n map.putAll(map1);\n System.out.println(map);\n String s3 = \"book[1]\";\n String[] ss1 = s3.split(\"[\\\\[ , \\\\]]\");\n System.out.println(ss1);\n String url = \"https://m.7hotest.com/item/detail3?id=731&pid=14\";\n url = url.replaceAll(\"(&\" + \"pid\" + \"=[^&]*)\", \"&\" + \"pid\" + \"=\" + 333);\n url = url.replaceAll(\"(\\\\?\" + \"id\" + \"=[^&]*)\", \"?\" + \"id\" + \"=\" + 444);\n //url = url.replaceAll(\"(\\\\?\"+\"id\" + \"=[^&]*)\", \"\\\\?\"+\"id\" + \"=\" + 333).replace(\"(\\\\&\"+\"pid\" + \"=[^&]*)\", \"pid\" + \"=\" + 444);\n System.out.println(url);\n String s4 = \"$abcde\";\n System.out.println(s4.substring(1, s4.length()));\n }\n}" }, { "identifier": "PioneerConfig", "path": "src/main/java/com/bulls/qa/configuration/PioneerConfig.java", "snippet": "@Data\npublic class PioneerConfig extends RequestConfig {\n @Setter\n @Getter\n int priority;\n\n\n\n private List<Map<String, String>> requiredParameter;\n @Getter\n private List<Map<String, String>> extractors;\n\n public void setRequiredParameter(String requiredParameter) {\n String s = requiredParameter.trim().replace(\"\\\\\", \"\");\n ObjectMapper mapper = new ObjectMapper();\n try {\n this.requiredParameter = mapper.readValue(s, new TypeReference<List<Map<String, Object>>>() {\n });\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void setExtractors(String extractors) {\n String s = extractors.trim().replace(\"\\\\\", \"\");\n ObjectMapper mapper = new ObjectMapper();\n try {\n this.extractors = mapper.readValue(s, new TypeReference<List<Map<String, Object>>>() {\n });\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" } ]
import com.bulls.qa.configuration.RequestConfigs; import com.bulls.qa.request.Request; import com.bulls.qa.configuration.PioneerConfig; import io.restassured.RestAssured; import io.restassured.filter.FilterContext; import io.restassured.response.Response; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.FilterableResponseSpecification; import io.restassured.spi.AuthFilter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.*;
9,306
package com.bulls.qa.service; @Service public class PioneerService { @Autowired
package com.bulls.qa.service; @Service public class PioneerService { @Autowired
private RequestConfigs requestConfigs;
0
2023-12-14 06:54:24+00:00
12k
DantSu/studio
core/src/main/java/studio/core/v1/writer/fs/FsStoryPackWriter.java
[ { "identifier": "ActionNode", "path": "core/src/main/java/studio/core/v1/model/ActionNode.java", "snippet": "public class ActionNode extends Node {\n\n private List<StageNode> options;\n\n public ActionNode(EnrichedNodeMetadata enriched, List<StageNode> options) {\n super(enriched);\n this.options = options;\n }\n\n public List<StageNode> getOptions() {\n return options;\n }\n\n public void setOptions(List<StageNode> options) {\n this.options = options;\n }\n}" }, { "identifier": "ControlSettings", "path": "core/src/main/java/studio/core/v1/model/ControlSettings.java", "snippet": "public class ControlSettings {\n\n private final boolean wheelEnabled;\n private final boolean okEnabled;\n private final boolean homeEnabled;\n private final boolean pauseEnabled;\n private final boolean autoJumpEnabled;\n\n public ControlSettings(boolean wheelEnabled, boolean okEnabled, boolean homeEnabled, boolean pauseEnabled, boolean autoJumpEnabled) {\n this.wheelEnabled = wheelEnabled;\n this.okEnabled = okEnabled;\n this.homeEnabled = homeEnabled;\n this.pauseEnabled = pauseEnabled;\n this.autoJumpEnabled = autoJumpEnabled;\n }\n\n public boolean isWheelEnabled() {\n return wheelEnabled;\n }\n\n public boolean isOkEnabled() {\n return okEnabled;\n }\n\n public boolean isHomeEnabled() {\n return homeEnabled;\n }\n\n public boolean isPauseEnabled() {\n return pauseEnabled;\n }\n\n public boolean isAutoJumpEnabled() {\n return autoJumpEnabled;\n }\n}" }, { "identifier": "StageNode", "path": "core/src/main/java/studio/core/v1/model/StageNode.java", "snippet": "public class StageNode extends Node {\n\n private String uuid;\n private ImageAsset image;\n private AudioAsset audio;\n private Transition okTransition;\n private Transition homeTransition;\n private ControlSettings controlSettings;\n\n public StageNode(String uuid, ImageAsset image, AudioAsset audio, Transition okTransition, Transition homeTransition, ControlSettings controlSettings, EnrichedNodeMetadata enriched) {\n super(enriched);\n this.uuid = uuid;\n this.image = image;\n this.audio = audio;\n this.okTransition = okTransition;\n this.homeTransition = homeTransition;\n this.controlSettings = controlSettings;\n }\n\n public String getUuid() {\n return uuid;\n }\n\n public void setUuid(String uuid) {\n this.uuid = uuid;\n }\n\n public ImageAsset getImage() {\n return image;\n }\n\n public void setImage(ImageAsset image) {\n this.image = image;\n }\n\n public AudioAsset getAudio() {\n return audio;\n }\n\n public void setAudio(AudioAsset audio) {\n this.audio = audio;\n }\n\n public Transition getOkTransition() {\n return okTransition;\n }\n\n public void setOkTransition(Transition okTransition) {\n this.okTransition = okTransition;\n }\n\n public Transition getHomeTransition() {\n return homeTransition;\n }\n\n public void setHomeTransition(Transition homeTransition) {\n this.homeTransition = homeTransition;\n }\n\n public ControlSettings getControlSettings() {\n return controlSettings;\n }\n\n public void setControlSettings(ControlSettings controlSettings) {\n this.controlSettings = controlSettings;\n }\n}" }, { "identifier": "StoryPack", "path": "core/src/main/java/studio/core/v1/model/StoryPack.java", "snippet": "public class StoryPack {\n\n private String uuid;\n private boolean factoryDisabled;\n private short version;\n private List<StageNode> stageNodes;\n private EnrichedPackMetadata enriched;\n private boolean nightModeAvailable = false;\n\n public String getUuid() {\n return uuid;\n }\n\n public void setUuid(String uuid) {\n this.uuid = uuid;\n }\n\n public boolean isFactoryDisabled() {\n return factoryDisabled;\n }\n\n public void setFactoryDisabled(boolean factoryDisabled) {\n this.factoryDisabled = factoryDisabled;\n }\n\n public short getVersion() {\n return version;\n }\n\n public void setVersion(short version) {\n this.version = version;\n }\n\n public List<StageNode> getStageNodes() {\n return stageNodes;\n }\n\n public void setStageNodes(List<StageNode> stageNodes) {\n this.stageNodes = stageNodes;\n }\n\n public EnrichedPackMetadata getEnriched() {\n return enriched;\n }\n\n public void setEnriched(EnrichedPackMetadata enriched) {\n this.enriched = enriched;\n }\n\n public boolean isNightModeAvailable() {\n return nightModeAvailable;\n }\n\n public void setNightModeAvailable(boolean nightModeAvailable) {\n this.nightModeAvailable = nightModeAvailable;\n }\n}" }, { "identifier": "Transition", "path": "core/src/main/java/studio/core/v1/model/Transition.java", "snippet": "public class Transition {\n\n private ActionNode actionNode;\n private short optionIndex;\n\n public Transition(ActionNode actionNode, short optionIndex) {\n this.actionNode = actionNode;\n this.optionIndex = optionIndex;\n }\n\n public ActionNode getActionNode() {\n return actionNode;\n }\n\n public void setActionNode(ActionNode actionNode) {\n this.actionNode = actionNode;\n }\n\n public short getOptionIndex() {\n return optionIndex;\n }\n\n public void setOptionIndex(short optionIndex) {\n this.optionIndex = optionIndex;\n }\n}" }, { "identifier": "AudioAsset", "path": "core/src/main/java/studio/core/v1/model/asset/AudioAsset.java", "snippet": "public class AudioAsset {\n\n private AudioType type;\n private byte[] rawData;\n\n public AudioAsset(AudioType type, byte[] rawData) {\n super();\n this.type = type;\n this.rawData = rawData;\n }\n\n public AudioType getType() {\n return type;\n }\n\n public void setType(AudioType type) {\n this.type = type;\n }\n\n public byte[] getRawData() {\n return rawData;\n }\n\n public void setRawData(byte[] rawData) {\n this.rawData = rawData;\n }\n\n}" }, { "identifier": "AudioType", "path": "core/src/main/java/studio/core/v1/model/asset/AudioType.java", "snippet": "public enum AudioType {\n\n WAV(\"audio/x-wav\", \".wav\"), MPEG(\"audio/mpeg\", \".mp3\"), MP3(\"audio/mp3\", \".mp3\"), OGG(\"audio/ogg\", \".ogg\", \".oga\");\n\n private final String mime;\n private final List<String> extensions;\n\n private AudioType(String mime, String... extensions) {\n this.mime = mime;\n this.extensions = Arrays.asList(extensions);\n }\n\n public static AudioType fromExtension(String extension) {\n for (AudioType e : values()) {\n if (e.extensions.contains(extension)) {\n return e;\n }\n }\n return null;\n }\n\n public static AudioType fromMime(String mime) {\n for (AudioType e : values()) {\n if (e.mime.equals(mime)) {\n return e;\n }\n }\n return null;\n }\n\n public String getMime() {\n return mime;\n }\n\n public List<String> getExtensions() {\n return extensions;\n }\n\n public String getFirstExtension() {\n return extensions.get(0);\n }\n}" }, { "identifier": "ImageAsset", "path": "core/src/main/java/studio/core/v1/model/asset/ImageAsset.java", "snippet": "public class ImageAsset {\n\n private ImageType type;\n private byte[] rawData;\n\n public ImageAsset(ImageType type, byte[] rawData) {\n super();\n this.type = type;\n this.rawData = rawData;\n }\n\n public ImageType getType() {\n return type;\n }\n\n public void setType(ImageType imageType) {\n this.type = imageType;\n }\n\n public byte[] getRawData() {\n return rawData;\n }\n\n public void setRawData(byte[] rawData) {\n this.rawData = rawData;\n }\n\n}" }, { "identifier": "ImageType", "path": "core/src/main/java/studio/core/v1/model/asset/ImageType.java", "snippet": "public enum ImageType {\n\n BMP(\"image/bmp\", \".bmp\"), PNG(\"image/png\", \".png\"), JPEG(\"image/jpeg\", \".jpg\", \".jpeg\");\n\n private final String mime;\n private final List<String> extensions;\n\n private ImageType(String mime, String... extensions) {\n this.mime = mime;\n this.extensions = Arrays.asList(extensions);\n }\n\n public static ImageType fromExtension(String extension) {\n for (ImageType e : values()) {\n if (e.extensions.contains(extension)) {\n return e;\n }\n }\n return null;\n }\n\n public static ImageType fromMime(String mime) {\n for (ImageType e : values()) {\n if (e.mime.equals(mime)) {\n return e;\n }\n }\n return null;\n }\n\n public String getMime() {\n return mime;\n }\n\n public List<String> getExtensions() {\n return extensions;\n }\n\n public String getFirstExtension() {\n return extensions.get(0);\n }\n\n}" }, { "identifier": "AudioConversion", "path": "core/src/main/java/studio/core/v1/utils/AudioConversion.java", "snippet": "public class AudioConversion {\n\n public static final float WAVE_SAMPLE_RATE = 32000.0f;\n public static final float OGG_SAMPLE_RATE = 44100.0f;\n public static final float MP3_SAMPLE_RATE = 44100.0f;\n public static final int BITSIZE = 16;\n public static final int MP3_BITSIZE = 32;\n public static final int CHANNELS = 1;\n\n private AudioConversion() {\n throw new IllegalArgumentException(\"Utility class\");\n }\n\n /** Make LameEncoder closeable. */\n private static class LameEncoderWrapper implements AutoCloseable {\n private final LameEncoder delegate;\n\n public LameEncoderWrapper(LameEncoder encoder) {\n delegate = encoder;\n }\n\n @Override\n public void close() throws IOException {\n delegate.close();\n }\n }\n\n public static byte[] oggToWave(byte[] oggData) throws IOException, UnsupportedAudioFileException {\n return anyToWave(oggData);\n }\n\n public static byte[] mp3ToWave(byte[] mp3Data) throws IOException, UnsupportedAudioFileException {\n return anyToWave(mp3Data);\n }\n\n public static byte[] anyToWave(byte[] data) throws IOException, UnsupportedAudioFileException {\n try (AudioInputStream inputAudio = AudioSystem.getAudioInputStream(new ByteArrayInputStream(data))) {\n\n float inputRate = inputAudio.getFormat().getSampleRate();\n int inputChannels = inputAudio.getFormat().getChannels();\n\n // First, convert to PCM\n AudioFormat pcmFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, inputRate, BITSIZE, //\n inputChannels, inputChannels * 2, inputRate, false);\n\n // Then, convert sample rate to 32000Hz, and to mono channel (the only format\n // that is supported by the story teller device)\n AudioFormat pcm32000Format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, WAVE_SAMPLE_RATE, BITSIZE, //\n CHANNELS, CHANNELS * 2, WAVE_SAMPLE_RATE, false);\n\n try (AudioInputStream pcm = AudioSystem.getAudioInputStream(pcmFormat, inputAudio);\n AudioInputStream pcm32000 = AudioSystem.getAudioInputStream(pcm32000Format, pcm);\n ByteArrayOutputStream baos = new ByteArrayOutputStream()) {\n\n // Read the whole stream in a byte array because length must be known\n baos.writeBytes(pcm32000.readAllBytes());\n\n try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\n AudioInputStream waveStream = new AudioInputStream(bais, pcm32000Format,\n baos.toByteArray().length);\n ByteArrayOutputStream output = new ByteArrayOutputStream();) {\n AudioSystem.write(waveStream, AudioFileFormat.Type.WAVE, output);\n return output.toByteArray();\n }\n }\n }\n }\n\n public static byte[] waveToOgg(byte[] waveData) throws IOException, VorbisEncodingException, UnsupportedAudioFileException {\n // Convert sample rate to 44100Hz (the only rate that is supported by the vorbis\n // encoding library)\n AudioFormat pcm44100Format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, OGG_SAMPLE_RATE, BITSIZE, //\n CHANNELS, CHANNELS * 2, OGG_SAMPLE_RATE, false);\n\n try (AudioInputStream inputAudio = AudioSystem.getAudioInputStream(new ByteArrayInputStream(waveData));\n AudioInputStream pcm44100 = AudioSystem.getAudioInputStream(pcm44100Format, inputAudio);) {\n return VorbisEncoder.encode(pcm44100);\n }\n }\n\n public static byte[] anyToMp3(byte[] data) throws IOException, UnsupportedAudioFileException {\n try (AudioInputStream inputAudio = AudioSystem.getAudioInputStream(new ByteArrayInputStream(data))) {\n\n float inputRate = inputAudio.getFormat().getSampleRate();\n int inputChannels = inputAudio.getFormat().getChannels();\n\n // First, convert to PCM\n AudioFormat pcmFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, inputRate, BITSIZE, //\n inputChannels, inputChannels * 2, inputRate, false);\n\n // Then, convert to mono **and oversample** (apparently the input stream is\n // always empty unless the sample rate changes)\n AudioFormat pcmOverSampledFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, inputRate * 2, BITSIZE, //\n CHANNELS, CHANNELS * 2, inputRate * 2, false);\n\n // Finally, convert sample rate to 44100Hz and sample bitsize to 32 bits\n AudioFormat pcm44100Format = new AudioFormat(AudioFormat.Encoding.PCM_FLOAT, MP3_SAMPLE_RATE, MP3_BITSIZE, //\n CHANNELS, CHANNELS * 4, MP3_SAMPLE_RATE, false);\n\n try (AudioInputStream pcm = AudioSystem.getAudioInputStream(pcmFormat, inputAudio);\n AudioInputStream pcmOverSampled = AudioSystem.getAudioInputStream(pcmOverSampledFormat, pcm);\n AudioInputStream pcm44100 = AudioSystem.getAudioInputStream(pcm44100Format, pcmOverSampled);) {\n return encodeMP3(pcm44100);\n }\n }\n }\n\n /** Convert Wav to MP3 with LameEncoder. */\n private static byte[] encodeMP3(AudioInputStream pcm44100) throws IOException {\n LameEncoder encoder = new LameEncoder(pcm44100.getFormat(), LameEncoder.BITRATE_AUTO, MPEGMode.MONO.ordinal(),\n 4, true);\n\n try (LameEncoderWrapper lameEncoderWrapper = new LameEncoderWrapper(encoder);\n ByteArrayOutputStream mp3 = new ByteArrayOutputStream()) {\n\n byte[] inputBuffer = new byte[encoder.getPCMBufferSize()];\n byte[] outputBuffer = new byte[encoder.getPCMBufferSize()];\n\n int bytesRead;\n int bytesWritten;\n\n while (0 < (bytesRead = pcm44100.read(inputBuffer))) {\n bytesWritten = encoder.encodeBuffer(inputBuffer, 0, bytesRead, outputBuffer);\n mp3.write(outputBuffer, 0, bytesWritten);\n }\n bytesWritten = encoder.encodeFinish(outputBuffer);\n mp3.write(outputBuffer, 0, bytesWritten);\n return mp3.toByteArray();\n }\n }\n\n}" }, { "identifier": "ID3Tags", "path": "core/src/main/java/studio/core/v1/utils/ID3Tags.java", "snippet": "public class ID3Tags {\n\n private static final Logger LOGGER = LogManager.getLogger(ID3Tags.class);\n\n private static final int ID3V1_SIZE = 128;\n private static final int ID3V2_HEADER_SIZE = 10;\n private static final int ID3V2_SIZE_OFFSET = 6;\n\n private ID3Tags() {\n throw new IllegalArgumentException(\"Utility class\");\n }\n\n public static boolean hasID3v1Tag(byte[] mp3Data) {\n // Look for ID3v1 tag at end of file\n ByteBuffer mp3Buffer = ByteBuffer.wrap(mp3Data);\n mp3Buffer.position(mp3Data.length - ID3V1_SIZE);\n byte char1 = mp3Buffer.get();\n byte char2 = mp3Buffer.get();\n byte char3 = mp3Buffer.get();\n return (char1 == 0x54 && char2 == 0x41 && char3 == 0x47); // \"TAG\"\n }\n\n public static byte[] removeID3v1Tag(byte[] mp3Data) {\n if (hasID3v1Tag(mp3Data)) {\n // Remove last 128 bytes\n LOGGER.debug(\"Removing ID3v1 tag at end of file (128 bytes).\");\n return Arrays.copyOfRange(mp3Data, 0, mp3Data.length - ID3V1_SIZE);\n }\n return mp3Data;\n }\n\n public static boolean hasID3v2Tag(byte[] mp3Data) {\n // Look for ID3v2 tag at beginning of file\n ByteBuffer mp3Buffer = ByteBuffer.wrap(mp3Data);\n byte char1 = mp3Buffer.get();\n byte char2 = mp3Buffer.get();\n byte char3 = mp3Buffer.get();\n return (char1 == 0x49 && char2 == 0x44 && char3 == 0x33); // \"ID3\"\n }\n\n public static byte[] removeID3v2Tag(byte[] mp3Data) {\n if (hasID3v2Tag(mp3Data)) {\n // Read tag size and remove first <n> bytes\n ByteBuffer mp3Buffer = ByteBuffer.wrap(mp3Data);\n mp3Buffer.position(ID3V2_SIZE_OFFSET);\n byte size1 = mp3Buffer.get();\n byte size2 = mp3Buffer.get();\n byte size3 = mp3Buffer.get();\n byte size4 = mp3Buffer.get();\n int size = ((size1 & 0x7f) << 21) | ((size2 & 0x7f) << 14) | ((size3 & 0x7f) << 7) | (size4 & 0x7f);\n size += ID3V2_HEADER_SIZE;\n LOGGER.debug(\"Removing ID3v2 tag at beginning of file ({} bytes).\", size);\n return Arrays.copyOfRange(mp3Data, size, mp3Data.length);\n }\n return mp3Data;\n }\n}" }, { "identifier": "SecurityUtils", "path": "core/src/main/java/studio/core/v1/utils/SecurityUtils.java", "snippet": "public class SecurityUtils {\n\n private static final Logger LOGGER = LogManager.getLogger(SecurityUtils.class);\n\n private static final byte[] HEX_ARRAY = \"0123456789abcdef\".getBytes(StandardCharsets.US_ASCII);\n\n private SecurityUtils() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n /**\n * Compute the sha1 of a byte array in Hex string\n * \n * @param input byte array\n * @return sha1 String\n */\n public static String sha1Hex(byte[] array) {\n try {\n byte[] digest = MessageDigest.getInstance(\"SHA1\").digest(array);\n return encodeHex(digest);\n } catch (NoSuchAlgorithmException e) {\n LOGGER.error(\"sha1 not supported\", e);\n return null;\n }\n }\n\n /**\n * Compute the sha1 of a String in Hex string\n * \n * @param input UTF-8 string\n * @return sha1 String\n */\n public static String sha1Hex(String s) {\n return sha1Hex(s.getBytes(StandardCharsets.UTF_8));\n }\n\n /**\n * Convert byte array to (lowercase) Hex String\n * \n * @param bytes byte array\n * @return hexadecimal string\n */\n public static String encodeHex(byte[] bytes) {\n byte[] hexChars = new byte[bytes.length * 2];\n for (int j = 0; j < bytes.length; j++) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = HEX_ARRAY[v >>> 4];\n hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];\n }\n return new String(hexChars, StandardCharsets.UTF_8);\n }\n\n /**\n * Convert UTF-8 String to (lowercase) Hex String\n * \n * @param s String\n * @return hexadecimal string\n */\n public static String encodeHex(String s) {\n return encodeHex(s.getBytes(StandardCharsets.UTF_8));\n }\n\n /**\n * Convert Hex String to byte array.\n * \n * @param s hexadecimal string\n * @return byte array\n */\n public static byte[] decodeHex(String s) {\n int len = s.length();\n if (len % 2 != 0) {\n throw new IllegalArgumentException(\"Invalid hex string (length % 2 != 0)\");\n }\n byte[] arr = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n arr[i / 2] = Integer.valueOf(s.substring(i, i + 2), 16).byteValue();\n }\n return arr;\n }\n\n}" }, { "identifier": "XXTEACipher", "path": "core/src/main/java/studio/core/v1/utils/XXTEACipher.java", "snippet": "public class XXTEACipher {\n\n private static final int DELTA = 0x9e3779b9;\n\n private static final byte[] COMMON_KEY = SecurityUtils.decodeHex(\"91bd7a0aa75440a9bbd49d6ce0dcc0e3\");\n\n public enum CipherMode {\n CIPHER, DECIPHER\n }\n\n private XXTEACipher() {\n throw new IllegalArgumentException(\"Utility class\");\n }\n\n /** (De-)cipher a block of data with a key. */\n public static byte[] cipher(CipherMode mode, byte[] data, int minSize, byte[] key) {\n byte[] block = Arrays.copyOfRange(data, 0, Math.min(minSize, data.length));\n int[] dataInt = toIntArray(block, ByteOrder.LITTLE_ENDIAN);\n int[] keyInt = toIntArray(key, ByteOrder.BIG_ENDIAN);\n int op = Math.min(128, data.length / 4);\n int[] encryptedInt = btea(dataInt, mode == CipherMode.DECIPHER ? -op : op, keyInt);\n return toByteArray(encryptedInt, ByteOrder.LITTLE_ENDIAN);\n }\n\n /** (De-)cipher data with the common key. */\n public static byte[] cipherCommonKey(CipherMode mode, byte[] data) {\n byte[] encryptedBlock = cipher(mode, data, 512, COMMON_KEY);\n ByteBuffer bb = ByteBuffer.allocate(data.length);\n bb.put(encryptedBlock);\n if (data.length > 512) {\n bb.put(Arrays.copyOfRange(data, 512, data.length));\n }\n return bb.array();\n }\n\n public static int[] toIntArray(byte[] data, ByteOrder endianness) {\n ByteBuffer bb = ByteBuffer.wrap(data);\n bb.order(endianness);\n List<Integer> ints = new ArrayList<>();\n for (int i=0; i<data.length/4; i++) {\n ints.add(bb.getInt());\n }\n return ints.stream().mapToInt(i->i).toArray();\n }\n\n public static byte[] toByteArray(int[] data, ByteOrder endianness) {\n ByteBuffer bb = ByteBuffer.allocate(data.length*4);\n bb.order(endianness);\n for (int i : data) {\n bb.putInt(i);\n }\n return bb.array();\n }\n\n public static int[] btea(int[] v, int n, int[] k) {\n int y;\n int z;\n int sum;\n int p;\n int rounds;\n int e;\n if (n > 1) { /* Coding Part */\n rounds = 1 + 52/n;\n sum = 0;\n z = v[n-1];\n do {\n sum += DELTA;\n e = (sum >>> 2) & 3;\n for (p=0; p<n-1; p++) {\n y = v[p+1];\n z = v[p] += mx(k, e, p, y, z, sum);\n }\n y = v[0];\n z = v[n-1] += mx(k, e, p, y, z, sum);\n } while (--rounds != 0);\n } else if (n < -1) { /* Decoding Part */\n n = -n;\n rounds = 1 + 52/n;\n sum = rounds*DELTA;\n y = v[0];\n do {\n e = (sum >>> 2) & 3;\n for (p=n-1; p>0; p--) {\n z = v[p-1];\n y = v[p] -= mx(k, e, p, y, z, sum);\n }\n z = v[n-1];\n y = v[0] -= mx(k, e, p, y, z, sum);\n sum -= DELTA;\n } while (--rounds != 0);\n }\n return v;\n }\n\n private static int mx(int[] k, int e, int p, int y, int z, int sum) {\n return (((z>>>5^y<<2) + (y>>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)));\n }\n}" }, { "identifier": "CipherMode", "path": "core/src/main/java/studio/core/v1/utils/XXTEACipher.java", "snippet": "public enum CipherMode {\n CIPHER, DECIPHER\n}" }, { "identifier": "StoryPackWriter", "path": "core/src/main/java/studio/core/v1/writer/StoryPackWriter.java", "snippet": "public interface StoryPackWriter {\n\n void write(StoryPack pack, Path path, boolean enriched) throws IOException;\n\n}" } ]
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import studio.core.v1.model.ActionNode; import studio.core.v1.model.ControlSettings; import studio.core.v1.model.StageNode; import studio.core.v1.model.StoryPack; import studio.core.v1.model.Transition; import studio.core.v1.model.asset.AudioAsset; import studio.core.v1.model.asset.AudioType; import studio.core.v1.model.asset.ImageAsset; import studio.core.v1.model.asset.ImageType; import studio.core.v1.utils.AudioConversion; import studio.core.v1.utils.ID3Tags; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.XXTEACipher; import studio.core.v1.utils.XXTEACipher.CipherMode; import studio.core.v1.writer.StoryPackWriter;
7,236
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.core.v1.writer.fs; /** * Writer for the new binary format coming with firmware 2.4<br/> * Assets must be prepared to match the expected format : 4-bits depth / RLE * encoding BMP for images, and mono 44100Hz MP3 for sounds.<br/> * The first 512 bytes of most files are scrambled with a common key, provided * in an external file. <br/> * The bt file uses a device-specific key. */ public class FsStoryPackWriter implements StoryPackWriter { private static final Logger LOGGER = LogManager.getLogger(FsStoryPackWriter.class); private static final String NODE_INDEX_FILENAME = "ni"; private static final String LIST_INDEX_FILENAME = "li"; private static final String IMAGE_INDEX_FILENAME = "ri"; private static final String IMAGE_FOLDER = "rf"; private static final String SOUND_INDEX_FILENAME = "si"; private static final String SOUND_FOLDER = "sf"; private static final String BOOT_FILENAME = "bt"; private static final String NIGHT_MODE_FILENAME = "nm"; /** Blank MP3 file. */ private static final byte[] BLANK_MP3 = readRelative("blank.mp3"); // TODO Enriched metadata in a dedicated file (pack's title, description and thumbnail, nodes' name, group, type and position) public void write(StoryPack pack, Path packFolder, boolean enriched) throws IOException { // Write night mode if (pack.isNightModeAvailable()) { Files.createFile(packFolder.resolve(NIGHT_MODE_FILENAME)); } // Store assets bytes TreeMap<String, byte[]> assets = new TreeMap<>(); // Keep track of action nodes and assets List<ActionNode> actionNodesOrdered = new ArrayList<>(); Map<ActionNode, Integer> actionNodesIndexes = new HashMap<>(); List<String> imageHashOrdered = new ArrayList<>(); List<String> audioHashOrdered = new ArrayList<>(); // Add nodes index file: ni Path niPath = packFolder.resolve(NODE_INDEX_FILENAME); try( DataOutputStream niDos = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(niPath)))) { ByteBuffer bb = ByteBuffer.allocate(512).order(ByteOrder.LITTLE_ENDIAN); // Nodes index file format version (1) bb.putShort((short) 1); // Story pack version (1) bb.putShort(pack.getVersion()); // Start of actual nodes list in this file (0x200 / 512) bb.putInt(512); // Size of a stage node in this file (0x2C / 44) bb.putInt(44); // Number of stage nodes in this file bb.putInt(pack.getStageNodes().size()); // Number of images (in RI file and rf/ folder) bb.putInt((int) pack.getStageNodes().stream()
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.core.v1.writer.fs; /** * Writer for the new binary format coming with firmware 2.4<br/> * Assets must be prepared to match the expected format : 4-bits depth / RLE * encoding BMP for images, and mono 44100Hz MP3 for sounds.<br/> * The first 512 bytes of most files are scrambled with a common key, provided * in an external file. <br/> * The bt file uses a device-specific key. */ public class FsStoryPackWriter implements StoryPackWriter { private static final Logger LOGGER = LogManager.getLogger(FsStoryPackWriter.class); private static final String NODE_INDEX_FILENAME = "ni"; private static final String LIST_INDEX_FILENAME = "li"; private static final String IMAGE_INDEX_FILENAME = "ri"; private static final String IMAGE_FOLDER = "rf"; private static final String SOUND_INDEX_FILENAME = "si"; private static final String SOUND_FOLDER = "sf"; private static final String BOOT_FILENAME = "bt"; private static final String NIGHT_MODE_FILENAME = "nm"; /** Blank MP3 file. */ private static final byte[] BLANK_MP3 = readRelative("blank.mp3"); // TODO Enriched metadata in a dedicated file (pack's title, description and thumbnail, nodes' name, group, type and position) public void write(StoryPack pack, Path packFolder, boolean enriched) throws IOException { // Write night mode if (pack.isNightModeAvailable()) { Files.createFile(packFolder.resolve(NIGHT_MODE_FILENAME)); } // Store assets bytes TreeMap<String, byte[]> assets = new TreeMap<>(); // Keep track of action nodes and assets List<ActionNode> actionNodesOrdered = new ArrayList<>(); Map<ActionNode, Integer> actionNodesIndexes = new HashMap<>(); List<String> imageHashOrdered = new ArrayList<>(); List<String> audioHashOrdered = new ArrayList<>(); // Add nodes index file: ni Path niPath = packFolder.resolve(NODE_INDEX_FILENAME); try( DataOutputStream niDos = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(niPath)))) { ByteBuffer bb = ByteBuffer.allocate(512).order(ByteOrder.LITTLE_ENDIAN); // Nodes index file format version (1) bb.putShort((short) 1); // Story pack version (1) bb.putShort(pack.getVersion()); // Start of actual nodes list in this file (0x200 / 512) bb.putInt(512); // Size of a stage node in this file (0x2C / 44) bb.putInt(44); // Number of stage nodes in this file bb.putInt(pack.getStageNodes().size()); // Number of images (in RI file and rf/ folder) bb.putInt((int) pack.getStageNodes().stream()
.map(StageNode::getImage)
2
2023-12-14 15:08:35+00:00
12k
conductor-oss/conductor-community
event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/config/AMQPEventQueueProvider.java
[ { "identifier": "AMQPObservableQueue", "path": "event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java", "snippet": "public class AMQPObservableQueue implements ObservableQueue {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AMQPObservableQueue.class);\n\n private final AMQPSettings settings;\n private final AMQPRetryPattern retrySettings;\n private final String QUEUE_TYPE = \"x-queue-type\";\n private final int batchSize;\n private final boolean useExchange;\n private int pollTimeInMS;\n private AMQPConnection amqpConnection;\n\n protected LinkedBlockingQueue<Message> messages = new LinkedBlockingQueue<>();\n private volatile boolean running;\n\n public AMQPObservableQueue(\n ConnectionFactory factory,\n Address[] addresses,\n boolean useExchange,\n AMQPSettings settings,\n AMQPRetryPattern retrySettings,\n int batchSize,\n int pollTimeInMS) {\n if (factory == null) {\n throw new IllegalArgumentException(\"Connection factory is undefined\");\n }\n if (addresses == null || addresses.length == 0) {\n throw new IllegalArgumentException(\"Addresses are undefined\");\n }\n if (settings == null) {\n throw new IllegalArgumentException(\"Settings are undefined\");\n }\n if (batchSize <= 0) {\n throw new IllegalArgumentException(\"Batch size must be greater than 0\");\n }\n if (pollTimeInMS <= 0) {\n throw new IllegalArgumentException(\"Poll time must be greater than 0 ms\");\n }\n this.useExchange = useExchange;\n this.settings = settings;\n this.batchSize = batchSize;\n this.amqpConnection = AMQPConnection.getInstance(factory, addresses, retrySettings);\n this.retrySettings = retrySettings;\n this.setPollTimeInMS(pollTimeInMS);\n }\n\n @Override\n public Observable<Message> observe() {\n Observable.OnSubscribe<Message> onSubscribe = null;\n // This will enabled the messages to be processed one after the other as per the\n // observable next behavior.\n if (settings.isSequentialProcessing()) {\n LOGGER.info(\"Subscribing for the message processing on schedule basis\");\n receiveMessages();\n onSubscribe =\n subscriber -> {\n Observable<Long> interval =\n Observable.interval(pollTimeInMS, TimeUnit.MILLISECONDS);\n interval.flatMap(\n (Long x) -> {\n if (!isRunning()) {\n LOGGER.debug(\n \"Component stopped, skip listening for messages from RabbitMQ\");\n return Observable.from(Collections.emptyList());\n } else {\n List<Message> available = new LinkedList<>();\n messages.drainTo(available);\n\n if (!available.isEmpty()) {\n AtomicInteger count = new AtomicInteger(0);\n StringBuilder buffer = new StringBuilder();\n available.forEach(\n msg -> {\n buffer.append(msg.getId())\n .append(\"=\")\n .append(msg.getPayload());\n count.incrementAndGet();\n\n if (count.get()\n < available.size()) {\n buffer.append(\",\");\n }\n });\n LOGGER.info(\n String.format(\n \"Batch from %s to conductor is %s\",\n settings\n .getQueueOrExchangeName(),\n buffer.toString()));\n }\n return Observable.from(available);\n }\n })\n .subscribe(subscriber::onNext, subscriber::onError);\n };\n LOGGER.info(\"Subscribed for the message processing on schedule basis\");\n } else {\n onSubscribe =\n subscriber -> {\n LOGGER.info(\"Subscribing for the event based AMQP message processing\");\n receiveMessages(subscriber);\n LOGGER.info(\"Subscribed for the event based AMQP message processing\");\n };\n }\n return Observable.create(onSubscribe);\n }\n\n @Override\n public String getType() {\n return useExchange ? AMQPConstants.AMQP_EXCHANGE_TYPE : AMQPConstants.AMQP_QUEUE_TYPE;\n }\n\n @Override\n public String getName() {\n return settings.getEventName();\n }\n\n @Override\n public String getURI() {\n return settings.getQueueOrExchangeName();\n }\n\n public int getBatchSize() {\n return batchSize;\n }\n\n public AMQPSettings getSettings() {\n return settings;\n }\n\n public Address[] getAddresses() {\n return amqpConnection.getAddresses();\n }\n\n public List<String> ack(List<Message> messages) {\n final List<String> failedMessages = new ArrayList<>();\n for (final Message message : messages) {\n try {\n ackMsg(message);\n } catch (final Exception e) {\n LOGGER.error(\"Cannot ACK message with delivery tag {}\", message.getReceipt(), e);\n failedMessages.add(message.getReceipt());\n }\n }\n return failedMessages;\n }\n\n public void ackMsg(Message message) throws Exception {\n int retryIndex = 1;\n while (true) {\n try {\n LOGGER.info(\"ACK message with delivery tag {}\", message.getReceipt());\n Channel chn =\n amqpConnection.getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName());\n chn.basicAck(Long.parseLong(message.getReceipt()), false);\n LOGGER.info(\"Ack'ed the message with delivery tag {}\", message.getReceipt());\n break;\n } catch (final Exception e) {\n AMQPRetryPattern retry = retrySettings;\n if (retry == null) {\n LOGGER.error(\n \"Cannot ACK message with delivery tag {}\", message.getReceipt(), e);\n throw e;\n }\n try {\n retry.continueOrPropogate(e, retryIndex);\n } catch (Exception ex) {\n LOGGER.error(\n \"Retries completed. Cannot ACK message with delivery tag {}\",\n message.getReceipt(),\n e);\n throw ex;\n }\n retryIndex++;\n }\n }\n }\n\n @Override\n public void nack(List<Message> messages) {\n for (final Message message : messages) {\n int retryIndex = 1;\n while (true) {\n try {\n LOGGER.info(\"NACK message with delivery tag {}\", message.getReceipt());\n Channel chn =\n amqpConnection.getOrCreateChannel(\n ConnectionType.SUBSCRIBER,\n getSettings().getQueueOrExchangeName());\n chn.basicNack(Long.parseLong(message.getReceipt()), false, false);\n LOGGER.info(\"Nack'ed the message with delivery tag {}\", message.getReceipt());\n break;\n } catch (final Exception e) {\n AMQPRetryPattern retry = retrySettings;\n if (retry == null) {\n LOGGER.error(\n \"Cannot NACK message with delivery tag {}\",\n message.getReceipt(),\n e);\n }\n try {\n retry.continueOrPropogate(e, retryIndex);\n } catch (Exception ex) {\n LOGGER.error(\n \"Retries completed. Cannot NACK message with delivery tag {}\",\n message.getReceipt(),\n e);\n break;\n }\n retryIndex++;\n }\n }\n }\n }\n\n private static AMQP.BasicProperties buildBasicProperties(\n final Message message, final AMQPSettings settings) {\n return new AMQP.BasicProperties.Builder()\n .messageId(\n StringUtils.isEmpty(message.getId())\n ? UUID.randomUUID().toString()\n : message.getId())\n .correlationId(\n StringUtils.isEmpty(message.getReceipt())\n ? UUID.randomUUID().toString()\n : message.getReceipt())\n .contentType(settings.getContentType())\n .contentEncoding(settings.getContentEncoding())\n .deliveryMode(settings.getDeliveryMode())\n .build();\n }\n\n private void publishMessage(Message message, String exchange, String routingKey) {\n Channel chn = null;\n int retryIndex = 1;\n while (true) {\n try {\n final String payload = message.getPayload();\n chn =\n amqpConnection.getOrCreateChannel(\n ConnectionType.PUBLISHER, getSettings().getQueueOrExchangeName());\n chn.basicPublish(\n exchange,\n routingKey,\n buildBasicProperties(message, settings),\n payload.getBytes(settings.getContentEncoding()));\n LOGGER.info(String.format(\"Published message to %s: %s\", exchange, payload));\n break;\n } catch (Exception ex) {\n AMQPRetryPattern retry = retrySettings;\n if (retry == null) {\n LOGGER.error(\n \"Failed to publish message {} to {}\",\n message.getPayload(),\n exchange,\n ex);\n throw new RuntimeException(ex);\n }\n try {\n retry.continueOrPropogate(ex, retryIndex);\n } catch (Exception e) {\n LOGGER.error(\n \"Retries completed. Failed to publish message {} to {}\",\n message.getPayload(),\n exchange,\n ex);\n throw new RuntimeException(ex);\n }\n retryIndex++;\n } finally {\n if (chn != null) {\n try {\n amqpConnection.returnChannel(ConnectionType.PUBLISHER, chn);\n } catch (Exception e) {\n LOGGER.error(\n \"Failed to return the channel of {}. {}\",\n ConnectionType.PUBLISHER,\n e);\n }\n }\n }\n }\n }\n\n @Override\n public void publish(List<Message> messages) {\n try {\n final String exchange, routingKey;\n if (useExchange) {\n // Use exchange + routing key for publishing\n getOrCreateExchange(\n ConnectionType.PUBLISHER,\n settings.getQueueOrExchangeName(),\n settings.getExchangeType(),\n settings.isDurable(),\n settings.autoDelete(),\n settings.getArguments());\n exchange = settings.getQueueOrExchangeName();\n routingKey = settings.getRoutingKey();\n } else {\n // Use queue for publishing\n final AMQP.Queue.DeclareOk declareOk =\n getOrCreateQueue(\n ConnectionType.PUBLISHER,\n settings.getQueueOrExchangeName(),\n settings.isDurable(),\n settings.isExclusive(),\n settings.autoDelete(),\n settings.getArguments());\n exchange = StringUtils.EMPTY; // Empty exchange name for queue\n routingKey = declareOk.getQueue(); // Routing name is the name of queue\n }\n messages.forEach(message -> publishMessage(message, exchange, routingKey));\n } catch (final RuntimeException ex) {\n throw ex;\n } catch (final Exception ex) {\n LOGGER.error(\"Failed to publish messages: {}\", ex.getMessage(), ex);\n throw new RuntimeException(ex);\n }\n }\n\n @Override\n public void setUnackTimeout(Message message, long unackTimeout) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public long size() {\n Channel chn = null;\n try {\n chn =\n amqpConnection.getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName());\n return chn.messageCount(settings.getQueueOrExchangeName());\n } catch (final Exception e) {\n throw new RuntimeException(e);\n } finally {\n if (chn != null) {\n try {\n amqpConnection.returnChannel(ConnectionType.SUBSCRIBER, chn);\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n }\n }\n\n @Override\n public void close() {\n amqpConnection.close();\n }\n\n @Override\n public void start() {\n LOGGER.info(\n \"Started listening to {}:{}\",\n getClass().getSimpleName(),\n settings.getQueueOrExchangeName());\n running = true;\n }\n\n @Override\n public void stop() {\n LOGGER.info(\n \"Stopped listening to {}:{}\",\n getClass().getSimpleName(),\n settings.getQueueOrExchangeName());\n running = false;\n }\n\n @Override\n public boolean isRunning() {\n return running;\n }\n\n public static class Builder {\n\n private final Address[] addresses;\n private final int batchSize;\n private final int pollTimeInMS;\n private final ConnectionFactory factory;\n private final AMQPEventQueueProperties properties;\n\n public Builder(AMQPEventQueueProperties properties) {\n this.properties = properties;\n this.addresses = buildAddressesFromHosts();\n this.factory = buildConnectionFactory();\n // messages polling settings\n this.batchSize = properties.getBatchSize();\n this.pollTimeInMS = (int) properties.getPollTimeDuration().toMillis();\n }\n\n private Address[] buildAddressesFromHosts() {\n // Read hosts from config\n final String hosts = properties.getHosts();\n if (StringUtils.isEmpty(hosts)) {\n throw new IllegalArgumentException(\"Hosts are undefined\");\n }\n return Address.parseAddresses(hosts);\n }\n\n private ConnectionFactory buildConnectionFactory() {\n final ConnectionFactory factory = new ConnectionFactory();\n // Get rabbitmq username from config\n final String username = properties.getUsername();\n if (StringUtils.isEmpty(username)) {\n throw new IllegalArgumentException(\"Username is null or empty\");\n } else {\n factory.setUsername(username);\n }\n // Get rabbitmq password from config\n final String password = properties.getPassword();\n if (StringUtils.isEmpty(password)) {\n throw new IllegalArgumentException(\"Password is null or empty\");\n } else {\n factory.setPassword(password);\n }\n // Get vHost from config\n final String virtualHost = properties.getVirtualHost();\n ;\n if (StringUtils.isEmpty(virtualHost)) {\n throw new IllegalArgumentException(\"Virtual host is null or empty\");\n } else {\n factory.setVirtualHost(virtualHost);\n }\n // Get server port from config\n final int port = properties.getPort();\n if (port <= 0) {\n throw new IllegalArgumentException(\"Port must be greater than 0\");\n } else {\n factory.setPort(port);\n }\n final boolean useNio = properties.isUseNio();\n if (useNio) {\n factory.useNio();\n }\n final boolean useSslProtocol = properties.isUseSslProtocol();\n if (useSslProtocol) {\n try {\n factory.useSslProtocol();\n } catch (NoSuchAlgorithmException | KeyManagementException e) {\n throw new IllegalArgumentException(\"Invalid sslProtocol \", e);\n }\n }\n factory.setConnectionTimeout(properties.getConnectionTimeoutInMilliSecs());\n factory.setRequestedHeartbeat(properties.getRequestHeartbeatTimeoutInSecs());\n factory.setNetworkRecoveryInterval(properties.getNetworkRecoveryIntervalInMilliSecs());\n factory.setHandshakeTimeout(properties.getHandshakeTimeoutInMilliSecs());\n factory.setAutomaticRecoveryEnabled(true);\n factory.setTopologyRecoveryEnabled(true);\n factory.setRequestedChannelMax(properties.getMaxChannelCount());\n return factory;\n }\n\n public AMQPObservableQueue build(final boolean useExchange, final String queueURI) {\n final AMQPSettings settings = new AMQPSettings(properties).fromURI(queueURI);\n final AMQPRetryPattern retrySettings =\n new AMQPRetryPattern(\n properties.getLimit(), properties.getDuration(), properties.getType());\n return new AMQPObservableQueue(\n factory,\n addresses,\n useExchange,\n settings,\n retrySettings,\n batchSize,\n pollTimeInMS);\n }\n }\n\n private AMQP.Exchange.DeclareOk getOrCreateExchange(ConnectionType connectionType)\n throws Exception {\n return getOrCreateExchange(\n connectionType,\n settings.getQueueOrExchangeName(),\n settings.getExchangeType(),\n settings.isDurable(),\n settings.autoDelete(),\n settings.getArguments());\n }\n\n private AMQP.Exchange.DeclareOk getOrCreateExchange(\n ConnectionType connectionType,\n String name,\n final String type,\n final boolean isDurable,\n final boolean autoDelete,\n final Map<String, Object> arguments)\n throws Exception {\n if (StringUtils.isEmpty(name)) {\n throw new RuntimeException(\"Exchange name is undefined\");\n }\n if (StringUtils.isEmpty(type)) {\n throw new RuntimeException(\"Exchange type is undefined\");\n }\n Channel chn = null;\n try {\n LOGGER.debug(\"Creating exchange {} of type {}\", name, type);\n chn =\n amqpConnection.getOrCreateChannel(\n connectionType, getSettings().getQueueOrExchangeName());\n return chn.exchangeDeclare(name, type, isDurable, autoDelete, arguments);\n } catch (final Exception e) {\n LOGGER.warn(\"Failed to create exchange {} of type {}\", name, type, e);\n throw e;\n } finally {\n if (chn != null) {\n try {\n amqpConnection.returnChannel(connectionType, chn);\n } catch (Exception e) {\n LOGGER.error(\"Failed to return the channel of {}. {}\", connectionType, e);\n }\n }\n }\n }\n\n private AMQP.Queue.DeclareOk getOrCreateQueue(ConnectionType connectionType) throws Exception {\n return getOrCreateQueue(\n connectionType,\n settings.getQueueOrExchangeName(),\n settings.isDurable(),\n settings.isExclusive(),\n settings.autoDelete(),\n settings.getArguments());\n }\n\n private AMQP.Queue.DeclareOk getOrCreateQueue(\n ConnectionType connectionType,\n final String name,\n final boolean isDurable,\n final boolean isExclusive,\n final boolean autoDelete,\n final Map<String, Object> arguments)\n throws Exception {\n if (StringUtils.isEmpty(name)) {\n throw new RuntimeException(\"Queue name is undefined\");\n }\n arguments.put(QUEUE_TYPE, settings.getQueueType());\n Channel chn = null;\n try {\n LOGGER.debug(\"Creating queue {}\", name);\n chn =\n amqpConnection.getOrCreateChannel(\n connectionType, getSettings().getQueueOrExchangeName());\n return chn.queueDeclare(name, isDurable, isExclusive, autoDelete, arguments);\n } catch (final Exception e) {\n LOGGER.warn(\"Failed to create queue {}\", name, e);\n throw e;\n } finally {\n if (chn != null) {\n try {\n amqpConnection.returnChannel(connectionType, chn);\n } catch (Exception e) {\n LOGGER.error(\"Failed to return the channel of {}. {}\", connectionType, e);\n }\n }\n }\n }\n\n private static Message asMessage(AMQPSettings settings, GetResponse response) throws Exception {\n if (response == null) {\n return null;\n }\n final Message message = new Message();\n message.setId(response.getProps().getMessageId());\n message.setPayload(new String(response.getBody(), settings.getContentEncoding()));\n message.setReceipt(String.valueOf(response.getEnvelope().getDeliveryTag()));\n return message;\n }\n\n private void receiveMessagesFromQueue(String queueName) throws Exception {\n LOGGER.debug(\"Accessing channel for queue {}\", queueName);\n\n Consumer consumer =\n new DefaultConsumer(\n amqpConnection.getOrCreateChannel(\n ConnectionType.SUBSCRIBER,\n getSettings().getQueueOrExchangeName())) {\n\n @Override\n public void handleDelivery(\n final String consumerTag,\n final Envelope envelope,\n final AMQP.BasicProperties properties,\n final byte[] body)\n throws IOException {\n try {\n Message message =\n asMessage(\n settings,\n new GetResponse(\n envelope, properties, body, Integer.MAX_VALUE));\n if (message != null) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\n \"Got message with ID {} and receipt {}\",\n message.getId(),\n message.getReceipt());\n }\n messages.add(message);\n LOGGER.info(\"receiveMessagesFromQueue- End method {}\", messages);\n }\n } catch (InterruptedException e) {\n LOGGER.error(\n \"Issue in handling the mesages for the subscriber with consumer tag {}. {}\",\n consumerTag,\n e);\n Thread.currentThread().interrupt();\n } catch (Exception e) {\n LOGGER.error(\n \"Issue in handling the mesages for the subscriber with consumer tag {}. {}\",\n consumerTag,\n e);\n }\n }\n\n public void handleCancel(String consumerTag) throws IOException {\n LOGGER.error(\n \"Recieved a consumer cancel notification for subscriber {}\",\n consumerTag);\n }\n };\n\n amqpConnection\n .getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName())\n .basicConsume(queueName, false, consumer);\n Monitors.recordEventQueueMessagesProcessed(getType(), queueName, messages.size());\n }\n\n private void receiveMessagesFromQueue(String queueName, Subscriber<? super Message> subscriber)\n throws Exception {\n LOGGER.debug(\"Accessing channel for queue {}\", queueName);\n\n Consumer consumer =\n new DefaultConsumer(\n amqpConnection.getOrCreateChannel(\n ConnectionType.SUBSCRIBER,\n getSettings().getQueueOrExchangeName())) {\n\n @Override\n public void handleDelivery(\n final String consumerTag,\n final Envelope envelope,\n final AMQP.BasicProperties properties,\n final byte[] body)\n throws IOException {\n try {\n Message message =\n asMessage(\n settings,\n new GetResponse(\n envelope, properties, body, Integer.MAX_VALUE));\n if (message == null) {\n return;\n }\n LOGGER.info(\n \"Got message with ID {} and receipt {}\",\n message.getId(),\n message.getReceipt());\n LOGGER.debug(\"Message content {}\", message);\n // Not using thread-pool here as the number of concurrent threads are\n // controlled\n // by the number of messages delivery using pre-fetch count in RabbitMQ\n Thread newThread =\n new Thread(\n () -> {\n LOGGER.info(\n \"Spawning a new thread for message with ID {}\",\n message.getId());\n subscriber.onNext(message);\n });\n newThread.start();\n } catch (InterruptedException e) {\n LOGGER.error(\n \"Issue in handling the mesages for the subscriber with consumer tag {}. {}\",\n consumerTag,\n e);\n Thread.currentThread().interrupt();\n } catch (Exception e) {\n LOGGER.error(\n \"Issue in handling the mesages for the subscriber with consumer tag {}. {}\",\n consumerTag,\n e);\n }\n }\n\n public void handleCancel(String consumerTag) throws IOException {\n LOGGER.error(\n \"Recieved a consumer cancel notification for subscriber {}\",\n consumerTag);\n }\n };\n amqpConnection\n .getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName())\n .basicConsume(queueName, false, consumer);\n }\n\n protected void receiveMessages() {\n try {\n amqpConnection\n .getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName())\n .basicQos(batchSize);\n String queueName;\n if (useExchange) {\n // Consume messages from an exchange\n getOrCreateExchange(ConnectionType.SUBSCRIBER);\n /*\n * Create queue if not present based on the settings provided in the queue URI\n * or configuration properties. Sample URI format:\n * amqp_exchange:myExchange?bindQueueName=myQueue&exchangeType=topic&routingKey=myRoutingKey&exclusive\n * =false&autoDelete=false&durable=true Default settings if not provided in the\n * queue URI or properties: isDurable: true, autoDelete: false, isExclusive:\n * false The same settings are currently used during creation of exchange as\n * well as queue. TODO: This can be enhanced further to get the settings\n * separately for exchange and queue from the URI\n */\n final AMQP.Queue.DeclareOk declareOk =\n getOrCreateQueue(\n ConnectionType.SUBSCRIBER,\n settings.getExchangeBoundQueueName(),\n settings.isDurable(),\n settings.isExclusive(),\n settings.autoDelete(),\n Maps.newHashMap());\n // Bind the declared queue to exchange\n queueName = declareOk.getQueue();\n amqpConnection\n .getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName())\n .queueBind(\n queueName,\n settings.getQueueOrExchangeName(),\n settings.getRoutingKey());\n } else {\n // Consume messages from a queue\n queueName = getOrCreateQueue(ConnectionType.SUBSCRIBER).getQueue();\n }\n // Consume messages\n LOGGER.info(\"Consuming from queue {}\", queueName);\n receiveMessagesFromQueue(queueName);\n } catch (Exception exception) {\n LOGGER.error(\"Exception while getting messages from RabbitMQ\", exception);\n Monitors.recordObservableQMessageReceivedErrors(getType());\n }\n }\n\n protected void receiveMessages(Subscriber<? super Message> subscriber) {\n try {\n amqpConnection\n .getOrCreateChannel(\n ConnectionType.SUBSCRIBER, getSettings().getQueueOrExchangeName())\n .basicQos(batchSize);\n String queueName;\n if (useExchange) {\n // Consume messages from an exchange\n getOrCreateExchange(ConnectionType.SUBSCRIBER);\n /*\n * Create queue if not present based on the settings provided in the queue URI\n * or configuration properties. Sample URI format:\n * amqp_exchange:myExchange?bindQueueName=myQueue&exchangeType=topic&routingKey=myRoutingKey&exclusive\n * =false&autoDelete=false&durable=true Default settings if not provided in the\n * queue URI or properties: isDurable: true, autoDelete: false, isExclusive:\n * false The same settings are currently used during creation of exchange as\n * well as queue. TODO: This can be enhanced further to get the settings\n * separately for exchange and queue from the URI\n */\n final AMQP.Queue.DeclareOk declareOk =\n getOrCreateQueue(\n ConnectionType.SUBSCRIBER,\n settings.getExchangeBoundQueueName(),\n settings.isDurable(),\n settings.isExclusive(),\n settings.autoDelete(),\n Maps.newHashMap());\n // Bind the declared queue to exchange\n queueName = declareOk.getQueue();\n amqpConnection\n .getOrCreateChannel(\n ConnectionType.SUBSCRIBER, settings.getQueueOrExchangeName())\n .queueBind(\n queueName,\n settings.getQueueOrExchangeName(),\n settings.getRoutingKey());\n } else {\n // Consume messages from a queue\n queueName = getOrCreateQueue(ConnectionType.SUBSCRIBER).getQueue();\n }\n // Consume messages\n LOGGER.info(\"Consuming from queue {}\", queueName);\n receiveMessagesFromQueue(queueName, subscriber);\n } catch (Exception exception) {\n LOGGER.error(\"Exception while getting messages from RabbitMQ\", exception);\n Monitors.recordObservableQMessageReceivedErrors(getType());\n }\n }\n\n public int getPollTimeInMS() {\n return pollTimeInMS;\n }\n\n public void setPollTimeInMS(int pollTimeInMS) {\n this.pollTimeInMS = pollTimeInMS;\n }\n}" }, { "identifier": "Builder", "path": "event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java", "snippet": "public static class Builder {\n\n private final Address[] addresses;\n private final int batchSize;\n private final int pollTimeInMS;\n private final ConnectionFactory factory;\n private final AMQPEventQueueProperties properties;\n\n public Builder(AMQPEventQueueProperties properties) {\n this.properties = properties;\n this.addresses = buildAddressesFromHosts();\n this.factory = buildConnectionFactory();\n // messages polling settings\n this.batchSize = properties.getBatchSize();\n this.pollTimeInMS = (int) properties.getPollTimeDuration().toMillis();\n }\n\n private Address[] buildAddressesFromHosts() {\n // Read hosts from config\n final String hosts = properties.getHosts();\n if (StringUtils.isEmpty(hosts)) {\n throw new IllegalArgumentException(\"Hosts are undefined\");\n }\n return Address.parseAddresses(hosts);\n }\n\n private ConnectionFactory buildConnectionFactory() {\n final ConnectionFactory factory = new ConnectionFactory();\n // Get rabbitmq username from config\n final String username = properties.getUsername();\n if (StringUtils.isEmpty(username)) {\n throw new IllegalArgumentException(\"Username is null or empty\");\n } else {\n factory.setUsername(username);\n }\n // Get rabbitmq password from config\n final String password = properties.getPassword();\n if (StringUtils.isEmpty(password)) {\n throw new IllegalArgumentException(\"Password is null or empty\");\n } else {\n factory.setPassword(password);\n }\n // Get vHost from config\n final String virtualHost = properties.getVirtualHost();\n ;\n if (StringUtils.isEmpty(virtualHost)) {\n throw new IllegalArgumentException(\"Virtual host is null or empty\");\n } else {\n factory.setVirtualHost(virtualHost);\n }\n // Get server port from config\n final int port = properties.getPort();\n if (port <= 0) {\n throw new IllegalArgumentException(\"Port must be greater than 0\");\n } else {\n factory.setPort(port);\n }\n final boolean useNio = properties.isUseNio();\n if (useNio) {\n factory.useNio();\n }\n final boolean useSslProtocol = properties.isUseSslProtocol();\n if (useSslProtocol) {\n try {\n factory.useSslProtocol();\n } catch (NoSuchAlgorithmException | KeyManagementException e) {\n throw new IllegalArgumentException(\"Invalid sslProtocol \", e);\n }\n }\n factory.setConnectionTimeout(properties.getConnectionTimeoutInMilliSecs());\n factory.setRequestedHeartbeat(properties.getRequestHeartbeatTimeoutInSecs());\n factory.setNetworkRecoveryInterval(properties.getNetworkRecoveryIntervalInMilliSecs());\n factory.setHandshakeTimeout(properties.getHandshakeTimeoutInMilliSecs());\n factory.setAutomaticRecoveryEnabled(true);\n factory.setTopologyRecoveryEnabled(true);\n factory.setRequestedChannelMax(properties.getMaxChannelCount());\n return factory;\n }\n\n public AMQPObservableQueue build(final boolean useExchange, final String queueURI) {\n final AMQPSettings settings = new AMQPSettings(properties).fromURI(queueURI);\n final AMQPRetryPattern retrySettings =\n new AMQPRetryPattern(\n properties.getLimit(), properties.getDuration(), properties.getType());\n return new AMQPObservableQueue(\n factory,\n addresses,\n useExchange,\n settings,\n retrySettings,\n batchSize,\n pollTimeInMS);\n }\n}" } ]
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; import com.netflix.conductor.contribs.queue.amqp.AMQPObservableQueue; import com.netflix.conductor.contribs.queue.amqp.AMQPObservableQueue.Builder; import com.netflix.conductor.core.events.EventQueueProvider; import com.netflix.conductor.core.events.queue.ObservableQueue;
7,679
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.queue.amqp.config; /** * @author Ritu Parathody */ public class AMQPEventQueueProvider implements EventQueueProvider { private static final Logger LOGGER = LoggerFactory.getLogger(AMQPEventQueueProvider.class); protected Map<String, AMQPObservableQueue> queues = new ConcurrentHashMap<>(); private final boolean useExchange; private final AMQPEventQueueProperties properties; private final String queueType; public AMQPEventQueueProvider( AMQPEventQueueProperties properties, String queueType, boolean useExchange) { this.properties = properties; this.queueType = queueType; this.useExchange = useExchange; } @Override public String getQueueType() { return queueType; } @Override @NonNull public ObservableQueue getQueue(String queueURI) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Retrieve queue with URI {}", queueURI); } // Build the queue with the inner Builder class of AMQPObservableQueue
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.queue.amqp.config; /** * @author Ritu Parathody */ public class AMQPEventQueueProvider implements EventQueueProvider { private static final Logger LOGGER = LoggerFactory.getLogger(AMQPEventQueueProvider.class); protected Map<String, AMQPObservableQueue> queues = new ConcurrentHashMap<>(); private final boolean useExchange; private final AMQPEventQueueProperties properties; private final String queueType; public AMQPEventQueueProvider( AMQPEventQueueProperties properties, String queueType, boolean useExchange) { this.properties = properties; this.queueType = queueType; this.useExchange = useExchange; } @Override public String getQueueType() { return queueType; } @Override @NonNull public ObservableQueue getQueue(String queueURI) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Retrieve queue with URI {}", queueURI); } // Build the queue with the inner Builder class of AMQPObservableQueue
return queues.computeIfAbsent(queueURI, q -> new Builder(properties).build(useExchange, q));
1
2023-12-08 06:06:20+00:00
12k
blueokanna/ReverseCoin
src/main/java/top/pulselink/java/reversecoin/ReverseCoin.java
[ { "identifier": "PeerMessages", "path": "src/main/java/BlockModel/PeerMessages.java", "snippet": "public class PeerMessages implements Serializable, ReverseCoinBlockMessagesInterface {\n\n private static final long serialVersionUID = 1145141919810L;\n\n private CommandCode CommandCode;\n private String BlockMessage;\n\n public PeerMessages() {\n }\n\n public PeerMessages(CommandCode code) {\n this.CommandCode = code;\n }\n\n public PeerMessages(CommandCode code, String message) {\n this.CommandCode = code;\n this.BlockMessage = message;\n }\n\n @Override\n public CommandCode getCommandCode() {\n return CommandCode;\n }\n\n @Override\n public void setCommandCode(CommandCode CommandCode) {\n this.CommandCode = CommandCode;\n }\n\n @Override\n public String getMessage() {\n return BlockMessage;\n }\n\n @Override\n public void setMessage(String message) {\n this.BlockMessage = message;\n }\n\n @Override\n public String toJsonString(String data) {\n return new GsonBuilder().create().toJson(data);\n }\n\n}" }, { "identifier": "ReverseCoinBlock", "path": "src/main/java/BlockModel/ReverseCoinBlock.java", "snippet": "public class ReverseCoinBlock implements Serializable, ReverseCoinBlockInterface {\n\n private static final long serialVersionUID = 1145141919810L;\n private byte version;\n private int index;\n private String PreviousHash;\n private CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData;\n private String TransactionHash;\n private long TimeStamp;\n private long nonce;\n private int difficulty;\n private String thisBlockHash;\n\n @Override\n public byte getVersion() {\n return version;\n }\n\n @Override\n public void setVersion(byte version) {\n this.version = version;\n }\n\n @Override\n public int getIndex() {\n return index;\n }\n\n @Override\n public void setIndex(int index) {\n this.index = index;\n }\n\n @Override\n public String getPreviousHash() {\n return PreviousHash;\n }\n\n @Override\n public void setPreviousHash(String PreviousHash) {\n this.PreviousHash = PreviousHash;\n }\n\n @Override\n public String getTransactionHash() {\n return TransactionHash;\n }\n\n @Override\n public void setTransactionHash(String TransactionHash) {\n this.TransactionHash = TransactionHash;\n } \n\n @Override\n public CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsData() {\n return TransactionsData;\n }\n\n @Override\n public void setTransactionsData(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData) {\n this.TransactionsData = TransactionsData;\n }\n\n @Override\n public long getTimeStamp() {\n return TimeStamp;\n }\n\n @Override\n public void setTimeStamp(long TimeStamp) {\n this.TimeStamp = TimeStamp;\n }\n\n @Override\n public int getDifficulty() {\n return difficulty;\n }\n\n @Override\n public void setDifficulty(int difficulty) {\n this.difficulty = difficulty;\n }\n\n @Override\n public long getNonce() {\n return nonce;\n }\n\n @Override\n public void setNonce(long nonce) {\n this.nonce = nonce;\n }\n\n @Override\n public String getThisBlockHash() {\n return thisBlockHash;\n }\n\n @Override\n public void setThisBlockHash(String thisBlockHash) {\n this.thisBlockHash = thisBlockHash;\n }\n\n @Override\n public String toBlockJsonString(ReverseCoinBlock blocks) {\n return new GsonBuilder().create().toJson(blocks);\n }\n\n}" }, { "identifier": "P2PClient", "path": "src/main/java/ClientSeverMach/P2PClient.java", "snippet": "public class P2PClient {\n\n public void connectToPeer(String address, ReverseCoinChainConfigInterface config, NewReverseCoinBlockInterface newblock, ReverseCoinBlockMessagesInterface peerMessages,P2PNetwork network) {\n try {\n WebSocketClient socketClient = new WebSocketClient(new URI(address)) {\n @Override\n public void onOpen(ServerHandshake serverHandshake) {\n network.PostRequest(this, network.FormatBlockMessages());\n network.getSockets(config).add(this);\n }\n\n @Override\n public void onMessage(String message) {\n network.handleMessage(this, newblock, peerMessages, network.getSockets(config), message, config);\n }\n\n @Override\n public void onClose(int i, String msg, boolean b) {\n network.getSockets(config).remove(this);\n System.out.println(\"connection closed\");\n }\n\n @Override\n public void onError(Exception e) {\n network.getSockets(config).remove(this);\n System.out.println(\"connection failed\");\n }\n };\n socketClient.connect();\n } catch (URISyntaxException e) {\n System.out.println(\"P2P connect is error:\" + e.getMessage());\n }\n }\n\n}" }, { "identifier": "P2PServer", "path": "src/main/java/ClientSeverMach/P2PServer.java", "snippet": "public class P2PServer {\n\n\n public void initP2PServer(int port, ReverseCoinChainConfigInterface config, NewReverseCoinBlockInterface newblock, ReverseCoinBlockMessagesInterface peerMessages,P2PNetwork network) {\n WebSocketServer socketServer = new WebSocketServer(new InetSocketAddress(port)) {\n\n /**\n * 连接建立后触发\n */\n @Override\n public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {\n network.getSockets(config).add(webSocket);\n }\n\n /**\n * 连接关闭后触发\n */\n @Override\n public void onClose(WebSocket webSocket, int i, String s, boolean b) {\n network.getSockets(config).remove(webSocket);\n System.out.println(\"connection closed to address:\" + webSocket.getRemoteSocketAddress());\n }\n\n /**\n * 接收到客户端消息时触发\n */\n @Override\n public void onMessage(WebSocket webSocket, String message) {\n //作为服务端,业务逻辑处理\n network.handleMessage(webSocket, newblock, peerMessages, network.getSockets(config), message, config);\n }\n\n /**\n * 发生错误时触发\n */\n @Override\n public void onError(WebSocket webSocket, Exception e) {\n network.getSockets(config).remove(webSocket);\n System.out.println(\"connection failed to address:\" + webSocket.getRemoteSocketAddress());\n }\n\n @Override\n public void onStart() {\n\n }\n\n };\n socketServer.start();\n System.out.println(\"listening websocket p2p port on: \" + port);\n }\n\n}" }, { "identifier": "BlockChainConfig", "path": "src/main/java/ReverseCoinBlockChainGeneration/BlockChainConfig.java", "snippet": "public class BlockChainConfig implements ReverseCoinChainConfigInterface {\n\n private volatile CopyOnWriteArrayList<ReverseCoinBlock> BlockList = new CopyOnWriteArrayList<>();\n private volatile CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList = new CopyOnWriteArrayList<>();\n private volatile CopyOnWriteArrayList<WebSocket> socketsList = new CopyOnWriteArrayList<>();\n\n private int difficulty;\n private int ports;\n private String addressPort;\n\n @Override\n public int getDifficulty() {\n return difficulty;\n }\n\n @Override\n public void setDifficulty(int difficulty) {\n this.difficulty = difficulty;\n }\n\n @Override\n public int getPorts() {\n return ports;\n }\n\n @Override\n public void setPorts(int ports) {\n this.ports = ports;\n }\n\n @Override\n public String getAddressPort() {\n return addressPort;\n }\n\n @Override\n public void setAddressPort(String addressPort) {\n this.addressPort = addressPort;\n }\n\n @Override\n public CopyOnWriteArrayList<ReverseCoinBlock> getBlockList() {\n return BlockList;\n }\n\n @Override\n public void setBlockList(CopyOnWriteArrayList<ReverseCoinBlock> BlockList) {\n this.BlockList = BlockList;\n }\n\n @Override\n public CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsList() {\n return TransactionsList;\n }\n\n @Override\n public void setTransactionsList(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList) {\n this.TransactionsList = TransactionsList;\n }\n\n @Override\n public CopyOnWriteArrayList<WebSocket> getSocketsList() {\n return socketsList;\n }\n\n @Override\n public void setSocketsList(CopyOnWriteArrayList<WebSocket> socketsList) {\n this.socketsList = socketsList;\n }\n\n @Override\n public ReverseCoinBlock getLatestBlock() {\n return !BlockList.isEmpty() ? BlockList.get(BlockList.size() - 1) : null;\n }\n\n @Override\n public String SHA3with256Hash(String input) {\n SHA3Digest digest = new SHA3Digest(256);\n digest.update(input.getBytes(), 0, input.getBytes().length);\n byte[] result = new byte[digest.getDigestSize()];\n digest.doFinal(result, 0);\n return Hex.toHexString(result);\n }\n\n}" }, { "identifier": "NewBlockCreation", "path": "src/main/java/ReverseCoinBlockChainGeneration/NewBlockCreation.java", "snippet": "public class NewBlockCreation implements NewReverseCoinBlockInterface {\n\n private final String previousHash = \"0000000000000000000000000000000000000000000000000000000000000000\";\n private volatile long timestamp = new TimeStampGenerator().TimeToSync();\n private volatile ReverseCoinBlock ReverseBlockHeader = new ReverseCoinBlock();\n private volatile ExecutorService executor;\n private volatile long nonce = 0;\n\n private CopyOnWriteArrayList<ReverseCoinTransaction> GenesisBlockTransData() {\n SecureRandom secureRandom = new SecureRandom();\n int numberGenerations = Math.abs(secureRandom.nextInt());\n while (numberGenerations > 100) {\n numberGenerations /= 2;\n }\n\n String Sender = \"ReverseCoin\";\n String Receiver = \"BlockChain\";\n double Amount = 114514;\n double gasFee = 1919.810;\n\n String data = Sender + Receiver + Amount + gasFee + timestamp;\n\n byte[] Signature = new PerformRingSign().performRingSign(data, numberGenerations, numberGenerations / 2);\n try {\n ReverseCoinTransaction transData = new ReverseCoinTransaction(Sender, Receiver, Amount, gasFee, Base64.getEncoder().encodeToString(Signature));\n CopyOnWriteArrayList<ReverseCoinTransaction> transList = new CopyOnWriteArrayList<>();\n transList.add(transData);\n return transList;\n } catch (Exception ex) {\n ex.getMessage();\n }\n return null;\n }\n\n public ReverseCoinBlock createGenesisBlock(ReverseCoinBlockInterface block, ReverseCoinChainConfigInterface config) throws Exception {\n System.out.println(\"Mining Genesis Block Now......\");\n int index = 1;\n\n CopyOnWriteArrayList<CompletableFuture<Void>> futures = new CopyOnWriteArrayList<>();\n executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() / 2);\n\n for (int i = 0; i < index; i++) {\n CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {\n\n while (true) {\n String text = previousHash + GenesisBlockTransData() + nonce;\n String hash = config.SHA3with256Hash(config.SHA3with256Hash(text));\n\n if (hash != null && hash.startsWith(new String(new char[config.getDifficulty()]).replace('\\0', '0'))) {\n ReverseBlockHeader.setVersion((byte) 0x01);\n ReverseBlockHeader.setIndex(index);\n ReverseBlockHeader.setPreviousHash(previousHash);\n ReverseBlockHeader.setTransactionsData(GenesisBlockTransData());\n ReverseBlockHeader.setTimeStamp(timestamp);\n ReverseBlockHeader.setDifficulty(config.getDifficulty());\n ReverseBlockHeader.setNonce(nonce);\n ReverseBlockHeader.setThisBlockHash(hash);\n return;\n\n }\n nonce++;\n }\n }, executor);\n futures.add(future);\n }\n\n CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new));\n allOf.join();\n\n executor.shutdown();\n\n config.getTransactionsList().addAll(ReverseBlockHeader.getTransactionsData());\n config.getBlockList().add(ReverseBlockHeader);\n return ReverseBlockHeader;\n }\n\n @Override\n public ReverseCoinBlock generatedNewBlock(String preHash, CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData, String TransactionHash, long nonce, String setBlockHash, ReverseCoinChainConfigInterface config) {\n ReverseCoinBlock petablock = new ReverseCoinBlock();\n petablock.setVersion((byte) 0x01);\n petablock.setIndex(config.getBlockList().size() + 1);\n petablock.setPreviousHash(preHash);\n petablock.setTransactionHash(TransactionHash);\n petablock.setTransactionsData(TransactionsData);\n petablock.setTimeStamp(timestamp);\n petablock.setDifficulty(config.getDifficulty());\n petablock.setNonce(nonce);\n petablock.setThisBlockHash(setBlockHash);\n if (addNewBlocks(petablock, config)) {\n return petablock;\n }\n return null;\n }\n\n @Override\n public boolean addNewBlocks(ReverseCoinBlock newBlock, ReverseCoinChainConfigInterface config) {\n if (checkPetaBlock(newBlock, config.getLatestBlock(), config)) {\n config.getTransactionsList().addAll(newBlock.getTransactionsData());\n config.getBlockList().add(newBlock);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public boolean checkPetaBlock(ReverseCoinBlock newReverseBlock, ReverseCoinBlock previousBlock, ReverseCoinChainConfigInterface config) {\n if (!previousBlock.getThisBlockHash().equals(newReverseBlock.getPreviousHash())) {\n System.out.println(\"Previous PetaBlock Hash is not matched\");\n return false;\n } else {\n String data = newReverseBlock.getPreviousHash() + newReverseBlock.getTransactionHash() + newReverseBlock.getNonce();\n String calHash = config.SHA3with256Hash(config.SHA3with256Hash(data));\n if (!calHash.equals(newReverseBlock.getThisBlockHash())) {\n System.out.println(\"Index is: \" + config.getBlockList().size());\n System.out.println(\"New PetaBlock verification failed, Hash value verification error!\");\n return false;\n }\n }\n System.out.println(\"ReverseCoin verification successful!\");\n return true;\n }\n\n @Override\n public void updatePetaChain(CopyOnWriteArrayList<ReverseCoinBlock> newChain, ReverseCoinChainConfigInterface config) {\n try {\n CopyOnWriteArrayList<ReverseCoinBlock> oldBlockChain = config.getBlockList();\n CopyOnWriteArrayList<ReverseCoinTransaction> transactionOnChain = config.getTransactionsList();\n\n if (isUpdateBlockChain(newChain, config) && newChain.size() > oldBlockChain.size()) {\n oldBlockChain = newChain;\n transactionOnChain.clear();\n\n oldBlockChain.forEach(block -> {\n transactionOnChain.addAll(block.getTransactionsData());\n });\n\n config.setBlockList(oldBlockChain);\n config.setTransactionsList(transactionOnChain);\n System.out.println(\"Updated ReverseCoin-BlockChain: \" + new GsonBuilder().setPrettyPrinting().create().toJson(config.getBlockList()));\n } else {\n System.out.println(\"The ReverseCoin-BlockChain is Invalid\");\n }\n } catch (Exception ex) {\n System.out.println(\"Error updating ReverseCoin-BlockChain: \" + ex.getMessage());\n }\n }\n\n @Override\n public boolean isUpdateBlockChain(CopyOnWriteArrayList<ReverseCoinBlock> petachain, ReverseCoinChainConfigInterface config) {\n int count = 1;\n ReverseCoinBlock previousBlock = petachain.get(0);\n\n while (count < petachain.size()) {\n ReverseCoinBlock petablock = petachain.get(count);\n if (!checkPetaBlock(petablock, previousBlock, config)) {\n return false;\n }\n previousBlock = petablock;\n count++;\n }\n return true;\n }\n\n @Override\n public boolean isSortedByIndex(ReverseCoinChainConfigInterface config) {\n CopyOnWriteArrayList<ReverseCoinBlock> block = config.getBlockList();\n for (int i = 1; i < block.size(); i++) {\n if (block.get(i - 1).getIndex() > block.get(i).getIndex()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean checkBlocksHash(String hash, String target, ReverseCoinChainConfigInterface config) {\n return hash.substring(0, config.getDifficulty()).equals(target);\n }\n\n}" }, { "identifier": "P2PNetwork", "path": "src/main/java/ReverseCoinChainNetwork/P2PNetwork.java", "snippet": "public class P2PNetwork {\n\n private static final Gson SimpleGson = new GsonBuilder().create();\n private static final Gson PrettyGson = new GsonBuilder().setPrettyPrinting().create();\n private static final Map<String, String> PetaJsonCache = new HashMap<>();\n\n public void handleMessage(WebSocket websocket, NewReverseCoinBlockInterface newblock, ReverseCoinBlockMessagesInterface peerMessages, CopyOnWriteArrayList<WebSocket> ListSocket, String receiveMessage, ReverseCoinChainConfigInterface config) {\n\n try {\n PeerMessages messages = SimpleGson.fromJson(receiveMessage, new TypeToken<PeerMessages>() {\n }.getType());\n\n CommandCode commandCode = messages.getCommandCode();\n\n if (commandCode == null) {\n return;\n }\n switch (commandCode) {\n case CheckLastestBlock ->\n PostRequest(websocket, responseNewBlockMessage(config));\n case CheckWholeChain ->\n PostRequest(websocket, responseBlockChainMessage(config));\n case ReturnLastestBlock ->\n handleReceiveBlockResponse(messages.getMessage(), newblock, ListSocket, config);\n case ReturnLastestBlockChain ->\n handleBlockChainResponse(messages.getMessage(), newblock, ListSocket, config);\n }\n } catch (JsonSyntaxException ex) {\n ex.getMessage();\n }\n }\n\n //同步区块\n public synchronized void handleReceiveBlockResponse(String blockData, NewReverseCoinBlockInterface newblock, CopyOnWriteArrayList<WebSocket> sockets, ReverseCoinChainConfigInterface config) {\n\n ReverseCoinBlock newBlockReceived = SimpleGson.fromJson(blockData, ReverseCoinBlock.class);\n ReverseCoinBlock BlockonChain = config.getLatestBlock();\n\n if (newBlockReceived != null) {\n if (BlockonChain != null) {\n if (newBlockReceived.getIndex() > BlockonChain.getIndex() + 1) {\n BroadCastBlockMessage(FormatBlockChainMessage(), config);\n } else if (newBlockReceived.getIndex() > BlockonChain.getIndex()\n && BlockonChain.getThisBlockHash().equals(newBlockReceived.getPreviousHash())) {\n if (newblock.addNewBlocks(newBlockReceived, config)) {\n BroadCastBlockMessage(FormatBlockMessages(), config);\n }\n System.out.println(\"Add Block to Local PetaChain\");\n System.out.println();\n }\n } else if (BlockonChain == null) {\n BroadCastBlockMessage(FormatBlockChainMessage(), config);\n }\n }\n }\n\n //同步区块链\n public synchronized void handleBlockChainResponse(String blockData, NewReverseCoinBlockInterface newblock, CopyOnWriteArrayList<WebSocket> sockets, ReverseCoinChainConfigInterface config) {\n\n CopyOnWriteArrayList<ReverseCoinBlock> receiveBlockchain = SimpleGson.fromJson(blockData, new TypeToken<CopyOnWriteArrayList<ReverseCoinBlock>>() {\n }.getType());\n\n if (receiveBlockchain != null && !receiveBlockchain.isEmpty() && newblock.isUpdateBlockChain(receiveBlockchain, config)) {\n if (!newblock.isSortedByIndex(config)) {\n Collections.sort(receiveBlockchain, (ReverseCoinBlock block1, ReverseCoinBlock block2) -> block1.getIndex() - block2.getIndex());\n }\n\n ReverseCoinBlock latestBlockReceived = receiveBlockchain.get(receiveBlockchain.size() - 1);\n ReverseCoinBlock latestBlockonChain = config.getLatestBlock();\n\n if (latestBlockonChain == null) {\n newblock.updatePetaChain(receiveBlockchain, config);\n } else {\n if (latestBlockReceived.getIndex() > latestBlockonChain.getIndex()) {\n if (latestBlockonChain.getThisBlockHash().equals(latestBlockReceived.getPreviousHash())) {\n if (newblock.addNewBlocks(latestBlockReceived, config)) {\n BroadCastBlockMessage(responseNewBlockMessage(config), config);\n }\n System.out.println(\"Add PetaBlock to PetaChain Network!\");\n } else {\n newblock.updatePetaChain(receiveBlockchain, config);\n }\n }\n }\n }\n }\n\n public String responseNewBlockMessage(ReverseCoinChainConfigInterface config) {\n String cachedMessage = PetaJsonCache.get(\"responseNewBlockMessage\");\n if (cachedMessage != null) {\n return cachedMessage;\n } else {\n PeerMessages peerMessages = new PeerMessages();\n\n peerMessages.setCommandCode(CommandCode.ReturnLastestBlock);\n peerMessages.setMessage(PrettyGson.toJson(config.getLatestBlock()));\n\n String JsonMessage = PrettyGson.toJson(peerMessages);\n\n PetaJsonCache.put(\"responseNewBlockMessage\", JsonMessage);\n return JsonMessage;\n }\n }\n\n public String responseBlockChainMessage(ReverseCoinChainConfigInterface config) {\n String cachedMessage = PetaJsonCache.get(\"responseBlockChainMessage\");\n if (cachedMessage != null) {\n return cachedMessage;\n } else {\n PeerMessages peerMessages = new PeerMessages();\n\n peerMessages.setCommandCode(CommandCode.ReturnLastestBlockChain);\n peerMessages.setMessage(PrettyGson.toJson(config.getBlockList()));\n\n String JsonMessage = PrettyGson.toJson(peerMessages);\n\n PetaJsonCache.put(\"responseBlockChainMessage\", JsonMessage);\n return JsonMessage;\n }\n }\n\n public String FormatBlockMessages() {\n String cachedMessage = PetaJsonCache.get(\"FormatBlockMessages\");\n if (cachedMessage != null) {\n return cachedMessage;\n } else {\n String JsonMessage = PrettyGson.toJson(new PeerMessages(CommandCode.CheckLastestBlock));\n PetaJsonCache.put(\"FormatBlockMessages\", JsonMessage);\n return JsonMessage;\n }\n }\n\n public String FormatBlockChainMessage() {\n String cachedMessage = PetaJsonCache.get(\"FormatBlockChainMessage\");\n if (cachedMessage != null) {\n return cachedMessage;\n } else {\n String JsonMessage = PrettyGson.toJson(new PeerMessages(CommandCode.CheckWholeChain));\n PetaJsonCache.put(\"FormatBlockChainMessage\", JsonMessage);\n return JsonMessage;\n }\n }\n\n public void BroadCastBlockMessage(String message, ReverseCoinChainConfigInterface config) {\n CopyOnWriteArrayList<WebSocket> socketsList = this.getSockets(config);\n if (socketsList.isEmpty()) {\n return;\n }\n System.out.println(\"<--------BroadCast Start: -------->\");\n for (WebSocket socket : socketsList) {\n System.out.println(\"Send This Messages to: \" + socket.getRemoteSocketAddress().getAddress().toString()\n + \":\" + socket.getRemoteSocketAddress().getPort() + \". The Block Message: \" + message);\n this.PostRequest(socket, message);\n\n }\n System.out.println(\"<--------BroadCast End: -------->\");\n }\n\n public void PostRequest(WebSocket websocket, String message) {\n websocket.send(message);\n }\n\n public CopyOnWriteArrayList<WebSocket> getSockets(ReverseCoinChainConfigInterface config) {\n return config.getSocketsList();\n }\n}" }, { "identifier": "NewReverseCoinBlockInterface", "path": "src/main/java/ConnectionAPI/NewReverseCoinBlockInterface.java", "snippet": "public interface NewReverseCoinBlockInterface {\n\n boolean addNewBlocks(ReverseCoinBlock newBlock, ReverseCoinChainConfigInterface config);\n\n boolean checkPetaBlock(ReverseCoinBlock newBlock, ReverseCoinBlock previousBlock, ReverseCoinChainConfigInterface config);\n\n ReverseCoinBlock generatedNewBlock(String preHash, CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData, String TransactionHash, long nonce, String setBlockHash, ReverseCoinChainConfigInterface config);\n\n void updatePetaChain(CopyOnWriteArrayList<ReverseCoinBlock> newChain, ReverseCoinChainConfigInterface config);\n\n boolean isUpdateBlockChain(CopyOnWriteArrayList<ReverseCoinBlock> petachain, ReverseCoinChainConfigInterface config);\n \n boolean isSortedByIndex(ReverseCoinChainConfigInterface config);\n\n boolean checkBlocksHash(String hash, String target, ReverseCoinChainConfigInterface config);\n\n}" }, { "identifier": "ReverseCoinBlockEventListener", "path": "src/main/java/ConnectionAPI/ReverseCoinBlockEventListener.java", "snippet": "public interface ReverseCoinBlockEventListener {\n\n String scanBlock(ReverseCoinChainConfigInterface config) throws Exception;\n\n String scanData(ReverseCoinChainConfigInterface config) throws Exception;\n\n String createGenesisBlock(ReverseCoinBlockInterface blocks, ReverseCoinChainConfigInterface config) throws Exception;\n\n String createNewBlock(NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface config) throws Exception;\n}" }, { "identifier": "ReverseCoinChainConfigInterface", "path": "src/main/java/ConnectionAPI/ReverseCoinChainConfigInterface.java", "snippet": "public interface ReverseCoinChainConfigInterface {\n\n int getDifficulty();\n\n int getPorts();\n\n String getAddressPort();\n\n CopyOnWriteArrayList<ReverseCoinBlock> getBlockList();\n\n CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsList();\n\n CopyOnWriteArrayList<WebSocket> getSocketsList();\n\n ReverseCoinBlock getLatestBlock();\n \n String SHA3with256Hash(String input);\n\n void setDifficulty(int difficulty);\n\n void setPorts(int ports);\n\n void setAddressPort(String AddressPort);\n\n void setBlockList(CopyOnWriteArrayList<ReverseCoinBlock> BlockList);\n\n void setTransactionsList(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList);\n\n void setSocketsList(CopyOnWriteArrayList<WebSocket> socketsList);\n}" }, { "identifier": "ReverseCoinBlockInterface", "path": "src/main/java/ConnectionAPI/ReverseCoinBlockInterface.java", "snippet": "public interface ReverseCoinBlockInterface {\n\n byte getVersion();\n\n int getIndex();\n\n String getPreviousHash();\n\n String getTransactionHash();\n\n CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsData();\n\n long getTimeStamp();\n\n int getDifficulty();\n\n long getNonce();\n\n String getThisBlockHash();\n\n String toBlockJsonString(ReverseCoinBlock blocks);\n\n void setVersion(byte version);\n\n void setIndex(int index);\n\n void setPreviousHash(String PreviousHash);\n\n void setTransactionHash(String TransactionHash);\n\n void setTransactionsData(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionHash);\n\n void setTimeStamp(long TimeStamp);\n\n void setDifficulty(int difficulty);\n\n void setNonce(long nonce);\n\n void setThisBlockHash(String thisBlockHash);\n\n}" } ]
import BlockModel.PeerMessages; import BlockModel.ReverseCoinBlock; import ClientSeverMach.P2PClient; import ClientSeverMach.P2PServer; import ReverseCoinBlockChainGeneration.BlockChainConfig; import ReverseCoinBlockChainGeneration.NewBlockCreation; import ReverseCoinChainNetwork.P2PNetwork; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ConnectionAPI.NewReverseCoinBlockInterface; import ConnectionAPI.ReverseCoinBlockEventListener; import ConnectionAPI.ReverseCoinChainConfigInterface; import ConnectionAPI.ReverseCoinBlockInterface;
7,339
package top.pulselink.java.reversecoin; public class ReverseCoin { private volatile BlockChainConfig blockConfig = new BlockChainConfig(); private volatile ReverseCoinBlock block = new ReverseCoinBlock(); private volatile NewBlockCreation newBlock = new NewBlockCreation(); private volatile PeerMessages message = new PeerMessages(); private volatile ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); private volatile P2PNetwork network = new P2PNetwork(); private static final Logger logger = LoggerFactory.getLogger(ReverseCoin.class); public ReverseCoin(String address, int port, int difficulty) { blockConfig.setDifficulty(difficulty); blockConfig.setPorts(port); blockConfig.setAddressPort(address); initializeConnections(); startInputReader(block, new BlockEventManager(), newBlock, blockConfig, address); } private synchronized void startInputReader(ReverseCoinBlockInterface block, ReverseCoinBlockEventListener listener, NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface configParams, String addressPort) { if (!executor.isShutdown() && !executor.isTerminated()) { CompletableFuture.runAsync(() -> { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { String str; while ((str = reader.readLine()) != null) { handleEvent(str, block, listener, addnewblock, configParams, addressPort); } } catch (IOException e) { logger.error(e.getMessage()); } }, executor); } } private void initializeConnections() { printNodeInfo(blockConfig); CompletableFuture<Void> serverInitFuture = CompletableFuture.runAsync(() -> initP2PServer()); CompletableFuture<Void> clientConnectFuture = CompletableFuture.runAsync(() -> connectToPeer()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { executor.shutdownNow(); try { executor.awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error(e.getMessage()); } })); CompletableFuture<Void> allTasks = CompletableFuture.allOf(serverInitFuture, clientConnectFuture); allTasks.join(); } private void printNodeInfo(ReverseCoinChainConfigInterface configParams) { int difficulty = configParams.getDifficulty(); int ports = configParams.getPorts(); String addressPort = configParams.getAddressPort(); System.out.println("------------------\nPetaBlock Difficulty: " + difficulty + "\n------------------"); System.out.println("------------------\nP2P Port: " + ports + "\n------------------"); System.out.println("------------------\nP2P Network IP with Port: " + addressPort + "\n------------------"); System.out.println(); } private void initP2PServer() { P2PServer server = new P2PServer(); server.initP2PServer(blockConfig.getPorts(), blockConfig, newBlock, message, network); } private void connectToPeer() {
package top.pulselink.java.reversecoin; public class ReverseCoin { private volatile BlockChainConfig blockConfig = new BlockChainConfig(); private volatile ReverseCoinBlock block = new ReverseCoinBlock(); private volatile NewBlockCreation newBlock = new NewBlockCreation(); private volatile PeerMessages message = new PeerMessages(); private volatile ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); private volatile P2PNetwork network = new P2PNetwork(); private static final Logger logger = LoggerFactory.getLogger(ReverseCoin.class); public ReverseCoin(String address, int port, int difficulty) { blockConfig.setDifficulty(difficulty); blockConfig.setPorts(port); blockConfig.setAddressPort(address); initializeConnections(); startInputReader(block, new BlockEventManager(), newBlock, blockConfig, address); } private synchronized void startInputReader(ReverseCoinBlockInterface block, ReverseCoinBlockEventListener listener, NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface configParams, String addressPort) { if (!executor.isShutdown() && !executor.isTerminated()) { CompletableFuture.runAsync(() -> { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { String str; while ((str = reader.readLine()) != null) { handleEvent(str, block, listener, addnewblock, configParams, addressPort); } } catch (IOException e) { logger.error(e.getMessage()); } }, executor); } } private void initializeConnections() { printNodeInfo(blockConfig); CompletableFuture<Void> serverInitFuture = CompletableFuture.runAsync(() -> initP2PServer()); CompletableFuture<Void> clientConnectFuture = CompletableFuture.runAsync(() -> connectToPeer()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { executor.shutdownNow(); try { executor.awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error(e.getMessage()); } })); CompletableFuture<Void> allTasks = CompletableFuture.allOf(serverInitFuture, clientConnectFuture); allTasks.join(); } private void printNodeInfo(ReverseCoinChainConfigInterface configParams) { int difficulty = configParams.getDifficulty(); int ports = configParams.getPorts(); String addressPort = configParams.getAddressPort(); System.out.println("------------------\nPetaBlock Difficulty: " + difficulty + "\n------------------"); System.out.println("------------------\nP2P Port: " + ports + "\n------------------"); System.out.println("------------------\nP2P Network IP with Port: " + addressPort + "\n------------------"); System.out.println(); } private void initP2PServer() { P2PServer server = new P2PServer(); server.initP2PServer(blockConfig.getPorts(), blockConfig, newBlock, message, network); } private void connectToPeer() {
P2PClient client = new P2PClient();
2
2023-12-11 05:18:04+00:00
12k
i-moonlight/Movie_Manager
backend/src/main/java/ch/xxx/moviemanager/usecase/service/MovieService.java
[ { "identifier": "MovieDbRestClient", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/client/MovieDbRestClient.java", "snippet": "public interface MovieDbRestClient {\n\tMovieDto fetchMovie(String moviedbkey, long movieDbId);\n\t\n\tWrapperCastDto fetchCast(String moviedbkey, Long movieId);\n\t\n\tActorDto fetchActor(String moviedbkey, Integer castId);\n\t\n\tActorDto fetchActor(String moviedbkey, Integer castId, Long delay);\n\t\n\tWrapperGenereDto fetchAllGeneres(String moviedbkey);\n\t\n\tWrapperMovieDto fetchImportMovie(String moviedbkey, String queryStr);\n}" }, { "identifier": "CommonUtils", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/common/CommonUtils.java", "snippet": "public class CommonUtils {\n\n\tpublic static Date convert(LocalDate localDate) {\n\t\treturn Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());\n\t}\n\n\tpublic static <T extends EntityBase> Collection<Long> findDublicates(List<T> entities) {\n\t\treturn entities.stream().collect(Collectors.toMap(EntityBase::getId, u -> false, (x, y) -> true)).entrySet()\n\t\t\t\t.stream().filter(Map.Entry::getValue).map(Map.Entry::getKey).collect(Collectors.toSet());\n\t}\n\n\tpublic static <T extends EntityBase> boolean filterForDublicates(T myEntity, Collection<Long> dublicates) {\n\t\treturn dublicates.stream().filter(myId -> myId.equals(myEntity.getId())).findAny().isPresent();\n\t}\n\n\tpublic static <T extends EntityBase> Collection<T> filterDublicates(Collection<T> myCol) {\n\t\treturn myCol.stream().collect(Collectors.toMap(EntityBase::getId, d -> d, (T x, T y) -> x == null ? y : x))\n\t\t\t\t.values();\n\t}\n}" }, { "identifier": "ActorDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/ActorDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class ActorDto {\n\tpublic enum Gender {\n\t\tFemale(1), Male(2), Unknown(0);\n\n\t\tprivate final Integer code;\n\n\t\tprivate Gender(Integer code) {\n\t\t\tthis.code = code;\n\t\t}\n\t\t\n\t\t@JsonValue\n\t\tpublic Integer getCode() {\n\t\t\treturn code;\n\t\t}\n\t}\n\n\tprivate Long id;\n\tprivate String name;\n\tprivate Integer gender;\n\tprivate Date birthday;\n\tprivate Date deathday;\n\tprivate String biography;\n\t@JsonProperty(\"place_of_birth\")\n\tprivate String placeOfBirth;\n\tprivate Double popularity;\n\t@JsonProperty(\"actor_id\")\n\tprivate Long actorId;\n\tprivate List<CastDto> myCasts = new ArrayList<>();\n\n\tpublic Long getActorId() {\n\t\treturn actorId;\n\t}\n\n\tpublic void setActorId(Long actorId) {\n\t\tthis.actorId = actorId;\n\t}\n\n\tpublic List<CastDto> getMyCasts() {\n\t\treturn myCasts;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Integer getGender() {\n\t\treturn gender;\n\t}\n\n\tpublic void setGender(Integer gender) {\n\t\tthis.gender = gender;\n\t}\n\n\tpublic Date getBirthday() {\n\t\treturn birthday;\n\t}\n\n\tpublic void setBirthday(Date birthday) {\n\t\tthis.birthday = birthday;\n\t}\n\n\tpublic Date getDeathday() {\n\t\treturn deathday;\n\t}\n\n\tpublic void setDeathday(Date deathday) {\n\t\tthis.deathday = deathday;\n\t}\n\n\tpublic String getBiography() {\n\t\treturn biography;\n\t}\n\n\tpublic void setBiography(String biography) {\n\t\tthis.biography = biography;\n\t}\n\n\tpublic String getPlaceOfBirth() {\n\t\treturn placeOfBirth;\n\t}\n\n\tpublic void setPlaceOfBirth(String placeOfBirth) {\n\t\tthis.placeOfBirth = placeOfBirth;\n\t}\n\n\tpublic void setMyCasts(List<CastDto> myCasts) {\n\t\tthis.myCasts = myCasts;\n\t}\n\n\tpublic Double getPopularity() {\n\t\treturn popularity;\n\t}\n\n\tpublic void setPopularity(Double popularity) {\n\t\tthis.popularity = popularity;\n\t}\n}" }, { "identifier": "CastDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/CastDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class CastDto {\n\tprivate int id;\n\tprivate String character;\n\tprivate String name;\n\tprivate MovieDto myMovie;\n\tprivate ActorDto myActor;\n\t\n\tpublic ActorDto getMyActor() {\n\t\treturn myActor;\n\t}\n\tpublic void setMyActor(ActorDto myActor) {\n\t\tthis.myActor = myActor;\n\t}\n\tpublic MovieDto getMyMovie() {\n\t\treturn myMovie;\n\t}\n\tpublic void setMyMovie(MovieDto myMovie) {\n\t\tthis.myMovie = myMovie;\n\t}\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getCharacter() {\n\t\treturn character;\n\t}\n\tpublic void setCharacter(String character) {\n\t\tthis.character = character;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n}" }, { "identifier": "GenereDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/GenereDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class GenereDto {\n\tprivate Long id;\n\tprivate String name;\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\t\n}" }, { "identifier": "MovieDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/MovieDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class MovieDto {\n\tprivate Long id;\n\tprivate String overview;\n\t@JsonProperty(\"release_date\")\n\tprivate Date releaseDate;\n\tprivate String title;\t\n\t@JsonProperty(\"movie_id\")\n\tprivate Long movieId;\n\tprivate Integer runtime;\n\tprivate Long revenue;\n\t@JsonProperty(\"vote_average\")\n\tprivate Double voteAverage;\n\t@JsonProperty(\"vote_count\")\n\tprivate Integer voteCount;\n\tprivate Long budget;\n\tprivate List<GenereDto> genres = new ArrayList<>();\n\tprivate List<CastDto> myCast = new ArrayList<>();\n\tprivate List<GenereDto> myGenere = new ArrayList<>();\n\t\n\tpublic Long getMovieId() {\n\t\treturn movieId;\n\t}\n\tpublic void setMovieId(Long movieId) {\n\t\tthis.movieId = movieId;\n\t}\n\tpublic List<CastDto> getMyCast() {\n\t\treturn myCast;\n\t}\n\tpublic List<GenereDto> getMyGenere() {\n\t\treturn myGenere;\n\t}\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getOverview() {\n\t\treturn overview;\n\t}\n\tpublic void setOverview(String overview) {\n\t\tthis.overview = overview;\n\t}\t\n\tpublic Date getReleaseDate() {\n\t\treturn releaseDate;\n\t}\n\tpublic void setReleaseDate(Date releaseDate) {\n\t\tthis.releaseDate = releaseDate;\n\t}\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\tpublic void setMyCast(List<CastDto> myCast) {\n\t\tthis.myCast = myCast;\n\t}\n\tpublic void setMyGenere(List<GenereDto> myGenere) {\n\t\tthis.myGenere = myGenere;\n\t}\n\tpublic Integer getRuntime() {\n\t\treturn runtime;\n\t}\n\tpublic void setRuntime(Integer runtime) {\n\t\tthis.runtime = runtime;\n\t}\n\tpublic Long getRevenue() {\n\t\treturn revenue;\n\t}\n\tpublic void setRevenue(Long revenue) {\n\t\tthis.revenue = revenue;\n\t}\n\tpublic Double getVoteAverage() {\n\t\treturn voteAverage;\n\t}\n\tpublic void setVoteAverage(Double voteAverage) {\n\t\tthis.voteAverage = voteAverage;\n\t}\n\tpublic Integer getVoteCount() {\n\t\treturn voteCount;\n\t}\n\tpublic void setVoteCount(Integer voteCount) {\n\t\tthis.voteCount = voteCount;\n\t}\n\tpublic Long getBudget() {\n\t\treturn budget;\n\t}\n\tpublic void setBudget(Long budget) {\n\t\tthis.budget = budget;\n\t}\n\tpublic List<GenereDto> getGenres() {\n\t\treturn genres;\n\t}\n\tpublic void setGenres(List<GenereDto> genres) {\n\t\tthis.genres = genres;\n\t}\n}" }, { "identifier": "MovieFilterCriteriaDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/MovieFilterCriteriaDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class MovieFilterCriteriaDto {\n\tprivate List<GenereDto> selectedGeneres;\n\tprivate LocalDate releaseFrom;\n\tprivate LocalDate releaseTo;\n\tprivate String movieTitle;\n\tprivate String movieActor;\n\tprivate int minLength;\n\tprivate int maxLength;\n\tprivate int minRating;\t\n\t@JsonProperty(\"searchTerm\")\n\tprivate SearchTermDto searchTermDto = new SearchTermDto();\n\t\n\tpublic List<GenereDto> getSelectedGeneres() {\n\t\treturn selectedGeneres;\n\t}\n\tpublic void setSelectedGeneres(List<GenereDto> selectedGeneres) {\n\t\tthis.selectedGeneres = selectedGeneres;\n\t}\n\tpublic LocalDate getReleaseFrom() {\n\t\treturn releaseFrom;\n\t}\n\tpublic void setReleaseFrom(LocalDate releaseFrom) {\n\t\tthis.releaseFrom = releaseFrom;\n\t}\n\tpublic LocalDate getReleaseTo() {\n\t\treturn releaseTo;\n\t}\n\tpublic void setReleaseTo(LocalDate releaseTo) {\n\t\tthis.releaseTo = releaseTo;\n\t}\n\tpublic String getMovieTitle() {\n\t\treturn movieTitle;\n\t}\n\tpublic void setMovieTitle(String movieTitle) {\n\t\tthis.movieTitle = movieTitle;\n\t}\n\tpublic String getMovieActor() {\n\t\treturn movieActor;\n\t}\n\tpublic void setMovieActor(String movieActor) {\n\t\tthis.movieActor = movieActor;\n\t}\n\tpublic int getMinLength() {\n\t\treturn minLength;\n\t}\n\tpublic void setMinLength(int minLength) {\n\t\tthis.minLength = minLength;\n\t}\n\tpublic int getMaxLength() {\n\t\treturn maxLength;\n\t}\n\tpublic void setMaxLength(int maxLength) {\n\t\tthis.maxLength = maxLength;\n\t}\n\tpublic int getMinRating() {\n\t\treturn minRating;\n\t}\n\tpublic void setMinRating(int minRating) {\n\t\tthis.minRating = minRating;\n\t}\n\tpublic SearchTermDto getSearchTermDto() {\n\t\treturn searchTermDto;\n\t}\n\tpublic void setSearchTermDto(SearchTermDto searchTermDto) {\n\t\tthis.searchTermDto = searchTermDto;\n\t}\n}" }, { "identifier": "SearchTermDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/SearchTermDto.java", "snippet": "public class SearchTermDto {\n\t@JsonProperty(\"searchPhrase\")\n\tprivate SearchPhraseDto searchPhraseDto = new SearchPhraseDto();\n\t@JsonProperty(\"searchStrings\")\n\tprivate SearchStringDto[] searchStringDtos = new SearchStringDto[0];\n\t\n\tpublic SearchPhraseDto getSearchPhraseDto() {\n\t\treturn searchPhraseDto;\n\t}\n\tpublic void setSearchPhraseDto(SearchPhraseDto searchPhraseDto) {\n\t\tthis.searchPhraseDto = searchPhraseDto;\n\t}\n\tpublic SearchStringDto[] getSearchStringDtos() {\n\t\treturn searchStringDtos;\n\t}\n\tpublic void setSearchStringDtos(SearchStringDto[] searchStringDtos) {\n\t\tthis.searchStringDtos = searchStringDtos;\n\t}\n}" }, { "identifier": "WrapperCastDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/WrapperCastDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class WrapperCastDto {\n\tprivate int id;\n\tprivate CastDto[] cast;\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\tpublic CastDto[] getCast() {\n\t\treturn cast;\n\t}\n\tpublic void setCast(CastDto[] cast) {\n\t\tthis.cast = cast;\n\t}\n\t\n}" }, { "identifier": "WrapperGenereDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/WrapperGenereDto.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class WrapperGenereDto {\n\tprivate GenereDto[] genres;\n\n\tpublic GenereDto[] getGenres() {\n\t\treturn genres;\n\t}\n\n\tpublic void setGenres(GenereDto[] genres) {\n\t\tthis.genres = genres;\n\t}\n\n\t\n}" }, { "identifier": "WrapperMovieDto", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/dto/WrapperMovieDto.java", "snippet": "public class WrapperMovieDto {\n\tprivate int page;\n\tprivate int total_results;\n\tprivate int total_pages;\n\tprivate MovieDto[] results;\n\t\n\tpublic int getPage() {\n\t\treturn page;\n\t}\n\tpublic void setPage(int page) {\n\t\tthis.page = page;\n\t}\n\tpublic int getTotal_results() {\n\t\treturn total_results;\n\t}\n\tpublic void setTotal_results(int total_results) {\n\t\tthis.total_results = total_results;\n\t}\n\tpublic int getTotal_pages() {\n\t\treturn total_pages;\n\t}\n\tpublic void setTotal_pages(int total_pages) {\n\t\tthis.total_pages = total_pages;\n\t}\n\tpublic MovieDto[] getResults() {\n\t\treturn results;\n\t}\n\tpublic void setResults(MovieDto[] results) {\n\t\tthis.results = results;\n\t}\n}" }, { "identifier": "Actor", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/Actor.java", "snippet": "@NamedQuery(name = \"Actor.count\", query = \"select count(a) from Actor a\")\n@Indexed\n@Entity\npublic class Actor extends EntityBase {\n\tprivate Long actorId;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String name;\n\tprivate Integer gender;\n\tprivate Date birthday;\n\tprivate Date deathday;\n\t@FullTextField(termVector = TermVector.YES)\n//\t@Lob\n\t@Column(columnDefinition = \"text\")\n\tprivate String biography;\n\tprivate Double popularity = 0.0;\n\tprivate String placeOfBirth;\n\t@OneToMany(mappedBy = \"actor\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)\n\tprivate List<Cast> casts = new ArrayList<>();\n\t@ManyToMany\n\t@JoinTable(name = \"actor_user\", joinColumns = @JoinColumn(name = \"actor_id\"), inverseJoinColumns = @JoinColumn(name = \"user_id\"))\n\tprivate Set<User> users = new HashSet<>();\n\n\tpublic Set<User> getUsers() {\n\t\treturn users;\n\t}\n\n\tpublic Long getActorId() {\n\t\treturn actorId;\n\t}\n\n\tpublic void setActorId(Long actorId) {\n\t\tthis.actorId = actorId;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Integer getGender() {\n\t\treturn gender;\n\t}\n\n\tpublic void setGender(Integer gender) {\n\t\tthis.gender = gender;\n\t}\n\n\tpublic Date getBirthday() {\n\t\treturn birthday;\n\t}\n\n\tpublic void setBirthday(Date birthday) {\n\t\tthis.birthday = birthday;\n\t}\n\n\tpublic Date getDeathday() {\n\t\treturn deathday;\n\t}\n\n\tpublic void setDeathday(Date deathday) {\n\t\tthis.deathday = deathday;\n\t}\n\n\tpublic String getBiography() {\n\t\treturn biography;\n\t}\n\n\tpublic void setBiography(String biography) {\n\t\tthis.biography = biography;\n\t}\n\n\tpublic String getPlaceOfBirth() {\n\t\treturn placeOfBirth;\n\t}\n\n\tpublic void setPlaceOfBirth(String placeOfBirth) {\n\t\tthis.placeOfBirth = placeOfBirth;\n\t}\n\n\tpublic List<Cast> getCasts() {\n\t\treturn casts;\n\t}\n\n\tpublic void setCasts(List<Cast> casts) {\n\t\tthis.casts = casts;\n\t}\n\n\tpublic Double getPopularity() {\n\t\treturn popularity;\n\t}\n\n\tpublic void setPopularity(Double popularity) {\n\t\tthis.popularity = popularity;\n\t}\n\n}" }, { "identifier": "ActorRepository", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/ActorRepository.java", "snippet": "public interface ActorRepository {\n\tList<Actor> findActorsByPage(Long userId, Pageable pageble);\n\tList<Actor> findByActorName(String name, Long userId, Pageable pageable);\n\tOptional<Actor> findByActorId(Long actorId, Long userId);\n\tvoid deleteById(Long id);\n\tOptional<Actor> findById(Long id);\n\tActor save(Actor actorEntity);\n\tList<Actor> findUnusedActors();\n\tList<Actor> findActorsByPhrase(SearchPhraseDto searchPhraseDto);\n\tList<Actor> findActorsBySearchStrings(List<SearchStringDto> searchStrings);\n\tList<Actor> findByFilterCriteria(ActorFilterCriteriaDto filterCriteriaDto, Long userId);\n}" }, { "identifier": "Cast", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/Cast.java", "snippet": "@Entity\n@Table(name=\"cast1\")\npublic class Cast extends EntityBase {\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String movieChar;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String characterName;\n\t@ManyToOne(fetch=FetchType.LAZY)\n\t@JoinColumn(name=\"movie_id\")\n\tprivate Movie movie;\n\t@ManyToOne(fetch=FetchType.LAZY)\n\t@JoinColumn(name=\"actor_id\")\n\tprivate Actor actor;\n\t\n\tpublic String getMovieChar() {\n\t\treturn movieChar;\n\t}\n\tpublic void setMovieChar(String movieChar) {\n\t\tthis.movieChar = movieChar;\n\t}\n\tpublic String getCharacterName() {\n\t\treturn characterName;\n\t}\n\tpublic void setCharacterName(String characterName) {\n\t\tthis.characterName = characterName;\n\t}\n\tpublic Movie getMovie() {\n\t\treturn movie;\n\t}\n\tpublic void setMovie(Movie movie) {\n\t\tthis.movie = movie;\n\t}\n\tpublic Actor getActor() {\n\t\treturn actor;\n\t}\n\tpublic void setActor(Actor actor) {\n\t\tthis.actor = actor;\n\t}\n\t\n}" }, { "identifier": "CastRepository", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/CastRepository.java", "snippet": "public interface CastRepository {\n\tCast save(Cast cast);\n}" }, { "identifier": "Genere", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/Genere.java", "snippet": "@Entity\npublic class Genere extends EntityBase {\n\tprivate Long genereId;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String name;\n\t@ManyToMany(mappedBy=\"generes\")\n\tprivate Set<Movie> movies = new HashSet<>();\n\t\n\tpublic Long getGenereId() {\n\t\treturn genereId;\n\t}\n\tpublic void setGenereId(Long genereId) {\n\t\tthis.genereId = genereId;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic Set<Movie> getMovies() {\n\t\treturn movies;\n\t}\n\tpublic void setMovies(Set<Movie> movies) {\n\t\tthis.movies = movies;\n\t}\n\t\n}" }, { "identifier": "GenereRepository", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/GenereRepository.java", "snippet": "public interface GenereRepository {\t\n\tpublic List<Genere> findAll();\n\tpublic Genere save(Genere genere);\n}" }, { "identifier": "Movie", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/Movie.java", "snippet": "@NamedQuery(name = \"Movie.count\", query = \"select count(m) from Movie m\")\n@Indexed\n@Entity\npublic class Movie extends EntityBase {\n\tprivate Date releaseDate;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String title;\n\t@FullTextField(termVector = TermVector.YES)\n//\t@Lob\n\t@Column(columnDefinition = \"text\")\n\tprivate String overview;\n\tprivate Integer runtime = 0;\n\tprivate Long revenue = 0L;\n\tprivate Double voteAverage = 0.0;\n\tprivate Integer voteCount = 0;\n\tprivate Long budget = 0L;\n\tprivate Long movieId;\n\t@OneToMany(mappedBy = \"movie\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)\n\tprivate List<Cast> cast = new ArrayList<>();\n\t@ManyToMany\n\t@JoinTable(name = \"movie_genere\", joinColumns = @JoinColumn(name = \"movie_id\"), inverseJoinColumns = @JoinColumn(name = \"genere_id\"))\n\tprivate Set<Genere> generes = new HashSet<>();\n\t@ManyToMany\n\t@JoinTable(name = \"movie_user\", joinColumns = @JoinColumn(name = \"movie_id\"), inverseJoinColumns = @JoinColumn(name = \"user_id\"))\n\tprivate Set<User> users = new HashSet<>();\n\n\tpublic Set<User> getUsers() {\n\t\treturn users;\n\t}\n\n\tpublic Long getMovieId() {\n\t\treturn movieId;\n\t}\n\n\tpublic void setMovieId(Long movieid) {\n\t\tthis.movieId = movieid;\n\t}\n\n\tpublic String getOverview() {\n\t\treturn overview;\n\t}\n\n\tpublic void setOverview(String overview) {\n\t\tthis.overview = overview;\n\t}\n\n\tpublic Date getReleaseDate() {\n\t\treturn releaseDate;\n\t}\n\n\tpublic void setReleaseDate(Date releaseDate) {\n\t\tthis.releaseDate = releaseDate;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic List<Cast> getCast() {\n\t\treturn cast;\n\t}\n\n\tpublic void setCast(List<Cast> cast) {\n\t\tthis.cast = cast;\n\t}\n\n\tpublic Set<Genere> getGeneres() {\n\t\treturn generes;\n\t}\n\n\tpublic void setGeneres(Set<Genere> generes) {\n\t\tthis.generes = generes;\n\t}\n\n\tpublic Integer getRuntime() {\n\t\treturn runtime;\n\t}\n\n\tpublic void setRuntime(Integer runtime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\tpublic Long getRevenue() {\n\t\treturn revenue;\n\t}\n\n\tpublic void setRevenue(Long revenue) {\n\t\tthis.revenue = revenue;\n\t}\n\n\tpublic Double getVoteAverage() {\n\t\treturn voteAverage;\n\t}\n\n\tpublic void setVoteAverage(Double voteAverage) {\n\t\tthis.voteAverage = voteAverage;\n\t}\n\n\tpublic Integer getVoteCount() {\n\t\treturn voteCount;\n\t}\n\n\tpublic void setVoteCount(Integer voteCount) {\n\t\tthis.voteCount = voteCount;\n\t}\n\n\tpublic Long getBudget() {\n\t\treturn budget;\n\t}\n\n\tpublic void setBudget(Long budget) {\n\t\tthis.budget = budget;\n\t}\n\n}" }, { "identifier": "MovieRepository", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/MovieRepository.java", "snippet": "public interface MovieRepository {\n\tList<Movie> findByTitle(String title, Long userId, Pageable pageable);\n\tList<Movie> findByGenereId(Long id, Long userId);\n\tList<Movie> findByTitleAndRelDate(String title, Date releaseDate, Long userId);\n\tOptional<Movie> findByMovieId(Long movieId, Long userId);\n\tList<Movie> findMoviesByPage(Long userId, Pageable pageable);\n\tOptional<Movie> findById(Long id);\n\tvoid deleteById(Long id);\n\tMovie save(Movie movieEntity);\n\tList<Movie> findUnusedMovies();\n\tOptional<Movie> findByIdWithCollections(Long id);\n\tList<Movie> findMoviesByPhrase(SearchPhraseDto searchPhraseDto);\n\tList<Movie> findMoviesBySearchStrings(List<SearchStringDto> searchStrings);\n\tList<Movie> findByFilterCriteria(MovieFilterCriteriaDto filterCriteriaDto, Long userId);\n}" }, { "identifier": "User", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/User.java", "snippet": "@Entity\n@Table(name=\"user1\")\npublic class User extends EntityBase {\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String username;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String password;\n\tprivate String moviedbkey;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String roles;\n\tprivate String emailAddress;\n\tprivate boolean locked;\n\tprivate boolean enabled;\n\tprivate String uuid;\n\tprivate LocalDate birthDate;\n\tprivate Long migration;\n\t\n\t\n\tpublic Long getMigration() {\n\t\treturn migration;\n\t}\n\tpublic void setMigration(Long migration) {\n\t\tthis.migration = migration;\n\t}\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\tpublic String getMoviedbkey() {\n\t\treturn moviedbkey;\n\t}\n\tpublic void setMoviedbkey(String moviedbkey) {\n\t\tthis.moviedbkey = moviedbkey;\n\t}\n\tpublic String getRoles() {\n\t\treturn roles;\n\t}\n\tpublic void setRoles(String roles) {\n\t\tthis.roles = roles;\n\t}\n\tpublic String getEmailAddress() {\n\t\treturn emailAddress;\n\t}\n\tpublic void setEmailAddress(String emailAddress) {\n\t\tthis.emailAddress = emailAddress;\n\t}\n\tpublic boolean isLocked() {\n\t\treturn locked;\n\t}\n\tpublic void setLocked(boolean locked) {\n\t\tthis.locked = locked;\n\t}\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\tpublic void setEnabled(boolean enabled) {\n\t\tthis.enabled = enabled;\n\t}\n\tpublic String getUuid() {\n\t\treturn uuid;\n\t}\n\tpublic void setUuid(String uuid) {\n\t\tthis.uuid = uuid;\n\t}\n\tpublic LocalDate getBirthDate() {\n\t\treturn birthDate;\n\t}\n\tpublic void setBirthDate(LocalDate birthDate) {\n\t\tthis.birthDate = birthDate;\n\t}\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result\n\t\t\t\t+ Objects.hash(birthDate, emailAddress, enabled, locked, moviedbkey, password, roles, username, uuid);\n\t\treturn result;\n\t}\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tUser other = (User) obj;\n\t\treturn Objects.equals(birthDate, other.birthDate) && Objects.equals(emailAddress, other.emailAddress)\n\t\t\t\t&& enabled == other.enabled && locked == other.locked && Objects.equals(moviedbkey, other.moviedbkey)\n\t\t\t\t&& Objects.equals(password, other.password) && Objects.equals(roles, other.roles)\n\t\t\t\t&& Objects.equals(username, other.username) && Objects.equals(uuid, other.uuid);\n\t}\t\n}" }, { "identifier": "DefaultMapper", "path": "backend/src/main/java/ch/xxx/moviemanager/usecase/mapper/DefaultMapper.java", "snippet": "@Service\npublic class DefaultMapper {\n\n\tpublic MovieDto convertMovieWithGenere(Movie entity) {\n\t\tMovieDto dto = convertMovie(entity, false);\n\t\treturn dto;\n\t}\n\n\tpublic MovieDto convertOnlyMovie(Movie entity) {\n\t\tMovieDto dto = convertMovie(entity, true);\n\t\treturn dto;\n\t}\n\t\n\tpublic MovieDto convert(Movie entity) {\n\t\tMovieDto dto = convertMovie(entity, false);\n\t\tentity.getCast().forEach(c -> {\n\t\t\tCastDto castDto = convert(c, true);\n\t\t\tdto.getMyCast().add(castDto);\n\t\t});\n\t\treturn dto;\n\t}\n\n\tpublic ActorDto convertOnlyActor(Actor entity) {\n\t\tActorDto dto = convertActor(entity);\n\t\treturn dto;\n\t}\n\t\n\tpublic ActorDto convert(Actor entity) {\n\t\tActorDto dto = convertActor(entity);\n\t\tentity.getCasts().forEach(c -> {\n\t\t\tCastDto castDto = convert(c, false);\n\t\t\tdto.getMyCasts().add(castDto);\n\t\t});\n\t\treturn dto;\n\t}\n\n\tpublic GenereDto convert(Genere entity) {\n\t\tGenereDto dto = new GenereDto();\n\t\tdto.setId(entity.getGenereId());\n\t\tdto.setName(entity.getName());\n\t\treturn dto;\n\t}\n\n\tprivate CastDto convert(Cast entity, boolean fromMovie) {\n\t\tCastDto dto = new CastDto();\n\t\tdto.setCharacter(entity.getMovieChar());\n\t\tdto.setName(entity.getCharacterName());\n\t\tif (fromMovie)\n\t\t\tdto.setMyActor(convertActor(entity.getActor()));\n\t\telse\n\t\t\tdto.setMyMovie(convertMovie(entity.getMovie(), false));\n\t\treturn dto;\n\t}\n\n\tprivate MovieDto convertMovie(Movie entity, boolean noGeneres) {\n\t\tMovieDto dto = new MovieDto();\n\t\tdto.setId(entity.getId());\n\t\tdto.setOverview(entity.getOverview());\n\t\tdto.setReleaseDate(entity.getReleaseDate());\n\t\tdto.setTitle(entity.getTitle());\n\t\tdto.setRuntime(entity.getRuntime());\n\t\tdto.setRevenue(entity.getRevenue());\n\t\tdto.setVoteAverage(entity.getVoteAverage());\n\t\tdto.setVoteCount(entity.getVoteCount());\n\t\tdto.setBudget(entity.getBudget());\n\t\tdto.setMovieId(entity.getMovieId());\n\t\tif (!noGeneres) {\n\t\t\tentity.getGeneres().forEach(g -> {\n\t\t\t\tGenereDto genereDto = convert(g);\n\t\t\t\tdto.getMyGenere().add(genereDto);\n\t\t\t});\n\t\t}\n\t\treturn dto;\n\t}\n\n\tprivate ActorDto convertActor(Actor entity) {\n\t\tActorDto dto = new ActorDto();\n\t\tdto.setBiography(entity.getBiography());\n\t\tdto.setBirthday(entity.getBirthday());\n\t\tdto.setDeathday(entity.getDeathday());\n\t\tdto.setGender(entity.getGender());\n\t\tdto.setName(entity.getName());\n\t\tdto.setPlaceOfBirth(entity.getPlaceOfBirth());\n\t\tdto.setPopularity(entity.getPopularity());\n\t\tdto.setId(entity.getId());\n\t\tdto.setActorId(entity.getActorId());\n\t\treturn dto;\n\t}\n\n\tpublic Genere convert(GenereDto dto) {\n\t\tGenere entity = new Genere();\n\t\tentity.setName(dto.getName());\n\t\tentity.setGenereId(dto.getId());\n\t\treturn entity;\n\t}\n\n\tpublic Movie convert(MovieDto dto) {\n\t\tMovie entity = new Movie();\n\t\tentity.setOverview(dto.getOverview());\n\t\tentity.setReleaseDate(dto.getReleaseDate());\n\t\tentity.setTitle(dto.getTitle());\n\t\tentity.setRuntime(dto.getRuntime());\n\t\tentity.setRevenue(dto.getRevenue());\n\t\tentity.setVoteAverage(dto.getVoteAverage());\n\t\tentity.setVoteCount(dto.getVoteCount());\n\t\tentity.setBudget(dto.getBudget());\n\t\tentity.setMovieId(dto.getMovieId());\n\t\treturn entity;\n\t}\n\n\tpublic Cast convert(CastDto dto) {\n\t\tCast entity = new Cast();\n\t\tentity.setCharacterName(dto.getName());\n\t\tentity.setMovieChar(dto.getCharacter());\n\t\treturn entity;\n\t}\n\n\tpublic Actor convert(ActorDto dto) {\n\t\tActor entity = new Actor();\n\t\tentity.setActorId(\n\t\t\t\tdto.getActorId() == null || dto.getActorId() == 0 ? dto.getId().intValue() : dto.getActorId());\n\t\tentity.setBiography(dto.getBiography());\n\t\tentity.setBirthday(dto.getBirthday());\n\t\tentity.setDeathday(dto.getDeathday());\n\t\tentity.setGender(dto.getGender());\n\t\tentity.setName(dto.getName());\n\t\tentity.setPlaceOfBirth(dto.getPlaceOfBirth());\n\t\tentity.setPopularity(dto.getPopularity());\n\t\treturn entity;\n\t}\n}" } ]
import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.crypto.tink.DeterministicAead; import com.google.crypto.tink.InsecureSecretKeyAccess; import com.google.crypto.tink.KeysetHandle; import com.google.crypto.tink.TinkJsonProtoKeysetFormat; import com.google.crypto.tink.daead.DeterministicAeadConfig; import ch.xxx.moviemanager.domain.client.MovieDbRestClient; import ch.xxx.moviemanager.domain.common.CommonUtils; import ch.xxx.moviemanager.domain.model.dto.ActorDto; import ch.xxx.moviemanager.domain.model.dto.CastDto; import ch.xxx.moviemanager.domain.model.dto.GenereDto; import ch.xxx.moviemanager.domain.model.dto.MovieDto; import ch.xxx.moviemanager.domain.model.dto.MovieFilterCriteriaDto; import ch.xxx.moviemanager.domain.model.dto.SearchTermDto; import ch.xxx.moviemanager.domain.model.dto.WrapperCastDto; import ch.xxx.moviemanager.domain.model.dto.WrapperGenereDto; import ch.xxx.moviemanager.domain.model.dto.WrapperMovieDto; import ch.xxx.moviemanager.domain.model.entity.Actor; import ch.xxx.moviemanager.domain.model.entity.ActorRepository; import ch.xxx.moviemanager.domain.model.entity.Cast; import ch.xxx.moviemanager.domain.model.entity.CastRepository; import ch.xxx.moviemanager.domain.model.entity.Genere; import ch.xxx.moviemanager.domain.model.entity.GenereRepository; import ch.xxx.moviemanager.domain.model.entity.Movie; import ch.xxx.moviemanager.domain.model.entity.MovieRepository; import ch.xxx.moviemanager.domain.model.entity.User; import ch.xxx.moviemanager.usecase.mapper.DefaultMapper; import jakarta.annotation.PostConstruct;
10,052
public List<Movie> findMoviesByGenereId(Long id, String bearerStr) { List<Movie> result = this.movieRep.findByGenereId(id, this.userDetailService.getCurrentUser(bearerStr).getId()); return result; } public Optional<Movie> findMovieById(Long id) { Optional<Movie> result = this.movieRep.findById(id); return result; } public boolean deleteMovieById(Long id, String bearerStr) { boolean result = true; try { User user = this.userDetailService.getCurrentUser(bearerStr); Optional<Movie> movieOpt = this.movieRep.findById(id); if (movieOpt.isPresent() && movieOpt.get().getUsers().contains(user)) { Movie movie = movieOpt.get(); movie.getUsers().remove(user); if (movie.getUsers().isEmpty()) { for (Cast c : movie.getCast()) { c.getActor().getCasts().remove(c); if (c.getActor().getCasts().isEmpty()) { this.actorRep.deleteById(c.getActor().getId()); } } this.movieRep.deleteById(id); } } } catch (RuntimeException re) { result = false; } return result; } public List<Movie> findMovie(String title, String bearerStr) { PageRequest pageRequest = PageRequest.of(0, 15, Sort.by("title").ascending()); List<Movie> result = this.movieRep.findByTitle(title, this.userDetailService.getCurrentUser(bearerStr).getId(), pageRequest); return result; } public List<Movie> findMoviesByPage(Integer page, String bearerStr) { User currentUser = this.userDetailService.getCurrentUser(bearerStr); List<Movie> result = this.movieRep.findMoviesByPage(currentUser.getId(), PageRequest.of((page - 1), 10)); result = result.stream().flatMap(movie -> Stream.of(this.movieRep.findByIdWithCollections(movie.getId()))) .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); return result; } public List<MovieDto> findImportMovie(String title, String bearerStr) throws GeneralSecurityException { User user = this.userDetailService.getCurrentUser(bearerStr); String queryStr = this.createQueryStr(title); WrapperMovieDto wrMovie = this.movieDbRestClient .fetchImportMovie(this.decrypt(user.getMoviedbkey(), user.getUuid()), queryStr); List<MovieDto> result = Arrays.asList(wrMovie.getResults()); return result; } public boolean cleanup() { this.movieRep.findUnusedMovies().forEach( movie -> LOG.info(String.format("Unused Movie id: %d title: %s", movie.getId(), movie.getTitle()))); return true; } private String decrypt(String cipherText, String uuid) throws GeneralSecurityException { String result = new String(daead.decryptDeterministically(Base64.getDecoder().decode(cipherText), uuid.getBytes(Charset.defaultCharset()))); return result; } public boolean importMovie(int movieDbId, String bearerStr) throws InterruptedException, GeneralSecurityException { User user = this.userDetailService.getCurrentUser(bearerStr); LOG.info("Start import"); LOG.info("Start import generes"); WrapperGenereDto result = this.movieDbRestClient .fetchAllGeneres(this.decrypt(user.getMoviedbkey(), user.getUuid())); List<Genere> generes = new ArrayList<>(this.genereRep.findAll()); for (GenereDto g : result.getGenres()) { Genere genereEntity = generes.stream() .filter(myGenere -> Optional.ofNullable(myGenere.getGenereId()).stream().anyMatch(myGenereId -> myGenereId.equals(g.getId()))) .findFirst().orElse(this.mapper.convert(g)); if (genereEntity.getId() == null) { genereEntity = genereRep.save(genereEntity); generes.add(genereEntity); } } LOG.info("Start import Movie with Id: {movieDbId}", movieDbId); MovieDto movieDto = this.movieDbRestClient.fetchMovie(this.decrypt(user.getMoviedbkey(), user.getUuid()), movieDbId); Optional<Movie> movieOpt = this.movieRep.findByMovieId(movieDto.getMovieId(), user.getId()); Movie movieEntity = movieOpt.isPresent() ? movieOpt.get() : null; if (movieOpt.isEmpty()) { LOG.info("Movie not found by id"); List<Movie> movies = this.movieRep.findByTitleAndRelDate(movieDto.getTitle(), movieDto.getReleaseDate(), this.userDetailService.getCurrentUser(bearerStr).getId()); if (!movies.isEmpty()) { LOG.info("Movie found by Title and Reldate"); movieEntity = movies.get(0); movieEntity.setMovieId(movieDto.getId()); } else { LOG.info("creating new Movie"); movieEntity = this.mapper.convert(movieDto); movieEntity.setMovieId(movieDto.getId()); for (Long genId : movieDto.getGenres().stream().map(myGenere -> myGenere.getId()).toList()) { Optional<Genere> myResult = generes.stream() .filter(myGenere -> genId.equals(myGenere.getGenereId())).findFirst(); if (myResult.isPresent()) { movieEntity.getGeneres().add(myResult.get()); myResult.get().getMovies().add(movieEntity); } } movieEntity = this.movieRep.save(movieEntity); } } if (!movieEntity.getUsers().contains(user)) { LOG.info("adding user to movie"); movieEntity.getUsers().add(user); }
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.moviemanager.usecase.service; @Transactional @Service public class MovieService { private static final Logger LOG = LoggerFactory.getLogger(MovieService.class); private final MovieRepository movieRep; private final CastRepository castRep; private final ActorRepository actorRep; private final GenereRepository genereRep; private final UserDetailService userDetailService; private final DefaultMapper mapper; private final MovieDbRestClient movieDbRestClient; @Value("${tink.json.key}") private String tinkJsonKey; private DeterministicAead daead; public MovieService(MovieRepository movieRep, CastRepository castRep, ActorRepository actorRep, GenereRepository genereRep, UserDetailService userDetailService, DefaultMapper mapper, MovieDbRestClient movieDbRestClient) { this.userDetailService = userDetailService; this.actorRep = actorRep; this.castRep = castRep; this.genereRep = genereRep; this.movieRep = movieRep; this.mapper = mapper; this.movieDbRestClient = movieDbRestClient; } @PostConstruct public void init() throws GeneralSecurityException { DeterministicAeadConfig.register(); KeysetHandle handle = TinkJsonProtoKeysetFormat.parseKeyset(this.tinkJsonKey, InsecureSecretKeyAccess.get()); this.daead = handle.getPrimitive(DeterministicAead.class); } public List<Genere> findAllGeneres() { List<Genere> result = this.genereRep.findAll(); return result; } public List<Movie> findMoviesByGenereId(Long id, String bearerStr) { List<Movie> result = this.movieRep.findByGenereId(id, this.userDetailService.getCurrentUser(bearerStr).getId()); return result; } public Optional<Movie> findMovieById(Long id) { Optional<Movie> result = this.movieRep.findById(id); return result; } public boolean deleteMovieById(Long id, String bearerStr) { boolean result = true; try { User user = this.userDetailService.getCurrentUser(bearerStr); Optional<Movie> movieOpt = this.movieRep.findById(id); if (movieOpt.isPresent() && movieOpt.get().getUsers().contains(user)) { Movie movie = movieOpt.get(); movie.getUsers().remove(user); if (movie.getUsers().isEmpty()) { for (Cast c : movie.getCast()) { c.getActor().getCasts().remove(c); if (c.getActor().getCasts().isEmpty()) { this.actorRep.deleteById(c.getActor().getId()); } } this.movieRep.deleteById(id); } } } catch (RuntimeException re) { result = false; } return result; } public List<Movie> findMovie(String title, String bearerStr) { PageRequest pageRequest = PageRequest.of(0, 15, Sort.by("title").ascending()); List<Movie> result = this.movieRep.findByTitle(title, this.userDetailService.getCurrentUser(bearerStr).getId(), pageRequest); return result; } public List<Movie> findMoviesByPage(Integer page, String bearerStr) { User currentUser = this.userDetailService.getCurrentUser(bearerStr); List<Movie> result = this.movieRep.findMoviesByPage(currentUser.getId(), PageRequest.of((page - 1), 10)); result = result.stream().flatMap(movie -> Stream.of(this.movieRep.findByIdWithCollections(movie.getId()))) .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); return result; } public List<MovieDto> findImportMovie(String title, String bearerStr) throws GeneralSecurityException { User user = this.userDetailService.getCurrentUser(bearerStr); String queryStr = this.createQueryStr(title); WrapperMovieDto wrMovie = this.movieDbRestClient .fetchImportMovie(this.decrypt(user.getMoviedbkey(), user.getUuid()), queryStr); List<MovieDto> result = Arrays.asList(wrMovie.getResults()); return result; } public boolean cleanup() { this.movieRep.findUnusedMovies().forEach( movie -> LOG.info(String.format("Unused Movie id: %d title: %s", movie.getId(), movie.getTitle()))); return true; } private String decrypt(String cipherText, String uuid) throws GeneralSecurityException { String result = new String(daead.decryptDeterministically(Base64.getDecoder().decode(cipherText), uuid.getBytes(Charset.defaultCharset()))); return result; } public boolean importMovie(int movieDbId, String bearerStr) throws InterruptedException, GeneralSecurityException { User user = this.userDetailService.getCurrentUser(bearerStr); LOG.info("Start import"); LOG.info("Start import generes"); WrapperGenereDto result = this.movieDbRestClient .fetchAllGeneres(this.decrypt(user.getMoviedbkey(), user.getUuid())); List<Genere> generes = new ArrayList<>(this.genereRep.findAll()); for (GenereDto g : result.getGenres()) { Genere genereEntity = generes.stream() .filter(myGenere -> Optional.ofNullable(myGenere.getGenereId()).stream().anyMatch(myGenereId -> myGenereId.equals(g.getId()))) .findFirst().orElse(this.mapper.convert(g)); if (genereEntity.getId() == null) { genereEntity = genereRep.save(genereEntity); generes.add(genereEntity); } } LOG.info("Start import Movie with Id: {movieDbId}", movieDbId); MovieDto movieDto = this.movieDbRestClient.fetchMovie(this.decrypt(user.getMoviedbkey(), user.getUuid()), movieDbId); Optional<Movie> movieOpt = this.movieRep.findByMovieId(movieDto.getMovieId(), user.getId()); Movie movieEntity = movieOpt.isPresent() ? movieOpt.get() : null; if (movieOpt.isEmpty()) { LOG.info("Movie not found by id"); List<Movie> movies = this.movieRep.findByTitleAndRelDate(movieDto.getTitle(), movieDto.getReleaseDate(), this.userDetailService.getCurrentUser(bearerStr).getId()); if (!movies.isEmpty()) { LOG.info("Movie found by Title and Reldate"); movieEntity = movies.get(0); movieEntity.setMovieId(movieDto.getId()); } else { LOG.info("creating new Movie"); movieEntity = this.mapper.convert(movieDto); movieEntity.setMovieId(movieDto.getId()); for (Long genId : movieDto.getGenres().stream().map(myGenere -> myGenere.getId()).toList()) { Optional<Genere> myResult = generes.stream() .filter(myGenere -> genId.equals(myGenere.getGenereId())).findFirst(); if (myResult.isPresent()) { movieEntity.getGeneres().add(myResult.get()); myResult.get().getMovies().add(movieEntity); } } movieEntity = this.movieRep.save(movieEntity); } } if (!movieEntity.getUsers().contains(user)) { LOG.info("adding user to movie"); movieEntity.getUsers().add(user); }
WrapperCastDto wrCast = this.movieDbRestClient.fetchCast(this.decrypt(user.getMoviedbkey(), user.getUuid()),
8
2023-12-11 13:53:51+00:00
12k
i-moonlight/Suricate
src/test/java/com/michelin/suricate/services/git/GitServiceTest.java
[ { "identifier": "Library", "path": "src/main/java/com/michelin/suricate/model/entities/Library.java", "snippet": "@Entity\n@Getter\n@Setter\n@ToString(callSuper = true)\n@NoArgsConstructor\npublic class Library extends AbstractAuditingEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String technicalName;\n\n @OneToOne(cascade = {CascadeType.REMOVE, CascadeType.DETACH})\n private Asset asset;\n\n @ToString.Exclude\n @ManyToMany(mappedBy = \"libraries\")\n private Set<Widget> widgets = new LinkedHashSet<>();\n\n public Library(String technicalName) {\n this.technicalName = technicalName;\n }\n\n /**\n * Hashcode method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Hashcode method\n *\n * @return The hash code\n */\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n /**\n * Equals method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Equals method\n *\n * @param other The other object to compare\n * @return true if equals, false otherwise\n */\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}" }, { "identifier": "Repository", "path": "src/main/java/com/michelin/suricate/model/entities/Repository.java", "snippet": "@Entity\n@Getter\n@Setter\n@ToString(callSuper = true)\n@NoArgsConstructor\npublic class Repository extends AbstractAuditingEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(unique = true)\n private String name;\n\n @Column\n private String url;\n\n @Column\n private String branch;\n\n @Column\n private String login;\n\n @Column\n private String password;\n\n @Column\n private String localPath;\n\n @Column(nullable = false)\n @Enumerated(EnumType.STRING)\n private RepositoryTypeEnum type;\n\n @Column(nullable = false)\n @Convert(converter = YesNoConverter.class)\n private boolean enabled = true;\n\n @Column(nullable = false)\n private int priority;\n\n @ToString.Exclude\n @OneToMany(mappedBy = \"repository\")\n private Set<Widget> widgets = new LinkedHashSet<>();\n\n /**\n * Hashcode method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Hashcode method\n *\n * @return The hash code\n */\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n /**\n * Equals method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Equals method\n *\n * @param other The other object to compare\n * @return true if equals, false otherwise\n */\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}" }, { "identifier": "RepositoryTypeEnum", "path": "src/main/java/com/michelin/suricate/model/enums/RepositoryTypeEnum.java", "snippet": "public enum RepositoryTypeEnum {\n REMOTE,\n LOCAL\n}" }, { "identifier": "ApplicationProperties", "path": "src/main/java/com/michelin/suricate/properties/ApplicationProperties.java", "snippet": "@Getter\n@Setter\n@Configuration\n@PropertySource(\"classpath:application.properties\")\n@ConfigurationProperties(prefix = \"application\", ignoreUnknownFields = false)\npublic class ApplicationProperties {\n private CorsConfiguration cors;\n private Authentication authentication;\n private Ssl ssl;\n private Widgets widgets;\n private Swagger swagger;\n\n /**\n * Authentication properties.\n */\n @Getter\n @Setter\n public static class Authentication {\n private Ldap ldap;\n private Jwt jwt;\n private PersonalAccessToken pat;\n private Oauth2 oauth2;\n @Pattern(regexp = \"ldap|database\")\n private String provider;\n private List<String> socialProviders;\n private Map<String, SocialProvidersConfig> socialProvidersConfig = new HashMap<>();\n }\n\n /**\n * LDAP properties.\n */\n @Getter\n @Setter\n public static class Ldap {\n private String url;\n private String userSearchFilter;\n private String userSearchBase = StringUtils.EMPTY;\n private String userDnPatterns = StringUtils.EMPTY;\n private String username = StringUtils.EMPTY;\n private String password = StringUtils.EMPTY;\n private String firstNameAttributeName;\n private String lastNameAttributeName;\n private String mailAttributeName;\n }\n\n /**\n * JWT properties.\n */\n @Getter\n @Setter\n public static class Jwt {\n @NotNull\n private long tokenValidityMs;\n\n @NotNull\n private String signingKey;\n }\n\n /**\n * Personal Access Token properties.\n */\n @Getter\n @Setter\n public static class PersonalAccessToken {\n @NotNull\n private String prefix;\n\n @NotNull\n private String checksumSecret;\n }\n\n /**\n * OAuth2 properties.\n */\n @Getter\n @Setter\n public static class Oauth2 {\n private String defaultTargetUrl;\n private boolean useReferer;\n }\n\n /**\n * SSL properties.\n */\n @Getter\n @Setter\n public static class Ssl {\n private KeyStore keyStore;\n private TrustStore trustStore;\n }\n\n /**\n * KeyStore properties.\n */\n @Getter\n @Setter\n public static class KeyStore {\n private String path;\n private String password;\n private String type;\n }\n\n /**\n * TrustStore properties.\n */\n @Getter\n @Setter\n public static class TrustStore {\n private String path;\n private String password;\n private String type;\n }\n\n /**\n * Widgets properties.\n */\n @Getter\n @Setter\n public static class Widgets {\n @NotNull\n private boolean updateEnable;\n private String cloneDir = \"/tmp\";\n }\n\n /**\n * Swagger properties.\n */\n @Getter\n @Setter\n public static class Swagger {\n private String title;\n private String description;\n private String version;\n private String termsOfServiceUrl;\n private String license;\n private String licenseUrl;\n private String groupName;\n private String protocols;\n private String contactName;\n private String contactUrl;\n private String contactEmail;\n }\n\n /**\n * Social providers properties.\n */\n @Getter\n @Setter\n public static class SocialProvidersConfig {\n private boolean nameCaseParse;\n }\n}" }, { "identifier": "CategoryService", "path": "src/main/java/com/michelin/suricate/services/api/CategoryService.java", "snippet": "@Service\npublic class CategoryService {\n @Autowired\n private AssetService assetService;\n\n @Autowired\n private CategoryRepository categoryRepository;\n\n @Autowired\n private CategoryParametersService categoryParametersService;\n\n /**\n * Get all the categories.\n *\n * @return The list of categories\n */\n @Cacheable(\"widget-categories\")\n @Transactional(readOnly = true)\n public Page<Category> getAll(String search, Pageable pageable) {\n return categoryRepository.findAll(new CategorySearchSpecification(search), pageable);\n }\n\n /**\n * Find a category by technical name.\n *\n * @param technicalName The technical name of the category\n * @return The related category\n */\n public Category findByTechnicalName(final String technicalName) {\n return categoryRepository.findByTechnicalName(technicalName);\n }\n\n /**\n * Add or update a category.\n *\n * @param category The category to add or update\n */\n @Transactional\n public void addOrUpdateCategory(Category category) {\n if (category == null) {\n return;\n }\n\n Category existingCategory = findByTechnicalName(category.getTechnicalName());\n\n if (category.getImage() != null) {\n if (existingCategory != null && existingCategory.getImage() != null) {\n category.getImage().setId(existingCategory.getImage().getId());\n }\n\n assetService.save(category.getImage());\n }\n\n if (existingCategory != null) {\n category.setId(existingCategory.getId());\n }\n\n // Save the configurations\n List<CategoryParameter> categoryOldConfigurations = existingCategory != null\n ? new ArrayList<>(existingCategory.getConfigurations()) : new ArrayList<>();\n\n Set<CategoryParameter> categoryNewConfigurations = category.getConfigurations();\n category.setConfigurations(new HashSet<>());\n\n // Create/Update category\n categoryRepository.save(category);\n\n // Create/Update configurations\n if (categoryNewConfigurations != null && !categoryNewConfigurations.isEmpty()) {\n List<String> categoryNewConfigurationsKeys = categoryNewConfigurations\n .stream()\n .map(CategoryParameter::getId)\n .toList();\n\n for (CategoryParameter categoryConfiguration : categoryOldConfigurations) {\n if (!categoryNewConfigurationsKeys.contains(categoryConfiguration.getId())) {\n categoryParametersService.deleteOneByKey(categoryConfiguration.getId());\n }\n }\n\n categoryParametersService.addOrUpdateCategoryConfiguration(categoryNewConfigurations, category);\n }\n }\n\n /**\n * Get the parameters of the category linked with the given widget.\n *\n * @param widget The widget\n * @return The category parameters\n */\n public List<WidgetParam> getCategoryParametersByWidget(final Widget widget) {\n Optional<List<CategoryParameter>> configurationsOptional = categoryParametersService\n .getParametersByCategoryId(widget.getCategory().getId());\n\n return configurationsOptional\n .map(configurations -> configurations\n .stream()\n .map(CategoryParametersService::convertCategoryParametersToWidgetParameters)\n .toList())\n .orElseGet(ArrayList::new);\n }\n}" }, { "identifier": "LibraryService", "path": "src/main/java/com/michelin/suricate/services/api/LibraryService.java", "snippet": "@Service\npublic class LibraryService {\n @Autowired\n private LibraryRepository libraryRepository;\n\n @Autowired\n private AssetService assetService;\n\n /**\n * Get all the libraries.\n *\n * @return The list of libraries\n */\n @Transactional(readOnly = true)\n public Page<Library> getAll(String search, Pageable pageable) {\n return libraryRepository.findAll(new LibrarySearchSpecification(search), pageable);\n }\n\n /**\n * Get all libraries of a project.\n *\n * @param project The project\n * @return The libraries\n */\n @Transactional(readOnly = true)\n public List<Library> getLibrariesByProject(Project project) {\n List<Long> widgetIds = project.getGrids()\n .stream()\n .map(ProjectGrid::getWidgets)\n .flatMap(Collection::stream)\n .map(projectWidget -> projectWidget.getWidget().getId())\n .distinct()\n .toList();\n\n if (widgetIds.isEmpty()) {\n return Collections.emptyList();\n }\n\n return libraryRepository.findDistinctByWidgetsIdIn(widgetIds);\n }\n\n /**\n * Get all library tokens of a project.\n *\n * @param project The project\n * @return The library tokens\n */\n @Transactional(readOnly = true)\n public List<String> getLibraryTokensByProject(Project project) {\n return getLibrariesByProject(project)\n .stream()\n .map(library -> library.getAsset().getId())\n .map(IdUtils::encrypt)\n .toList();\n }\n\n /**\n * Create or update a list of libraries.\n *\n * @param libraries All the libraries to create/update\n * @return The created/updated libraries\n */\n @Transactional\n public List<Library> createUpdateLibraries(List<Library> libraries) {\n if (libraries == null) {\n return Collections.emptyList();\n }\n\n for (Library library : libraries) {\n Library lib = libraryRepository.findByTechnicalName(library.getTechnicalName());\n\n if (library.getAsset() != null) {\n if (lib != null && lib.getAsset() != null) {\n library.getAsset().setId(lib.getAsset().getId());\n }\n assetService.save(library.getAsset());\n }\n\n if (lib != null) {\n library.setId(lib.getId());\n }\n }\n\n libraryRepository.saveAll(libraries);\n\n return libraryRepository.findAll();\n }\n}" }, { "identifier": "RepositoryService", "path": "src/main/java/com/michelin/suricate/services/api/RepositoryService.java", "snippet": "@Service\npublic class RepositoryService {\n @Autowired\n private RepositoryRepository repositoryRepository;\n\n /**\n * Get all repositories.\n *\n * @param search The search string\n * @param pageable The pageable object\n * @return The paginated list of repositories\n */\n @Transactional(readOnly = true)\n public Page<Repository> getAll(String search, Pageable pageable) {\n return repositoryRepository.findAll(new RepositorySearchSpecification(search), pageable);\n }\n\n /**\n * Get the full list of repository by enabled.\n *\n * @param enabled Tru if we want every enabled repositories\n * @return The related list\n */\n @Transactional(readOnly = true)\n public Optional<List<Repository>> findAllByEnabledOrderByPriorityDescCreatedDateAsc(final boolean enabled) {\n return repositoryRepository.findAllByEnabledOrderByPriorityDescCreatedDateAsc(enabled);\n }\n\n /**\n * Get the repository by id.\n *\n * @param repositoryId The repository id to find\n * @return The repository as optional\n */\n @Transactional(readOnly = true)\n public Optional<Repository> getOneById(final Long repositoryId) {\n return repositoryRepository.findById(repositoryId);\n }\n\n /**\n * Get the repository by name.\n *\n * @param name The repository name\n * @return The repository as optional\n */\n @Transactional(readOnly = true)\n public Optional<Repository> findByName(final String name) {\n return repositoryRepository.findByName(name);\n }\n\n /**\n * Check if the repository exists.\n *\n * @param repositoryId The repository id to check\n * @return True if exist false otherwise\n */\n @Transactional(readOnly = true)\n public boolean existsById(final Long repositoryId) {\n return repositoryRepository.existsById(repositoryId);\n }\n\n /**\n * Add or update a repository.\n *\n * @param repository The repository to process\n */\n @Transactional\n public void addOrUpdateRepository(Repository repository) {\n repositoryRepository.save(repository);\n }\n\n /**\n * Add or update a list of repositories.\n *\n * @param repositories All the repositories to add/update\n */\n @Transactional\n public void addOrUpdateRepositories(List<Repository> repositories) {\n repositoryRepository.saveAll(repositories);\n }\n}" }, { "identifier": "WidgetService", "path": "src/main/java/com/michelin/suricate/services/api/WidgetService.java", "snippet": "@Slf4j\n@Service\npublic class WidgetService {\n @Autowired\n private AssetService assetService;\n\n @Autowired\n private WidgetRepository widgetRepository;\n\n @Autowired\n private WidgetParamRepository widgetParamRepository;\n\n @Autowired\n private CategoryService categoryService;\n\n /**\n * Find a widget by id.\n *\n * @param id The id\n * @return The widget\n */\n @Transactional(readOnly = true)\n public Optional<Widget> findOne(final Long id) {\n return widgetRepository.findById(id);\n }\n\n /**\n * Find a widget by technical name.\n *\n * @param technicalName The technical name\n * @return The widget\n */\n @Transactional(readOnly = true)\n public Optional<Widget> findOneByTechnicalName(final String technicalName) {\n return widgetRepository.findByTechnicalName(technicalName);\n }\n\n /**\n * Return every widgets order by category name.\n *\n * @return The list of widgets order by category name\n */\n @Transactional(readOnly = true)\n public Page<Widget> getAll(String search, Pageable pageable) {\n return widgetRepository.findAll(new WidgetSearchSpecification(search), pageable);\n }\n\n /**\n * Get every widget for a category.\n *\n * @param categoryId The category id used for found widgets\n * @return The list of related widgets\n */\n @Transactional\n public Optional<List<Widget>> getWidgetsByCategory(final Long categoryId) {\n List<Widget> widgets = widgetRepository.findAllByCategoryIdOrderByNameAsc(categoryId);\n\n if (widgets == null || widgets.isEmpty()) {\n return Optional.empty();\n }\n\n return Optional.of(widgets);\n }\n\n /**\n * Return the full list of parameters of a widget including the parameters of the widget\n * and the global parameters of the category.\n *\n * @param widget The widget\n * @return A list of parameters\n */\n @Transactional\n public List<WidgetParam> getWidgetParametersWithCategoryParameters(final Widget widget) {\n List<WidgetParam> widgetParameters = new ArrayList<>(widget.getWidgetParams());\n widgetParameters.addAll(categoryService.getCategoryParametersByWidget(widget));\n\n return widgetParameters;\n }\n\n /**\n * Get the list of widget parameters.\n *\n * @param widget The widget\n * @return The list of widget parameters\n */\n @Transactional\n public List<WidgetVariableResponseDto> getWidgetParametersForJsExecution(final Widget widget) {\n List<WidgetVariableResponseDto> widgetVariableResponseDtos = new ArrayList<>();\n\n List<WidgetParam> widgetParameters = getWidgetParametersWithCategoryParameters(widget);\n\n for (WidgetParam widgetParameter : widgetParameters) {\n WidgetVariableResponseDto widgetVariableResponseDto = new WidgetVariableResponseDto();\n widgetVariableResponseDto.setName(widgetParameter.getName());\n widgetVariableResponseDto.setDescription(widgetParameter.getDescription());\n widgetVariableResponseDto.setType(widgetParameter.getType());\n widgetVariableResponseDto.setDefaultValue(widgetParameter.getDefaultValue());\n\n if (widgetVariableResponseDto.getType() == DataTypeEnum.COMBO\n || widgetVariableResponseDto.getType() == DataTypeEnum.MULTIPLE) {\n widgetVariableResponseDto.setValues(\n getWidgetParamValuesAsMap(widgetParameter.getPossibleValuesMap()));\n } else {\n widgetVariableResponseDto.setData(StringUtils.trimToNull(widgetParameter.getDefaultValue()));\n }\n\n widgetVariableResponseDtos.add(widgetVariableResponseDto);\n }\n\n return widgetVariableResponseDtos;\n }\n\n /**\n * Update a widget.\n *\n * @param widgetId The widget id to update\n * @param widgetRequestDto The object that holds changes\n * @return The widget update\n */\n @Transactional\n public Optional<Widget> updateWidget(final Long widgetId, final WidgetRequestDto widgetRequestDto) {\n Optional<Widget> widgetToBeModified = findOne(widgetId);\n if (widgetToBeModified.isPresent()) {\n widgetToBeModified.get().setWidgetAvailability(widgetRequestDto.getWidgetAvailability());\n return Optional.of(widgetRepository.save(widgetToBeModified.get()));\n }\n\n return Optional.empty();\n }\n\n /**\n * Add or update the given widgets from the given repository\n * Find the matching existing widget if it exists.\n * Update the libraries of the widget.\n * Update the image of the widget.\n * Update the parameters of the widget. If the new widget does not contain some\n * parameters anymore, then delete these parameters.\n * Set the activated state by default to the widget.\n * Set the category and the repository to the widget.\n *\n * @param category The category\n * @param libraries The libraries\n * @param repository The git repository\n */\n @Transactional\n public void addOrUpdateWidgets(Category category, List<Library> libraries, final Repository repository) {\n if (category == null || category.getWidgets() == null) {\n return;\n }\n\n for (Widget widget : category.getWidgets()) {\n Optional<Widget> currentWidget = widgetRepository.findByTechnicalName(widget.getTechnicalName());\n\n if (widget.getLibraries() != null && !widget.getLibraries().isEmpty() && libraries != null) {\n List<Library> widgetLibraries = new ArrayList<>(widget.getLibraries());\n\n widgetLibraries.replaceAll(widgetLibrary -> libraries\n .stream()\n .filter(library -> library.getTechnicalName().equals(widgetLibrary.getTechnicalName()))\n .findFirst().orElse(null));\n\n widget.setLibraries(new HashSet<>(widgetLibraries));\n }\n\n if (widget.getImage() != null) {\n if (currentWidget.isPresent() && currentWidget.get().getImage() != null) {\n widget.getImage().setId(currentWidget.get().getImage().getId());\n }\n\n assetService.save(widget.getImage());\n }\n\n // Replace the existing list of params and values by the new one\n if (widget.getWidgetParams() != null && !widget.getWidgetParams().isEmpty()\n && currentWidget.isPresent() && currentWidget.get().getWidgetParams() != null\n && !currentWidget.get().getWidgetParams().isEmpty()) {\n\n Set<WidgetParam> currentWidgetParams = currentWidget.get().getWidgetParams();\n\n widget.getWidgetParams().forEach(widgetParam -> {\n Optional<WidgetParam> widgetParamToFind = currentWidgetParams\n .stream()\n .filter(currentParam -> currentParam.getName().equals(widgetParam.getName()))\n .findAny();\n\n widgetParamToFind.ifPresent(currentWidgetParamFound -> {\n // Set the ID of the new object with the current one\n widgetParam.setId(currentWidgetParamFound.getId());\n\n // Search params with the current WidgetParam in DB\n if (widgetParam.getPossibleValuesMap() != null\n && !widgetParam.getPossibleValuesMap().isEmpty()\n && currentWidgetParamFound.getPossibleValuesMap() != null\n && !currentWidgetParamFound.getPossibleValuesMap().isEmpty()) {\n\n widgetParam.getPossibleValuesMap().forEach(possibleValueMap -> {\n //Search the current widget possible values in DB\n Optional<WidgetParamValue> possibleValueMapToFind =\n currentWidgetParamFound.getPossibleValuesMap()\n .stream()\n .filter(currentPossibleValueMap -> currentPossibleValueMap.getJsKey()\n .equals(possibleValueMap.getJsKey()))\n .findAny();\n //Set ID of the new object with the current one in DB\n possibleValueMapToFind.ifPresent(\n possibleValueMapFound -> possibleValueMap.setId(possibleValueMapFound.getId()));\n });\n }\n });\n });\n }\n\n // Set ID and remove parameters which are not present anymore\n if (currentWidget.isPresent()) {\n widget.setWidgetAvailability(\n currentWidget.get().getWidgetAvailability()); // Keep the previous widget state\n widget.setId(currentWidget.get().getId());\n\n for (WidgetParam oldWidgetParameter : currentWidget.get().getWidgetParams()) {\n if (!widget.getWidgetParams().contains(oldWidgetParameter)) {\n widgetParamRepository.deleteById(oldWidgetParameter.getId());\n }\n }\n }\n\n if (widget.getWidgetAvailability() == null) {\n widget.setWidgetAvailability(WidgetAvailabilityEnum.ACTIVATED);\n }\n\n widget.setCategory(category);\n widget.setRepository(repository);\n\n widgetRepository.save(widget);\n\n log.info(\"Widget {} updated from the branch {} of the repository {}\", widget.getTechnicalName(),\n widget.getRepository().getBranch(), widget.getRepository().getName());\n }\n }\n\n /**\n * Get the widget param list as a Map.\n *\n * @param widgetParamValues The list of the widget param values\n * @return The list\n */\n public Map<String, String> getWidgetParamValuesAsMap(Set<WidgetParamValue> widgetParamValues) {\n return widgetParamValues\n .stream()\n .collect(Collectors.toMap(WidgetParamValue::getJsKey, WidgetParamValue::getValue));\n }\n}" }, { "identifier": "CacheService", "path": "src/main/java/com/michelin/suricate/services/cache/CacheService.java", "snippet": "@Slf4j\n@Service\npublic class CacheService {\n @Autowired\n private CacheManager cacheManager;\n\n /**\n * Clear all caches.\n */\n public void clearAllCache() {\n cacheManager.getCacheNames().forEach(this::clearCache);\n }\n\n /**\n * Method used to clear cache by cache name.\n *\n * @param cacheName the cache name to clear\n */\n public void clearCache(String cacheName) {\n Cache cache = cacheManager.getCache(cacheName);\n if (cache != null) {\n cache.clear();\n log.debug(\"Cache {} cleared\", cacheName);\n }\n }\n}" }, { "identifier": "JsExecutionScheduler", "path": "src/main/java/com/michelin/suricate/services/js/scheduler/JsExecutionScheduler.java", "snippet": "@Slf4j\n@Service\npublic class JsExecutionScheduler {\n private static final int EXECUTOR_POOL_SIZE = 60;\n\n private static final long JS_IMMEDIATE_EXECUTION_DELAY = 1L;\n\n private final Map<Long, Pair<WeakReference<ScheduledFuture<JsResultDto>>,\n WeakReference<ScheduledFuture<Void>>>> jsTasksByProjectWidgetId = new ConcurrentHashMap<>();\n\n private ScheduledThreadPoolExecutor jsExecutionExecutor;\n\n private ScheduledThreadPoolExecutor jsResultExecutor;\n\n @Autowired\n private ApplicationContext applicationContext;\n\n @Lazy\n @Autowired\n private ProjectWidgetService projectWidgetService;\n\n @Autowired\n private WidgetService widgetService;\n\n @Autowired\n private JsExecutionService jsExecutionService;\n\n @Lazy\n @Autowired\n private DashboardScheduleService dashboardScheduleService;\n\n @Autowired\n @Qualifier(\"jasyptStringEncryptor\")\n private StringEncryptor stringEncryptor;\n\n /**\n * Init the Js executors.\n */\n @Transactional\n public void init() {\n log.debug(\"Initializing the JavaScript executors\");\n\n if (jsExecutionExecutor != null) {\n jsExecutionExecutor.shutdownNow();\n }\n\n jsExecutionExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(EXECUTOR_POOL_SIZE);\n jsExecutionExecutor.setRemoveOnCancelPolicy(true);\n\n if (jsResultExecutor != null) {\n jsResultExecutor.shutdownNow();\n }\n\n jsResultExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(EXECUTOR_POOL_SIZE);\n jsResultExecutor.setRemoveOnCancelPolicy(true);\n\n jsTasksByProjectWidgetId.clear();\n\n projectWidgetService.resetProjectWidgetsState();\n }\n\n /**\n * Schedule a list of Js executions.\n *\n * @param jsExecutionDtos The list of Js execution to schedule\n * @param startJsRequestNow Should the Js execution starts now or from the widget configured delay\n */\n public void scheduleJsRequests(final List<JsExecutionDto> jsExecutionDtos, boolean startJsRequestNow) {\n try {\n jsExecutionDtos.forEach(jsExecRequest -> schedule(jsExecRequest, startJsRequestNow));\n } catch (Exception e) {\n log.error(\"An error has occurred when scheduling a JavaScript request for a new project subscription\", e);\n }\n }\n\n /**\n * Method used to schedule the Js execution updating the associated widget.\n * Checks if the given Js execution can be executed and set the widget in a pause state\n * if it cannot be.\n * If the widget was in a pause state from a previous execution, then set the widget in a running\n * state before executing the request.\n * Create an asynchronous task which will execute the Js execution and execute the widget. Schedule\n * this task according to the computed delay.\n * Create another asynchronous task which will wait for the result of the first task\n * (the result of the widget execution).\n * It waits during the whole duration set in the widget description as timeout.\n *\n * @param jsExecutionDto The Js execution\n * @param startJsRequestNow Should the Js execution starts now or from the widget configured delay\n */\n public void schedule(final JsExecutionDto jsExecutionDto, final boolean startJsRequestNow) {\n if (jsExecutionDto == null || jsExecutionExecutor == null || jsResultExecutor == null) {\n return;\n }\n\n log.debug(\"Scheduling the JavaScript execution of the widget instance {}\", jsExecutionDto.getProjectWidgetId());\n\n if (!jsExecutionService.isJsExecutable(jsExecutionDto)) {\n projectWidgetService.updateState(WidgetStateEnum.STOPPED, jsExecutionDto.getProjectWidgetId(), new Date());\n return;\n }\n\n if (WidgetStateEnum.STOPPED == jsExecutionDto.getWidgetState()) {\n log.debug(\n \"The widget instance {} of the JavaScript execution was stopped. \"\n + \"Setting the widget instance to running\", jsExecutionDto.getProjectWidgetId());\n projectWidgetService.updateState(WidgetStateEnum.RUNNING, jsExecutionDto.getProjectWidgetId(), new Date());\n }\n\n ProjectWidget projectWidget = projectWidgetService\n .getOne(jsExecutionDto.getProjectWidgetId()).orElse(new ProjectWidget());\n\n List<WidgetVariableResponseDto> widgetParameters = widgetService\n .getWidgetParametersForJsExecution(projectWidget.getWidget());\n\n long jsRequestExecutionDelay = startJsRequestNow ? JS_IMMEDIATE_EXECUTION_DELAY : jsExecutionDto.getDelay();\n\n log.debug(\"The JavaScript execution of the widget instance {} will start in {} second(s)\",\n jsExecutionDto.getProjectWidgetId(), jsRequestExecutionDelay);\n\n ScheduledFuture<JsResultDto> scheduledJsRequestTask = jsExecutionExecutor\n .schedule(new JsExecutionAsyncTask(jsExecutionDto, stringEncryptor, widgetParameters),\n jsRequestExecutionDelay,\n TimeUnit.SECONDS);\n\n JsResultAsyncTask jsResultAsyncTask = applicationContext\n .getBean(JsResultAsyncTask.class, scheduledJsRequestTask, jsExecutionDto, this, dashboardScheduleService);\n\n ScheduledFuture<Void> scheduledJsResponseTask = jsResultExecutor\n .schedule(jsResultAsyncTask, jsRequestExecutionDelay, TimeUnit.SECONDS);\n\n jsTasksByProjectWidgetId.put(jsExecutionDto.getProjectWidgetId(), ImmutablePair.of(\n new WeakReference<>(scheduledJsRequestTask),\n new WeakReference<>(scheduledJsResponseTask)\n ));\n }\n\n /**\n * Cancel the current widget execution and schedule a new Js execution for this widget.\n *\n * @param jsExecutionDto The new Js execution to schedule\n */\n public void cancelAndScheduleJsExecution(JsExecutionDto jsExecutionDto) {\n cancelWidgetExecution(jsExecutionDto.getProjectWidgetId());\n schedule(jsExecutionDto, true);\n }\n\n /**\n * Cancel all the widgets executions from a given project.\n *\n * @param project The project\n */\n public void cancelWidgetsExecutionByProject(final Project project) {\n project.getGrids()\n .stream()\n .map(ProjectGrid::getWidgets)\n .flatMap(Collection::stream)\n .toList()\n .forEach(projectWidget -> cancelWidgetExecution(projectWidget.getId()));\n }\n\n /**\n * Cancel all the widgets executions from a given project grid.\n *\n * @param projectGrid The project grid\n */\n public void cancelWidgetsExecutionByGrid(final ProjectGrid projectGrid) {\n projectGrid\n .getWidgets()\n .forEach(projectWidget -> cancelWidgetExecution(projectWidget.getId()));\n }\n\n /**\n * Cancel the widget execution by canceling both Js tasks.\n *\n * @param projectWidgetId the widget instance ID\n */\n public void cancelWidgetExecution(Long projectWidgetId) {\n Pair<WeakReference<ScheduledFuture<JsResultDto>>, WeakReference<ScheduledFuture<Void>>> pairOfJsFutureTasks =\n jsTasksByProjectWidgetId.get(projectWidgetId);\n\n if (pairOfJsFutureTasks != null) {\n cancelScheduledFutureTask(projectWidgetId, pairOfJsFutureTasks.getLeft());\n cancelScheduledFutureTask(projectWidgetId, pairOfJsFutureTasks.getRight());\n }\n\n projectWidgetService.updateState(WidgetStateEnum.STOPPED, projectWidgetId);\n }\n\n /**\n * Cancel a scheduled future task for a widget instance.\n *\n * @param projectWidgetId The widget instance ID\n * @param scheduledFutureTaskReference The reference containing the future task\n */\n public void cancelScheduledFutureTask(Long projectWidgetId,\n WeakReference<? extends ScheduledFuture<?>> scheduledFutureTaskReference) {\n if (scheduledFutureTaskReference != null) {\n ScheduledFuture<?> scheduledFutureTask = scheduledFutureTaskReference.get();\n\n if (scheduledFutureTask != null && (!scheduledFutureTask.isDone() || !scheduledFutureTask.isCancelled())) {\n log.debug(\"Canceling the future JavaScript execution task for the widget instance {}\", projectWidgetId);\n\n scheduledFutureTask.cancel(true);\n }\n }\n }\n}" }, { "identifier": "DashboardWebSocketService", "path": "src/main/java/com/michelin/suricate/services/websocket/DashboardWebSocketService.java", "snippet": "@Slf4j\n@Lazy(false)\n@Service\npublic class DashboardWebSocketService {\n private final Multimap<String, WebsocketClient> websocketClientByProjectToken =\n Multimaps.synchronizedListMultimap(ArrayListMultimap.create());\n\n @Autowired\n private JsExecutionScheduler jsExecutionScheduler;\n\n @Autowired\n private SimpMessagingTemplate simpMessagingTemplate;\n\n @Lazy\n @Autowired\n private ProjectService projectService;\n\n @Lazy\n @Autowired\n private ProjectMapper projectMapper;\n\n @Autowired\n private JsExecutionService jsExecutionService;\n\n /**\n * Send a connect project event through the associated websocket to the unique subscriber.\n * The path of the websocket contains a screen code so it is unique for each\n * screen (so each subscriber).\n * Used to connect a screen to a dashboard just after the subscriber waits on the screen code\n * waiting screen.\n *\n * @param project The project\n * @param screenCode The unique screen code\n */\n public void sendConnectProjectEventToScreenSubscriber(final Project project, final String screenCode) {\n UpdateEvent updateEvent = UpdateEvent.builder()\n .type(UpdateType.CONNECT_DASHBOARD)\n .content(projectMapper.toProjectDto(project))\n .build();\n\n log.debug(\"Sending the event {} to the screen {}\", updateEvent.getType(),\n screenCode.replaceAll(\"[\\n\\r\\t]\", \"_\"));\n\n simpMessagingTemplate.convertAndSendToUser(\n screenCode,\n \"/queue/connect\",\n updateEvent\n );\n }\n\n /**\n * Send an event through the associated websocket to all subscribers.\n * The path of the websocket contains a project token and a project widget ID so it is unique for each\n * project widget.\n * Used to update a widget.\n *\n * @param projectToken The project token\n * @param projectWidgetId The project widget id\n * @param payload The payload content\n */\n @Async\n public void sendEventToWidgetInstanceSubscribers(final String projectToken, final Long projectWidgetId,\n final UpdateEvent payload) {\n log.debug(\"Sending the event {} for the widget instance {} of the project {}\", payload.getType(),\n projectWidgetId, projectToken);\n\n if (projectToken == null) {\n log.error(\"Project token null for payload: {}\", payload);\n return;\n }\n\n if (projectWidgetId == null) {\n log.error(\"Widget instance ID null for payload: {}\", payload);\n return;\n }\n\n simpMessagingTemplate.convertAndSendToUser(\n projectToken.trim() + \"-projectWidget-\" + projectWidgetId,\n \"/queue/live\",\n payload\n );\n }\n\n /**\n * Send an event through the associated websocket to all subscribers.\n * The path of the websocket contains a project token so it is unique for each\n * project.\n * Used to reload a project,\n * display the screen code number of a project,\n * disconnect all screens from a project\n * or reposition a widget of a project.\n *\n * @param projectToken The project token\n * @param payload The payload content\n */\n @Async\n public void sendEventToProjectSubscribers(String projectToken, UpdateEvent payload) {\n log.debug(\"Sending the event {} to the project {}\", payload.getType(), projectToken);\n\n if (projectToken == null) {\n log.error(\"Project token null for payload: {}\", payload);\n return;\n }\n\n simpMessagingTemplate.convertAndSendToUser(\n projectToken.trim(),\n \"/queue/live\",\n payload\n );\n }\n\n /**\n * Add a new link between a project (dashboard) materialized by its projectToken\n * and a client materialized by its WebsocketClient.\n * Triggered when a new subscription to a dashboard is done.\n * If no client is connected to the dashboard already,\n * initialize a Js execution for each widget of the project to refresh them.\n *\n * @param project The connected project\n * @param websocketClient The related websocket client\n */\n public void addClientToProject(final Project project, final WebsocketClient websocketClient) {\n boolean refreshProject = !websocketClientByProjectToken.containsKey(project.getToken());\n websocketClientByProjectToken.put(project.getToken(), websocketClient);\n\n if (refreshProject) {\n List<JsExecutionDto> jsExecutionDtos = jsExecutionService.getJsExecutionsByProject(project);\n jsExecutionScheduler.scheduleJsRequests(jsExecutionDtos, true);\n }\n }\n\n /**\n * Get the list of every connected dashboard.\n *\n * @param projectToken The project token used for find every websocket clients\n * @return The list of related websocket clients\n */\n public List<WebsocketClient> getWebsocketClientsByProjectToken(final String projectToken) {\n return new ArrayList<>(websocketClientByProjectToken.get(projectToken));\n }\n\n /**\n * Get a websocket by session ID.\n *\n * @param sessionId The session ID\n * @return The websocket\n */\n public Optional<WebsocketClient> getWebsocketClientsBySessionId(final String sessionId) {\n return websocketClientByProjectToken.values()\n .stream()\n .filter(websocketClient -> websocketClient.getSessionId().equals(sessionId))\n .findFirst();\n }\n\n /**\n * Count the number of connected clients.\n *\n * @return The websocket\n */\n public int countWebsocketClients() {\n return websocketClientByProjectToken.values().size();\n }\n\n /**\n * Get a websocket by session ID and subscription ID.\n *\n * @param sessionId The session ID\n * @param subscriptionId The subscription ID\n * @return The websocket\n */\n public Optional<WebsocketClient> getWebsocketClientsBySessionIdAndSubscriptionId(final String sessionId,\n final String subscriptionId) {\n return websocketClientByProjectToken.values()\n .stream()\n .filter(websocketClient -> websocketClient.getSessionId().equals(sessionId)\n && websocketClient.getSubscriptionId().equals(subscriptionId))\n .findFirst();\n }\n\n /**\n * Remove a given websocket from the project/connection map.\n *\n * @param websocketClient The websocket to remove\n */\n public void removeClientFromProject(WebsocketClient websocketClient) {\n websocketClientByProjectToken.remove(websocketClient.getProjectToken(), websocketClient);\n\n if (!websocketClientByProjectToken.containsKey(websocketClient.getProjectToken())) {\n projectService.getOneByToken(websocketClient.getProjectToken())\n .ifPresent(jsExecutionScheduler::cancelWidgetsExecutionByProject);\n }\n }\n\n /**\n * Disconnect screen from project.\n *\n * @param projectToken The project token\n * @param screenCode The screen code\n */\n @Async\n public void disconnectClient(final String projectToken, final String screenCode) {\n UpdateEvent payload = UpdateEvent.builder().type(UpdateType.DISCONNECT).build();\n\n log.info(\"Sending the event {} to the project {} of the screen {}\", payload.getType(), projectToken,\n screenCode.replaceAll(\"[\\n\\r\\t]\", \"_\"));\n\n simpMessagingTemplate.convertAndSendToUser(\n projectToken.trim() + \"-\" + screenCode,\n \"/queue/unique\",\n payload\n );\n }\n\n /**\n * Reload all the connected clients to all the projects.\n */\n public void reloadAllConnectedClientsToAllProjects() {\n websocketClientByProjectToken.forEach((key, value) -> reloadAllConnectedClientsToProject(key));\n }\n\n /**\n * Method that force the reloading of every connected clients for a project.\n *\n * @param projectToken The project token\n */\n public void reloadAllConnectedClientsToProject(final String projectToken) {\n if (!websocketClientByProjectToken.get(projectToken).isEmpty()) {\n sendEventToProjectSubscribers(projectToken, UpdateEvent.builder().type(UpdateType.RELOAD).build());\n }\n }\n}" } ]
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.michelin.suricate.model.entities.Library; import com.michelin.suricate.model.entities.Repository; import com.michelin.suricate.model.enums.RepositoryTypeEnum; import com.michelin.suricate.properties.ApplicationProperties; import com.michelin.suricate.services.api.CategoryService; import com.michelin.suricate.services.api.LibraryService; import com.michelin.suricate.services.api.RepositoryService; import com.michelin.suricate.services.api.WidgetService; import com.michelin.suricate.services.cache.CacheService; import com.michelin.suricate.services.js.scheduler.JsExecutionScheduler; import com.michelin.suricate.services.websocket.DashboardWebSocketService; import java.io.IOException; import java.util.Collections; import java.util.Optional; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension;
10,229
package com.michelin.suricate.services.git; @ExtendWith(MockitoExtension.class) class GitServiceTest { @Mock private JsExecutionScheduler jsExecutionScheduler; @Mock private ApplicationProperties applicationProperties; @Mock private WidgetService widgetService; @Mock private CategoryService categoryService; @Mock
package com.michelin.suricate.services.git; @ExtendWith(MockitoExtension.class) class GitServiceTest { @Mock private JsExecutionScheduler jsExecutionScheduler; @Mock private ApplicationProperties applicationProperties; @Mock private WidgetService widgetService; @Mock private CategoryService categoryService; @Mock
private LibraryService libraryService;
5
2023-12-11 11:28:37+00:00
12k
NaerQAQ/js4bukkit
src/main/java/org/js4bukkit/script/ScriptHandler.java
[ { "identifier": "Js4Bukkit", "path": "src/main/java/org/js4bukkit/Js4Bukkit.java", "snippet": "public class Js4Bukkit extends JavaPlugin {\n /**\n * 实例。\n */\n @Getter\n @Setter\n private static Js4Bukkit instance;\n\n /**\n * 服务器版本。\n */\n @Getter\n @Setter\n private static Double serverVersion;\n\n /**\n * 插件配置文件夹路径。\n */\n @Getter\n @Setter\n private static String dataFolderAbsolutePath;\n\n @Getter\n @Setter\n private static String nmsVersion;\n\n /**\n * 插件开启。\n *\n * @author 2000000\n */\n @Override\n @SneakyThrows\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public void onEnable() {\n setInstance(this);\n setDataFolderAbsolutePath(getDataFolder().getAbsolutePath());\n\n String serverPackage =\n getServer().getClass().getPackage().getName();\n\n setNmsVersion(\n serverPackage.replace(\".\", \",\").split(\",\")[3]\n );\n\n String[] arrayVersion = StringUtils.substringsBetween(\n serverPackage, \".v\", \"_R\"\n );\n\n String stringVersion = Arrays.toString(arrayVersion)\n .replace(\"_\", \"0\")\n .replace(\"[\", \"\")\n .replace(\"]\", \"\");\n\n setServerVersion(\n Double.parseDouble(stringVersion)\n );\n\n // 配置文件与注解处理\n ConfigManager.getConfig();\n AnnotatedClassProcessor.processAnnotatedClasses();\n\n // Maven 依赖与外部依赖加载\n MavenDependencyLoader.download();\n ThirdPartyJarLoader.load();\n\n // 脚本注册\n ScriptHandler.registerScripts();\n }\n\n /**\n * 插件卸载。\n *\n * @author 2000000\n */\n @Override\n public void onDisable() {\n ScriptHandler.unloadScripts();\n\n QuickUtils.sendMessage(\n ConsoleMessageTypeEnum.NORMAL,\n \"Plugin has been disabled.\"\n );\n }\n}" }, { "identifier": "ConfigManager", "path": "src/main/java/org/js4bukkit/io/config/ConfigManager.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ConfigManager {\n static {\n loadConfigs(\"configs\");\n loadConfigs(\"plugins\");\n }\n\n /**\n * {@code config.yml} 配置文件实例。\n */\n @Getter\n private static final Yaml config = YamlManager.getInstance().get(\n \"config\",\n Js4Bukkit.getDataFolderAbsolutePath() + \"/configs/\",\n true\n );\n\n /**\n * {@code language.yml} 配置文件实例。\n */\n @Getter\n private static final Yaml language = YamlManager.getInstance().get(\n \"language\",\n Js4Bukkit.getDataFolderAbsolutePath() + \"/configs/\",\n true\n );\n\n /**\n * {@code plugins.yml} 配置文件实例。\n */\n @Getter\n private static final Yaml plugins = YamlManager.getInstance().get(\n \"plugins\",\n Js4Bukkit.getDataFolderAbsolutePath() + \"/configs/\",\n true\n );\n\n /**\n * {@code maven-dependencies.yml} 配置文件实例。\n */\n @Getter\n private static final Yaml mavenDependencies = YamlManager.getInstance().get(\n \"maven-dependencies\",\n Js4Bukkit.getDataFolderAbsolutePath() + \"/configs/\",\n true\n );\n\n /**\n * 从 Jar 文件中加载指定文件夹内的配置文件。\n *\n * <p>\n * 该方法将配置文件从JAR文件复制到本地文件系统中的目标文件夹。\n * </p>\n *\n * <p>\n * 如果目标文件夹已经存在,则不执行任何操作。\n * </p>\n *\n * @param folder 文件夹名称\n */\n @SneakyThrows\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public static void loadConfigs(String folder) {\n // 路径构造\n String dataFolderAbsolutePath =\n Js4Bukkit.getDataFolderAbsolutePath();\n\n String targetFolder =\n dataFolderAbsolutePath + \"/\" + folder;\n\n File destinationFolder = new File(targetFolder);\n\n // 如果已经存在\n if (destinationFolder.exists()) {\n return;\n }\n\n // 读取 Jar\n String jarFilePath =\n Js4Bukkit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();\n\n @Cleanup JarFile jarFile = new JarFile(jarFilePath);\n\n Enumeration<JarEntry> entries = jarFile.entries();\n\n // 遍历条目\n while (entries.hasMoreElements()) {\n JarEntry entry = entries.nextElement();\n\n String entryName = entry.getName();\n\n // 如果不属于指定文件夹\n if (!entryName.startsWith(folder)) {\n continue;\n }\n\n // 删除文件夹前缀构造文件名\n String fileName = entryName.substring(folder.length());\n File destinationFile = new File(targetFolder, fileName);\n\n if (entry.isDirectory()) {\n destinationFile.mkdirs();\n continue;\n }\n\n FileUtils.copyInputStreamToFile(\n jarFile.getInputStream(entry), destinationFile\n );\n }\n }\n}" }, { "identifier": "CommandInterop", "path": "src/main/java/org/js4bukkit/script/interop/command/CommandInterop.java", "snippet": "@Getter\n@Setter\n@Accessors(chain = true)\npublic class CommandInterop implements InteropInterface {\n /**\n * 所有实例。\n */\n public static final Queue<CommandInterop> COMMAND_INTEROPS =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 指令主名。\n */\n private String name;\n\n /**\n * 指令别名。\n */\n private String aliases;\n\n /**\n * 描述。\n */\n private String description;\n\n /**\n * 用于处理指令执行的代码。\n */\n private TriFunction<CommandSender, String, String[], Boolean> commandExecute;\n\n /**\n * 用于处理 Tab 补全的代码。\n */\n private TriFunction<CommandSender, String, String[], List<String>> tabComplete;\n\n /**\n * Command 实例。\n */\n private Command command = null;\n\n /**\n * 注册指令。\n */\n @Override\n public void register() {\n toCommand();\n CommandUtils.registerCommand(command);\n COMMAND_INTEROPS.add(this);\n }\n\n /**\n * 注销指令。\n */\n @Override\n public void unregister() {\n if (command != null) {\n CommandUtils.unregister(command);\n COMMAND_INTEROPS.remove(this);\n }\n }\n\n /**\n * 转换 Command 实例。\n */\n private void toCommand() {\n command = new Command(name) {\n @Override\n public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {\n return commandExecute.apply(sender, commandLabel, args);\n }\n\n @NotNull\n @Override\n public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {\n return tabComplete.apply(sender, alias, args);\n }\n }.setAliases(Arrays.stream(aliases.split(\",\"))\n .map(String::trim)\n .collect(Collectors.toList()))\n .setDescription(description);\n }\n}" }, { "identifier": "EasyEventListenerInterop", "path": "src/main/java/org/js4bukkit/script/interop/listener/EasyEventListenerInterop.java", "snippet": "@Getter\n@Setter\n@SuppressWarnings(\"unchecked\")\npublic class EasyEventListenerInterop<T extends Event> implements InteropInterface {\n /**\n * 所有简易监听器。\n */\n public static final Queue<EasyEventListenerInterop<?>> EASY_EVENT_LISTENERS =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 所有简易监听器数据。\n */\n public static final Queue<EasyEventListenerData> EASY_EVENT_LISTENERS_DATA =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 执行的函数式接口。\n */\n private Consumer<T> executor;\n\n /**\n * 监听器数据。\n */\n private EventRegistrationInfo eventRegistrationInfo;\n\n /**\n * 通过名称获取简易事件监听器数据。\n *\n * @param name 名称\n * @return 简易事件监听器数据\n */\n public static EasyEventListenerData getEasyEventListenerDataWithName(String name) {\n return EASY_EVENT_LISTENERS_DATA.stream()\n .filter(data ->\n data.getEventListener().getEventRegistrationInfo().getName().equals(name)\n )\n .findFirst()\n .orElse(null);\n }\n\n /**\n * 处理事件的方法。\n *\n * @param event 事件对象\n */\n public void accept(Event event) {\n executor.accept((T) event);\n }\n\n /**\n * 注册事件监听。\n */\n public void register() {\n EASY_EVENT_LISTENERS.add(this);\n\n // 在已有监听器中通过 EventListenerInterop 获取 EventRegistrationInfo 一样的对象\n Optional<EasyEventListenerData> optionalData = EASY_EVENT_LISTENERS_DATA.stream()\n .filter(data ->\n data.getEventListener().getEventRegistrationInfo().equals(\n eventRegistrationInfo\n )\n )\n .findFirst();\n\n // 找到了则代表有 EasyEventListenerData 对象,将其添加进与之关联的简易事件监听器\n if (optionalData.isPresent()) {\n optionalData.get().getEasyEventListeners().add(this);\n return;\n }\n\n // 如果没找到则创建一个新提供服务的 EventListenerInterop\n org.js4bukkit.script.interop.listener.EventListenerInterop<T> eventListenerInterop = new EventListenerInterop<T>()\n .setEventRegistrationInfo(eventRegistrationInfo)\n // 从中获取所有 EventRegistrationInfo 一样的对象\n .setExecutor(event -> EASY_EVENT_LISTENERS_DATA.stream()\n .filter(data ->\n data.getEventListener().getEventRegistrationInfo().equals(\n eventRegistrationInfo\n )\n )\n // 遍历异步调用 accept\n .forEach(data -> data.getEasyEventListeners().forEach(easyEventListenerInterop -> new Scheduler()\n .setSchedulerTypeEnum(SchedulerTypeEnum.RUN)\n .setSchedulerExecutionMode(SchedulerExecutionMode.ASYNC)\n .setRunnable(() -> easyEventListenerInterop.accept(event))\n .run()\n )\n )\n );\n\n // 创建一个新队列并添加进去\n Queue<EasyEventListenerInterop<?>> easyEventListenerInterops =\n new ConcurrentLinkedQueue<>();\n easyEventListenerInterops.add(this);\n\n // 创建一个新的 EasyEventListenerData 对象\n EasyEventListenerData newEasyEventListenerData = new EasyEventListenerData()\n .setEventListener(eventListenerInterop)\n .setEasyEventListeners(easyEventListenerInterops);\n\n // 注册提供服务的常规事件监听器对象,并且添加 newEasyEventListenerData\n eventListenerInterop.register();\n EASY_EVENT_LISTENERS_DATA.add(newEasyEventListenerData);\n }\n\n /**\n * 注销事件监听。\n */\n public void unregister() {\n Optional.ofNullable(getEasyEventListenerData())\n .ifPresent(listenerData -> listenerData.remove(this));\n }\n\n /**\n * 获取简易事件监听器数据。\n *\n * @return 简易事件监听器数据\n */\n public EasyEventListenerData getEasyEventListenerData() {\n return getEasyEventListenerDataWithName(eventRegistrationInfo.getName());\n }\n}" }, { "identifier": "EventListenerInterop", "path": "src/main/java/org/js4bukkit/script/interop/listener/EventListenerInterop.java", "snippet": "@Getter\n@Setter\n@Accessors(chain = true)\npublic class EventListenerInterop<T extends Event> implements InteropInterface {\n /**\n * 监听列表。\n */\n public static final Queue<EventListenerInterop<?>> EVENT_LISTENERS =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 执行的函数式接口。\n */\n private Consumer<T> executor;\n\n /**\n * 监听器数据。\n */\n private EventRegistrationInfo eventRegistrationInfo;\n\n /**\n * 注册事件监听。\n */\n @Override\n @SuppressWarnings(\"unchecked\")\n public void register() {\n EVENT_LISTENERS.add(this);\n\n Bukkit.getPluginManager().registerEvent(\n eventRegistrationInfo.getEventClass(),\n eventRegistrationInfo.getListener(),\n eventRegistrationInfo.getEventPriority(),\n (listener, event) -> executor.accept((T) event),\n Js4Bukkit.getInstance(),\n eventRegistrationInfo.isIgnoreCancelled()\n );\n }\n\n /**\n * 注销事件监听。\n */\n @Override\n public void unregister() {\n EVENT_LISTENERS.remove(this);\n HandlerList.unregisterAll(eventRegistrationInfo.getListener());\n }\n}" }, { "identifier": "PlaceholderInterop", "path": "src/main/java/org/js4bukkit/script/interop/placeholder/PlaceholderInterop.java", "snippet": "@Getter\n@Setter\n@Accessors(chain = true)\npublic class PlaceholderInterop implements InteropInterface {\n /**\n * 所有实例。\n */\n public static final Queue<PlaceholderInterop> PLACEHOLDER_INTEROPS =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 作者。\n */\n private String author;\n\n /**\n * 版本。\n */\n private String version;\n\n /**\n * 标识符。\n */\n private String identifier;\n\n /**\n * 用于处理占位符执行的函数。\n */\n private BiFunction<OfflinePlayer, String, String> executor;\n\n /**\n * PlaceholderExpansion 实例。\n */\n private PlaceholderExpansion placeholderExpansion = null;\n\n /**\n * 注册 PlaceholderExpansion 实例。\n */\n @Override\n public void register() {\n boolean succeed = toPlaceholderExpansion();\n\n if (!succeed) {\n return;\n }\n\n PLACEHOLDER_INTEROPS.add(this);\n placeholderExpansion.register();\n }\n\n /**\n * 注销 PlaceholderExpansion 实例。\n * 低版本 Placeholder API 没有 unregister 方法,捕获异常以取消注销。\n */\n @Override\n public void unregister() {\n if (placeholderExpansion == null) {\n return;\n }\n\n try {\n placeholderExpansion.unregister();\n PLACEHOLDER_INTEROPS.remove(this);\n } catch (Throwable throwable) {\n QuickUtils.sendMessage(\n ConsoleMessageTypeEnum.ERROR,\n \"&ePlaceholder API&c logout exception. Is this the latest version? Please try updating it: &ehttps://www.spigotmc.org/resources/placeholderapi.6245\\n\"\n );\n }\n }\n\n /**\n * 转换 PlaceholderExpansion 实例。\n */\n private boolean toPlaceholderExpansion() {\n if (!Bukkit.getPluginManager().isPluginEnabled(\"PlaceholderAPI\")) {\n QuickUtils.sendMessage(\n ConsoleMessageTypeEnum.ERROR,\n \"&cYou haven't installed the &ePlaceholder API&c. If needed, please download it: &ehttps://www.spigotmc.org/resources/placeholderapi.6245\\n\"\n );\n\n return false;\n }\n\n placeholderExpansion = new PlaceholderExpansion() {\n @Override\n public @NotNull String getIdentifier() {\n return identifier;\n }\n\n @Override\n public @NotNull String getAuthor() {\n return author;\n }\n\n @Override\n public @NotNull String getVersion() {\n return version;\n }\n\n @Override\n public @Nullable String onRequest(OfflinePlayer player, @NotNull String params) {\n return executor.apply(player, params);\n }\n };\n\n return true;\n }\n}" }, { "identifier": "CustomContextHandler", "path": "src/main/java/org/js4bukkit/script/objects/handler/CustomContextHandler.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class CustomContextHandler {\n /**\n * 所有的 {@link CustomContextHandler} 对象。\n */\n public static final Queue<CustomContext> CUSTOM_CONTEXTS =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 获取指定名称的 {@link CustomContextHandler} 对象。\n *\n * @param name 指定名称\n * @return 指定名称的 {@link CustomContextHandler} 对象\n */\n public static CustomContext getCustomContext(String name) {\n return CUSTOM_CONTEXTS.stream()\n .filter(customContext -> customContext.getName().equalsIgnoreCase(name))\n .findFirst()\n .orElse(null);\n }\n\n /**\n * 添加 {@link CustomContext} 对象。\n *\n * @param customContext {@link CustomContext} 对象\n */\n public static void addCustomContext(CustomContext customContext) {\n CUSTOM_CONTEXTS.add(customContext);\n }\n\n /**\n * 删除指定名称的 {@link CustomContext} 对象。\n *\n * @param name 名称\n */\n public static void removeCustomContext(String name) {\n removeCustomContext(getCustomContext(name));\n }\n\n /**\n * 删除指定的 {@link CustomContext} 对象。\n *\n * @param customContext {@link CustomContext} 对象\n */\n public static void removeCustomContext(CustomContext customContext) {\n if (customContext == null) {\n return;\n }\n\n // 释放资源\n customContext.getContext().close();\n\n CUSTOM_CONTEXTS.remove(customContext);\n }\n}" }, { "identifier": "ScriptExecutorHandler", "path": "src/main/java/org/js4bukkit/script/objects/handler/ScriptExecutorHandler.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ScriptExecutorHandler {\n /**\n * 所有的 {@link ScriptExecutorHandler} 对象。\n */\n public static final Queue<ScriptExecutor> SCRIPT_EXECUTORS =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 添加 {@link ScriptExecutor} 对象。\n *\n * @param scriptExecutor {@link ScriptExecutor}\n */\n public static void addScriptExecutor(ScriptExecutor scriptExecutor) {\n SCRIPT_EXECUTORS.add(scriptExecutor);\n }\n\n /**\n * 删除 {@link ScriptExecutor} 对象。\n *\n * @param scriptExecutor {@link ScriptExecutor}\n */\n public static void removeScriptExecutor(ScriptExecutor scriptExecutor) {\n SCRIPT_EXECUTORS.remove(scriptExecutor);\n }\n\n /**\n * 调用所有脚本的指定函数。\n *\n * @param function 函数名称\n */\n public static void invoke(String function) {\n SCRIPT_EXECUTORS.forEach(\n scriptExecutor -> scriptExecutor.invoke(function)\n );\n }\n\n /**\n * 使用指定 {@link CustomContext} 对象调用所有脚本的指定函数。\n *\n * @param function 函数名称\n * @param customContext 指定 {@link CustomContext} 对象\n */\n public static void invoke(String function, CustomContext customContext) {\n SCRIPT_EXECUTORS.forEach(\n scriptExecutor -> scriptExecutor.invoke(function, customContext)\n );\n }\n}" }, { "identifier": "ScriptExecutor", "path": "src/main/java/org/js4bukkit/script/objects/objects/ScriptExecutor.java", "snippet": "@Getter\n@Setter\n@Accessors(chain = true)\npublic class ScriptExecutor extends ObjectNameImpl {\n /**\n * 脚本文件。\n */\n private final File scriptFile;\n\n /**\n * 脚本文件文件名。\n */\n private final String fileName;\n\n /**\n * 脚本内容。\n */\n private final String scriptCode;\n\n /**\n * {@link Context} 对象。\n */\n private org.js4bukkit.script.objects.objects.CustomContext customContext;\n\n /**\n * 构造器。\n *\n * @param file 脚本文件\n * @throws IOException 读取脚本文件时出现异常\n */\n public ScriptExecutor(File file) throws IOException {\n scriptFile = file;\n fileName = file.getName();\n\n scriptCode = FileUtils.readFileToString(\n scriptFile, StandardCharsets.UTF_8\n );\n\n customContext = getCustomContext();\n CustomContextHandler.addCustomContext(customContext);\n }\n\n /**\n * 调用指定函数。\n *\n * @param function 函数名称\n * @return 结果\n */\n public Object invoke(String function) {\n return invoke(function, customContext);\n }\n\n /**\n * 使用指定 {@link org.js4bukkit.script.objects.objects.CustomContext} 对象调用指定函数。\n *\n * @param function 函数名称\n * @param customContext 指定 {@link org.js4bukkit.script.objects.objects.CustomContext} 对象\n * @return 结果\n */\n public Object invoke(String function, org.js4bukkit.script.objects.objects.CustomContext customContext) {\n Context context =\n customContext.getContext();\n ScriptableObject scriptableObject =\n customContext.getScriptableObject();\n\n Object object = scriptableObject.get(\n function, scriptableObject\n );\n\n Function functionObject = (Function) object;\n\n return functionObject.call(\n context, scriptableObject, scriptableObject, null\n );\n }\n\n /**\n * 获取该脚本应该使用的 {@link org.js4bukkit.script.objects.objects.CustomContext} 对象。\n *\n * @return 该脚本应该使用的 {@link org.js4bukkit.script.objects.objects.CustomContext} 对象\n */\n private org.js4bukkit.script.objects.objects.CustomContext getCustomContext() {\n Context preContext = Context.enter();\n ScriptableObject preScriptableObject = preContext.initStandardObjects();\n\n org.js4bukkit.script.objects.objects.CustomContext preCustomContext =\n new org.js4bukkit.script.objects.objects.CustomContext()\n .setName(fileName)\n .to(org.js4bukkit.script.objects.objects.CustomContext.class)\n .setContext(preContext)\n .setScriptableObject(preScriptableObject);\n\n // 预加载\n preContext.evaluateString(\n preScriptableObject, scriptCode, fileName, 1, null\n );\n\n // 使用 preCustomContext 执行 getContext() 函数\n Object result = invoke(\n ScriptHandler.GET_CONTEXT_FUNCTION, preCustomContext\n );\n\n // 如果返回的是 null 则直接使用 preCustomContext\n if (result == null) {\n return preCustomContext;\n }\n\n // 如果有指定 context 名称\n String name = result.toString();\n org.js4bukkit.script.objects.objects.CustomContext newCustomContext =\n CustomContextHandler.getCustomContext(name);\n\n // 如果靠这个名称找到了对应 context\n if (newCustomContext != null) {\n // 先释放 preCustomContext 再返回对应 context\n CustomContextHandler.removeCustomContext(preCustomContext);\n return newCustomContext;\n }\n\n // 如果没有找到则将 preCustomContext 改名返回\n return preCustomContext\n .setName(name)\n .to(CustomContext.class);\n }\n}" }, { "identifier": "ScriptPlugin", "path": "src/main/java/org/js4bukkit/script/objects/objects/ScriptPlugin.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class ScriptPlugin implements ObjectAutoInit {\n /**\n * 文件夹。\n */\n private String folder;\n\n /**\n * 名称。\n */\n private String name;\n\n /**\n * 作者。\n */\n private String author;\n\n /**\n * 版本。\n */\n private String version;\n\n /**\n * 描述。\n */\n private String description;\n\n /**\n * 所有的脚本插件对象实例。\n */\n private Queue<File> scriptFiles =\n new ConcurrentLinkedQueue<>();\n\n /**\n * 通过指定 Yaml 文件读取指定键值属性设置对象属性。\n *\n * @param yaml 指定 Yaml 文件\n * @param yamlKey 键值\n * @return 设置完成后的对象\n */\n @Override\n public ScriptPlugin init(Yaml yaml, String yamlKey) {\n setFolder(yamlKey);\n\n ObjectAutoInit.super.init(yaml, yamlKey);\n\n // 处理本文件后返回\n return setScriptFiles(\n IOUtils.getFiles(ScriptHandler.SCRIPT_PATH + folder).stream()\n .filter(file -> file.getName().endsWith(\".js\"))\n .collect(Collectors.toCollection(ConcurrentLinkedQueue::new))\n );\n }\n}" }, { "identifier": "Scheduler", "path": "src/main/java/org/js4bukkit/thread/Scheduler.java", "snippet": "@Setter\n@Getter\n@Accessors(chain = true)\npublic class Scheduler {\n /**\n * {@link Runnable} 对象。\n *\n * <p>\n * 若没有使用 {@link BukkitRunnable} 中的一些方法,则推荐直接传入 {@link Runnable} 对象。\n * </p>\n *\n * @see BukkitRunnable\n */\n private Runnable runnable;\n\n /**\n * {@link BukkitRunnable} 对象。\n */\n private BukkitRunnable bukkitRunnable;\n\n /**\n * 任务类型。\n */\n private SchedulerTypeEnum schedulerTypeEnum;\n\n /**\n * 任务执行模式。\n */\n private SchedulerExecutionMode schedulerExecutionMode;\n\n /**\n * 延迟。\n *\n * <p>\n * 仅在 {@link #schedulerTypeEnum} 为非 {@link SchedulerTypeEnum#RUN} 时有用。\n * </p>\n */\n private int delay;\n\n /**\n * 重复间隔。\n *\n * <p>\n * 仅在 {@link #schedulerTypeEnum} 为非 {@link SchedulerTypeEnum#RUN} 时有用。\n * </p>\n */\n private int period;\n\n /**\n * 运行任务调度器,根据设定的参数执行相应的任务。\n */\n public void run() {\n BukkitRunnable finalBukkitRunnable;\n\n Js4Bukkit js4Bukkit = Js4Bukkit.getInstance();\n\n // 如果传入的为 runnable 则转换为 bukkit runnable\n if (runnable == null) {\n finalBukkitRunnable = bukkitRunnable;\n } else {\n finalBukkitRunnable = new BukkitRunnable() {\n @Override\n public void run() {\n runnable.run();\n }\n };\n }\n\n switch (schedulerTypeEnum) {\n case RUN:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTask(js4Bukkit);\n } else {\n finalBukkitRunnable.runTaskAsynchronously(js4Bukkit);\n }\n return;\n\n case LATER:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTaskLater(js4Bukkit, delay);\n } else {\n finalBukkitRunnable.runTaskLaterAsynchronously(js4Bukkit, delay);\n }\n return;\n\n case TIMER:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTaskTimer(js4Bukkit, delay, period);\n } else {\n finalBukkitRunnable.runTaskTimerAsynchronously(js4Bukkit, delay, period);\n }\n return;\n\n case NEW_THREAD:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTask(js4Bukkit);\n } else {\n new Thread(finalBukkitRunnable).start();\n }\n }\n }\n}" }, { "identifier": "SchedulerExecutionMode", "path": "src/main/java/org/js4bukkit/thread/enums/SchedulerExecutionMode.java", "snippet": "public enum SchedulerExecutionMode {\n /**\n * 同步执行。\n */\n SYNC,\n\n /**\n * 异步执行。\n */\n ASYNC\n}" }, { "identifier": "SchedulerTypeEnum", "path": "src/main/java/org/js4bukkit/thread/enums/SchedulerTypeEnum.java", "snippet": "public enum SchedulerTypeEnum {\n /**\n * 直接运行。\n */\n RUN,\n\n /**\n * 重复运行。\n */\n TIMER,\n\n /**\n * 延迟运行。\n */\n LATER,\n\n /**\n * 新建线程\n */\n NEW_THREAD\n}" }, { "identifier": "QuickUtils", "path": "src/main/java/org/js4bukkit/utils/common/text/QuickUtils.java", "snippet": "@UtilityClass\npublic class QuickUtils {\n /**\n * 向控制台发送输出消息。\n *\n * @param consoleMessageTypeEnum 信息类型\n * @param message 要处理的发向控制台的字符串\n * @param params 替换的可选参数\n */\n public static void sendMessage(ConsoleMessageTypeEnum consoleMessageTypeEnum, String message, String... params) {\n StringBuilder prefix = new StringBuilder()\n .append(\"&f[&6Js4Bukkit&f] \");\n\n switch (consoleMessageTypeEnum) {\n case DEBUG:\n prefix.append(\"&e[DEBUG] &e\");\n break;\n\n case ERROR:\n prefix.append(\"&4[ERROR] &c\");\n break;\n\n case NORMAL:\n prefix.append(\"&f\");\n break;\n\n default:\n case NO_PREFIX:\n prefix.setLength(0);\n break;\n }\n\n Bukkit.getConsoleSender().sendMessage(\n StringUtils.handle(prefix + message, params)\n );\n }\n\n /**\n * 读取语言配置文件内对应键值字符串列表,向命令发送者发送输出消息。\n *\n * @param commandSender 命令发送者\n * @param key 键值\n * @param params 替换的可选参数\n */\n public static void sendMessageByKey(CommandSender commandSender, String key, String... params) {\n Yaml yaml = ConfigManager.getLanguage();\n\n List<String> messages = StringUtils.handle(\n yaml.getStringList(key), params\n );\n\n messages.forEach(commandSender::sendMessage);\n }\n\n /**\n * 读取语言配置文件内对应键值字符串列表,向控制台发送输出消息。\n *\n * @param consoleMessageTypeEnum 信息类型\n * @param key 键值\n * @param params 替换的可选参数\n */\n public static void sendMessageByKey(ConsoleMessageTypeEnum consoleMessageTypeEnum, String key, String... params) {\n Yaml yaml = ConfigManager.getLanguage();\n\n List<String> messages = StringUtils.handle(\n yaml.getStringList(key), params\n );\n\n messages.forEach(message -> sendMessage(consoleMessageTypeEnum, message));\n }\n}" }, { "identifier": "ConsoleMessageTypeEnum", "path": "src/main/java/org/js4bukkit/utils/common/text/enums/ConsoleMessageTypeEnum.java", "snippet": "public enum ConsoleMessageTypeEnum {\n /**\n * 普通信息。\n */\n NORMAL,\n\n /**\n * 调试信息。\n */\n DEBUG,\n\n /**\n * 错误信息。\n */\n ERROR,\n\n /**\n * 无前缀信息。\n */\n NO_PREFIX\n}" } ]
import de.leonhard.storage.Yaml; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.SneakyThrows; import org.js4bukkit.Js4Bukkit; import org.js4bukkit.io.config.ConfigManager; import org.js4bukkit.script.interop.command.CommandInterop; import org.js4bukkit.script.interop.listener.EasyEventListenerInterop; import org.js4bukkit.script.interop.listener.EventListenerInterop; import org.js4bukkit.script.interop.placeholder.PlaceholderInterop; import org.js4bukkit.script.objects.handler.CustomContextHandler; import org.js4bukkit.script.objects.handler.ScriptExecutorHandler; import org.js4bukkit.script.objects.objects.ScriptExecutor; import org.js4bukkit.script.objects.objects.ScriptPlugin; import org.js4bukkit.thread.Scheduler; import org.js4bukkit.thread.enums.SchedulerExecutionMode; import org.js4bukkit.thread.enums.SchedulerTypeEnum; import org.js4bukkit.utils.common.text.QuickUtils; import org.js4bukkit.utils.common.text.enums.ConsoleMessageTypeEnum; import java.io.File; import java.util.Objects; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collectors;
8,576
package org.js4bukkit.script; /** * 脚本处理程序。 * * @author NaerQAQ / 2000000 * @version 1.0 * @since 2023/10/12 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ScriptHandler { /** * 脚本所在文件夹。 */ public static final String SCRIPT_PATH = Js4Bukkit.getDataFolderAbsolutePath() + "/plugins/"; /** * 获取上下文的函数名称。 */ public static final String GET_CONTEXT_FUNCTION = "getContext"; /** * 所有脚本插件对象。 */ public static final Queue<ScriptPlugin> SCRIPT_PLUGINS = new ConcurrentLinkedQueue<>(); /** * 注册脚本插件对象。 */ public static void registerScriptPlugins() { Yaml plugins = ConfigManager.getPlugins(); SCRIPT_PLUGINS.addAll( plugins.singleLayerKeySet() .stream() .map(folder -> new ScriptPlugin().init(plugins, folder)) .filter(Objects::nonNull) .collect(Collectors.toList()) ); } /** * 获取所有脚本文件。 * * @return 所有脚本文件 */ public static Queue<File> getScriptFiles() { return SCRIPT_PLUGINS.stream() .flatMap(scriptPlugin -> scriptPlugin.getScriptFiles().stream()) .collect(Collectors.toCollection(ConcurrentLinkedQueue::new)); } /** * 注册所有脚本。 */ @SneakyThrows public static void registerScripts() { registerScriptPlugins(); Queue<File> scriptFiles = getScriptFiles(); scriptFiles.forEach(scriptFile -> { String scriptName = scriptFile.getName(); try { ScriptExecutorHandler.addScriptExecutor( new ScriptExecutor(scriptFile) .setName(scriptName) .to(ScriptExecutor.class) ); QuickUtils.sendMessage( ConsoleMessageTypeEnum.NORMAL, "&6Script successfully registered: <script_name>.", "<script_name>", scriptName ); } catch (Exception exception) { String message = exception.getMessage(); QuickUtils.sendMessage( ConsoleMessageTypeEnum.ERROR, "Unable to register script: <script_name>, message: <message>.", "<script_name>", scriptName, "<message>", message ); } }); // 注册完毕后调用所有 Script 的 onLoad 函数 ScriptExecutorHandler.invoke("onLoad"); } /** * 卸载脚本。 */ public static void unloadScripts() { ScriptExecutorHandler.invoke("onUnload"); // 指令注销
package org.js4bukkit.script; /** * 脚本处理程序。 * * @author NaerQAQ / 2000000 * @version 1.0 * @since 2023/10/12 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ScriptHandler { /** * 脚本所在文件夹。 */ public static final String SCRIPT_PATH = Js4Bukkit.getDataFolderAbsolutePath() + "/plugins/"; /** * 获取上下文的函数名称。 */ public static final String GET_CONTEXT_FUNCTION = "getContext"; /** * 所有脚本插件对象。 */ public static final Queue<ScriptPlugin> SCRIPT_PLUGINS = new ConcurrentLinkedQueue<>(); /** * 注册脚本插件对象。 */ public static void registerScriptPlugins() { Yaml plugins = ConfigManager.getPlugins(); SCRIPT_PLUGINS.addAll( plugins.singleLayerKeySet() .stream() .map(folder -> new ScriptPlugin().init(plugins, folder)) .filter(Objects::nonNull) .collect(Collectors.toList()) ); } /** * 获取所有脚本文件。 * * @return 所有脚本文件 */ public static Queue<File> getScriptFiles() { return SCRIPT_PLUGINS.stream() .flatMap(scriptPlugin -> scriptPlugin.getScriptFiles().stream()) .collect(Collectors.toCollection(ConcurrentLinkedQueue::new)); } /** * 注册所有脚本。 */ @SneakyThrows public static void registerScripts() { registerScriptPlugins(); Queue<File> scriptFiles = getScriptFiles(); scriptFiles.forEach(scriptFile -> { String scriptName = scriptFile.getName(); try { ScriptExecutorHandler.addScriptExecutor( new ScriptExecutor(scriptFile) .setName(scriptName) .to(ScriptExecutor.class) ); QuickUtils.sendMessage( ConsoleMessageTypeEnum.NORMAL, "&6Script successfully registered: <script_name>.", "<script_name>", scriptName ); } catch (Exception exception) { String message = exception.getMessage(); QuickUtils.sendMessage( ConsoleMessageTypeEnum.ERROR, "Unable to register script: <script_name>, message: <message>.", "<script_name>", scriptName, "<message>", message ); } }); // 注册完毕后调用所有 Script 的 onLoad 函数 ScriptExecutorHandler.invoke("onLoad"); } /** * 卸载脚本。 */ public static void unloadScripts() { ScriptExecutorHandler.invoke("onUnload"); // 指令注销
CommandInterop.COMMAND_INTEROPS.forEach(
2
2023-12-14 13:50:24+00:00
12k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/aircraft/LocalFeederService.java
[ { "identifier": "Configuration", "path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java", "snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\[email protected]\npublic class Configuration {\n\n @Autowired\n private Environment environment;\n\n // Name und Version der App\n private final String appName = \"The Beluga Project\";\n private final String appVersion = \"3-1-1\";\n\n // Angezeigte Feeder-Position auf der Karte\n @Value(\"${location.latitude}\")\n private Double latFeeder;\n\n @Value(\"${location.longitude}\")\n private Double lonFeeder;\n\n // Anzahl der Feeder\n @Value(\"${feeder.amount}\")\n @Min(1)\n private Double amountFeeder;\n\n // Skalierung der Icons\n @Value(\"${scale.icons}\")\n private Double scaleIcons;\n\n // Ip-Adressen der Feeder\n @Value(\"#{'${feeder.ip}'.split(',\\\\s*')}\")\n private List<String> listIpFeeder;\n\n // Art der Feeder\n @Value(\"#{'${feeder.type}'.split(',\\\\s*')}\")\n private List<String> listTypeFeeder;\n\n // Namen der Feeder\n @Value(\"#{'${feeder.name}'.split(',\\\\s*')}\")\n private List<String> listNameFeeder;\n\n // Farben der Feeder\n @Value(\"#{'${feeder.color}'.split(',\\\\s*')}\")\n private List<String> listColorFeeder;\n\n // Anzuzeigende Range Ringe\n @Value(\"#{'${circle.distance.of.rings}'.split(',\\\\s*')}\")\n private List<Integer> listCircleDistancesInNm;\n\n @Value(\"${opensky.network.username}\")\n private String openskyUsername;\n\n @Value(\"${opensky.network.password}\")\n private char[] openskyPassword;\n\n // Url zur Photo-Suche einer Suchmaschine\n @Value(\"${search.engine.url}\")\n private String searchEngineUrl;\n\n // Liste mit Feedern aus der Konfigurationsdatei\n private List<Feeder> listFeeder;\n\n // Map mit typeDesignator als Key und ShapeData als Value\n private Map<String, Object> shapesMap = null;\n\n // Map mit category als Key und shapeDesignator plus shapeScale als Values\n private Map<String, Object[]> catMap = null;\n\n // Map mit typeDesignator als Key und shapeDesignator plus shapeScale als Values\n private Map<String, Object[]> typesMap = null;\n\n public void addFeederToList(Feeder feeder) {\n if (listFeeder == null) listFeeder = new ArrayList<>();\n listFeeder.add(feeder);\n }\n\n /**\n * Methode liest die Konfigurationseinstellungen aus der Datei \"application.properties\"\n * und erstellt Feeder-Objekte mit den jeweiligen Mappings\n *\n * @throws IOException IOException\n */\n @EventListener(ApplicationReadyEvent.class)\n public void init() throws IOException {\n // Zeigt einen Willkommensbanner auf der Konsole\n showWelcomeBannerAndVersion();\n\n // Erstelle Feeder-Objekte und weise Mappings zu\n createFeedersFromConfiguration();\n }\n\n /**\n * Erstellt die Feeder aus den Werten der Konfigurationsdatei\n *\n * @throws IOException IOException\n */\n private void createFeedersFromConfiguration() throws IOException {\n // Erstelle Feeder-Objekte und weise Mappings zu\n for (int i = 0; i < getListIpFeeder().size(); i++) {\n\n // Erstelle einen Feeder\n Feeder feeder = new Feeder(getListNameFeeder().get(i), getListIpFeeder().get(i),\n getListTypeFeeder().get(i), getListColorFeeder().get(i));\n\n // Weise Feeder die Mappings von der jeweiligen Konfigurationsdatei zu\n FeederMapping mapping = getMappingsFromConfig(feeder.getType());\n feeder.setMapping(mapping);\n\n // Füge Feeder zur Liste an Feedern hinzu\n addFeederToList(feeder);\n }\n }\n\n /**\n * Zeigt einen Willkommens-Banner mit aktueller Version und Name der Anwendung\n * an\n */\n private void showWelcomeBannerAndVersion() {\n System.out.println(\"================================================================\");\n System.out.println(\" ____ _ ____ _ _ \\n\"\n + \"| __ ) ___| |_ _ __ _ __ _| _ \\\\ _ __ ___ (_) ___ ___| |_ \\n\"\n + \"| _ \\\\ / _ \\\\ | | | |/ _` |/ _` | |_) | '__/ _ \\\\| |/ _ \\\\/ __| __|\\n\"\n + \"| |_) | __/ | |_| | (_| | (_| | __/| | | (_) | | __/ (__| |_ \\n\"\n + \"|____/ \\\\___|_|\\\\__,_|\\\\__, |\\\\__,_|_| |_| \\\\___// |\\\\___|\\\\___|\\\\__|\\n\"\n + \" |___/ |__/ \");\n System.out.println(\" :: \" + getAppName() + \" :: \" + \"\t\t\t\" + \"Version: \"\n + getAppVersion());\n System.out.println(\" made by RexKramer1 and amnesica\");\n System.out.println(\"================================================================\");\n }\n\n /**\n * Gibt ein FeederMapping mit den Zuweisungen aus der Konfigurationsdatei mit\n * dem Namen aus typeFeederProperty\n *\n * @param typeFeederProperty String\n * @return FeederMapping\n * @throws IOException IOException\n */\n private FeederMapping getMappingsFromConfig(String typeFeederProperty) throws IOException {\n FeederMapping mapping = new FeederMapping();\n\n final String pathToFeederMappings = \"config\" + File.separator + \"feederMappings\" + File.separator;\n\n if (typeFeederProperty != null && !typeFeederProperty.isEmpty()) {\n Properties propsFeeder = readPropertiesFromResourcesFile(pathToFeederMappings + typeFeederProperty + \".config\");\n\n if (propsFeeder.getProperty(\"hex\") != null) {\n mapping.setHex(propsFeeder.getProperty(\"hex\"));\n }\n if (propsFeeder.getProperty(\"latitude\") != null) {\n mapping.setLatitude(propsFeeder.getProperty(\"latitude\"));\n }\n if (propsFeeder.getProperty(\"longitude\") != null) {\n mapping.setLongitude(propsFeeder.getProperty(\"longitude\"));\n }\n if (propsFeeder.getProperty(\"altitude\") != null) {\n mapping.setAltitude(propsFeeder.getProperty(\"altitude\"));\n }\n if (propsFeeder.getProperty(\"track\") != null) {\n mapping.setTrack(propsFeeder.getProperty(\"track\"));\n }\n if (propsFeeder.getProperty(\"type\") != null) {\n mapping.setType(propsFeeder.getProperty(\"type\"));\n }\n if (propsFeeder.getProperty(\"registration\") != null) {\n mapping.setRegistration(propsFeeder.getProperty(\"registration\"));\n }\n if (propsFeeder.getProperty(\"onGround\") != null) {\n mapping.setOnGround(propsFeeder.getProperty(\"onGround\"));\n }\n if (propsFeeder.getProperty(\"speed\") != null) {\n mapping.setSpeed(propsFeeder.getProperty(\"speed\"));\n }\n if (propsFeeder.getProperty(\"squawk\") != null) {\n mapping.setSquawk(propsFeeder.getProperty(\"squawk\"));\n }\n if (propsFeeder.getProperty(\"flightId\") != null) {\n mapping.setFlightId(propsFeeder.getProperty(\"flightId\"));\n }\n if (propsFeeder.getProperty(\"verticalRate\") != null) {\n mapping.setVerticalRate(propsFeeder.getProperty(\"verticalRate\"));\n }\n if (propsFeeder.getProperty(\"rssi\") != null) {\n mapping.setRssi(propsFeeder.getProperty(\"rssi\"));\n }\n if (propsFeeder.getProperty(\"category\") != null) {\n mapping.setCategory(propsFeeder.getProperty(\"category\"));\n }\n if (propsFeeder.getProperty(\"temperature\") != null) {\n mapping.setTemperature(propsFeeder.getProperty(\"temperature\"));\n }\n if (propsFeeder.getProperty(\"windSpeed\") != null) {\n mapping.setWindSpeed(propsFeeder.getProperty(\"windSpeed\"));\n }\n if (propsFeeder.getProperty(\"windFromDirection\") != null) {\n mapping.setWindFromDirection(propsFeeder.getProperty(\"windFromDirection\"));\n }\n if (propsFeeder.getProperty(\"destination\") != null) {\n mapping.setDestination(propsFeeder.getProperty(\"destination\"));\n }\n if (propsFeeder.getProperty(\"origin\") != null) {\n mapping.setOrigin(propsFeeder.getProperty(\"origin\"));\n }\n if (propsFeeder.getProperty(\"distance\") != null) {\n mapping.setDistance(propsFeeder.getProperty(\"distance\"));\n }\n if (propsFeeder.getProperty(\"autopilotEngaged\") != null) {\n mapping.setAutopilotEngaged(propsFeeder.getProperty(\"autopilotEngaged\"));\n }\n if (propsFeeder.getProperty(\"elipsoidalAltitude\") != null) {\n mapping.setElipsoidalAltitude(propsFeeder.getProperty(\"elipsoidalAltitude\"));\n }\n if (propsFeeder.getProperty(\"selectedQnh\") != null) {\n mapping.setSelectedQnh(propsFeeder.getProperty(\"selectedQnh\"));\n }\n if (propsFeeder.getProperty(\"selectedAltitude\") != null) {\n mapping.setSelectedAltitude(propsFeeder.getProperty(\"selectedAltitude\"));\n }\n if (propsFeeder.getProperty(\"selectedHeading\") != null) {\n mapping.setSelectedHeading(propsFeeder.getProperty(\"selectedHeading\"));\n }\n if (propsFeeder.getProperty(\"feeder\") != null) {\n mapping.setFeeder(propsFeeder.getProperty(\"feeder\"));\n }\n if (propsFeeder.getProperty(\"lastSeen\") != null) {\n mapping.setLastSeen(propsFeeder.getProperty(\"lastSeen\"));\n }\n if (propsFeeder.getProperty(\"source\") != null) {\n mapping.setSource(propsFeeder.getProperty(\"source\"));\n }\n }\n return mapping;\n }\n\n /**\n * Gibt Properties-Objekt zurück, welches aus dem resources-Verzeichnis mit dem\n * Namen filename stammt\n *\n * @param filename String\n * @return Properties\n * @throws IOException IOException\n */\n private Properties readPropertiesFromResourcesFile(String filename) throws IOException {\n Properties props = new Properties();\n InputStream configStream = null;\n try {\n configStream = Application.class.getResourceAsStream(\"/\" + filename);\n if (configStream != null) {\n props.load(configStream);\n }\n } finally {\n if (configStream != null) {\n configStream.close();\n }\n configStream = null;\n }\n\n return props;\n }\n\n /**\n * Methode prüft, ob die Zugangsdaten für Opensky gesetzt wurden\n *\n * @return true, wenn Zugangsdaten gesetzt wurden\n */\n public boolean openskyCredentialsAreValid() {\n if (openskyUsername == null || openskyUsername.isBlank()\n || openskyUsername.equals(\"TODO\") || openskyPassword == null\n || openskyPassword.length == 0 ||\n Arrays.equals(openskyPassword, new char[]{'T', 'O', 'D', 'O'})) {\n log.info(\"Opensky: Credentials have not been set in application.properties. Opensky cannot be used!\");\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Programm wird nach Anzeige einer Meldung terminiert\n *\n * @param message String\n */\n private void exitProgram(String message) {\n log.error(message);\n System.exit(0);\n }\n}" }, { "identifier": "Feeder", "path": "server/src/main/java/com/amnesica/belugaproject/config/Feeder.java", "snippet": "@Data\npublic class Feeder {\n // Allgemeine Informationen über Feeder\n private String name;\n private String ipAddress;\n private String type;\n private String color;\n\n // Zuweisungen\n private FeederMapping mapping;\n\n // Konstruktor\n public Feeder(String name, String ipAddress, String type, String color) {\n super();\n this.name = name;\n this.ipAddress = ipAddress;\n this.type = type;\n this.color = color;\n }\n}" }, { "identifier": "StaticValues", "path": "server/src/main/java/com/amnesica/belugaproject/config/StaticValues.java", "snippet": "public class StaticValues {\n // Lokale Feeder - Scheduler\n public static final int INTERVAL_UPDATE_LOCAL_FEEDER = 2000; // 2 Sekunden\n public static final int INTERVAL_LOCAL_PLANES_TO_HISTORY = 600000; // 10 Minuten\n public static final int INTERVAL_REMOVE_OLD_TRAILS_LOCAL = 600000; // 10 Minuten\n public static final long INTERVAL_REMOVE_OLD_DATA = 2592000000L; // 30 Tage\n public static final String INTERVAL_REMOVE_OLD_TRAILS_FROM_HISTORY = \"0 0 2 * * ?\"; // cron expression: every day at 02:00 a.m.\n public static final int RETENTION_DAYS_TRAILS_IN_HISTORY = 2; // 2 Tage\n public static final String INTERVAL_REMOVE_OLD_AIRCRAFT_FROM_HISTORY = \"0 0 1 * * ?\"; // cron expression: every day at 01:00 a.m.\n public static final int RETENTION_DAYS_AIRCRAFT_IN_HISTORY = 30; // 30 Tage\n\n // Opensky-Network - Scheduler\n public static final int INTERVAL_UPDATE_OPENSKY = 5000; // 5 Sekunden\n public static final int INTERVAL_REMOVE_OLD_PLANES_OPENSKY = 600000; // 10 Minuten\n\n // ISS - Scheduler\n public static final int INTERVAL_UPDATE_ISS = 2000; // 2 Sekunden\n public static final int INTERVAL_REMOVE_OLD_TRAILS_ISS = 600000; // 10 Minuten\n}" }, { "identifier": "Aircraft", "path": "server/src/main/java/com/amnesica/belugaproject/entities/aircraft/Aircraft.java", "snippet": "@Entity\n@Table(name = \"aircraft\")\npublic class Aircraft extends AircraftSuperclass {\n\n public Aircraft() {\n // Benötiger, leerer Konstruktor\n }\n\n public Aircraft(String hex, Double latitude, Double longitude) {\n super(hex, latitude, longitude);\n }\n}" }, { "identifier": "AirportData", "path": "server/src/main/java/com/amnesica/belugaproject/entities/data/AirportData.java", "snippet": "@Data\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@Entity\npublic class AirportData {\n\n @Id\n private String ident;\n private String type;\n private String name;\n private Double latitude_deg;\n private Double longitude_deg;\n private String elevation_ft;\n private String continent;\n private String iso_country;\n private String iso_region;\n private String municipality;\n private String scheduled_service;\n private String gps_code;\n private String iata_code;\n private String local_code;\n private String home_link;\n private String wikipedia_link;\n\n // Höhere Größe, da ein Eintrag länger als 255 ist\n @Column(length = 260)\n private String keywords;\n\n private Integer numberAirport;\n\n public AirportData() {\n // Benötiger, leerer Konstruktor\n }\n}" }, { "identifier": "AircraftRepository", "path": "server/src/main/java/com/amnesica/belugaproject/repositories/aircraft/AircraftRepository.java", "snippet": "@Repository\npublic interface AircraftRepository extends CrudRepository<Aircraft, String> {\n Aircraft findByHex(String hex);\n\n List<Aircraft> findAllByLastUpdateLessThanEqual(long time);\n\n @Query(value = \"select * from aircraft where last_update >= ?1 and longitude between ?2 and ?4 and latitude between ?3 and ?5\", nativeQuery = true)\n List<Aircraft> findAllByLastUpdateAndWithinExtent(long timeStart, double lomin, double lamin, double lomax,\n double lamax);\n\n @Query(value = \"select * from aircraft where last_update >= ?1 and ?2 = ANY(feeder_list) and longitude between ?3 and ?5 and latitude between ?4 and ?6\", nativeQuery = true)\n List<Aircraft> findAllByLastUpdateAndFeederAndWithinExtent(long startTime, String feeder, double lomin,\n double lamin, double lomax, double lamax);\n}" }, { "identifier": "AircraftDataService", "path": "server/src/main/java/com/amnesica/belugaproject/services/data/AircraftDataService.java", "snippet": "@Slf4j\n@Service\npublic class AircraftDataService {\n\n @Autowired\n private AircraftDataRepository aircraftDataRepository;\n\n @Autowired\n private AircraftService aircraftService;\n\n /**\n * Gibt alle Informationen über ein Flugzeug mit Angabe der hex aus der\n * Datenbank zurück\n *\n * @return AircraftData\n */\n public void addAircraftData(AircraftSuperclass aircraft) {\n AircraftData aircraftData = null;\n\n if (aircraft.getHex() != null && !aircraft.getHex().isEmpty() && !aircraft.getHex().equals(\"null\") && !aircraft.getHex().equals(\"ISS\")) {\n // Hole Daten aus Datenbank mit Angabe der Hex\n\n try {\n aircraftData = aircraftDataRepository.findByHex(aircraft.getHex());\n } catch (Exception e) {\n log.error(\"Server - DB-Error when reading AircraftData for hex \" + aircraft.getHex() + \": Exception = \"\n + e);\n }\n\n if (aircraftData != null) {\n // Speichere Informationen am Flugzeug\n if ((aircraft.getRegistration() == null || aircraft.getRegistration().isEmpty())\n && !aircraftData.getRegistration().isEmpty()) {\n aircraft.setRegistration(aircraftData.getRegistration().trim());\n }\n\n if ((aircraft.getType() == null || aircraft.getType().isEmpty())\n && !aircraftData.getTypecode().isEmpty()) {\n aircraft.setType(aircraftData.getTypecode().trim());\n }\n\n if (aircraft.getFullType() == null || aircraft.getFullType().isEmpty()) {\n String manufacturerName = aircraftData.getManufacturerName();\n String model = aircraftData.getModel();\n\n if (manufacturerName != null && model != null) {\n aircraft.setFullType(manufacturerName.trim() + \" \" + model.trim());\n }\n }\n\n if (!aircraftData.getOperatorIcao().isEmpty()) {\n aircraft.setOperatorIcao(aircraftData.getOperatorIcao().trim());\n }\n\n if (!aircraftData.getSerialNumber().isEmpty()) {\n aircraft.setSerialNumber(aircraftData.getSerialNumber().trim());\n }\n\n if (!aircraftData.getLineNumber().isEmpty()) {\n aircraft.setLineNumber(aircraftData.getLineNumber().trim());\n }\n\n if (!aircraftData.getTestReg().isEmpty()) {\n aircraft.setTestReg(aircraftData.getTestReg().trim());\n }\n\n if (!aircraftData.getRegistered().isEmpty()) {\n aircraft.setRegistered(aircraftData.getRegistered().trim());\n }\n\n if (!aircraftData.getRegUntil().isEmpty()) {\n aircraft.setRegUntil(aircraftData.getRegUntil().trim());\n }\n\n if (!aircraftData.getStatus().isEmpty()) {\n aircraft.setStatus(aircraftData.getStatus().trim());\n }\n\n if (!aircraftData.getBuilt().isEmpty()) {\n String built = aircraftData.getBuilt();\n aircraft.setBuilt(aircraftData.getBuilt().trim());\n\n // Berechne Alter des Flugzeugs und setze dieses\n aircraftService.calcAndSetAge(aircraft, built);\n }\n\n if (!aircraftData.getFirstFlightDate().isEmpty()) {\n aircraft.setFirstFlightDate(aircraftData.getFirstFlightDate().trim());\n }\n\n if (!aircraftData.getIcaoAircraftType().isEmpty()) {\n aircraft.setIcaoAircraftType(aircraftData.getIcaoAircraftType().trim());\n }\n\n if (!aircraftData.getEngines().isEmpty()) {\n String engines = aircraftData.getEngines().trim();\n if(engines.contains(\"<br>\")){\n engines = engines.replace(\"<br>\", \"\");\n }\n aircraft.setEngines(engines);\n }\n }\n }\n }\n}" }, { "identifier": "AirportDataService", "path": "server/src/main/java/com/amnesica/belugaproject/services/data/AirportDataService.java", "snippet": "@Slf4j\n@Service\npublic class AirportDataService {\n\n @Autowired\n private AirportDataRepository airportDataRepository;\n\n /**\n * Gibt alle Informationen über einen Flughafen mit Angabe der ident aus der\n * Datenbank zurück\n *\n * @param ident String\n * @return AirportData\n */\n public AirportData getAirportData(String ident) {\n AirportData airportData = null;\n\n if (ident != null && !ident.isEmpty() && !ident.equals(\"null\")) {\n // Hole Daten aus Datenbank mit Angabe der Ident (bspw. \"EDHI\")\n\n try {\n airportData = airportDataRepository.findByIdent(ident);\n } catch (Exception e) {\n log.error(\"Server - DB error while reading AirportData for ident \" + ident + \": Exception = \" + e);\n }\n\n }\n\n return airportData;\n }\n\n /**\n * Gibt alle Flughäfen innerhalb eines Extents zurück\n *\n * @param lomin lower bound for the longitude in decimal degrees\n * @param lamin lower bound for the latitude in decimal degrees\n * @param lomax upper bound for the longitude in decimal degrees\n * @param lamax upper bound for the latitude in decimal degrees\n * @param zoomLevel Aktuelles Zoomlevel\n * @return List<AirportData>\n */\n public List<AirportData> getAirportsInExtent(double lomin, double lamin, double lomax, double lamax,\n double zoomLevel) {\n List<AirportData> listAirports = null;\n\n try {\n // Wenn Zoom-Level > 8 ist, zeige alle Flughäfen an\n if (zoomLevel > 8) {\n listAirports = (List<AirportData>) airportDataRepository.findAllWithinExtent(lomin, lamin, lomax,\n lamax);\n }\n // Wenn Zoom-Level = 8 ist, zeige große und mittlere Flughäfen an\n else if (zoomLevel == 8) {\n listAirports = (List<AirportData>) airportDataRepository\n .findAllMediumAndLargeAirportsWithinExtent(lomin, lamin, lomax, lamax);\n } else {\n listAirports = (List<AirportData>) airportDataRepository.findAllLargeAirportsWithinExtent(lomin, lamin,\n lomax, lamax);\n }\n\n } catch (Exception e) {\n log.error(\"Server - DB error when fetching airports from database: Exception = \" + e);\n }\n\n return listAirports;\n }\n}" }, { "identifier": "RangeDataService", "path": "server/src/main/java/com/amnesica/belugaproject/services/data/RangeDataService.java", "snippet": "@Slf4j\n@Service\npublic class RangeDataService {\n\n @Autowired\n private RangeDataRepository rangeDataRepository;\n\n /**\n * Gibt eine Liste mit Range-Data, Start- und Endpunkt von Flugzeugen,\n * welche in dem Zeitslot empfangen wurden\n *\n * @param startTime long\n * @param endTime long\n * @return List<RangeData>\n */\n public List<RangeData> getRangeDataBetweenTimestamps(long startTime, long endTime) {\n List<RangeData> listRangeData = null;\n\n if (startTime == 0 && endTime == 0) return null;\n\n try {\n listRangeData = rangeDataRepository.findAllByTimestampBetween(startTime, endTime);\n } catch (Exception e) {\n log.error(\"Server - DB error reading RangeData for startTime \" + DateFormat.getDateTimeInstance().format(new Date(startTime)) +\n \" and endTime \" + DateFormat.getDateTimeInstance().format(new Date(endTime)) + \" : Exception = \" + e);\n }\n\n return listRangeData;\n }\n\n /**\n * Erstellt einen RangeData-Eintrag für ein Flugzeug\n *\n * @param aircraft Aircraft\n */\n public void createAndSaveRangeDataEntry(Aircraft aircraft) {\n if (aircraft == null) return;\n\n try {\n // Erstelle RangeData (Hinweis: Timestamp ist LastUpdate hier!)\n RangeData rangeData = new RangeData(aircraft.getHex(), aircraft.getLatitude(), aircraft.getLongitude(),\n aircraft.getDistance(), aircraft.getAltitude(), aircraft.getType(), aircraft.getCategory(), aircraft.getRegistration(),\n aircraft.getFlightId(), aircraft.getLastUpdate(), aircraft.getFeederList(), aircraft.getSourceList());\n\n rangeDataRepository.save(rangeData);\n } catch (Exception e) {\n log.error(\"Server - DB error saving RangeData for hex \" + aircraft.getHex() + \" : Exception = \" + e);\n }\n }\n\n /**\n * Löscht alle Range-Data, welche älter sind als 30 Tage endgültig.\n * Methode wird alle INTERVAL_REMOVE_OLD_DATA Millisekunden aufgerufen\n */\n @Transactional\n @Scheduled(fixedRate = StaticValues.INTERVAL_REMOVE_OLD_DATA)\n private void deleteRangeDataOlderThanOneMonth() {\n // Berechne timestamp vor 30 Tagen in Millisekunden,\n // damit nur alte Range-Data gelöscht werden\n long startTime = System.currentTimeMillis() - 2592000000L;\n\n // Lösche Range-Data, welche älter sind als startTime\n try {\n rangeDataRepository.deleteAllByTimestampLessThanEqual(startTime);\n } catch (Exception e) {\n log.error(\"Server - DB error when removing range data from RangeData older than \"\n + new Date(startTime).toLocaleString() + \" days : Exception = \" + e);\n }\n }\n}" }, { "identifier": "NetworkHandlerService", "path": "server/src/main/java/com/amnesica/belugaproject/services/helper/NetworkHandlerService.java", "snippet": "@Slf4j\n@Service\npublic class NetworkHandlerService {\n\n // Networkhandler (Standard-Timeout)\n private final OkHttpClient client = new OkHttpClient();\n\n // Networkhandler (geringes Connect-Timeout für lokale Feeder,\n // damit reentered-Aircraft-Zustand nicht falsch gesetzt wird,\n // da Timeout zu groß ist)\n private final OkHttpClient clientLocalFeeder = new OkHttpClient.Builder()\n .connectTimeout(1000, TimeUnit.MILLISECONDS)\n .build();\n\n private final String userAgentBelugaProject = \"The Beluga Project\";\n\n /**\n * Macht einen Get-Call zu einer Url und gibt die Antwort als String zurück\n *\n * @param url String\n * @return String\n */\n public String makeServiceCall(String url) {\n try {\n Request request = new Request.Builder()\n .url(url)\n .header(\"User-Agent\", userAgentBelugaProject)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n return response.body().string();\n }\n } catch (Exception e) {\n log.error(\"Server - Error when retrieving information from url \" + url + \": Exception = \" + e);\n }\n\n return null;\n }\n\n /**\n * Macht einen Get-Call zum Opensky-Network mit den Credentials aus\n * application.properties und gibt die Antwort als String zurück\n *\n * @param url String\n * @param username Opensky-Network username as String\n * @param password Opensky-Network password as char[]\n * @return String\n */\n public String makeOpenskyServiceCall(String url, String username, char[] password) {\n try {\n // Breche ab, wenn url, username oder password invalide sind\n if (url == null || url.isBlank()) throw new Exception(\"Invalid url. Request aborted.\");\n if ((username == null || username.isBlank()) || (password == null))\n throw new Exception(\"Invalid opensky-network credentials. Request aborted.\");\n\n // Baue kodierten String aus Credentials\n String credential = Credentials.basic(username, String.valueOf(password), StandardCharsets.UTF_8);\n\n Request request = new Request.Builder()\n .url(url)\n .method(\"GET\", null)\n .header(\"User-Agent\", userAgentBelugaProject)\n .addHeader(\"Authorization\", credential)\n .build();\n try (Response response = client.newCall(request).execute()) {\n return response.body().string();\n }\n } catch (Exception e) {\n log.error(\"Server - Error when retrieving information from url \" + url + \": Exception = \" + e);\n }\n return null;\n }\n\n /**\n * Macht einen Get-Call zu einer Url und gibt die Antwort als String zurück.\n * Benutzt wird dabei der OkHttpClient mit reduziertem Connect-Timeout für\n * lokale Feeder, damit reentered-Aircraft-Zustand nicht falsch gesetzt wird,\n * da Timeout zu groß ist\n *\n * @param url String\n * @return String\n */\n public String makeServiceCallLocalFeeder(String url) {\n if (!url.equalsIgnoreCase(\"none\")) {\n try {\n Request request = new Request.Builder()\n .url(url)\n .header(\"User-Agent\", userAgentBelugaProject)\n .build();\n\n try (Response response = clientLocalFeeder.newCall(request).execute()) {\n return response.body().string();\n }\n } catch (Exception e) {\n log.error(\"Server - Error when retrieving information from url \" + url + \": Exception = \" + e);\n }\n }\n return null;\n }\n}" }, { "identifier": "AircraftTrailService", "path": "server/src/main/java/com/amnesica/belugaproject/services/trails/AircraftTrailService.java", "snippet": "@Slf4j\n@Service\npublic class AircraftTrailService {\n @Autowired\n private AircraftTrailRepository aircraftTrailRepository;\n @Autowired\n private HistoryAircraftTrailService historyAircraftTrailService;\n\n /**\n * Speichert einen Trail im AircraftTrailRepository\n *\n * @param aircraft AircraftSuperclass\n * @param feederName String\n */\n public void addTrail(AircraftSuperclass aircraft, String feederName) {\n if (aircraft != null) {\n // Erstelle neues Trail-Element\n AircraftTrail trail = new AircraftTrail(aircraft.getHex(), aircraft.getLongitude(), aircraft.getLatitude(),\n aircraft.getAltitude(), aircraft.getReenteredAircraft(), System.currentTimeMillis(), feederName,\n aircraft.getSourceCurrentFeeder());\n\n try {\n // Speichere Trail in Datenbank\n aircraftTrailRepository.save(trail);\n } catch (Exception e) {\n log.error(\"Server - DB error when saving trail for aircraft with hex \" + trail.getHex()\n + \": Exception = \" + e);\n }\n }\n }\n\n /**\n * Gibt alle Trails zu einem Hex und einem Feeder zurück\n *\n * @param hex String\n * @param selectedFeeder String\n * @return List<AircraftTrail>\n */\n public List<AircraftTrail> getAllTrailsToHexAndFeeder(String hex, String selectedFeeder) {\n List<AircraftTrail> trails = null;\n if (hex != null && !hex.isEmpty()) {\n if (selectedFeeder != null && !selectedFeeder.isEmpty() && !selectedFeeder.equals(\"AllFeeder\")) {\n // Gebe nur Trails vom selektierten Feeder zurück\n try {\n trails = aircraftTrailRepository.findAllByHexAndFeederOrderByTimestampAsc(hex, selectedFeeder);\n } catch (Exception e) {\n log.error(\"Server - DB error when retrieving all trails for aircraft with hex \" + hex\n + \": Exception = \" + e);\n }\n } else if (selectedFeeder != null && !selectedFeeder.isEmpty()) {\n // Geben Trails (von allen Feedern) eines Flugzeugs zurück\n try {\n trails = aircraftTrailRepository.findAllByHexOrderByTimestampAsc(hex);\n } catch (Exception e) {\n log.error(\"Server - DB error when retrieving all trails for aircraft with hex \" + hex\n + \": Exception = \" + e);\n }\n }\n }\n return trails;\n }\n\n /**\n * Bestimmt, ob ein Flugzeug als 'reentered'-Flugzeug bezeichnet werden kann\n *\n * @param hex String\n * @param selectedFeeder String\n * @return boolean\n */\n public boolean getIsReenteredAircraft(String hex, String selectedFeeder) {\n if (selectedFeeder != null && !selectedFeeder.isEmpty() && !selectedFeeder.equals(\"AllFeeder\")) {\n try {\n long time = System.currentTimeMillis();\n\n AircraftTrail trail = aircraftTrailRepository.findFirstByHexAndFeederOrderByTimestampDesc(hex,\n selectedFeeder);\n\n return trail != null && (time - trail.getTimestamp() > 3000);\n } catch (Exception e) {\n log.error(\"Server - DB error when retrieving all trails for aircraft with hex \" + hex + \": Exception = \"\n + e);\n return false;\n }\n }\n return false;\n }\n\n /**\n * Methode kopiert alle Trails, die älter als eine Stunde sind\n * in die HistoryTrails-Tabelle und löscht die betroffenen Trails aus der\n * AircraftTrails-Tabelle. Methode wird alle INTERVAL_REMOVE_OLD_TRAILS_LOCAL\n * Sekunden aufgerufen\n */\n @Scheduled(fixedRate = StaticValues.INTERVAL_REMOVE_OLD_TRAILS_LOCAL)\n private void putOldTrailsInTrailsHistoryTable() {\n // Berechne timestamp vor 1 Stunde (3600 Sekunden, entspricht 3600000\n // Millisekunden), damit nur alte Trails kopiert und gelöscht werden\n long startTime = System.currentTimeMillis() - 3600000;\n\n // Hole Trails der aktuellen Iteration\n List<AircraftTrail> listOldTrails = aircraftTrailRepository\n .findAllByTimestampLessThanEqual(startTime);\n\n // Kopiere und lösche alle alten Trails\n if (listOldTrails != null) {\n\n // Packe alte Trails in History-Trails-Tabelle\n boolean successful = historyAircraftTrailService.putListTrailsInTrailsHistoryTable(listOldTrails);\n\n // Wenn Speicherung in TrailsHistory-Tabelle erfolgreich war, lösche alle betroffenen\n // Flugzeuge aus der AircraftTrails-Tabelle\n if (successful) {\n aircraftTrailRepository.deleteAll(listOldTrails);\n }\n }\n }\n}" } ]
import com.amnesica.belugaproject.config.Configuration; import com.amnesica.belugaproject.config.Feeder; import com.amnesica.belugaproject.config.StaticValues; import com.amnesica.belugaproject.entities.aircraft.Aircraft; import com.amnesica.belugaproject.entities.data.AirportData; import com.amnesica.belugaproject.repositories.aircraft.AircraftRepository; import com.amnesica.belugaproject.services.data.AircraftDataService; import com.amnesica.belugaproject.services.data.AirportDataService; import com.amnesica.belugaproject.services.data.RangeDataService; import com.amnesica.belugaproject.services.helper.NetworkHandlerService; import com.amnesica.belugaproject.services.trails.AircraftTrailService; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.List;
8,832
package com.amnesica.belugaproject.services.aircraft; @Slf4j @EnableScheduling @Service public class LocalFeederService { @Autowired private AircraftService aircraftService; @Autowired private NetworkHandlerService networkHandler; @Autowired private AircraftDataService aircraftDataService; @Autowired private HistoryAircraftService historyAircraftService; @Autowired private AircraftTrailService aircraftTrailService; @Autowired private AirportDataService airportDataService; @Autowired private RangeDataService rangeDataService; @Autowired private AircraftRepository aircraftRepository; @Autowired private Configuration configuration; // Sets mit hex der Flugzeuge, um Flugzeuge temporär zu speichern // (nötig um feederList und sourceList jeweils zu füllen) private final HashSet<String> currentIterationSet = new HashSet<>(); private final HashSet<String> previousIterationSet = new HashSet<>(); /** * Methode fragt Flugzeuge von den lokalen Feedern ab und speichert diese in der * Tabelle aircraft. Methode wird alle INTERVAL_UPDATE_LOCAL_FEEDER Sekunden * aufgerufen */
package com.amnesica.belugaproject.services.aircraft; @Slf4j @EnableScheduling @Service public class LocalFeederService { @Autowired private AircraftService aircraftService; @Autowired private NetworkHandlerService networkHandler; @Autowired private AircraftDataService aircraftDataService; @Autowired private HistoryAircraftService historyAircraftService; @Autowired private AircraftTrailService aircraftTrailService; @Autowired private AirportDataService airportDataService; @Autowired private RangeDataService rangeDataService; @Autowired private AircraftRepository aircraftRepository; @Autowired private Configuration configuration; // Sets mit hex der Flugzeuge, um Flugzeuge temporär zu speichern // (nötig um feederList und sourceList jeweils zu füllen) private final HashSet<String> currentIterationSet = new HashSet<>(); private final HashSet<String> previousIterationSet = new HashSet<>(); /** * Methode fragt Flugzeuge von den lokalen Feedern ab und speichert diese in der * Tabelle aircraft. Methode wird alle INTERVAL_UPDATE_LOCAL_FEEDER Sekunden * aufgerufen */
@Scheduled(fixedRate = StaticValues.INTERVAL_UPDATE_LOCAL_FEEDER)
2
2023-12-11 11:37:46+00:00
12k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-example/src/main/java/io/fiber/net/example/Main.java
[ { "identifier": "Engine", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/Engine.java", "snippet": "public class Engine implements Destroyable {\n private static final Logger log = LoggerFactory.getLogger(Engine.class);\n\n\n private static class InterceptorNode implements Interceptor.Invocation {\n private final Interceptor interceptor;\n private Interceptor.Invocation next;\n\n public InterceptorNode(Interceptor interceptor) {\n this.interceptor = interceptor;\n }\n\n @Override\n public void invoke(String project, HttpExchange httpExchange) throws Exception {\n interceptor.intercept(project, httpExchange, next);\n }\n }\n\n private class FindProjectInvocation implements Interceptor.Invocation {\n @Override\n public void invoke(String project, HttpExchange httpExchange) throws Exception {\n runInternal(project, httpExchange);\n }\n }\n\n protected Interceptor.Invocation invocation = new FindProjectInvocation();\n private final Map<String, RequestHandlerRouter> projectMap = new ConcurrentHashMap<>();\n private InterceptorNode tail;\n private final Injector injector;\n private RouterNameFetcher routerNameFetcher = RouterNameFetcher.DEF_NAME;\n\n public Engine(Injector injector) {\n this.injector = injector;\n }\n\n public void installExt() throws Exception {\n routerNameFetcher = injector.getInstance(RouterNameFetcher.class);\n Interceptor[] interceptors = injector.getInstances(Interceptor.class);\n if (ArrayUtils.isNotEmpty(interceptors)) {\n addInterceptors(interceptors);\n }\n StartListener[] startListeners = injector.getInstances(StartListener.class);\n if (ArrayUtils.isNotEmpty(startListeners)) {\n for (StartListener startListener : startListeners) {\n startListener.onStart(this);\n }\n }\n }\n\n public void addInterceptor(Interceptor interceptor) {\n Predictions.notNull(interceptor, \"interceptor must not null\");\n InterceptorNode node = new InterceptorNode(interceptor);\n if (tail != null) {\n node.next = tail.next;\n tail.next = node;\n } else {\n node.next = invocation;\n invocation = node;\n }\n Predictions.assertTrue(node.next instanceof FindProjectInvocation, \"last is not FindProjectInvocation??\");\n this.tail = node;\n }\n\n public final void addInterceptors(Interceptor... interceptor) {\n for (Interceptor ipr : interceptor) {\n addInterceptor(ipr);\n }\n }\n\n public final void run(String projectName, HttpExchange httpExchange) throws Exception {\n invocation.invoke(projectName, httpExchange);\n }\n\n public void run(HttpExchange httpExchange) throws Exception {\n run(routerNameFetcher.fetchName(httpExchange), httpExchange);\n }\n\n public void addHandlerRouter(RequestHandlerRouter handlerRouter) {\n String managerName = handlerRouter.getRouterName();\n RequestHandlerRouter old = projectMap.put(managerName, handlerRouter);\n if (old != null) {\n old.destroy();\n log.info(\"project {} is replaced\", managerName);\n } else {\n log.info(\"project {} is added\", managerName);\n }\n }\n\n public void removeHandlerRouter(String projectName) {\n RequestHandlerRouter handlerRouter = projectMap.remove(projectName);\n if (handlerRouter != null) {\n handlerRouter.destroy();\n log.info(\"project {} is removed\", projectName);\n }\n }\n\n protected void runInternal(String project, HttpExchange httpExchange) throws Exception {\n RequestHandlerRouter handlerManager = getHandlerRouter(project);\n if (handlerManager == null) {\n httpExchange.discardReqBody();\n httpExchange.writeJson(404, \"NOT_FOUND\");\n return;\n }\n handlerManager.invoke(httpExchange);\n }\n\n public RequestHandlerRouter getHandlerRouter(String projectName) {\n return projectMap.get(projectName);\n }\n\n public final Injector getInjector() {\n return injector;\n }\n\n @Override\n public void destroy() {\n for (Map.Entry<String, RequestHandlerRouter> entry : projectMap.entrySet()) {\n entry.getValue().destroy();\n log.info(\"project {} is removed\", entry.getKey());\n }\n projectMap.clear();\n }\n}" }, { "identifier": "Binder", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/ioc/Binder.java", "snippet": "public interface Binder {\n <T> void bind(Class<? super T> clz, T instance);\n\n <T> void forceBind(Class<? super T> clz, T instance);\n\n <T> void bindFactory(Class<? super T> clz, Function<Injector, T> creator);\n\n <T> void bindLink(Class<? super T> clz, Class<T> real);\n\n <T> void forceBindFactory(Class<? super T> clz, Function<Injector, T> creator);\n\n <T> void bindPrototype(Class<? super T> clz, Function<Injector, T> creator);\n\n <T> void forceBindPrototype(Class<? super T> clz, Function<Injector, T> creator);\n\n <T> void forceBindLink(Class<? super T> clz, Class<T> real);\n\n <T, V extends T> void bindMultiBean(Class<T> clz, Class<V> real);\n\n <T> boolean removeBind(Class<T> clz);\n}" }, { "identifier": "ArrayUtils", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/utils/ArrayUtils.java", "snippet": "public class ArrayUtils {\n public static <T> boolean isEmpty(char[] arr) {\n return arr == null || arr.length == 0;\n }\n\n public static <T> boolean isEmpty(T[] arr) {\n return arr == null || arr.length == 0;\n }\n\n public static <T> boolean isNotEmpty(T[] arr) {\n return arr != null && arr.length != 0;\n }\n\n public static <T> boolean contains(T[] arr, T search) {\n if (arr == null) {\n return false;\n }\n for (T t : arr) {\n if (t == search) {\n return true;\n }\n if (search != null && search.equals(t)) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean isNotEmpty(byte[] body) {\n return body != null && body.length > 0;\n }\n}" }, { "identifier": "StringUtils", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/utils/StringUtils.java", "snippet": "public class StringUtils {\n private static final int INDEX_NOT_FOUND = -1;\n\n public static boolean isNotEmpty(CharSequence s) {\n return s != null && s.length() > 0;\n }\n\n public static String[] translateCommandline(String toProcess) {\n if (toProcess == null || toProcess.length() == 0) {\n //no command? no string\n return Constant.EMPTY_STR_ARR;\n }\n\n // parse with a simple finite state machine\n\n final int normal = 0;\n final int inQuote = 1;\n final int inDoubleQuote = 2;\n boolean escape = false;\n int state = normal;\n StringTokenizer tok = new StringTokenizer(toProcess, \"\\\\\\\"\\' \", true);\n List<String> v = new ArrayList<>();\n StringBuilder current = new StringBuilder();\n boolean lastTokenHasBeenQuoted = false;\n\n while (tok.hasMoreTokens()) {\n String nextTok = tok.nextToken();\n if (escape) {\n if (!nextTok.equals(\"\\\"\") && !nextTok.equals(\"'\") && !nextTok.equals(\"\\\\\") && !nextTok.equals(\" \")) {\n current.append('\\\\');\n }\n current.append(nextTok);\n escape = false;\n continue;\n } else if (nextTok.equals(\"\\\\\")) {\n escape = true;\n continue;\n }\n switch (state) {\n case inQuote:\n if (\"\\'\".equals(nextTok)) {\n lastTokenHasBeenQuoted = true;\n state = normal;\n } else {\n current.append(nextTok);\n }\n break;\n case inDoubleQuote:\n if (\"\\\"\".equals(nextTok)) {\n lastTokenHasBeenQuoted = true;\n state = normal;\n } else {\n current.append(nextTok);\n }\n break;\n default:\n if (\"\\'\".equals(nextTok)) {\n state = inQuote;\n } else if (\"\\\"\".equals(nextTok)) {\n state = inDoubleQuote;\n } else if (\" \".equals(nextTok)) {\n if (lastTokenHasBeenQuoted || current.length() != 0) {\n v.add(current.toString());\n current = new StringBuilder();\n }\n } else {\n current.append(nextTok);\n }\n lastTokenHasBeenQuoted = false;\n break;\n }\n }\n\n if (lastTokenHasBeenQuoted || current.length() != 0) {\n v.add(current.toString());\n }\n\n if (state == inQuote || state == inDoubleQuote) {\n throw new IllegalArgumentException(\"unbalanced quotes in \" + toProcess);\n }\n\n return v.toArray(Constant.EMPTY_STR_ARR);\n }\n\n public static boolean isEmpty(Object str) {\n return (str == null || \"\".equals(str));\n }\n\n public static boolean isEmpty(CharSequence str) {\n return (str == null || \"\".contentEquals(str));\n }\n\n public static boolean isEmpty(String str) {\n return (str == null || \"\".equals(str));\n }\n\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n public static String camelToKebabCase(String camel) {\n if (StringUtils.isEmpty(camel)) {\n return camel;\n }\n StringBuilder sb = new StringBuilder(camel.length() + 4);\n boolean f = true;\n for (int i = 0; i < camel.length(); i++) {\n char c = camel.charAt(i);\n if (c >= 'A' && c <= 'Z') {\n if (!f) {\n sb.append('-');\n }\n sb.append(Character.toLowerCase(c));\n } else {\n sb.append(c);\n }\n f = false;\n }\n return sb.toString();\n }\n\n public static int lastIndexOfIgnoreCase(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return INDEX_NOT_FOUND;\n }\n return lastIndexOfIgnoreCase(str, searchStr, str.length());\n }\n\n /**\n * <p>Case in-sensitive find of the last index within a String\n * from the specified position.</p>\n *\n * <p>A <code>null</code> String will return <code>-1</code>.\n * A negative start position returns <code>-1</code>.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.</p>\n *\n * <pre>\n * StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1\n * StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 8) = 7\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 8) = 5\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\", 8) = 4\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 9) = 5\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = -1\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 0) = 0\n * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 0) = -1\n * </pre>\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position\n * @return the first index of the search String,\n * -1 if no match or <code>null</code> string input\n */\n public static int lastIndexOfIgnoreCase(String str, String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return INDEX_NOT_FOUND;\n }\n if (startPos > (str.length() - searchStr.length())) {\n startPos = str.length() - searchStr.length();\n }\n if (startPos < 0) {\n return INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n\n for (int i = startPos; i >= 0; i--) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return INDEX_NOT_FOUND;\n }\n\n public static String trimRight(String src, String search) {\n if (isEmpty(src) || isEmpty(search)) {\n return src;\n }\n int len = search.length();\n int e = src.length() - len;\n while (e >= 0 && src.regionMatches(e, search, 0, len)) {\n e -= len;\n }\n return src.substring(0, e + len);\n }\n\n public static String trimLeft(String src, String search) {\n if (isEmpty(src) || isEmpty(search)) {\n return src;\n }\n int len = search.length();\n int oLen = src.length();\n int s = 0;\n while (s < oLen && src.regionMatches(s, search, 0, len)) {\n s += len;\n }\n return src.substring(s);\n }\n\n public static String trim(String src, String search) {\n if (isEmpty(src) || isEmpty(search)) {\n return src;\n }\n int len = search.length();\n int oLen = src.length();\n int s = 0, e = oLen - len;\n while (s < oLen && src.regionMatches(s, search, 0, len)) {\n s += len;\n }\n\n while (e >= s && src.regionMatches(e, search, 0, len)) {\n e -= len;\n }\n e += len;\n if (s >= e) {\n return \"\";\n }\n return src.substring(s, e);\n }\n\n public static String trimLeftEmpty(String src) {\n if (isEmpty(src)) {\n return src;\n }\n char[] val = CharArrUtil.toCharArr(src);\n int len = val.length;\n int st = 0;\n\n while ((st < len) && (val[st] <= ' ')) {\n st++;\n }\n return (st > 0) ? new String(val, st, len) : src;\n }\n\n public static String trimRightEmpty(String src) {\n if (isEmpty(src)) {\n return src;\n }\n char[] val = CharArrUtil.toCharArr(src);\n int len = val.length;\n\n while ((0 < len) && (val[len - 1] <= ' ')) {\n len--;\n }\n return len == val.length ? new String(val, 0, len) : src;\n }\n\n /**\n * Performs the logic for the {@code split} and\n * {@code splitPreserveAllTokens} methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be {@code null}\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if {@code true}, adjacent separators are\n * treated as empty token separators; if {@code false}, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, {@code null} if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len == 0) {\n return Constant.EMPTY_STR_ARR;\n }\n final List<String> list = new ArrayList<String>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n final char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(Constant.EMPTY_STR_ARR);\n }\n\n public static String[] split(final String str, final String separatorChars) {\n return splitWorker(str, separatorChars, -1, false);\n }\n\n public static boolean containsAny(final String src, final char... searchChars) {\n if (isEmpty(src) || ArrayUtils.isEmpty(searchChars)) {\n return false;\n }\n char[] cs = CharArrUtil.toCharArr(src);\n final int csLength = cs.length;\n final int searchLength = searchChars.length;\n final int csLast = csLength - 1;\n final int searchLast = searchLength - 1;\n for (int i = 0; i < csLength; i++) {\n final char ch = cs[i];\n for (int j = 0; j < searchLength; j++) {\n if (searchChars[j] == ch) {\n if (Character.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return true;\n }\n if (i < csLast && searchChars[j + 1] == cs[i + 1]) {\n return true;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return true;\n }\n }\n }\n }\n return false;\n }\n\n public static int indexOfAny(final String src, final char... searchChars) {\n if (isEmpty(src) || ArrayUtils.isEmpty(searchChars)) {\n return INDEX_NOT_FOUND;\n }\n char[] cs = CharArrUtil.toCharArr(src);\n final int csLen = cs.length;\n final int csLast = csLen - 1;\n final int searchLen = searchChars.length;\n final int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n final char ch = cs[i];\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {\n // ch is a supplementary character\n if (searchChars[j + 1] == cs[i + 1]) {\n return i;\n }\n } else {\n return i;\n }\n }\n }\n }\n return INDEX_NOT_FOUND;\n }\n}" }, { "identifier": "DubboModule", "path": "fiber-gateway-dubbo/src/main/java/io/fiber/net/dubbo/nacos/DubboModule.java", "snippet": "public class DubboModule implements Module {\n private static DubboConfig defaultConfig() {\n String registry = SystemPropertyUtil.get(\"fiber.dubbo.registry\");\n if (StringUtils.isEmpty(registry)) {\n throw new IllegalStateException(\"no dubbo registry configured. -Dfiber.dubbo.registry=\");\n }\n DubboConfig config = new DubboConfig();\n config.setRegistryAddr(registry);\n config.setApplicationName(SystemPropertyUtil.get(\"fiber.dubbo.appName\", config.getApplicationName()));\n config.setProtocol(SystemPropertyUtil.get(\"fiber.dubbo.protocol\", config.getProtocol()));\n return config;\n }\n\n public static void install(Binder binder, DubboConfig config) {\n binder.bindFactory(DubboClient.class, injector -> new DubboClient(config));\n binder.bindMultiBean(ProxyModule.class, ScriptModule.class);\n binder.bind(ScriptModule.class, ScriptModule.INSTANCE);\n }\n\n private final DubboConfig config;\n\n public DubboModule() {\n this(defaultConfig());\n }\n\n public DubboModule(DubboConfig config) {\n this.config = config;\n }\n\n @Override\n public void install(Binder binder) {\n install(binder, config);\n }\n\n\n private static class ScriptModule implements ProxyModule {\n static final ScriptModule INSTANCE = new ScriptModule();\n\n @Override\n public void install(Binder binder) {\n binder.bindPrototype(DubboLibConfigure.class, DubboLibConfigure::new);\n binder.bindMultiBean(HttpLibConfigure.class, DubboLibConfigure.class);\n }\n }\n}" }, { "identifier": "ConfigWatcher", "path": "fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/ConfigWatcher.java", "snippet": "public interface ConfigWatcher {\n ConfigWatcher NOOP_WATCHER = engine -> {\n };\n\n void startWatch(Engine engine) throws Exception;\n}" }, { "identifier": "LibProxyMainModule", "path": "fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/LibProxyMainModule.java", "snippet": "public class LibProxyMainModule implements Module {\n\n private static class SubModule implements ProxyModule {\n private final Injector engineInjector;\n private Injector projectInjector;\n\n public SubModule(Injector engineInjector) {\n this.engineInjector = engineInjector;\n }\n\n\n @Override\n public void install(Binder binder) {\n binder.bindPrototype(ProjectRouterBuilder.class, ProjectRouterBuilder::new);\n }\n\n synchronized void createProject(String projectName, String code) throws Exception {\n Injector injector;\n if (projectInjector != null) {\n injector = projectInjector.fork();\n } else {\n injector = projectInjector = engineInjector.createChild(engineInjector.getInstances(ProxyModule.class));\n }\n\n try {\n ProjectRouterBuilder builder = injector.getInstance(ProjectRouterBuilder.class);\n builder.setCode(code);\n builder.setName(projectName);\n injector.getInstance(Engine.class).addHandlerRouter(builder.build());\n } catch (Throwable e) {\n injector.destroy();\n throw e;\n }\n }\n }\n\n private static class ProxyStartListener implements StartListener {\n @Override\n public void onStart(Engine engine) throws Exception {\n ConfigWatcher watcher = engine.getInjector().getInstance(ConfigWatcher.class);\n watcher.startWatch(engine);\n }\n }\n\n @Override\n public void install(Binder binder) {\n binder.bindFactory(HttpClient.class, injector -> {\n EngineModule.EventLoopGroupHolder groupHolder = injector.getInstance(EngineModule.EventLoopGroupHolder.class);\n return new DefaultHttpClient(groupHolder.getGroup());\n });\n binder.bindMultiBean(ProxyModule.class, SubModule.class);\n binder.bindFactory(SubModule.class, SubModule::new);\n binder.bindMultiBean(StartListener.class, ProxyStartListener.class);\n binder.bind(ProxyStartListener.class, new ProxyStartListener());\n binder.bind(ConfigWatcher.class, ConfigWatcher.NOOP_WATCHER);\n }\n\n public static void createProject(Engine engine, String projectName, String code) throws Exception {\n SubModule subModule = engine.getInjector().getInstance(SubModule.class);\n assert subModule.engineInjector == engine.getInjector();\n subModule.createProject(projectName, code);\n }\n\n public static Engine createEngineWithSPI(ClassLoader loader) throws Exception {\n ServiceLoader<Module> serviceLoader = ServiceLoader.load(Module.class,\n loader == null ? Thread.currentThread().getContextClassLoader() : loader);\n return createEngine(serviceLoader);\n }\n\n public static Engine createEngine(Module... extModules) throws Exception {\n return createEngine(Arrays.asList(extModules));\n }\n\n public static Engine createEngine(Iterable<Module> extModules) throws Exception {\n List<Module> modules = new ArrayList<>();\n modules.add(new EngineModule());\n modules.add(new LibProxyMainModule());\n for (Module module : extModules) {\n modules.add(module);\n }\n\n Injector injector = Injector.getRoot().createChild(modules);\n Engine engine = injector.getInstance(Engine.class);\n try {\n engine.installExt();\n } catch (Throwable e) {\n injector.destroy();\n throw e;\n }\n return engine;\n }\n\n}" }, { "identifier": "HttpServer", "path": "fiber-gateway-server/src/main/java/io/fiber/net/server/HttpServer.java", "snippet": "public interface HttpServer extends Destroyable {\n void start(ServerConfig config, Engine engine) throws Exception;\n\n void awaitShutdown();\n}" }, { "identifier": "ServerConfig", "path": "fiber-gateway-server/src/main/java/io/fiber/net/server/ServerConfig.java", "snippet": "public class ServerConfig {\n public static final int DEF_BACKLOG = SystemPropertyUtil.getInt(\"fiber.http.server.backlog\", 128);\n public static final int DEF_MAX_INITIAL_LINE_LENGTH\n = SystemPropertyUtil.getInt(\"fiber.http.server.maxInitialLineLen\", 32 << 10);\n public static final int DEF_MAX_HEADER_SIZE =\n SystemPropertyUtil.getInt(\"fiber.http.server.maxHeaderSize\", 64 << 10);\n public static final int DEF_MAX_CHUNK_SIZE =\n SystemPropertyUtil.getInt(\"fiber.http.server.maxChunkSize\", 128 << 10);\n public static final int DEF_SERVER_PORT =\n SystemPropertyUtil.getInt(\"fiber.http.server.serverPort\", 16688);\n\n public static final int DEF_MAX_BODY_SIZE =\n SystemPropertyUtil.getInt(\"fiber.http.server.maxBodySize\", 16 << 20);\n public static final boolean DEF_TCP_NO_DELAY =\n SystemPropertyUtil.getBoolean(\"fiber.http.server.tcpNoDelay\", true);\n public static final boolean DEF_TCP_KEEP_ALIVE =\n SystemPropertyUtil.getBoolean(\"fiber.http.server.tcpKeepAlive\", true);\n\n private int backlog = DEF_BACKLOG;\n private int maxInitialLineLength = DEF_MAX_INITIAL_LINE_LENGTH;\n private int maxHeaderSize = DEF_MAX_HEADER_SIZE;\n private int maxChunkSize = DEF_MAX_CHUNK_SIZE;\n private int serverPort = DEF_SERVER_PORT;\n\n private int maxBodySize = DEF_MAX_BODY_SIZE;\n private boolean tcpNoDelay = DEF_TCP_NO_DELAY;\n private boolean tcpKeepAlive = DEF_TCP_KEEP_ALIVE;\n private String bindIp;\n\n public int getBacklog() {\n return backlog;\n }\n\n public void setBacklog(int backlog) {\n this.backlog = backlog;\n }\n\n public int getMaxInitialLineLength() {\n return maxInitialLineLength;\n }\n\n public void setMaxInitialLineLength(int maxInitialLineLength) {\n this.maxInitialLineLength = maxInitialLineLength;\n }\n\n public int getMaxHeaderSize() {\n return maxHeaderSize;\n }\n\n public void setMaxHeaderSize(int maxHeaderSize) {\n this.maxHeaderSize = maxHeaderSize;\n }\n\n public int getMaxChunkSize() {\n return maxChunkSize;\n }\n\n public void setMaxChunkSize(int maxChunkSize) {\n this.maxChunkSize = maxChunkSize;\n }\n\n public int getServerPort() {\n return serverPort;\n }\n\n public void setServerPort(int serverPort) {\n this.serverPort = serverPort;\n }\n\n public boolean isTcpNoDelay() {\n return tcpNoDelay;\n }\n\n public void setTcpNoDelay(boolean tcpNoDelay) {\n this.tcpNoDelay = tcpNoDelay;\n }\n\n public boolean isTcpKeepAlive() {\n return tcpKeepAlive;\n }\n\n public void setTcpKeepAlive(boolean tcpKeepAlive) {\n this.tcpKeepAlive = tcpKeepAlive;\n }\n\n public int getMaxBodySize() {\n return maxBodySize;\n }\n\n public void setMaxBodySize(int maxBodySize) {\n this.maxBodySize = maxBodySize;\n }\n\n public String getBindIp() {\n return bindIp;\n }\n\n public void setBindIp(String bindIp) {\n this.bindIp = bindIp;\n }\n}" } ]
import io.fiber.net.common.Engine; import io.fiber.net.common.ioc.Binder; import io.fiber.net.common.utils.ArrayUtils; import io.fiber.net.common.utils.StringUtils; import io.fiber.net.dubbo.nacos.DubboModule; import io.fiber.net.proxy.ConfigWatcher; import io.fiber.net.proxy.LibProxyMainModule; import io.fiber.net.server.HttpServer; import io.fiber.net.server.ServerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File;
7,473
package io.fiber.net.example; public class Main { private static final Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { if (ArrayUtils.isEmpty(args) || StringUtils.isEmpty(args[0])) { throw new IllegalArgumentException("onInit path is required"); } File file = new File(args[0]); if (!file.exists() || !file.isDirectory()) { throw new IllegalArgumentException("onInit path must be directory"); }
package io.fiber.net.example; public class Main { private static final Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { if (ArrayUtils.isEmpty(args) || StringUtils.isEmpty(args[0])) { throw new IllegalArgumentException("onInit path is required"); } File file = new File(args[0]); if (!file.exists() || !file.isDirectory()) { throw new IllegalArgumentException("onInit path must be directory"); }
Engine engine = LibProxyMainModule.createEngine(
6
2023-12-08 15:18:05+00:00
12k
sigbla/sigbla-pds
src/main/java/sigbla/app/pds/collection/TreeMap.java
[ { "identifier": "AbstractIterable", "path": "src/main/java/sigbla/app/pds/collection/internal/base/AbstractIterable.java", "snippet": "public abstract class AbstractIterable<E> extends AbstractTraversable<E> implements sigbla.app.pds.collection.Iterable<E> {\n @SuppressWarnings(\"NullableProblems\")\n @Override\n public <U> void forEach(@NotNull final Function<E, U> f) {\n for (E next : this) {\n f.invoke(next);\n }\n }\n}" }, { "identifier": "AbstractSortedMap", "path": "src/main/java/sigbla/app/pds/collection/internal/base/AbstractSortedMap.java", "snippet": "public abstract class AbstractSortedMap<K, V> extends AbstractMap<K, V> implements SortedMap<K, V> {\n @NotNull\n @Override\n public SortedMap<K, V> from(@NotNull K key, boolean inclusive) {\n Pair<K, V> last = last();\n if (last == null) return this;\n return range(key, inclusive, last.component1(), true);\n }\n\n @NotNull\n @Override\n public SortedMap<K, V> to(@NotNull K key, boolean inclusive) {\n Pair<K, V> first = first();\n if (first == null) return this;\n return range(first.component1(), true, key, inclusive);\n }\n\n @NotNull\n @Override\n public java.util.SortedMap<K, V> asSortedMap() {\n return new SortedMapAdapter<K, V>(this);\n }\n}" }, { "identifier": "AbstractSelfBuilder", "path": "src/main/java/sigbla/app/pds/collection/internal/builder/AbstractSelfBuilder.java", "snippet": "public abstract class AbstractSelfBuilder<E, R> extends AbstractBuilder<E, R> {\n protected R result;\n\n protected AbstractSelfBuilder(R empty) {\n this.result = empty;\n }\n\n @NotNull\n @Override\n public R doBuild() {\n return result;\n }\n}" }, { "identifier": "DefaultTreeFactory", "path": "src/main/java/sigbla/app/pds/collection/internal/redblack/DefaultTreeFactory.java", "snippet": "public class DefaultTreeFactory implements TreeFactory {\n public <K, V> Tree<K, V> red(K key, V value, Tree<K, V> left, Tree<K, V> right) {\n return new DefaultRedTree<K, V>(key, value, left, right);\n }\n\n public <K, V> Tree<K, V> black(K key, V value, Tree<K, V> left, Tree<K, V> right) {\n return new DefaultBlackTree<K, V>(key, value, left, right);\n }\n}" }, { "identifier": "DerivedKeyFactory", "path": "src/main/java/sigbla/app/pds/collection/internal/redblack/DerivedKeyFactory.java", "snippet": "public class DerivedKeyFactory implements TreeFactory {\n public <K, V> Tree<K, V> red(K key, V value, Tree<K, V> left, Tree<K, V> right) {\n return new DerivedKeyRedTree<K, V>(left, right, value);\n }\n\n public <K, V> Tree<K, V> black(K key, V value, Tree<K, V> left, Tree<K, V> right) {\n return new DerivedKeyBlackTree<K, V>(left, right, value);\n }\n}" }, { "identifier": "RedBlackTree", "path": "src/main/java/sigbla/app/pds/collection/internal/redblack/RedBlackTree.java", "snippet": "public class RedBlackTree<K, V> {\n private final TreeFactory factory;\n private final Comparator<? super K> ordering;\n private final KeyFunction<K, V> kf;\n\n @SuppressWarnings(\"unchecked\")\n private static final Comparator DEFAULT_COMPARATOR = new Comparator() {\n public int compare(@NotNull Object o1, @NotNull Object o2) {\n return ((Comparable) o1).compareTo(o2);\n }\n };\n\n public RedBlackTree() {\n this(new DefaultTreeFactory(), null, null);\n }\n\n @SuppressWarnings(\"unchecked\")\n public RedBlackTree(TreeFactory factory, Comparator<? super K> ordering, KeyFunction<K, V> keyFunction) {\n this.factory = factory;\n this.kf = keyFunction;\n\n if (ordering == null) {\n ordering = DEFAULT_COMPARATOR;\n }\n\n this.ordering = ordering;\n }\n\n public KeyFunction<K, V> getKeyFunction() {\n return kf;\n }\n\n public Comparator<? super K> getOrdering() {\n return ordering == DEFAULT_COMPARATOR ? null : ordering;\n }\n\n public boolean isEmpty(Tree<K, V> tree) {\n return tree == null;\n }\n\n public boolean contains(Tree<K, V> tree, K x) {\n return lookup(tree, x) != null;\n }\n\n public V get(Tree<K, V> tree, K x) {\n Tree<K, V> lookup = lookup(tree, x);\n return lookup == null ? null : lookup.getValue();\n }\n\n // TODO: Remove recursion @tailrec\n public Tree<K, V> lookup(Tree<K, V> tree, K x) {\n if (tree == null)\n return null;\n\n int cmp = ordering.compare(x, tree.getKey(kf));\n\n if (cmp < 0) return lookup(tree.getLeft(), x);\n else if (cmp > 0) return lookup(tree.getRight(), x);\n else return tree;\n }\n\n public static int count(Tree<?, ?> tree) {\n return tree == null ? 0 : tree.count();\n }\n\n public Tree<K, V> update(Tree<K, V> tree, K k, V v, boolean overwrite) {\n return blacken(upd(tree, k, v, overwrite));\n }\n\n public Tree<K, V> delete(Tree<K, V> tree, K k) {\n return blacken(del(tree, k));\n }\n\n public Tree<K, V> range(Tree<K, V> tree, K from, boolean fromInclusive, K until, boolean untilInclusive) {\n return blacken(doRange(tree, from, fromInclusive, until, untilInclusive));\n }\n\n public Tree<K, V> from(Tree<K, V> tree, K from, boolean inclusive) {\n return blacken(doFrom(tree, from, inclusive));\n }\n\n public Tree<K, V> until(Tree<K, V> tree, K key, boolean inclusive) {\n return blacken(doUntil(tree, key, inclusive));\n }\n\n public Tree<K, V> drop(Tree<K, V> tree, int n) {\n return blacken(doDrop(tree, n));\n }\n\n public Tree<K, V> take(Tree<K, V> tree, int n) {\n return blacken(doTake(tree, n));\n }\n\n public Tree<K, V> slice(Tree<K, V> tree, int from, int until) {\n return blacken(doSlice(tree, from, until));\n }\n\n public Tree<K, V> smallest(Tree<K, V> tree) {\n if (tree == null) throw new NoSuchElementException(\"empty map\");\n Tree<K, V> result = tree;\n while (result.getLeft() != null) result = result.getLeft();\n return result;\n }\n\n public Tree<K, V> greatest(Tree<K, V> tree) {\n if (tree == null) throw new NoSuchElementException(\"empty map\");\n Tree<K, V> result = tree;\n while (result.getRight() != null) result = result.getRight();\n return result;\n }\n\n public <U> void forEach(Tree<K, V> tree, Function<Pair<K, V>, U> f) {\n if (tree != null) {\n if (tree.getLeft() != null) {\n forEach(tree.getLeft(), f);\n }\n f.invoke(new Pair<K, V>(tree.getKey(kf), tree.getValue()));\n if (tree.getRight() != null) {\n forEach(tree.getRight(), f);\n }\n }\n }\n\n // def foreach[K, V, U](tree: Tree[K, V], f: ((K, V)) => U): Unit = if (tree ne null) {\n// if (tree.left ne null) foreach(tree.left, f)\n// f((tree.key, tree.value))\n// if (tree.right ne null) foreach(tree.right, f)\n// }\n\n\n// def foreachKey[K, U](tree: Tree[K, _], f: K => U): Unit = if (tree ne null) {\n// if (tree.left ne null) foreachKey(tree.left, f)\n// f(tree.key)\n// if (tree.right ne null) foreachKey(tree.right, f)\n// }\n\n public Iterator<Pair<K, V>> iterator(Tree<K, V> tree) {\n return new EntriesIterator<K, V>(tree);\n }\n\n public Iterator<K> keysIterator(Tree<K, V> tree) {\n return new KeysIterator<K, V>(tree, kf);\n }\n\n public Iterator<V> valuesIterator(Tree<K, V> tree) {\n return new ValuesIterator<K, V>(tree);\n }\n\n private boolean isRedTree(Tree<?, ?> tree) {\n return tree != null && tree.isRed();\n }\n\n private boolean isBlackTree(Tree<?, ?> tree) {\n return tree != null && tree.isBlack();\n }\n\n private Tree<K, V> blacken(Tree<K, V> t) {\n return (t == null) ? null : t.black();\n }\n\n private Tree<K, V> mkTree(boolean isBlack, K k, V v, Tree<K, V> l, Tree<K, V> r) {\n return isBlack ? factory.black(k, v, l, r) : factory.red(k, v, l, r);\n }\n\n private Tree<K, V> balanceLeft(boolean isBlack, K z, V zv, Tree<K, V> l, Tree<K, V> d) {\n if (isRedTree(l) && isRedTree(l.getLeft()))\n return factory.red(l.getKey(kf), l.getValue(), factory.black(l.getLeft().getKey(kf), l.getLeft().getValue(), l.getLeft().getLeft(), l.getLeft().getRight()), factory.black(z, zv, l.getRight(), d));\n else if (isRedTree(l) && isRedTree(l.getRight()))\n return factory.red(l.getRight().getKey(kf), l.getRight().getValue(), factory.black(l.getKey(kf), l.getValue(), l.getLeft(), l.getRight().getLeft()), factory.black(z, zv, l.getRight().getRight(), d));\n else\n return mkTree(isBlack, z, zv, l, d);\n }\n\n private Tree<K, V> balanceRight(boolean isBlack, K x, V xv, Tree<K, V> a, Tree<K, V> r) {\n if (isRedTree(r) && isRedTree(r.getLeft()))\n return factory.red(r.getLeft().getKey(kf), r.getLeft().getValue(), factory.black(x, xv, a, r.getLeft().getLeft()), factory.black(r.getKey(kf), r.getValue(), r.getLeft().getRight(), r.getRight()));\n else if (isRedTree(r) && isRedTree(r.getRight()))\n return factory.red(r.getKey(kf), r.getValue(), factory.black(x, xv, a, r.getLeft()), factory.black(r.getRight().getKey(kf), r.getRight().getValue(), r.getRight().getLeft(), r.getRight().getRight()));\n else\n return mkTree(isBlack, x, xv, a, r);\n }\n\n private Tree<K, V> upd(Tree<K, V> tree, K k, V v, boolean overwrite) {\n if (tree == null)\n return factory.red(k, v, null, null);\n\n int cmp = ordering.compare(k, tree.getKey(kf));\n\n if (cmp < 0)\n return balanceLeft(isBlackTree(tree), tree.getKey(kf), tree.getValue(), upd(tree.getLeft(), k, v, overwrite), tree.getRight());\n\n if (cmp > 0)\n return balanceRight(isBlackTree(tree), tree.getKey(kf), tree.getValue(), tree.getLeft(), upd(tree.getRight(), k, v, overwrite));\n\n if (overwrite || !k.equals(tree.getKey(kf))) // Hmmm ... how can these not be equal\n return mkTree(isBlackTree(tree), k, v, tree.getLeft(), tree.getRight());\n\n return tree;\n }\n\n private Tree<K, V> updNth(Tree<K, V> tree, int idx, K k, V v, boolean overwrite) {\n if (tree == null) {\n return mkTree(false, k, v, null, null);\n } else {\n int rank = count(tree.getLeft()) + 1;\n if (idx < rank) {\n return balanceLeft(isBlackTree(tree), tree.getKey(kf), tree.getValue(), updNth(tree.getLeft(), idx, k, v, overwrite), tree.getRight());\n } else if (idx > rank) {\n return balanceRight(isBlackTree(tree), tree.getKey(kf), tree.getValue(), tree.getLeft(), updNth(tree.getRight(), idx - rank, k, v, overwrite));\n } else if (overwrite) {\n return mkTree(isBlackTree(tree), k, v, tree.getLeft(), tree.getRight());\n }\n return tree;\n }\n }\n\n /* Based on Stefan Kahrs' Haskell version of Okasaki's Red&Black Trees\n * http://www.cse.unsw.edu.au/~dons/data/RedBlackTree.html */\n private Tree<K, V> del(Tree<K, V> tree, K k) {\n if (tree == null)\n return null;\n\n int cmp = ordering.compare(k, tree.getKey(kf));\n if (cmp < 0) return delLeft(tree, k);\n else if (cmp > 0) return delRight(tree, k);\n else return append(tree.getLeft(), tree.getRight());\n }\n\n private Tree<K, V> balance(K x, V xv, Tree<K, V> tl, Tree<K, V> tr) {\n if (isRedTree(tl)) {\n if (isRedTree(tr)) {\n return factory.red(x, xv, tl.black(), tr.black());\n } else if (isRedTree(tl.getLeft())) {\n return factory.red(tl.getKey(kf), tl.getValue(), tl.getLeft().black(), factory.black(x, xv, tl.getRight(), tr));\n } else if (isRedTree(tl.getRight())) {\n return factory.red(tl.getRight().getKey(kf), tl.getRight().getValue(), factory.black(tl.getKey(kf), tl.getValue(), tl.getLeft(), tl.getRight().getLeft()), factory.black(x, xv, tl.getRight().getRight(), tr));\n } else {\n return factory.black(x, xv, tl, tr);\n }\n } else if (isRedTree(tr)) {\n if (isRedTree(tr.getRight())) {\n return factory.red(tr.getKey(kf), tr.getValue(), factory.black(x, xv, tl, tr.getLeft()), tr.getRight().black());\n } else if (isRedTree(tr.getLeft())) {\n return factory.red(tr.getLeft().getKey(kf), tr.getLeft().getValue(), factory.black(x, xv, tl, tr.getLeft().getLeft()), factory.black(tr.getKey(kf), tr.getValue(), tr.getLeft().getRight(), tr.getRight()));\n } else {\n return factory.black(x, xv, tl, tr);\n }\n } else {\n return factory.black(x, xv, tl, tr);\n }\n }\n\n private Tree<K, V> subl(Tree<K, V> t) {\n if (isBlackTree(t))\n return t.red();\n\n throw new RuntimeException(\"Defect: invariance violation; expected black, got \" + t);\n }\n\n private Tree<K, V> balLeft(K x, V xv, Tree<K, V> tl, Tree<K, V> tr) {\n if (isRedTree(tl)) {\n return factory.red(x, xv, tl.black(), tr);\n } else if (isBlackTree(tr)) {\n return balance(x, xv, tl, tr.red());\n } else if (isRedTree(tr) && isBlackTree(tr.getLeft())) {\n return factory.red(tr.getLeft().getKey(kf), tr.getLeft().getValue(), factory.black(x, xv, tl, tr.getLeft().getLeft()), balance(tr.getKey(kf), tr.getValue(), tr.getLeft().getRight(), subl(tr.getRight())));\n } else {\n throw new RuntimeException(\"Defect: invariance violation\");\n }\n }\n\n private Tree<K, V> balRight(K x, V xv, Tree<K, V> tl, Tree<K, V> tr) {\n if (isRedTree(tr)) {\n return factory.red(x, xv, tl, tr.black());\n } else if (isBlackTree(tl)) {\n return balance(x, xv, tl.red(), tr);\n } else if (isRedTree(tl) && isBlackTree(tl.getRight())) {\n return factory.red(tl.getRight().getKey(kf), tl.getRight().getValue(), balance(tl.getKey(kf), tl.getValue(), subl(tl.getLeft()), tl.getRight().getLeft()), factory.black(x, xv, tl.getRight().getRight(), tr));\n } else {\n throw new RuntimeException(\"Defect: invariance violation\");\n }\n }\n\n private Tree<K, V> delLeft(Tree<K, V> tree, K k) {\n return isBlackTree(tree.getLeft()) ? balLeft(tree.getKey(kf), tree.getValue(), del(tree.getLeft(), k), tree.getRight()) : factory.red(tree.getKey(kf), tree.getValue(), del(tree.getLeft(), k), tree.getRight());\n }\n\n private Tree<K, V> delRight(Tree<K, V> tree, K k) {\n return isBlackTree(tree.getRight()) ? balRight(tree.getKey(kf), tree.getValue(), tree.getLeft(), del(tree.getRight(), k)) : factory.red(tree.getKey(kf), tree.getValue(), tree.getLeft(), del(tree.getRight(), k));\n }\n\n public Tree<K, V> append(Tree<K, V> tl, Tree<K, V> tr) {\n if (tl == null) {\n return tr;\n } else if (tr == null) {\n return tl;\n } else if (isRedTree(tl) && isRedTree(tr)) {\n Tree<K, V> bc = append(tl.getRight(), tr.getLeft());\n if (isRedTree(bc)) {\n return factory.red(bc.getKey(kf), bc.getValue(), factory.red(tl.getKey(kf), tl.getValue(), tl.getLeft(), bc.getLeft()), factory.red(tr.getKey(kf), tr.getValue(), bc.getRight(), tr.getRight()));\n } else {\n return factory.red(tl.getKey(kf), tl.getValue(), tl.getLeft(), factory.red(tr.getKey(kf), tr.getValue(), bc, tr.getRight()));\n }\n } else if (isBlackTree(tl) && isBlackTree(tr)) {\n Tree<K, V> bc = append(tl.getRight(), tr.getLeft());\n if (isRedTree(bc)) {\n return factory.red(bc.getKey(kf), bc.getValue(), factory.black(tl.getKey(kf), tl.getValue(), tl.getLeft(), bc.getLeft()), factory.black(tr.getKey(kf), tr.getValue(), bc.getRight(), tr.getRight()));\n } else {\n return balLeft(tl.getKey(kf), tl.getValue(), tl.getLeft(), factory.black(tr.getKey(kf), tr.getValue(), bc, tr.getRight()));\n }\n } else if (isRedTree(tr)) {\n return factory.red(tr.getKey(kf), tr.getValue(), append(tl, tr.getLeft()), tr.getRight());\n } else if (isRedTree(tl)) {\n return factory.red(tl.getKey(kf), tl.getValue(), tl.getLeft(), append(tl.getRight(), tr));\n } else {\n throw new RuntimeException(\"unmatched tree on append: \" + tl + \", \" + tr);\n }\n }\n\n private Tree<K, V> doFrom(Tree<K, V> tree, K from, boolean inclusive) {\n if (tree == null) return null;\n if (inclusive) {\n if (ordering.compare(tree.getKey(kf), from) < 0) return doFrom(tree.getRight(), from, true);\n } else {\n if (ordering.compare(tree.getKey(kf), from) <= 0) return doFrom(tree.getRight(), from, false);\n }\n\n Tree<K, V> newLeft = doFrom(tree.getLeft(), from, inclusive);\n if (newLeft != null && newLeft.equals(tree.getLeft())) return tree;\n else if (newLeft == null) return upd(tree.getRight(), tree.getKey(kf), tree.getValue(), false);\n else return rebalance(tree, newLeft, tree.getRight());\n }\n\n private Tree<K, V> doUntil(Tree<K, V> tree, K until, boolean inclusive) {\n if (tree == null) return null;\n if (inclusive) {\n if (ordering.compare(until, tree.getKey(kf)) < 0) return doUntil(tree.getLeft(), until, true);\n } else {\n if (ordering.compare(until, tree.getKey(kf)) <= 0) return doUntil(tree.getLeft(), until, false);\n }\n\n Tree<K, V> newRight = doUntil(tree.getRight(), until, inclusive);\n if (newRight != null && newRight.equals(tree.getRight())) return tree;\n else if (newRight == null) return upd(tree.getLeft(), tree.getKey(kf), tree.getValue(), false);\n else return rebalance(tree, tree.getLeft(), newRight);\n }\n\n private Tree<K, V> doRange(Tree<K, V> tree, K from, boolean fromInclusive, K until, boolean untilInclusive) {\n if (tree == null) return null;\n\n if (fromInclusive) {\n if (ordering.compare(tree.getKey(kf), from) < 0)\n return doRange(tree.getRight(), from, true, until, untilInclusive);\n } else {\n if (ordering.compare(tree.getKey(kf), from) <= 0)\n return doRange(tree.getRight(), from, false, until, untilInclusive);\n }\n\n if (untilInclusive) {\n if (ordering.compare(until, tree.getKey(kf)) < 0)\n return doRange(tree.getLeft(), from, fromInclusive, until, true);\n } else {\n if (ordering.compare(until, tree.getKey(kf)) <= 0)\n return doRange(tree.getLeft(), from, fromInclusive, until, false);\n }\n\n Tree<K, V> newLeft = doFrom(tree.getLeft(), from, fromInclusive);\n Tree<K, V> newRight = doUntil(tree.getRight(), until, untilInclusive);\n if ((newLeft == tree.getLeft()) && (newRight == tree.getRight())) return tree;\n else if (newLeft == null) return upd(newRight, tree.getKey(kf), tree.getValue(), false);\n else if (newRight == null) return upd(newLeft, tree.getKey(kf), tree.getValue(), false);\n else return rebalance(tree, newLeft, newRight);\n }\n\n private Tree<K, V> doDrop(Tree<K, V> tree, int n) {\n if (n <= 0) return tree;\n if (n >= count(tree)) return null;\n int count = count(tree.getLeft());\n if (n > count) return doDrop(tree.getRight(), n - count - 1);\n Tree<K, V> newLeft = doDrop(tree.getLeft(), n);\n if (newLeft == tree.getLeft()) return tree;\n else if (newLeft == null)\n return updNth(tree.getRight(), n - count - 1, tree.getKey(kf), tree.getValue(), false);\n else return rebalance(tree, newLeft, tree.getRight());\n }\n\n private Tree<K, V> doTake(Tree<K, V> tree, int n) {\n if (n <= 0) return null;\n if (n >= count(tree)) return tree;\n int count = count(tree.getLeft());\n if (n <= count) return doTake(tree.getLeft(), n);\n Tree<K, V> newRight = doTake(tree.getRight(), n - count - 1);\n if (newRight == tree.getRight()) return tree;\n else if (newRight == null) return updNth(tree.getLeft(), n, tree.getKey(kf), tree.getValue(), false);\n else return rebalance(tree, tree.getLeft(), newRight);\n }\n\n private Tree<K, V> doSlice(Tree<K, V> tree, int from, int until) {\n if (tree == null) return null;\n int count = count(tree.getLeft());\n if (from > count) return doSlice(tree.getRight(), from - count - 1, until - count - 1);\n if (until <= count) return doSlice(tree.getLeft(), from, until);\n Tree<K, V> newLeft = doDrop(tree.getLeft(), from);\n Tree<K, V> newRight = doTake(tree.getRight(), until - count - 1);\n if ((newLeft == tree.getLeft()) && (newRight == tree.getRight())) return tree;\n else if (newLeft == null) return updNth(newRight, from - count - 1, tree.getKey(kf), tree.getValue(), false);\n else if (newRight == null) return updNth(newLeft, until, tree.getKey(kf), tree.getValue(), false);\n else return rebalance(tree, newLeft, newRight);\n }\n\n // The zipper returned might have been traversed left-most (always the left child)\n // or right-most (always the right child). Left trees are traversed right-most,\n // and right trees are traversed leftmost.\n\n // Returns the zipper for the side with deepest black nodes depth, a flag\n // indicating whether the trees were unbalanced at all, and a flag indicating\n // whether the zipper was traversed left-most or right-most.\n\n // If the trees were balanced, returns an empty zipper\n\n @SuppressWarnings(\"unchecked\")\n private Zipper<K, V> compareDepth(Tree<K, V> left, Tree<K, V> right) {\n return unzipBoth(left, right, (List<Tree<K, V>>) Collections.EMPTY_LIST, (List<Tree<K, V>>) Collections.EMPTY_LIST, 0);\n }\n\n // Once a side is found to be deeper, unzip it to the bottom\n private List<Tree<K, V>> unzip(List<Tree<K, V>> zipper, boolean leftMost) {\n Tree<K, V> next = leftMost ? zipper.get(0).getLeft() : zipper.get(0).getRight();\n if (next == null)\n return zipper;\n\n return unzip(cons(next, zipper), leftMost);\n }\n\n // TODO ... do something more efficient\n private <E> List<E> cons(E value, List<E> list) {\n List<E> result = new ArrayList<E>(list.size() + 1);\n result.add(value);\n result.addAll(list);\n return result;\n }\n\n // Unzip left tree on the rightmost side and right tree on the leftmost side until one is\n // found to be deeper, or the bottom is reached\n @SuppressWarnings(\"unchecked\")\n private Zipper<K, V> unzipBoth(Tree<K, V> left, Tree<K, V> right, List<Tree<K, V>> leftZipper, List<Tree<K, V>> rightZipper, int smallerDepth) {\n if (isBlackTree(left) && isBlackTree(right)) {\n return unzipBoth(left.getRight(), right.getLeft(), cons(left, leftZipper), cons(right, rightZipper), smallerDepth + 1);\n } else if (isRedTree(left) && isRedTree(right)) {\n return unzipBoth(left.getRight(), right.getLeft(), cons(left, leftZipper), cons(right, rightZipper), smallerDepth);\n } else if (isRedTree(right)) {\n return unzipBoth(left, right.getLeft(), leftZipper, cons(right, rightZipper), smallerDepth);\n } else if (isRedTree(left)) {\n return unzipBoth(left.getRight(), right, cons(left, leftZipper), rightZipper, smallerDepth);\n } else if ((left == null) && (right == null)) {\n return new Zipper<K, V>((List<Tree<K, V>>) Collections.EMPTY_LIST, true, false, smallerDepth);\n } else if ((left == null) && isBlackTree(right)) {\n return new Zipper<K, V>(unzip(cons(right, rightZipper), true), false, true, smallerDepth);\n } else if (isBlackTree(left) && (right == null)) {\n return new Zipper<K, V>(unzip(cons(left, leftZipper), false), false, false, smallerDepth);\n } else {\n throw new RuntimeException(\"unmatched trees in unzip: \" + left + \", \" + right);\n }\n }\n\n // This is like drop(n-1), but only counting black nodes\n private List<Tree<K, V>> findDepth(List<Tree<K, V>> zipper, int depth) {\n if (zipper.isEmpty())\n throw new RuntimeException(\"Defect: unexpected empty zipper while computing range\");\n\n if (isBlackTree(zipper.get(0))) {\n return depth <= 1 ? zipper : findDepth(zipper.subList(1, zipper.size()), depth - 1);\n } else {\n return findDepth(zipper.subList(1, zipper.size()), depth);\n }\n }\n\n private Tree<K, V> rebalance(Tree<K, V> tree, Tree<K, V> newLeft, Tree<K, V> newRight) {\n // Blackening the smaller tree avoids balancing problems on union;\n // this can't be done later, though, or it would change the result of compareDepth\n Tree<K, V> blkNewLeft = blacken(newLeft);\n Tree<K, V> blkNewRight = blacken(newRight);\n Zipper<K, V> zipper = compareDepth(blkNewLeft, blkNewRight);\n\n if (zipper.levelled) {\n return factory.black(tree.getKey(kf), tree.getValue(), blkNewLeft, blkNewRight);\n } else {\n List<Tree<K, V>> zipFrom = findDepth(zipper.zipper, zipper.smallerDepth);\n\n Tree<K, V> result = zipper.leftMost ?\n factory.red(tree.getKey(kf), tree.getValue(), blkNewLeft, zipFrom.get(0)) :\n factory.red(tree.getKey(kf), tree.getValue(), zipFrom.get(0), blkNewRight);\n\n for (Tree<K, V> node : zipFrom.subList(1, zipFrom.size())) {\n if (zipper.leftMost) {\n result = balanceLeft(isBlackTree(node), node.getKey(kf), node.getValue(), result, node.getRight());\n } else {\n result = balanceRight(isBlackTree(node), node.getKey(kf), node.getValue(), node.getLeft(), result);\n }\n }\n\n return result;\n }\n }\n}" }, { "identifier": "Tree", "path": "src/main/java/sigbla/app/pds/collection/internal/redblack/Tree.java", "snippet": "public interface Tree<K, V> {\n int count();\n\n boolean isBlack();\n\n boolean isRed();\n\n Tree<K, V> black();\n\n Tree<K, V> red();\n\n K getKey(KeyFunction<K, V> keyFunction);\n\n V getValue();\n\n Tree<K, V> getLeft();\n\n Tree<K, V> getRight();\n}" }, { "identifier": "TreeFactory", "path": "src/main/java/sigbla/app/pds/collection/internal/redblack/TreeFactory.java", "snippet": "public interface TreeFactory {\n <K, V> Tree<K, V> red(K key, V value, Tree<K, V> left, Tree<K, V> right);\n\n <K, V> Tree<K, V> black(K key, V value, Tree<K, V> left, Tree<K, V> right);\n}" } ]
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Comparator; import java.util.Iterator; import sigbla.app.pds.collection.internal.base.AbstractIterable; import sigbla.app.pds.collection.internal.base.AbstractSortedMap; import sigbla.app.pds.collection.internal.builder.AbstractSelfBuilder; import sigbla.app.pds.collection.internal.redblack.DefaultTreeFactory; import sigbla.app.pds.collection.internal.redblack.DerivedKeyFactory; import sigbla.app.pds.collection.internal.redblack.RedBlackTree; import sigbla.app.pds.collection.internal.redblack.Tree; import sigbla.app.pds.collection.internal.redblack.TreeFactory;
8,884
/* * Copyright (c) 2014 Andrew O'Malley * * 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 sigbla.app.pds.collection; /** * {@code TreeMap} is an implementation of {@code SortedMap} based on a * <a href="http://en.wikipedia.org/wiki/Red%E2%80%93black_tree">red-black tree</a>. * <p/> * <p>{@code TreeMaps} can be constructed with a {@link sigbla.app.pds.collection.KeyFunction} * to provide modest memory saving per node. See {@link sigbla.app.pds.collection.DerivedKeyHashMap} * for an example of using a key function. */ public class TreeMap<K, V> extends AbstractSortedMap<K, V> { private final Tree<K, V> tree; private final RedBlackTree<K, V> redBlackTree; public TreeMap() { tree = null; redBlackTree = new RedBlackTree<K, V>(); } @NotNull public static <K, V> BuilderFactory<Pair<K, V>, TreeMap<K, V>> factory(final Comparator<? super K> ordering, final KeyFunction<K, V> keyFunction) { return new BuilderFactory<Pair<K, V>, TreeMap<K, V>>() { @NotNull @Override public Builder<Pair<K, V>, TreeMap<K, V>> newBuilder() { return new AbstractSelfBuilder<Pair<K, V>, TreeMap<K, V>>(new TreeMap<K, V>(ordering, keyFunction)) { @NotNull @Override public Builder<Pair<K, V>, TreeMap<K, V>> add(Pair<K, V> element) { result = result.put(element.component1(), element.component2()); return this; } }; } }; } @Override public Comparator<? super K> comparator() { return redBlackTree.getOrdering(); } public TreeMap(Comparator<? super K> ordering, KeyFunction<K, V> keyFunction) { TreeFactory factory = keyFunction == null ? new DefaultTreeFactory() : new DerivedKeyFactory(); tree = null; redBlackTree = new RedBlackTree<K, V>(factory, ordering, keyFunction); } private TreeMap(Tree<K, V> tree, RedBlackTree<K, V> redBlackTree) { this.tree = tree; this.redBlackTree = redBlackTree; } @Override public boolean containsKey(@NotNull K key) { return redBlackTree.contains(tree, key); } @NotNull @Override public TreeMap<K, V> put(@NotNull K key, V value) { return new TreeMap<K, V>(redBlackTree.update(tree, key, value, true), redBlackTree); } @Override public V get(@NotNull K key) { return redBlackTree.get(tree, key); } @Override public int size() { return RedBlackTree.count(tree); } @Override public boolean isEmpty() { return redBlackTree.isEmpty(tree); } @NotNull @Override public TreeMap<K, V> remove(@NotNull K key) { return new TreeMap<K, V>(redBlackTree.delete(tree, key), redBlackTree); } @NotNull @Override public Iterator<Pair<K, V>> iterator() { return redBlackTree.iterator(tree); } public <U> void forEach(@NotNull Function<Pair<K, V>, U> f) { redBlackTree.forEach(tree, f); } @Nullable @Override public Pair<K, V> first() { return tree != null ? toPair(redBlackTree.smallest(tree)) : null; } private Pair<K, V> toPair(Tree<K, V> tree) { return new Pair<K, V>(tree.getKey(redBlackTree.getKeyFunction()), tree.getValue()); } @Nullable @Override public Pair<K, V> last() { return tree != null ? toPair(redBlackTree.greatest(tree)) : null; } @NotNull @Override public SortedMap<K, V> drop(int number) { return new TreeMap<K, V>(redBlackTree.drop(tree, number), redBlackTree); } @NotNull @Override public SortedMap<K, V> take(int number) { return new TreeMap<K, V>(redBlackTree.take(tree, number), redBlackTree); } @NotNull @Override public SortedMap<K, V> from(@NotNull K key, boolean inclusive) { return new TreeMap<K, V>(redBlackTree.from(tree, key, inclusive), redBlackTree); } @NotNull @Override public SortedMap<K, V> to(@NotNull K key, boolean inclusive) { return new TreeMap<K, V>(redBlackTree.until(tree, key, inclusive), redBlackTree); } @NotNull @Override public SortedMap<K, V> range(@NotNull K from, boolean fromInclusive, @NotNull K to, boolean toInclusive) { return new TreeMap<K, V>(redBlackTree.range(tree, from, fromInclusive, to, toInclusive), redBlackTree); } @NotNull @Override public Iterable<K> keys() {
/* * Copyright (c) 2014 Andrew O'Malley * * 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 sigbla.app.pds.collection; /** * {@code TreeMap} is an implementation of {@code SortedMap} based on a * <a href="http://en.wikipedia.org/wiki/Red%E2%80%93black_tree">red-black tree</a>. * <p/> * <p>{@code TreeMaps} can be constructed with a {@link sigbla.app.pds.collection.KeyFunction} * to provide modest memory saving per node. See {@link sigbla.app.pds.collection.DerivedKeyHashMap} * for an example of using a key function. */ public class TreeMap<K, V> extends AbstractSortedMap<K, V> { private final Tree<K, V> tree; private final RedBlackTree<K, V> redBlackTree; public TreeMap() { tree = null; redBlackTree = new RedBlackTree<K, V>(); } @NotNull public static <K, V> BuilderFactory<Pair<K, V>, TreeMap<K, V>> factory(final Comparator<? super K> ordering, final KeyFunction<K, V> keyFunction) { return new BuilderFactory<Pair<K, V>, TreeMap<K, V>>() { @NotNull @Override public Builder<Pair<K, V>, TreeMap<K, V>> newBuilder() { return new AbstractSelfBuilder<Pair<K, V>, TreeMap<K, V>>(new TreeMap<K, V>(ordering, keyFunction)) { @NotNull @Override public Builder<Pair<K, V>, TreeMap<K, V>> add(Pair<K, V> element) { result = result.put(element.component1(), element.component2()); return this; } }; } }; } @Override public Comparator<? super K> comparator() { return redBlackTree.getOrdering(); } public TreeMap(Comparator<? super K> ordering, KeyFunction<K, V> keyFunction) { TreeFactory factory = keyFunction == null ? new DefaultTreeFactory() : new DerivedKeyFactory(); tree = null; redBlackTree = new RedBlackTree<K, V>(factory, ordering, keyFunction); } private TreeMap(Tree<K, V> tree, RedBlackTree<K, V> redBlackTree) { this.tree = tree; this.redBlackTree = redBlackTree; } @Override public boolean containsKey(@NotNull K key) { return redBlackTree.contains(tree, key); } @NotNull @Override public TreeMap<K, V> put(@NotNull K key, V value) { return new TreeMap<K, V>(redBlackTree.update(tree, key, value, true), redBlackTree); } @Override public V get(@NotNull K key) { return redBlackTree.get(tree, key); } @Override public int size() { return RedBlackTree.count(tree); } @Override public boolean isEmpty() { return redBlackTree.isEmpty(tree); } @NotNull @Override public TreeMap<K, V> remove(@NotNull K key) { return new TreeMap<K, V>(redBlackTree.delete(tree, key), redBlackTree); } @NotNull @Override public Iterator<Pair<K, V>> iterator() { return redBlackTree.iterator(tree); } public <U> void forEach(@NotNull Function<Pair<K, V>, U> f) { redBlackTree.forEach(tree, f); } @Nullable @Override public Pair<K, V> first() { return tree != null ? toPair(redBlackTree.smallest(tree)) : null; } private Pair<K, V> toPair(Tree<K, V> tree) { return new Pair<K, V>(tree.getKey(redBlackTree.getKeyFunction()), tree.getValue()); } @Nullable @Override public Pair<K, V> last() { return tree != null ? toPair(redBlackTree.greatest(tree)) : null; } @NotNull @Override public SortedMap<K, V> drop(int number) { return new TreeMap<K, V>(redBlackTree.drop(tree, number), redBlackTree); } @NotNull @Override public SortedMap<K, V> take(int number) { return new TreeMap<K, V>(redBlackTree.take(tree, number), redBlackTree); } @NotNull @Override public SortedMap<K, V> from(@NotNull K key, boolean inclusive) { return new TreeMap<K, V>(redBlackTree.from(tree, key, inclusive), redBlackTree); } @NotNull @Override public SortedMap<K, V> to(@NotNull K key, boolean inclusive) { return new TreeMap<K, V>(redBlackTree.until(tree, key, inclusive), redBlackTree); } @NotNull @Override public SortedMap<K, V> range(@NotNull K from, boolean fromInclusive, @NotNull K to, boolean toInclusive) { return new TreeMap<K, V>(redBlackTree.range(tree, from, fromInclusive, to, toInclusive), redBlackTree); } @NotNull @Override public Iterable<K> keys() {
return new AbstractIterable<K>() {
0
2023-12-10 15:10:13+00:00
12k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCryptoTest.java
[ { "identifier": "AsymmetricCipherKeyPair", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AsymmetricCipherKeyPair.java", "snippet": "public interface AsymmetricCipherKeyPair {\n\n /**\n * Returns the public key parameters.\n *\n * @return the public key parameters.\n */\n AsymmetricKeyParameter publicParameters();\n\n /**\n * Returns the private key parameters.\n *\n * @return the private key parameters.\n */\n AsymmetricKeyParameter privateParameters();\n}" }, { "identifier": "AsymmetricKeyParameter", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AsymmetricKeyParameter.java", "snippet": "public interface AsymmetricKeyParameter {\n\n /**\n * Returns the parameter as byte encoded or {@code null}\n * if not supported by the used implementation or parameter type.\n *\n * @return encoded.\n */\n byte[] encoded();\n\n /**\n * Returns {@code true} if this is the private key, {@code false} otherwise.\n *\n * @return {@code true} if this is the private key.\n */\n boolean isPrivate();\n}" }, { "identifier": "OHttpCryptoProvider", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/OHttpCryptoProvider.java", "snippet": "public interface OHttpCryptoProvider {\n /**\n * Creates a new {@link AEADContext} instance implementation of\n * <a href=\"https://datatracker.ietf.org/doc/html/rfc5116\">An AEAD encryption algorithm [RFC5116]</a>.\n *\n * @param aead the {@link AEAD} to use.\n * @param key the key to use.\n * @param baseNonce the nounce to use.\n * @return the created {@link AEADContext} based on the given arguments.\n */\n AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce);\n\n /**\n * Establish a {@link HPKESenderContext} that can be used for encryption.\n *\n * @param kem the {@link KEM} to use.\n * @param kdf the {@link KDF} to use.\n * @param aead the {@link AEAD} to use.\n * @param pkR the public key.\n * @param info info parameter.\n * @param kpE the ephemeral keypair that is used for the seed or {@code null} if none should be used.\n * @return the context.\n */\n HPKESenderContext setupHPKEBaseS(KEM kem, KDF kdf, AEAD aead,\n AsymmetricKeyParameter pkR, byte[] info, AsymmetricCipherKeyPair kpE);\n\n /**\n * Establish a {@link HPKERecipientContext} that can be used for decryption.\n *\n * @param kem the {@link KEM} to use.\n * @param kdf the {@link KDF} to use.\n * @param aead the {@link AEAD} to use.\n * @param enc an encapsulated KEM shared secret.\n * @param skR the private key.\n * @param info info parameter.\n * @return the context.\n */\n HPKERecipientContext setupHPKEBaseR(KEM kem, KDF kdf, AEAD aead, byte[] enc,\n AsymmetricCipherKeyPair skR, byte[] info);\n\n /**\n * Deserialize the input and return the private key.\n *\n * @param kem the {@link KEM} that is used.\n * @param privateKeyBytes the private key\n * @param publicKeyBytes the public key.\n * @return the deserialized {@link AsymmetricCipherKeyPair}.\n */\n AsymmetricCipherKeyPair deserializePrivateKey(KEM kem, byte[] privateKeyBytes, byte[] publicKeyBytes);\n\n /**\n * Deserialize the input and return the public key.\n *\n * @param kem the {@link KEM} that is used.\n * @param publicKeyBytes the public key.\n * @return the deserialized {@link AsymmetricKeyParameter}.\n */\n AsymmetricKeyParameter deserializePublicKey(KEM kem, byte[] publicKeyBytes);\n\n /**\n * Generate a random private key. Please note that this might not be possible for all of the {@link KEM} and so\n * this method might throw an {@link UnsupportedOperationException}.\n *\n * @param kem the {@link KEM} that is used.\n * @return the generated key.\n */\n AsymmetricCipherKeyPair newRandomPrivateKey(KEM kem);\n\n /**\n * Returns {@code true} if the given {@link AEAD} is supported by the implementation, {@code false} otherwise.\n *\n * @param aead the {@link AEAD}.\n * @return if supported.\n */\n boolean isSupported(AEAD aead);\n\n /**\n * Returns {@code true} if the given {@link KEM} is supported by the implementation, {@code false} otherwise.\n *\n * @param kem the {@link KEM}.\n * @return if supported.\n */\n boolean isSupported(KEM kem);\n\n /**\n * Returns {@code true} if the given {@link KDF} is supported by the implementation, {@code false} otherwise.\n *\n * @param kdf the {@link KDF}.\n * @return if supported.\n */\n boolean isSupported(KDF kdf);\n}" }, { "identifier": "BoringSSLHPKE", "path": "codec-ohttp-hpke-classes-boringssl/src/main/java/io/netty/incubator/codec/hpke/boringssl/BoringSSLHPKE.java", "snippet": "public final class BoringSSLHPKE {\n\n @SuppressWarnings(\"unchecked\")\n private static final Throwable UNAVAILABILITY_CAUSE;\n\n static {\n Throwable cause = null;\n\n try {\n long ctx = BoringSSL.EVP_HPKE_KEY_new();\n BoringSSL.EVP_HPKE_CTX_cleanup_and_free(ctx);\n } catch (Throwable error) {\n cause = error;\n }\n\n UNAVAILABILITY_CAUSE = cause;\n }\n\n /**\n * Returns {@code true} if and only if the HPKE implementation is usable on the running platform is available.\n *\n * @return {@code true} if this HPKE implementation can be used on the current platform, {@code false} otherwise.\n */\n public static boolean isAvailable() {\n return UNAVAILABILITY_CAUSE == null;\n }\n\n /**\n * Ensure that HPKE implementation is usable on the running platform is available.\n *\n * @throws UnsatisfiedLinkError if unavailable\n */\n public static void ensureAvailability() {\n if (UNAVAILABILITY_CAUSE != null) {\n throw (Error) new UnsatisfiedLinkError(\n \"failed to load the required native library\").initCause(UNAVAILABILITY_CAUSE);\n }\n }\n\n /**\n * Returns the cause of unavailability.\n *\n * @return the cause if unavailable. {@code null} if available.\n */\n public static Throwable unavailabilityCause() {\n return UNAVAILABILITY_CAUSE;\n }\n\n private BoringSSLHPKE() { }\n}" }, { "identifier": "BoringSSLOHttpCryptoProvider", "path": "codec-ohttp-hpke-classes-boringssl/src/main/java/io/netty/incubator/codec/hpke/boringssl/BoringSSLOHttpCryptoProvider.java", "snippet": "public final class BoringSSLOHttpCryptoProvider implements OHttpCryptoProvider {\n\n /**\n * {@link BoringSSLOHttpCryptoProvider} instance.\n */\n public static final BoringSSLOHttpCryptoProvider INSTANCE = new BoringSSLOHttpCryptoProvider();\n\n private BoringSSLOHttpCryptoProvider() {\n }\n\n @Override\n public AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce) {\n long boringSSLAead = boringSSLAEAD(aead);\n int keyLength = BoringSSL.EVP_AEAD_key_length(boringSSLAead);\n if (keyLength != key.length) {\n throw new IllegalArgumentException(\"key length must be \" + keyLength + \": \" + key.length);\n }\n int nounceLength = BoringSSL.EVP_AEAD_nonce_length(boringSSLAead);\n if (nounceLength != baseNonce.length) {\n throw new IllegalArgumentException(\"baseNonce length must be \" + nounceLength + \": \" + baseNonce.length);\n }\n\n int maxOverhead = BoringSSL.EVP_AEAD_max_overhead(boringSSLAead);\n long ctx = BoringSSL.EVP_AEAD_CTX_new_or_throw(boringSSLAead, key, BoringSSL.EVP_AEAD_DEFAULT_TAG_LENGTH);\n try {\n BoringSSLAEADContext aeadCtx = new BoringSSLAEADContext(ctx, maxOverhead, baseNonce);\n ctx = -1;\n return aeadCtx;\n } finally {\n if (ctx != -1) {\n BoringSSL.EVP_AEAD_CTX_cleanup_and_free(ctx);\n }\n }\n }\n\n private static long boringSSLAEAD(AEAD aead) {\n switch (aead) {\n case AES_GCM128:\n return BoringSSL.EVP_aead_aes_128_gcm;\n case AES_GCM256:\n return BoringSSL.EVP_aead_aes_256_gcm;\n case CHACHA20_POLY1305:\n return BoringSSL.EVP_aead_chacha20_poly1305;\n default:\n throw new IllegalArgumentException(\"AEAD not supported: \" + aead);\n }\n }\n\n private static long boringSSLKDF(KDF kdf) {\n if (kdf != KDF.HKDF_SHA256) {\n throw new IllegalArgumentException(\"KDF not supported: \" + kdf);\n }\n return BoringSSL.EVP_hpke_hkdf_sha256;\n }\n\n private static long boringSSLKEM(KEM kem) {\n if (kem != KEM.X25519_SHA256) {\n throw new IllegalArgumentException(\"KEM not supported: \" + kem);\n }\n return BoringSSL.EVP_hpke_x25519_hkdf_sha256;\n }\n\n private static long boringSSLHPKEAEAD(AEAD aead) {\n switch (aead) {\n case AES_GCM128:\n return BoringSSL.EVP_hpke_aes_128_gcm;\n case AES_GCM256:\n return BoringSSL.EVP_hpke_aes_256_gcm;\n case CHACHA20_POLY1305:\n return BoringSSL.EVP_hpke_chacha20_poly1305;\n default:\n throw new IllegalArgumentException(\"AEAD not supported: \" + aead);\n }\n }\n\n @Override\n public HPKESenderContext setupHPKEBaseS(KEM kem, KDF kdf, AEAD aead, AsymmetricKeyParameter pkR,\n byte[] info, AsymmetricCipherKeyPair kpE) {\n long boringSSLKem = boringSSLKEM(kem);\n long boringSSLKdf = boringSSLKDF(kdf);\n long boringSSLAead = boringSSLHPKEAEAD(aead);\n final byte[] pkRBytes = encodedAsymmetricKeyParameter(pkR);\n final byte[] encapsulation;\n long ctx = BoringSSL.EVP_HPKE_CTX_new_or_throw();\n try {\n if (kpE == null) {\n encapsulation = BoringSSL.EVP_HPKE_CTX_setup_sender(\n ctx, boringSSLKem, boringSSLKdf, boringSSLAead, pkRBytes, info);\n } else {\n encapsulation = BoringSSL.EVP_HPKE_CTX_setup_sender_with_seed_for_testing(\n ctx, boringSSLKem, boringSSLKdf, boringSSLAead, pkRBytes, info,\n // As we only support X25519 it is the right thing to just use the private key as seed.\n // See https://github.com/google/boringssl/blob/master/include/openssl/hpke.h#L235C44-L235C50\n encodedAsymmetricKeyParameter(kpE.privateParameters()));\n }\n if (encapsulation == null) {\n throw new IllegalStateException(\"Unable to setup EVP_HPKE_CTX\");\n }\n BoringSSLHPKESenderContext hpkeCtx =\n new BoringSSLHPKESenderContext(ctx, encapsulation);\n ctx = -1;\n return hpkeCtx;\n } finally {\n if (ctx != -1) {\n BoringSSL.EVP_HPKE_CTX_cleanup_and_free(ctx);\n }\n }\n }\n\n private static byte[] encodedAsymmetricKeyParameter(AsymmetricKeyParameter parameter) {\n if (parameter instanceof BoringSSLAsymmetricKeyParameter) {\n // No copy needed.\n return ((BoringSSLAsymmetricKeyParameter) parameter).bytes;\n }\n return parameter.encoded();\n }\n\n @Override\n public HPKERecipientContext setupHPKEBaseR(KEM kem, KDF kdf, AEAD aead, byte[] enc,\n AsymmetricCipherKeyPair skR, byte[] info) {\n // Validate that KEM is supported by BoringSSL\n long boringSSLKem = boringSSLKEM(kem);\n long boringSSLKdf = boringSSLKDF(kdf);\n long boringSSLAead = boringSSLHPKEAEAD(aead);\n\n long ctx = -1;\n long key = -1;\n try {\n byte[] privateKeyBytes = encodedAsymmetricKeyParameter(skR.privateParameters());\n key = BoringSSL.EVP_HPKE_KEY_new_and_init_or_throw(boringSSLKem, privateKeyBytes);\n ctx = BoringSSL.EVP_HPKE_CTX_new_or_throw();\n if (BoringSSL.EVP_HPKE_CTX_setup_recipient(ctx, key, boringSSLKdf, boringSSLAead, enc, info) != 1) {\n throw new IllegalStateException(\"Unable to setup EVP_HPKE_CTX\");\n }\n\n BoringSSLHPKERecipientContext hpkeCtx = new BoringSSLHPKERecipientContext(ctx);\n ctx = -1;\n return hpkeCtx;\n } finally {\n BoringSSL.EVP_HPKE_KEY_cleanup_and_free(key);\n if (ctx != -1) {\n BoringSSL.EVP_HPKE_CTX_cleanup_and_free(ctx);\n }\n }\n }\n\n @Override\n public AsymmetricCipherKeyPair deserializePrivateKey(KEM kem, byte[] privateKeyBytes, byte[] publicKeyBytes) {\n // Validate that KEM is supported by BoringSSL\n long boringSSLKem = boringSSLKEM(kem);\n\n long key = -1;\n try {\n key = BoringSSL.EVP_HPKE_KEY_new_and_init_or_throw(boringSSLKem, privateKeyBytes);\n byte[] extractedPublicKey = BoringSSL.EVP_HPKE_KEY_public_key(key);\n if (!Arrays.equals(publicKeyBytes, extractedPublicKey)) {\n throw new IllegalArgumentException(\n \"publicKeyBytes does not contain a valid public key: \" + Arrays.toString(publicKeyBytes));\n }\n // No need to clone extractedPublicKey as it was returned by our native call.\n return new BoringSSLAsymmetricCipherKeyPair(privateKeyBytes.clone(), extractedPublicKey);\n } finally {\n BoringSSL.EVP_HPKE_KEY_cleanup_and_free(key);\n }\n }\n\n @Override\n public AsymmetricKeyParameter deserializePublicKey(KEM kem, byte[] publicKeyBytes) {\n // Validate that KEM is supported by BoringSSL.\n long boringSSLKem = boringSSLKEM(kem);\n // The best we can do is to check if the length is correct.\n if (BoringSSL.EVP_HPKE_KEM_public_key_len(boringSSLKem) != publicKeyBytes.length) {\n throw new IllegalArgumentException(\n \"publicKeyBytes does not contain a valid public key: \" + Arrays.toString(publicKeyBytes));\n }\n return new BoringSSLAsymmetricKeyParameter(publicKeyBytes.clone(), false);\n }\n\n @Override\n public AsymmetricCipherKeyPair newRandomPrivateKey(KEM kem) {\n // Validate that KEM is supported by BoringSSL.\n long boringSSLKem = boringSSLKEM(kem);\n\n long key = BoringSSL.EVP_HPKE_KEY_new_and_generate_or_throw(boringSSLKem);\n try {\n byte[] privateKeyBytes = BoringSSL.EVP_HPKE_KEY_private_key(key);\n byte[] publicKeyBytes = BoringSSL.EVP_HPKE_KEY_public_key(key);\n if (privateKeyBytes == null || publicKeyBytes == null) {\n throw new IllegalStateException(\"Unable to generate random key\");\n }\n return new BoringSSLAsymmetricCipherKeyPair(privateKeyBytes, publicKeyBytes);\n } finally {\n BoringSSL.EVP_HPKE_KEY_cleanup_and_free(key);\n }\n }\n\n @Override\n public boolean isSupported(AEAD aead) {\n if (aead == null) {\n return false;\n }\n switch (aead) {\n case AES_GCM128:\n case AES_GCM256:\n case CHACHA20_POLY1305:\n return true;\n default:\n return false;\n }\n }\n\n @Override\n public boolean isSupported(KEM kem) {\n return kem == KEM.X25519_SHA256;\n }\n\n @Override\n public boolean isSupported(KDF kdf) {\n return kdf == KDF.HKDF_SHA256;\n }\n}" }, { "identifier": "BouncyCastleOHttpCryptoProvider", "path": "codec-ohttp-hpke-bouncycastle/src/main/java/io/netty/incubator/codec/hpke/bouncycastle/BouncyCastleOHttpCryptoProvider.java", "snippet": "public final class BouncyCastleOHttpCryptoProvider implements OHttpCryptoProvider {\n public static final BouncyCastleOHttpCryptoProvider INSTANCE = new BouncyCastleOHttpCryptoProvider();\n private final SecureRandom random = new SecureRandom();\n private static final byte MODE_BASE = (byte) 0x00;\n\n private BouncyCastleOHttpCryptoProvider() { }\n\n @Override\n public AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce) {\n return new BouncyCastleAEADCryptoContext(new org.bouncycastle.crypto.hpke.AEAD(aead.id(), key, baseNonce));\n }\n\n private static BouncyCastleAsymmetricKeyParameter castOrThrow(AsymmetricKeyParameter param) {\n if (!(param instanceof BouncyCastleAsymmetricKeyParameter)) {\n throw new IllegalArgumentException(\n \"param must be of type \" + BouncyCastleAsymmetricKeyParameter.class + \": \" + param);\n }\n return (BouncyCastleAsymmetricKeyParameter) param;\n }\n\n private static BouncyCastleAsymmetricCipherKeyPair castOrThrow(AsymmetricCipherKeyPair pair) {\n if (!(pair instanceof BouncyCastleAsymmetricCipherKeyPair)) {\n throw new IllegalArgumentException(\n \"pair must be of type \" + BouncyCastleAsymmetricCipherKeyPair.class + \": \" + pair);\n }\n return (BouncyCastleAsymmetricCipherKeyPair) pair;\n }\n\n @Override\n public HPKESenderContext setupHPKEBaseS(KEM kem, KDF kdf, AEAD aead,\n AsymmetricKeyParameter pkR, byte[] info,\n AsymmetricCipherKeyPair kpE) {\n org.bouncycastle.crypto.hpke.HPKE hpke =\n new org.bouncycastle.crypto.hpke.HPKE(MODE_BASE, kem.id(), kdf.id(), aead.id());\n final org.bouncycastle.crypto.hpke.HPKEContextWithEncapsulation ctx;\n if (kpE == null) {\n ctx = hpke.setupBaseS(castOrThrow(pkR).param, info);\n } else {\n ctx = hpke.setupBaseS(castOrThrow(pkR).param, info, castOrThrow(kpE).pair);\n }\n return new BouncyCastleHPKESenderContext(ctx);\n }\n\n @Override\n public HPKERecipientContext setupHPKEBaseR(KEM kem, KDF kdf, AEAD aead, byte[] enc,\n AsymmetricCipherKeyPair skR, byte[] info) {\n org.bouncycastle.crypto.hpke.HPKE hpke =\n new org.bouncycastle.crypto.hpke.HPKE(MODE_BASE, kem.id(), kdf.id(), aead.id());\n return new BouncyCastleHPKERecipientContext(hpke.setupBaseR(enc, castOrThrow(skR).pair, info));\n }\n\n @Override\n public AsymmetricCipherKeyPair deserializePrivateKey(KEM kem, byte[] privateKeyBytes, byte[] publicKeyBytes) {\n return new BouncyCastleAsymmetricCipherKeyPair(\n deserializePrivateKeyBouncyCastle(kem, privateKeyBytes, publicKeyBytes));\n }\n\n private static org.bouncycastle.crypto.AsymmetricCipherKeyPair deserializePrivateKeyBouncyCastle(\n KEM kem, byte[] privateKeyBytes, byte[] publicKeyBytes) {\n // See https://github.com/bcgit/bc-java/blob/\n // f1367f0b89962b29460eea381a12063fa7cd2428/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java#L204\n org.bouncycastle.crypto.params.AsymmetricKeyParameter publicKey =\n deserializePublicKeyBouncyCastle(kem, publicKeyBytes);\n switch (kem) {\n case P256_SHA256:\n case P384_SHA348:\n case P521_SHA512:\n BigInteger bigInt = new BigInteger(1, privateKeyBytes);\n return new org.bouncycastle.crypto.AsymmetricCipherKeyPair(publicKey,\n new ECPrivateKeyParameters(bigInt, ((ECPublicKeyParameters) publicKey).getParameters()));\n case X25519_SHA256:\n return new org.bouncycastle.crypto.AsymmetricCipherKeyPair(publicKey,\n new X25519PrivateKeyParameters(privateKeyBytes));\n case X448_SHA512:\n return new org.bouncycastle.crypto.AsymmetricCipherKeyPair(publicKey,\n new X448PrivateKeyParameters(privateKeyBytes));\n default:\n throw new IllegalArgumentException(\"invalid kem: \" + kem);\n }\n }\n\n @Override\n public AsymmetricKeyParameter deserializePublicKey(KEM kem, byte[] publicKeyBytes) {\n return new BouncyCastleAsymmetricKeyParameter(deserializePublicKeyBouncyCastle(kem, publicKeyBytes));\n }\n\n private static org.bouncycastle.crypto.params.AsymmetricKeyParameter deserializePublicKeyBouncyCastle(\n KEM kem, byte[] publicKeyBytes) {\n // See https://github.com/bcgit/bc-java/blob/\n // f1367f0b89962b29460eea381a12063fa7cd2428/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java#L186\n switch (kem) {\n case P256_SHA256:\n case P384_SHA348:\n case P521_SHA512:\n ECDomainParameters parameters = ecDomainParameters(kem);\n ECPoint decoded = parameters.getCurve().decodePoint(publicKeyBytes);\n return new ECPublicKeyParameters(decoded, parameters);\n case X25519_SHA256:\n return new X25519PublicKeyParameters(publicKeyBytes);\n case X448_SHA512:\n return new X448PublicKeyParameters(publicKeyBytes);\n default:\n throw new IllegalArgumentException(\"invalid kem: \" + kem);\n }\n }\n\n // See https://github.com/bcgit/bc-java/blob/\n // f1367f0b89962b29460eea381a12063fa7cd2428/core/src/main/java/org/bouncycastle/crypto/hpke/DHKEM.java#L59\n private static ECDomainParameters ecDomainParameters(KEM kem) {\n switch (kem) {\n case P256_SHA256:\n SecP256R1Curve p256R1Curve = new SecP256R1Curve();\n byte[] p256R1Magnitude1 =\n Hex.decode(\"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296\");\n byte[] p256R1Magnitude2 =\n Hex.decode(\"4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5\");\n byte[] p256R1Seed = Hex.decode(\"c49d360886e704936a6678e1139d26b7819f7e90\");\n return new ECDomainParameters(\n p256R1Curve,\n p256R1Curve.createPoint(\n new BigInteger(1, p256R1Magnitude1),\n new BigInteger(1, p256R1Magnitude2)\n ),\n p256R1Curve.getOrder(),\n p256R1Curve.getCofactor(),\n p256R1Seed\n );\n case P384_SHA348:\n SecP384R1Curve p384R1Curve = new SecP384R1Curve();\n byte[] p384R1Magnitude1 = Hex.decode(\"aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e\" +\n \"082542a385502f25dbf55296c3a545e3872760ab7\");\n byte[] p384R1Magnitude2 = Hex.decode(\"3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da311\" +\n \"3b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f\");\n byte[] p384R11Seed = Hex.decode(\"a335926aa319a27a1d00896a6773a4827acdac73\");\n return new ECDomainParameters(\n p384R1Curve,\n p384R1Curve.createPoint(\n new BigInteger(1, p384R1Magnitude1),\n new BigInteger(1, p384R1Magnitude2)\n ),\n p384R1Curve.getOrder(),\n p384R1Curve.getCofactor(),\n p384R11Seed\n );\n case P521_SHA512:\n SecP521R1Curve p521R1Curve = new SecP521R1Curve();\n return new ECDomainParameters(\n p521R1Curve,\n p521R1Curve.createPoint(\n new BigInteger(\"c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d\" +\n \"3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66\", 16),\n new BigInteger(\"11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273\" +\n \"e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650\", 16)\n ),\n p521R1Curve.getOrder(),\n p521R1Curve.getCofactor(),\n Hex.decode(\"d09e8800291cb85396cc6717393284aaa0da64ba\")\n );\n default:\n throw new IllegalArgumentException(\"invalid kem: \" + kem);\n }\n }\n\n @Override\n public AsymmetricCipherKeyPair newRandomPrivateKey(KEM kem) {\n return new BouncyCastleAsymmetricCipherKeyPair(newRandomPair(kem, random));\n }\n\n private static org.bouncycastle.crypto.AsymmetricCipherKeyPair newRandomPair(KEM kem, SecureRandom random) {\n switch (kem) {\n case X25519_SHA256:\n X25519PrivateKeyParameters x25519PrivateKey = new X25519PrivateKeyParameters(random);\n return new org.bouncycastle.crypto.AsymmetricCipherKeyPair(\n x25519PrivateKey.generatePublicKey(), x25519PrivateKey);\n case X448_SHA512:\n X448PrivateKeyParameters x448PrivateKey = new X448PrivateKeyParameters(random);\n return new org.bouncycastle.crypto.AsymmetricCipherKeyPair(\n x448PrivateKey.generatePublicKey(), x448PrivateKey);\n default:\n throw new UnsupportedOperationException(\"Can't generate random key for kem: \" + kem);\n }\n }\n\n @Override\n public boolean isSupported(AEAD aead) {\n if (aead == null) {\n return false;\n }\n switch (aead) {\n case AES_GCM128:\n case AES_GCM256:\n case CHACHA20_POLY1305:\n return true;\n default:\n return false;\n }\n }\n\n @Override\n public boolean isSupported(KEM kem) {\n if (kem == null) {\n return false;\n }\n switch (kem) {\n case X25519_SHA256:\n case P256_SHA256:\n case P384_SHA348:\n case P521_SHA512:\n case X448_SHA512:\n return true;\n default:\n return false;\n }\n }\n\n @Override\n public boolean isSupported(KDF kdf) {\n if (kdf == null) {\n return false;\n }\n switch (kdf) {\n case HKDF_SHA256:\n case HKDF_SHA384:\n case HKDF_SHA512:\n return true;\n default:\n return false;\n }\n }\n}" }, { "identifier": "CryptoException", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/CryptoException.java", "snippet": "public final class CryptoException extends Exception {\n\n public CryptoException(String message) {\n super(message);\n }\n\n public CryptoException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public CryptoException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "AEAD", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AEAD.java", "snippet": "public enum AEAD {\n AES_GCM128((short) 0x0001, 16, 12),\n AES_GCM256((short) 0x0002, 32, 12),\n CHACHA20_POLY1305((short) 0x0003, 32, 12);\n\n public static AEAD forId(short id) {\n for (AEAD val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown AEAD id \" + id);\n }\n\n private final short id;\n private final int nk;\n private final int nn;\n\n AEAD(short id, int nk, int nn) {\n this.id = id;\n this.nk = nk;\n this.nn = nn;\n }\n\n public short id() {\n return id;\n }\n\n public int nk() {\n return nk;\n }\n\n public int nn() {\n return nn;\n }\n}" }, { "identifier": "KDF", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/KDF.java", "snippet": "public enum KDF {\n HKDF_SHA256((short) 0x0001),\n HKDF_SHA384((short) 0x0002),\n HKDF_SHA512((short) 0x0003);\n\n public static KDF forId(short id) {\n for (KDF val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown KDF id \" + id);\n }\n\n private final short id;\n\n KDF(short id) {\n this.id = id;\n }\n\n public short id() {\n return id;\n }\n}" }, { "identifier": "KEM", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/KEM.java", "snippet": "public enum KEM {\n P256_SHA256((short) 16, 65, 65),\n P384_SHA348((short) 17, 97, 97),\n P521_SHA512((short) 18, 133, 133),\n X25519_SHA256((short) 32, 32, 32),\n X448_SHA512((short) 33, 56, 56);\n\n public static KEM forId(short id) {\n for (KEM val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown KEM id \" + id);\n }\n\n KEM(short id, int nenc, int npk) {\n this.id = id;\n this.nenc = nenc;\n this.npk = npk;\n }\n\n private final short id;\n private final int nenc;\n private final int npk;\n\n public short id() {\n return id;\n }\n\n public int nenc() {\n return nenc;\n }\n\n public int npk() {\n return npk;\n }\n}" } ]
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair; import io.netty.incubator.codec.hpke.AsymmetricKeyParameter; import io.netty.incubator.codec.hpke.OHttpCryptoProvider; import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE; import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider; import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider; import io.netty.incubator.codec.hpke.CryptoException; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.handler.codec.DecoderException; import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; import org.bouncycastle.crypto.params.X25519PublicKeyParameters; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import io.netty.incubator.codec.hpke.AEAD; import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
8,437
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCryptoTest { private static final class OHttpCryptoProviderArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE));
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCryptoTest { private static final class OHttpCryptoProviderArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE));
if (BoringSSLHPKE.isAvailable()) {
3
2023-12-06 09:14:09+00:00
12k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/framebody/AbstractFrameBodyPairs.java
[ { "identifier": "InvalidTagException", "path": "android/src/main/java/org/jaudiotagger/tag/InvalidTagException.java", "snippet": "public class InvalidTagException extends TagException\n{\n /**\n * Creates a new InvalidTagException datatype.\n */\n public InvalidTagException()\n {\n }\n\n /**\n * Creates a new InvalidTagException datatype.\n *\n * @param ex the cause.\n */\n public InvalidTagException(Throwable ex)\n {\n super(ex);\n }\n\n /**\n * Creates a new InvalidTagException datatype.\n *\n * @param msg the detail message.\n */\n public InvalidTagException(String msg)\n {\n super(msg);\n }\n\n /**\n * Creates a new InvalidTagException datatype.\n *\n * @param msg the detail message.\n * @param ex the cause.\n */\n public InvalidTagException(String msg, Throwable ex)\n {\n super(msg, ex);\n }\n}" }, { "identifier": "DataTypes", "path": "android/src/main/java/org/jaudiotagger/tag/datatype/DataTypes.java", "snippet": "public class DataTypes\n{\n /**\n * Represents a text encoding, now only IDv2Frames not Lyrics3 tags use\n * text encoding objects but both use Object Strings and these check\n * for a text encoding. The method below returns a default if one not set.\n */\n public static final String OBJ_TEXT_ENCODING = \"TextEncoding\";\n //Reference to datatype holding the main textual data\n public static final String OBJ_TEXT = \"Text\";\n //Reference to datatype holding non textual textual data\n public static final String OBJ_DATA = \"Data\";\n //Reference to datatype holding a description of the textual data\n public static final String OBJ_DESCRIPTION = \"Description\";\n //Reference to datatype holding reference to owner of frame.\n public static final String OBJ_OWNER = \"Owner\";\n //Reference to datatype holding a number\n public static final String OBJ_NUMBER = \"Number\";\n //Reference to timestamps\n public static final String OBJ_DATETIME = \"DateTime\";\n /**\n *\n */\n public static final String OBJ_GENRE = \"Genre\";\n /**\n *\n */\n public static final String OBJ_ID3V2_FRAME_DESCRIPTION = \"ID3v2FrameDescription\";\n\n //ETCO Frame\n public static final String OBJ_TYPE_OF_EVENT = \"TypeOfEvent\";\n public static final String OBJ_TIMED_EVENT = \"TimedEvent\";\n public static final String OBJ_TIMED_EVENT_LIST = \"TimedEventList\";\n //SYTC Frame\n public static final String OBJ_SYNCHRONISED_TEMPO_DATA = \"SynchronisedTempoData\";\n public static final String OBJ_SYNCHRONISED_TEMPO = \"SynchronisedTempo\";\n public static final String OBJ_SYNCHRONISED_TEMPO_LIST = \"SynchronisedTempoList\";\n /**\n *\n */\n public static final String OBJ_TIME_STAMP_FORMAT = \"TimeStampFormat\";\n /**\n *\n */\n public static final String OBJ_TYPE_OF_CHANNEL = \"TypeOfChannel\";\n /**\n *\n */\n public static final String OBJ_RECIEVED_AS = \"RecievedAs\";\n\n //APIC Frame\n public static final String OBJ_PICTURE_TYPE = \"PictureType\";\n public static final String OBJ_PICTURE_DATA = \"PictureData\";\n public static final String OBJ_MIME_TYPE = \"MIMEType\";\n public static final String OBJ_IMAGE_FORMAT = \"ImageType\";\n\n //AENC Frame\n public static final String OBJ_PREVIEW_START = \"PreviewStart\";\n public static final String OBJ_PREVIEW_LENGTH = \"PreviewLength\";\n public static final String OBJ_ENCRYPTION_INFO = \"EncryptionInfo\";\n\n //COMR Frame\n public static final String OBJ_PRICE_STRING = \"PriceString\";\n public static final String OBJ_VALID_UNTIL = \"ValidUntil\";\n public static final String OBJ_CONTACT_URL = \"ContactURL\";\n public static final String OBJ_SELLER_NAME = \"SellerName\";\n public static final String OBJ_SELLER_LOGO = \"SellerLogo\";\n\n //CRM Frame\n public static final String OBJ_ENCRYPTED_DATABLOCK = \"EncryptedDataBlock\";\n\n //ENCR Frame\n public static final String OBJ_METHOD_SYMBOL = \"MethodSymbol\";\n\n //EQU2 Frame\n public static final String OBJ_FREQUENCY = \"Frequency\";\n public static final String OBJ_VOLUME_ADJUSTMENT = \"Volume Adjustment\";\n public static final String OBJ_INTERPOLATION_METHOD = \"InterpolationMethod\";\n\n public static final String OBJ_FILENAME = \"Filename\";\n\n //GRID Frame\n public static final String OBJ_GROUP_SYMBOL = \"GroupSymbol\";\n public static final String OBJ_GROUP_DATA = \"GroupData\";\n\n //LINK Frame\n public static final String OBJ_URL = \"URL\";\n public static final String OBJ_ID = \"ID\";\n\n //OWNE Frame\n public static final String OBJ_PRICE_PAID = \"PricePaid\";\n public static final String OBJ_PURCHASE_DATE = \"PurchaseDate\";\n\n //POPM Frame\n public static final String OBJ_EMAIL = \"Email\";\n public static final String OBJ_RATING = \"Rating\";\n public static final String OBJ_COUNTER = \"Counter\";\n\n //POSS Frame\n public static final String OBJ_POSITION = \"Position\";\n\n //RBUF Frame\n public static final String OBJ_BUFFER_SIZE = \"BufferSize\";\n public static final String OBJ_EMBED_FLAG = \"EmbedFlag\";\n public static final String OBJ_OFFSET = \"Offset\";\n\n //RVRB Frame\n public static final String OBJ_REVERB_LEFT = \"ReverbLeft\";\n public static final String OBJ_REVERB_RIGHT = \"ReverbRight\";\n public static final String OBJ_REVERB_BOUNCE_LEFT = \"ReverbBounceLeft\";\n public static final String OBJ_REVERB_BOUNCE_RIGHT = \"ReverbBounceRight\";\n public static final String OBJ_REVERB_FEEDBACK_LEFT_TO_LEFT = \"ReverbFeedbackLeftToLeft\";\n public static final String OBJ_REVERB_FEEDBACK_LEFT_TO_RIGHT = \"ReverbFeedbackLeftToRight\";\n public static final String OBJ_REVERB_FEEDBACK_RIGHT_TO_RIGHT = \"ReverbFeedbackRightToRight\";\n public static final String OBJ_REVERB_FEEDBACK_RIGHT_TO_LEFT = \"ReverbFeedbackRightToLeft\";\n public static final String OBJ_PREMIX_LEFT_TO_RIGHT = \"PremixLeftToRight\";\n public static final String OBJ_PREMIX_RIGHT_TO_LEFT = \"PremixRightToLeft\";\n\n //SIGN Frame\n public static final String OBJ_SIGNATURE = \"Signature\";\n\n //SYLT Frame\n public static final String OBJ_CONTENT_TYPE = \"contentType\";\n\n //ULST Frame\n public static final String OBJ_LANGUAGE = \"Language\";\n public static final String OBJ_LYRICS = \"Lyrics\";\n public static final String OBJ_URLLINK = \"URLLink\";\n\n //CHAP Frame\n public static final String OBJ_ELEMENT_ID = \"ElementID\";\n public static final String OBJ_START_TIME = \"StartTime\";\n public static final String OBJ_END_TIME = \"EndTime\";\n public static final String OBJ_START_OFFSET = \"StartOffset\";\n public static final String OBJ_END_OFFSET = \"EndOffset\";\n\n //CTOC Frame\n}" }, { "identifier": "NumberHashMap", "path": "android/src/main/java/org/jaudiotagger/tag/datatype/NumberHashMap.java", "snippet": "public class NumberHashMap extends NumberFixedLength implements HashMapInterface<Integer, String>\n{\n\n /**\n * key to value map\n */\n private Map<Integer, String> keyToValue = null;\n\n /**\n * value to key map\n */\n private Map<String, Integer> valueToKey = null;\n\n /**\n *\n */\n private boolean hasEmptyValue = false;\n\n\n /**\n * Creates a new ObjectNumberHashMap datatype.\n *\n * @param identifier\n * @param frameBody\n * @param size\n * @throws IllegalArgumentException\n */\n public NumberHashMap(String identifier, AbstractTagFrameBody frameBody, int size)\n {\n super(identifier, frameBody, size);\n\n if (identifier.equals(DataTypes.OBJ_GENRE))\n {\n valueToKey = GenreTypes.getInstanceOf().getValueToIdMap();\n keyToValue = GenreTypes.getInstanceOf().getIdToValueMap();\n\n //genres can be an id or literal value\n hasEmptyValue = true;\n }\n else if (identifier.equals(DataTypes.OBJ_TEXT_ENCODING))\n {\n valueToKey = TextEncoding.getInstanceOf().getValueToIdMap();\n keyToValue = TextEncoding.getInstanceOf().getIdToValueMap();\n }\n else if (identifier.equals(DataTypes.OBJ_INTERPOLATION_METHOD))\n {\n valueToKey = InterpolationTypes.getInstanceOf().getValueToIdMap();\n keyToValue = InterpolationTypes.getInstanceOf().getIdToValueMap();\n }\n else if (identifier.equals(DataTypes.OBJ_PICTURE_TYPE))\n {\n valueToKey = PictureTypes.getInstanceOf().getValueToIdMap();\n keyToValue = PictureTypes.getInstanceOf().getIdToValueMap();\n\n //Issue #224 Values should map, but have examples where they dont, this is a workaround\n hasEmptyValue = true;\n }\n else if (identifier.equals(DataTypes.OBJ_TYPE_OF_EVENT))\n {\n valueToKey = EventTimingTypes.getInstanceOf().getValueToIdMap();\n keyToValue = EventTimingTypes.getInstanceOf().getIdToValueMap();\n }\n else if (identifier.equals(DataTypes.OBJ_TIME_STAMP_FORMAT))\n {\n valueToKey = EventTimingTimestampTypes.getInstanceOf().getValueToIdMap();\n keyToValue = EventTimingTimestampTypes.getInstanceOf().getIdToValueMap();\n }\n else if (identifier.equals(DataTypes.OBJ_TYPE_OF_CHANNEL))\n {\n valueToKey = ChannelTypes.getInstanceOf().getValueToIdMap();\n keyToValue = ChannelTypes.getInstanceOf().getIdToValueMap();\n }\n else if (identifier.equals(DataTypes.OBJ_RECIEVED_AS))\n {\n valueToKey = ReceivedAsTypes.getInstanceOf().getValueToIdMap();\n keyToValue = ReceivedAsTypes.getInstanceOf().getIdToValueMap();\n }\n else if (identifier.equals(DataTypes.OBJ_CONTENT_TYPE))\n {\n valueToKey = SynchronisedLyricsContentType.getInstanceOf().getValueToIdMap();\n keyToValue = SynchronisedLyricsContentType.getInstanceOf().getIdToValueMap();\n }\n else\n {\n throw new IllegalArgumentException(\"Hashmap identifier not defined in this class: \" + identifier);\n }\n }\n\n public NumberHashMap(NumberHashMap copyObject)\n {\n super(copyObject);\n\n this.hasEmptyValue = copyObject.hasEmptyValue;\n\n // we don't need to clone/copy the maps here because they are static\n this.keyToValue = copyObject.keyToValue;\n this.valueToKey = copyObject.valueToKey;\n }\n\n /**\n * @return the key to value map\n */\n public Map<Integer, String> getKeyToValue()\n {\n return keyToValue;\n }\n\n /**\n * @return the value to key map\n */\n public Map<String, Integer> getValueToKey()\n {\n return valueToKey;\n }\n\n /**\n * @param value\n */\n public void setValue(Object value)\n {\n if (value instanceof Byte)\n {\n this.value = (long) ((Byte) value).byteValue();\n }\n else if (value instanceof Short)\n {\n this.value = (long) ((Short) value).shortValue();\n }\n else if (value instanceof Integer)\n {\n this.value = (long) ((Integer) value).intValue();\n }\n else\n {\n this.value = value;\n }\n }\n\n /**\n * @param obj\n * @return\n */\n public boolean equals(Object obj)\n {\n if(obj==this)\n {\n return true;\n }\n \n if (!(obj instanceof NumberHashMap))\n {\n return false;\n }\n\n NumberHashMap that = (NumberHashMap) obj;\n\n return\n EqualsUtil.areEqual(hasEmptyValue, that.hasEmptyValue) &&\n EqualsUtil.areEqual(keyToValue, that.keyToValue) &&\n EqualsUtil.areEqual(valueToKey, that.valueToKey) &&\n super.equals(that);\n }\n\n /**\n * @return\n */\n public Iterator<String> iterator()\n {\n if (keyToValue == null)\n {\n return null;\n }\n else\n {\n // put them in a treeset first to sort them\n TreeSet<String> treeSet = new TreeSet<String>(keyToValue.values());\n\n if (hasEmptyValue)\n {\n treeSet.add(\"\");\n }\n\n return treeSet.iterator();\n }\n }\n\n /**\n * Read the key from the buffer.\n *\n * @param arr\n * @param offset\n * @throws InvalidDataTypeException if emptyValues are not allowed and the eky was invalid.\n */\n public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException\n {\n super.readByteArray(arr, offset);\n\n //Mismatch:Superclass uses Long, but maps expect Integer\n Integer intValue = ((Long) value).intValue();\n if (!keyToValue.containsKey(intValue))\n {\n if (!hasEmptyValue)\n {\n throw new InvalidDataTypeException(ErrorMessage.MP3_REFERENCE_KEY_INVALID.getMsg(identifier, intValue));\n }\n else if (identifier.equals(DataTypes.OBJ_PICTURE_TYPE))\n {\n logger.warning(ErrorMessage.MP3_PICTURE_TYPE_INVALID.getMsg(value));\n }\n }\n }\n\n /**\n * @return\n */\n public String toString()\n {\n if (value == null)\n {\n return \"\";\n }\n else if (keyToValue.get(value) == null)\n {\n return \"\";\n }\n else\n {\n return keyToValue.get(value);\n }\n }\n}" }, { "identifier": "Pair", "path": "android/src/main/java/org/jaudiotagger/tag/datatype/Pair.java", "snippet": "public class Pair\n{\n private String key;\n private String value;\n\n public Pair(String key,String value)\n {\n setKey(key);\n setValue(value);\n }\n\n public String getKey()\n {\n return key;\n }\n\n public void setKey(String key)\n {\n this.key = key;\n }\n\n public String getValue()\n {\n return value;\n }\n\n public void setValue(String value)\n {\n this.value = value;\n }\n\n public String getPairValue()\n {\n return getKey() + '\\0' + getValue();\n }\n}" }, { "identifier": "PairedTextEncodedStringNullTerminated", "path": "android/src/main/java/org/jaudiotagger/tag/datatype/PairedTextEncodedStringNullTerminated.java", "snippet": "public class PairedTextEncodedStringNullTerminated extends AbstractDataType\n{\n public PairedTextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody)\n {\n super(identifier, frameBody);\n value = new ValuePairs();\n }\n\n public PairedTextEncodedStringNullTerminated(TextEncodedStringSizeTerminated object)\n {\n super(object);\n value = new ValuePairs();\n }\n\n public PairedTextEncodedStringNullTerminated(PairedTextEncodedStringNullTerminated object)\n {\n super(object);\n }\n\n public boolean equals(Object obj)\n {\n if (obj == this)\n {\n return true;\n }\n\n if (!(obj instanceof PairedTextEncodedStringNullTerminated))\n {\n return false;\n }\n\n PairedTextEncodedStringNullTerminated that = (PairedTextEncodedStringNullTerminated) obj;\n\n return EqualsUtil.areEqual(value, that.value);\n }\n\n /**\n * Returns the size in bytes of this dataType when written to file\n *\n * @return size of this dataType\n */\n public int getSize()\n {\n return size;\n }\n\n /**\n * Check the value can be encoded with the specified encoding\n *\n * @return\n */\n public boolean canBeEncoded()\n {\n for (Pair entry : ((ValuePairs) value).mapping)\n {\n TextEncodedStringNullTerminated next = new TextEncodedStringNullTerminated(identifier, frameBody, entry.getValue());\n if (!next.canBeEncoded())\n {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Read Null Terminated Strings from the array starting at offset, continue until unable to find any null terminated\n * Strings or until reached the end of the array. The offset should be set to byte after the last null terminated\n * String found.\n *\n * @param arr to read the Strings from\n * @param offset in the array to start reading from\n * @throws InvalidDataTypeException if unable to find any null terminated Strings\n */\n public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException\n {\n logger.finer(\"Reading PairTextEncodedStringNullTerminated from array from offset:\" + offset);\n //Continue until unable to read a null terminated String\n while (true)\n {\n try\n {\n //Read Key\n TextEncodedStringNullTerminated key = new TextEncodedStringNullTerminated(identifier, frameBody);\n key.readByteArray(arr, offset);\n size += key.getSize();\n offset += key.getSize();\n if (key.getSize() == 0)\n {\n break;\n }\n\n try\n {\n //Read Value\n TextEncodedStringNullTerminated result = new TextEncodedStringNullTerminated(identifier, frameBody);\n result.readByteArray(arr, offset);\n size += result.getSize();\n offset += result.getSize();\n if (result.getSize() == 0)\n {\n break;\n }\n //Add to value\n ((ValuePairs) value).add((String) key.getValue(),(String) result.getValue());\n }\n catch (InvalidDataTypeException idte)\n {\n //Value may not be null terminated if it is the last value\n //Read Value\n if(offset>=arr.length)\n {\n break;\n }\n TextEncodedStringSizeTerminated result = new TextEncodedStringSizeTerminated(identifier, frameBody);\n result.readByteArray(arr, offset);\n size += result.getSize();\n offset += result.getSize();\n if (result.getSize() == 0)\n {\n break;\n }\n //Add to value\n ((ValuePairs) value).add((String) key.getValue(),(String) result.getValue());\n break;\n }\n }\n catch (InvalidDataTypeException idte)\n {\n break;\n }\n\n if (size == 0)\n {\n logger.warning(\"No null terminated Strings found\");\n throw new InvalidDataTypeException(\"No null terminated Strings found\");\n }\n }\n logger.finer(\"Read PairTextEncodedStringNullTerminated:\" + value + \" size:\" + size);\n }\n\n\n /**\n * For every String write to byteBuffer\n *\n * @return byteBuffer that should be written to file to persist this dataType.\n */\n public byte[] writeByteArray()\n {\n logger.finer(\"Writing PairTextEncodedStringNullTerminated\");\n\n int localSize = 0;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n try\n {\n for (Pair pair : ((ValuePairs) value).mapping)\n {\n {\n TextEncodedStringNullTerminated next = new TextEncodedStringNullTerminated(identifier, frameBody, pair.getKey());\n buffer.write(next.writeByteArray());\n localSize += next.getSize();\n }\n {\n TextEncodedStringNullTerminated next = new TextEncodedStringNullTerminated(identifier, frameBody, pair.getValue());\n buffer.write(next.writeByteArray());\n localSize += next.getSize();\n }\n }\n }\n catch (IOException ioe)\n {\n //This should never happen because the write is internal with the JVM it is not to a file\n logger.log(Level.SEVERE, \"IOException in MultipleTextEncodedStringNullTerminated when writing byte array\", ioe);\n throw new RuntimeException(ioe);\n }\n\n //Update size member variable\n size = localSize;\n\n logger.finer(\"Written PairTextEncodedStringNullTerminated\");\n return buffer.toByteArray();\n }\n\n public String toString()\n {\n return value.toString();\n }\n\n /**\n * This holds the values held by this PairedTextEncodedDataType, always held as pairs of values\n */\n public static class ValuePairs\n {\n private List<Pair> mapping = new ArrayList<Pair>();\n\n public ValuePairs()\n {\n super();\n }\n\n public void add(Pair pair)\n {\n mapping.add(pair);\n }\n /**\n * Add String Data type to the value list\n *\n * @param value to add to the list\n */\n public void add(String key, String value)\n {\n mapping.add(new Pair(key,value));\n }\n\n\n /**\n * Return the list of values\n *\n * @return the list of values\n */\n public List<Pair> getMapping()\n {\n return mapping;\n }\n\n /**\n * @return no of values\n */\n public int getNumberOfValues()\n {\n return mapping.size();\n }\n\n /**\n * Return the list of values as a single string separated by a colon,comma\n *\n * @return a string representation of the value\n */\n public String toString()\n {\n StringBuffer sb = new StringBuffer();\n for(Pair next:mapping)\n {\n sb.append(next.getKey()+':'+next.getValue()+',');\n }\n if(sb.length()>0)\n {\n sb.setLength(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * @return no of values\n */\n public int getNumberOfPairs()\n {\n return mapping.size();\n }\n\n public boolean equals(Object obj)\n {\n if (obj == this)\n {\n return true;\n }\n\n if (!(obj instanceof ValuePairs))\n {\n return false;\n }\n\n ValuePairs that = (ValuePairs) obj;\n\n return EqualsUtil.areEqual(getNumberOfValues(), that.getNumberOfValues());\n }\n }\n\n public ValuePairs getValue()\n {\n return (ValuePairs) value;\n }\n}" }, { "identifier": "TextEncoding", "path": "android/src/main/java/org/jaudiotagger/tag/id3/valuepair/TextEncoding.java", "snippet": "public class TextEncoding extends AbstractIntStringValuePair\n{\n\n //Supported ID3 charset ids\n public static final byte ISO_8859_1 = 0;\n public static final byte UTF_16 = 1; //We use UTF-16 with LE byte-ordering and byte order mark by default\n //but can also use BOM with BE byte ordering\n public static final byte UTF_16BE = 2;\n public static final byte UTF_8 = 3;\n\n /** The number of bytes used to hold the text encoding field size. */\n public static final int TEXT_ENCODING_FIELD_SIZE = 1;\n\n private static TextEncoding textEncodings;\n\n private final Map<Integer, Charset> idToCharset = new HashMap<Integer, Charset>();\n\n /**\n * Get singleton for this class.\n *\n * @return singleton\n */\n public static synchronized TextEncoding getInstanceOf()\n {\n if (textEncodings == null)\n {\n textEncodings = new TextEncoding();\n }\n return textEncodings;\n }\n\n private TextEncoding()\n {\n idToCharset.put((int) ISO_8859_1, StandardCharsets.ISO_8859_1);\n idToCharset.put((int) UTF_16, StandardCharsets.UTF_16);\n idToCharset.put((int) UTF_16BE, StandardCharsets.UTF_16BE);\n idToCharset.put((int) UTF_8, StandardCharsets.UTF_8);\n\n for (final Map.Entry<Integer, Charset> e : idToCharset.entrySet()) {\n idToValue.put(e.getKey(), e.getValue().name());\n }\n\n createMaps();\n }\n\n /**\n * Allows to lookup id directly via the {@link Charset} instance.\n *\n * @param charset charset\n * @return id, e.g. {@link #ISO_8859_1}, or {@code null}, if not found\n */\n public Integer getIdForCharset(final Charset charset)\n {\n return valueToId.get(charset.name());\n }\n\n /**\n * Allows direct lookup of the {@link Charset} instance via an id.\n *\n * @param id id, e.g. {@link #ISO_8859_1}\n * @return charset or {@code null}, if not found\n */\n public Charset getCharsetForId(final int id)\n {\n return idToCharset.get(id);\n }\n}" } ]
import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.StringTokenizer; import org.jaudiotagger.tag.InvalidTagException; import org.jaudiotagger.tag.datatype.DataTypes; import org.jaudiotagger.tag.datatype.NumberHashMap; import org.jaudiotagger.tag.datatype.Pair; import org.jaudiotagger.tag.datatype.PairedTextEncodedStringNullTerminated; import org.jaudiotagger.tag.id3.valuepair.TextEncoding;
7,559
/** * @author : Paul Taylor * @author : Eric Farng * * Version @version:$Id$ * * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Description: * People List * */ package org.jaudiotagger.tag.id3.framebody; /** * Used by frames that take a pair of values such as TIPL, IPLS and TMCL * */ public abstract class AbstractFrameBodyPairs extends AbstractID3v2FrameBody implements ID3v24FrameBody { /** * Creates a new AbstractFrameBodyPairs datatype. */ public AbstractFrameBodyPairs() { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param textEncoding * @param text */ public AbstractFrameBodyPairs(byte textEncoding, String text) { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, textEncoding); setText(text); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param byteBuffer * @param frameSize * @throws org.jaudiotagger.tag.InvalidTagException */ public AbstractFrameBodyPairs(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public abstract String getIdentifier(); /** * Set the text, decoded as pairs of involvee - involvement * * @param text */ public void setText(String text) { PairedTextEncodedStringNullTerminated.ValuePairs value = new PairedTextEncodedStringNullTerminated.ValuePairs(); StringTokenizer stz = new StringTokenizer(text, "\0"); while (stz.hasMoreTokens()) { String key =stz.nextToken(); if(stz.hasMoreTokens()) { value.add(key, stz.nextToken()); } } setObjectValue(DataTypes.OBJ_TEXT, value); } /** * Parse text as a null separated pairing of function and name * * @param text */ public void addPair(String text) { StringTokenizer stz = new StringTokenizer(text, "\0"); if (stz.countTokens()==2) { addPair(stz.nextToken(),stz.nextToken()); } else { addPair("", text); } } /** * Add pair * * @param function * @param name */ public void addPair(String function,String name) { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.add(function, name); } /** * Remove all Pairs */ public void resetPairs() { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.getMapping().clear(); } /** * Because have a text encoding we need to check the data values do not contain characters that cannot be encoded in * current encoding before we write data. If they do change the encoding. */ public void write(ByteArrayOutputStream tagBuffer) { if (!((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).canBeEncoded()) { this.setTextEncoding(TextEncoding.UTF_16); } super.write(tagBuffer); } /** * Consists of a text encoding , and then a series of null terminated Strings, there should be an even number * of Strings as they are paired as involvement/involvee */ protected void setupObjectList() { objectList.add(new NumberHashMap(DataTypes.OBJ_TEXT_ENCODING, this, TextEncoding.TEXT_ENCODING_FIELD_SIZE)); objectList.add(new PairedTextEncodedStringNullTerminated(DataTypes.OBJ_TEXT, this)); } public PairedTextEncodedStringNullTerminated.ValuePairs getPairing() { return (PairedTextEncodedStringNullTerminated.ValuePairs) getObject(DataTypes.OBJ_TEXT).getValue(); } /** * Get key at index * * @param index * @return value at index */ public String getKeyAtIndex(int index) { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); return text.getValue().getMapping().get(index).getKey(); } /** * Get value at index * * @param index * @return value at index */ public String getValueAtIndex(int index) { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); return text.getValue().getMapping().get(index).getValue(); } /** * @return number of text pairs */ public int getNumberOfPairs() { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); return text.getValue().getNumberOfPairs(); } public String getText() { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); StringBuilder sb = new StringBuilder(); int count = 1;
/** * @author : Paul Taylor * @author : Eric Farng * * Version @version:$Id$ * * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Description: * People List * */ package org.jaudiotagger.tag.id3.framebody; /** * Used by frames that take a pair of values such as TIPL, IPLS and TMCL * */ public abstract class AbstractFrameBodyPairs extends AbstractID3v2FrameBody implements ID3v24FrameBody { /** * Creates a new AbstractFrameBodyPairs datatype. */ public AbstractFrameBodyPairs() { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param textEncoding * @param text */ public AbstractFrameBodyPairs(byte textEncoding, String text) { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, textEncoding); setText(text); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param byteBuffer * @param frameSize * @throws org.jaudiotagger.tag.InvalidTagException */ public AbstractFrameBodyPairs(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public abstract String getIdentifier(); /** * Set the text, decoded as pairs of involvee - involvement * * @param text */ public void setText(String text) { PairedTextEncodedStringNullTerminated.ValuePairs value = new PairedTextEncodedStringNullTerminated.ValuePairs(); StringTokenizer stz = new StringTokenizer(text, "\0"); while (stz.hasMoreTokens()) { String key =stz.nextToken(); if(stz.hasMoreTokens()) { value.add(key, stz.nextToken()); } } setObjectValue(DataTypes.OBJ_TEXT, value); } /** * Parse text as a null separated pairing of function and name * * @param text */ public void addPair(String text) { StringTokenizer stz = new StringTokenizer(text, "\0"); if (stz.countTokens()==2) { addPair(stz.nextToken(),stz.nextToken()); } else { addPair("", text); } } /** * Add pair * * @param function * @param name */ public void addPair(String function,String name) { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.add(function, name); } /** * Remove all Pairs */ public void resetPairs() { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.getMapping().clear(); } /** * Because have a text encoding we need to check the data values do not contain characters that cannot be encoded in * current encoding before we write data. If they do change the encoding. */ public void write(ByteArrayOutputStream tagBuffer) { if (!((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).canBeEncoded()) { this.setTextEncoding(TextEncoding.UTF_16); } super.write(tagBuffer); } /** * Consists of a text encoding , and then a series of null terminated Strings, there should be an even number * of Strings as they are paired as involvement/involvee */ protected void setupObjectList() { objectList.add(new NumberHashMap(DataTypes.OBJ_TEXT_ENCODING, this, TextEncoding.TEXT_ENCODING_FIELD_SIZE)); objectList.add(new PairedTextEncodedStringNullTerminated(DataTypes.OBJ_TEXT, this)); } public PairedTextEncodedStringNullTerminated.ValuePairs getPairing() { return (PairedTextEncodedStringNullTerminated.ValuePairs) getObject(DataTypes.OBJ_TEXT).getValue(); } /** * Get key at index * * @param index * @return value at index */ public String getKeyAtIndex(int index) { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); return text.getValue().getMapping().get(index).getKey(); } /** * Get value at index * * @param index * @return value at index */ public String getValueAtIndex(int index) { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); return text.getValue().getMapping().get(index).getValue(); } /** * @return number of text pairs */ public int getNumberOfPairs() { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); return text.getValue().getNumberOfPairs(); } public String getText() { PairedTextEncodedStringNullTerminated text = (PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT); StringBuilder sb = new StringBuilder(); int count = 1;
for (Pair entry : text.getValue().getMapping())
3
2023-12-11 05:58:19+00:00
12k
Ender-Cube/Endercube
Parkour/src/main/java/net/endercube/Parkour/ParkourMinigame.java
[ { "identifier": "EndercubeMinigame", "path": "Common/src/main/java/net/endercube/Common/EndercubeMinigame.java", "snippet": "public abstract class EndercubeMinigame {\n\n public static final Logger logger;\n private HoconConfigurationLoader configLoader;\n public CommentedConfigurationNode config;\n protected ConfigUtils configUtils;\n protected @NotNull EventNode<Event> eventNode;\n protected ArrayList<InstanceContainer> instances;\n private EndercubeServer endercubeServer;\n\n // Create an instance of the logger\n static {\n logger = LoggerFactory.getLogger(EndercubeMinigame.class);\n }\n\n protected EndercubeMinigame(EndercubeServer endercubeServer) {\n this.endercubeServer = endercubeServer;\n\n createConfig();\n\n // Initialise instances\n instances = new ArrayList<>();\n instances = initInstances();\n\n // Create the eventNode\n // Filter if the event is an instanceEvent happening in our instances or a minigameEvent on this minigame\n eventNode = EventNode.event(getName(), EventFilter.ALL, (Event event) -> {\n if (event instanceof InstanceEvent instanceEvent) {\n return getInstances().contains(instanceEvent.getInstance());\n }\n\n if (event instanceof PlayerMinigameEvent minigameEvent) {\n return minigameEvent.getMinigame().equals(getName());\n }\n\n return false;\n });\n\n // Register the event node\n MinecraftServer.getGlobalEventHandler().addChild(eventNode);\n\n\n }\n\n\n /**\n * The name of this minigame. must be unique\n * @return The name\n */\n public abstract String getName();\n\n /**\n * Loads all the instances\n * @return An ArrayList of InstanceContainer's\n */\n protected abstract ArrayList<InstanceContainer> initInstances();\n\n /**\n * Called to add subcommands to the rootCommand given\n * @param rootCommand The root command (/<this.getName())\n * @return The root command with extra commands added to it (or not! I don't mind)\n */\n protected abstract Command initCommands(Command rootCommand);\n\n public TextComponent getChatPrefix() {\n return Component.text(\"\")\n .append(Component.text(\"[\").color(NamedTextColor.DARK_GRAY))\n .append(Component.text(StringUtils.capitalize(this.getName())).color(NamedTextColor.AQUA).decorate(TextDecoration.BOLD))\n .append(Component.text(\"] \").color(NamedTextColor.DARK_GRAY));\n }\n\n protected void registerCommands() {\n // Init and register commands\n MinecraftServer.getCommandManager().register(\n this.initCommands(new GenericRootCommand(this.getName()))\n );\n }\n\n /**\n * Get the instances associated with this minigame\n * @return The instances\n */\n public ArrayList<InstanceContainer> getInstances() {\n return instances;\n }\n\n public void setEndercubeServer(EndercubeServer server) {\n endercubeServer = server;\n }\n\n @Nullable\n public EndercubeServer getEndercubeServer() {\n return endercubeServer;\n }\n\n /**\n * Creates a database object\n * @param clazz The class extending AbstractDatabase to use\n * @return An instance of the database\n */\n public <T extends AbstractDatabase> T createDatabase(Class<T> clazz) throws Exception {\n return clazz.getConstructor(JedisPooled.class, String.class).newInstance(this.getEndercubeServer().getJedisPooled(), this.getName());\n }\n\n private void createConfig() {\n // Create config and configUtils\n String fileName = getName() + \".conf\";\n\n\n configLoader = HoconConfigurationLoader.builder()\n .path(Paths.get(\"./config/\" + fileName))\n .defaultOptions(configurationOptions -> configurationOptions.header(\"This is the configuration file for the \" + getName() + \" minigame\"))\n .build();\n\n\n try {\n config = configLoader.load();\n } catch (ConfigurateException e) {\n logger.error(\"An error occurred while loading \\\"\" + fileName + \"\\\": \" + e.getMessage());\n logger.error(Arrays.toString(e.getStackTrace()));\n MinecraftServer.stopCleanly();\n }\n\n configUtils = new ConfigUtils(configLoader, config);\n\n // Required to create the config file\n configUtils.saveConfig();\n }\n}" }, { "identifier": "EndercubeServer", "path": "Common/src/main/java/net/endercube/Common/EndercubeServer.java", "snippet": "public class EndercubeServer {\n\n private final ArrayList<EndercubeMinigame> minigames = new ArrayList<>();\n private final CommentedConfigurationNode globalConfig;\n private final ConfigUtils globalConfigUtils;\n\n private static final Logger logger;\n\n\n // Initializes the logger, only on the first initialization of this class\n static {\n logger = LoggerFactory.getLogger(EndercubeServer.class);\n }\n\n private EndercubeServer(EndercubeServerBuilder builder) {\n this.globalConfig = builder.globalConfig;\n this.globalConfigUtils = builder.globalConfigUtils;\n }\n\n /**\n * Add a minigame to the server\n * @param minigame The minigame to add\n * @return The builder\n */\n public EndercubeServer addMinigame(EndercubeMinigame minigame) {\n minigame.setEndercubeServer(this);\n minigames.add(minigame);\n return this;\n }\n\n public @NotNull CommentedConfigurationNode getGlobalConfig() {\n return globalConfig;\n }\n public @NotNull ConfigUtils getGlobalConfigUtils() {\n return globalConfigUtils;\n }\n\n @Nullable\n public EndercubeMinigame getMinigameByName(@NotNull String name) {\n return minigames.stream()\n .filter(((endercubeMinigame) -> endercubeMinigame.getName().equals(name)))\n .findFirst()\n .orElse(null);\n }\n\n @NotNull\n public JedisPooled getJedisPooled() {\n String jedisURL = globalConfigUtils.getOrSetDefault(globalConfig.node(\"database\", \"redis\", \"url\"), \"localhost\");\n int jedisPort = Integer.parseInt(globalConfigUtils.getOrSetDefault(globalConfig.node(\"database\", \"redis\", \"port\"), \"6379\"));\n return new JedisPooled(jedisURL, jedisPort);\n }\n\n /**\n * A builder for EndercubeServer\n */\n public static class EndercubeServerBuilder {\n private final EventNode<Event> globalEvents;\n private CommentedConfigurationNode globalConfig;\n private ConfigUtils globalConfigUtils;\n private HashMap<NamespaceID, Supplier<BlockHandler>> blockHandlers = new HashMap<>();\n\n public EndercubeServerBuilder() {\n globalEvents = EventNode.all(\"globalListeners\");\n }\n\n\n /**\n * Add a global event, will be called regardless of minigame\n * @param listener The listener\n * @return The builder\n */\n public EndercubeServerBuilder addGlobalEvent(EventListener<?> listener) {\n globalEvents.addListener(listener);\n return this;\n }\n\n /**\n * Add a global event, will be called regardless of minigame\n * @param eventType The type of event to listen for\n * @param listener The listener\n * @return The builder\n */\n public <E extends Event> EndercubeServerBuilder addGlobalEvent(@NotNull Class<E> eventType, @NotNull Consumer<E> listener) {\n globalEvents.addListener(eventType, listener);\n return this;\n }\n\n /**\n * Add a block handler\n * @param namespace The namespace name for this block\n * @param handlerSupplier THe handler for this block\n * @return The builder\n */\n public EndercubeServerBuilder addBlockHandler(NamespaceID namespace, Supplier<BlockHandler> handlerSupplier) {\n // Add block handlers\n blockHandlers.put(namespace, handlerSupplier);\n return this;\n }\n\n /**\n * Creates and loads the global config\n */\n private void initGlobalConfig() {\n String fileName = \"globalConfig.conf\";\n\n // Create config directories\n if (!Files.exists(Paths.get(\"./config/worlds/\"))) {\n logger.info(\"Creating configuration files\");\n\n try {\n Files.createDirectories(Paths.get(\"./config/worlds/\"));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n HoconConfigurationLoader loader = HoconConfigurationLoader.builder()\n .path(Paths.get(\"./config/globalConfig.conf\"))\n .build();\n\n try {\n globalConfig = loader.load();\n } catch (ConfigurateException e) {\n logger.error(\"An error occurred while loading \" + fileName + \": \" + e.getMessage());\n logger.error(Arrays.toString(e.getStackTrace()));\n MinecraftServer.stopCleanly();\n }\n\n globalConfigUtils = new ConfigUtils(loader, globalConfig);\n }\n\n /**\n * Start Minestom and the like\n */\n public void createServer() {\n\n // Server Initialization\n MinecraftServer minecraftServer = MinecraftServer.init();\n\n // Add global events\n MinecraftServer.getGlobalEventHandler().addChild(globalEvents);\n\n // Init block handlers\n for(Map.Entry<NamespaceID, Supplier<BlockHandler>> entry : blockHandlers.entrySet()) {\n MinecraftServer.getBlockManager().registerHandler(entry.getKey(), entry.getValue());\n logger.debug(\"Added a block handler for \" + entry.getKey());\n }\n\n // Set encryption\n EncryptionMode encryptionMode;\n try {\n encryptionMode = EncryptionMode.valueOf(globalConfigUtils.getOrSetDefault(globalConfig.node(\"connection\", \"mode\"), \"online\").toUpperCase());\n } catch (IllegalArgumentException e) {\n logger.warn(\"Cannot read encryption mode from config, falling back to ONLINE\");\n encryptionMode = EncryptionMode.ONLINE;\n }\n initEncryption(encryptionMode, globalConfigUtils.getOrSetDefault(globalConfig.node(\"connection\", \"velocitySecret\"), \"\"));\n\n // Start server\n int port = Integer.parseInt(globalConfigUtils.getOrSetDefault(globalConfig.node(\"connection\", \"port\"), \"25565\"));\n minecraftServer.start(\"0.0.0.0\", port);\n logger.info(\"Started server on port \" + port + \" with \" + encryptionMode + \" encryption\");\n\n // Set player provider\n MinecraftServer.getConnectionManager().setPlayerProvider(EndercubePlayer::new);\n logger.debug(\"Set player provider\");\n\n // Register the void\n // Register minecraft:the_void\n MinecraftServer.getBiomeManager().addBiome(Biome\n .builder()\n .name(NamespaceID.from(\"minecraft:the_void\"))\n .build()\n );\n }\n\n enum EncryptionMode {\n ONLINE,\n VELOCITY\n }\n\n private void initEncryption(EncryptionMode mode, String velocitySecret) {\n switch (mode) {\n case ONLINE -> MojangAuth.init();\n case VELOCITY -> {\n if (!Objects.equals(velocitySecret, \"\")) {\n VelocityProxy.enable(velocitySecret);\n logger.debug(\"Velocity enabled: \" + VelocityProxy.isEnabled());\n } else {\n logger.error(\"Velocity is enabled but no secret is specified. Stopping server\");\n MinecraftServer.stopCleanly();\n }\n }\n }\n }\n\n /**\n * Sets the logback logging level\n * @param level The level to set to, INFO by default\n */\n private static void setLoggingLevel(Level level) {\n // https://stackoverflow.com/a/9787965/13247146\n ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);\n root.setLevel(level);\n }\n\n\n public EndercubeServer startServer() {\n // Init config\n this.initGlobalConfig();\n\n // Make logging level configurable\n Level logLevel = Level.toLevel(\n globalConfigUtils.getOrSetDefault(\n globalConfig.node(\"logLevel\"),\n \"INFO\"\n )\n );\n\n setLoggingLevel(logLevel);\n logger.trace(\"Log level is: \" + logLevel.levelStr);\n\n // Start the server\n this.createServer();\n\n return new EndercubeServer(this);\n }\n }\n\n\n}" }, { "identifier": "FullbrightDimension", "path": "Common/src/main/java/net/endercube/Common/dimensions/FullbrightDimension.java", "snippet": "public class FullbrightDimension {\n public static final DimensionType INSTANCE = DimensionType.builder(NamespaceID.from(\"minestom:full_bright\"))\n .ambientLight(2.0f)\n .build();\n\n static {\n MinecraftServer.getDimensionTypeManager().addDimension(INSTANCE);\n }\n}" }, { "identifier": "EndercubePlayer", "path": "Common/src/main/java/net/endercube/Common/players/EndercubePlayer.java", "snippet": "public class EndercubePlayer extends Player {\n public EndercubePlayer(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) {\n super(uuid, username, playerConnection);\n }\n\n /**\n * Get the current minigame\n * @return the name of the minigame or \"hub\" if in the hub\n */\n public String getCurrentMinigame() {\n return this.getTag(Tag.String(\"minigame\"));\n }\n\n /**\n * Sets the player's current minigame\n */\n public void setCurrentMinigame(String minigame) {\n this.setTag(Tag.String(\"minigame\"), minigame);\n }\n\n /**\n * Teleport the player to the hub\n */\n public void gotoHub() {\n if (Objects.equals(this.getCurrentMinigame(), \"hub\")) {\n this.sendMessage(\"Sending you to the hub spawn\");\n this.teleport(this.getInstance().getTag(Tag.Transient(\"spawnPos\")));\n return;\n }\n this.sendMessage(\"Sending you to the hub\");\n MinecraftServer.getGlobalEventHandler().call(new MinigamePlayerLeaveEvent(this.getCurrentMinigame(), this));\n MinecraftServer.getGlobalEventHandler().call(new MinigamePlayerJoinEvent(\"hub\", this, null));\n }\n}" }, { "identifier": "LeaderboardCommand", "path": "Parkour/src/main/java/net/endercube/Parkour/commands/LeaderboardCommand.java", "snippet": "public class LeaderboardCommand extends Command {\n public LeaderboardCommand() {\n super(\"leaderboard\");\n var mapArgument = ArgumentType.Word(\"mapArgument\").from(getMaps());\n\n // No map defined\n setDefaultExecutor(((sender, context) -> {\n sender.sendMessage(Component.text(\"[ERROR] You must specify a map\").color(NamedTextColor.RED));\n }));\n\n // Non-existent map defined\n mapArgument.setCallback(((sender, exception) -> {\n final String input = exception.getInput();\n sender.sendMessage(Component.text(\"[ERROR] The map \" + input + \" does not exist!\").color(NamedTextColor.RED));\n }));\n\n // Actually execute command\n addSyntax(((sender, context) -> {\n final String map = context.get(mapArgument);\n sender.sendMessage(createLeaderboard(map));\n }), mapArgument);\n }\n\n /**\n * Generates a leaderboard\n * @param mapName The map\n * @return A leaderboard or formatted text for an error if there is one\n */\n private TextComponent createLeaderboard(String mapName) {\n Component placementComponent = Component.text(\"\");\n\n // Get list of times from db\n List<Tuple> leaderboardTuple = database.getLeaderboard(mapName, 9);\n\n // Tell the player and the log that something went wrong if the database returns null\n if (leaderboardTuple == null) {\n logger.warn(\"The database call for leaderboards in parkour was null for some reason, continuing but something has gone wrong\");\n return Component.text(\"\")\n .append(Component.text(\"[ERROR] \")\n .color(NamedTextColor.RED)\n .decorate(TextDecoration.BOLD)\n )\n .append(Component.text(\"Something went wrong when reading the database. Please contact admins on the Endercube Discord\")\n .color(NamedTextColor.RED)\n );\n }\n\n // Tell the player what happened if there are no times\n if (leaderboardTuple.isEmpty()) {\n return Component.text(\"\")\n .append(Component.text(\"No times exist for \").color(NamedTextColor.AQUA))\n .append(Component.text(mapName).color(NamedTextColor.GOLD).decorate(TextDecoration.BOLD))\n .append(Component.text(\" yet! Why not set some?\").color(NamedTextColor.AQUA));\n }\n\n // Add places 1-3\n if (leaderboardTuple.size() >= 1) { // This is always true. Leaving it in to make this easier to read\n placementComponent = placementComponent.append(leaderboardEntry(\"#FFD700\",\n leaderboardTuple.get(0).getElement(),\n leaderboardTuple.get(0).getScore(),\n 1)\n );\n }\n\n if (leaderboardTuple.size() >= 2) {\n placementComponent = placementComponent.append(leaderboardEntry(\"#808080\",\n leaderboardTuple.get(1).getElement(),\n leaderboardTuple.get(1).getScore(),\n 2)\n );\n }\n\n if (leaderboardTuple.size() >= 3) {\n placementComponent = placementComponent.append(leaderboardEntry(\"#CD7F32\",\n leaderboardTuple.get(2).getElement(),\n leaderboardTuple.get(2).getScore(),\n 3)\n ).append(Component.newline());\n }\n\n\n // Add places 4-10\n if (leaderboardTuple.size() >= 4) {\n for (int i = 3; i < leaderboardTuple.size(); i++) {\n placementComponent = placementComponent.append(leaderboardEntry(\"#AAAAAA\",\n leaderboardTuple.get(i).getElement(),\n leaderboardTuple.get(i).getScore(),\n i + 1)\n );\n }\n }\n\n\n\n return Component.text()\n .append(ComponentUtils.centerComponent(MiniMessage.miniMessage().deserialize(\"<bold><gradient:#FF416C:#FF4B2B>All Time Leaderboard For \" + mapName)))\n .append(Component.newline())\n .append(Component.newline())\n .append(placementComponent)\n .build();\n }\n\n private Component leaderboardEntry(String color, String player, double time, int placement) {\n String placementToNameGap;\n if (placement >= 10) {\n placementToNameGap = \" \";\n } else {\n placementToNameGap = \" \";\n }\n return MiniMessage.miniMessage()\n .deserialize(\"<\" + color + \">#<bold>\" + placement + placementToNameGap + player + \"</bold> \" + ComponentUtils.toHumanReadableTime((long) time))\n .append(Component.newline());\n }\n\n private String[] getMaps() {\n ArrayList<String> mapNames = new ArrayList<>();\n\n for (InstanceContainer instance : parkourMinigame.getInstances()) {\n mapNames.add(instance.getTag(Tag.String(\"name\")));\n }\n\n return mapNames.toArray(new String[0]);\n }\n}" }, { "identifier": "ParkourDatabase", "path": "Parkour/src/main/java/net/endercube/Parkour/database/ParkourDatabase.java", "snippet": "public class ParkourDatabase extends AbstractDatabase {\n\n\n /**\n * A parkour database\n *\n * @param jedis A {@code JedisPooled} to get jedis instances from\n * @param nameSpace The prefix for all keys, does not need a colon on the end\n */\n public ParkourDatabase(JedisPooled jedis, String nameSpace) {\n super(jedis, nameSpace);\n }\n\n /**\n * Adds a time to the database\n *\n * @param player The player the time belongs to\n * @param course The {@link String} id of the course to look up\n * @param time The time in milliseconds\n * @return true if new pb, false if not new PB\n */\n public boolean addTime(Player player, String course, Long time) {\n String key = nameSpace + course + \":times\";\n String uuid = player.getUuid().toString();\n\n Double oldTime = jedis.zscore(key, uuid);\n\n if (oldTime != null) {\n if (oldTime <= time) {\n logger.trace(\"Did not add new time for \" + player.getUsername() + \" because their current time of \" + oldTime + \" Is less than than the new time of \" + time);\n return false;\n }\n }\n\n jedis.zadd(key, time, uuid);\n logger.debug(\"Added run to the database with:\");\n logger.debug(\" player: \" + player.getUsername());\n logger.debug(\" course: \" + course);\n logger.debug(\" time: \" + time);\n return true;\n }\n\n /**\n * Removes a player's times from the leaderboard\n *\n * @param player The player whose times to remove\n * @param course The course to remove times from\n */\n public void removeTime(Player player, String course) {\n jedis.zrem(nameSpace + course + \":times\", player.getUuid().toString());\n logger.debug(\"Removed \" + player.getUsername() + \"'s times for \" + course);\n }\n\n /**\n * Removes a player's times from the leaderboard\n *\n * @param playerUUID The player's UUID whose times are to be removed\n * @param course The course to remove times from\n */\n public void removeTime(UUID playerUUID, String course) {\n jedis.zrem(nameSpace + course + \":times\", playerUUID.toString());\n logger.debug(\"Removed \" + playerUUID + \"'s times for \" + course);\n }\n\n /**\n * @param course The course to get a leaderboard for\n * @param maxRange an {@code int} for the number of results to return\n * @return A {@code List<Tuple>} containing players and their times\n */\n @Nullable\n public List<Tuple> getLeaderboard(String course, int maxRange) {\n return getLeaderboard(course, 0, maxRange);\n }\n\n /**\n * @param course The course to get a leaderboard for\n * @param minRange an {@code int} for the nth minimum result\n * @param maxRange an {@code int} for the nth maximum result\n * @return A {@code List<Tuple>} containing players and their times\n */\n @Nullable\n public List<Tuple> getLeaderboard(String course, int minRange, int maxRange) {\n logger.debug(\"Getting leaderboard for \" + course + \" in range \" + minRange + \" to \" + maxRange);\n List<Tuple> databaseTuple = jedis.zrangeWithScores(nameSpace + course + \":times\", minRange, maxRange);\n\n return databaseTuple.stream()\n .map((tuple ->\n new Tuple(\n MojangUtils.fromUuid(tuple.getElement()).get(\"name\").getAsString(),\n tuple.getScore())\n )\n )\n .toList();\n\n }\n\n /**\n * Set the grinding mode\n * @param player The player to set for\n * @param grindMode The grind mode to set\n */\n public void setGrindMode(EndercubePlayer player, @NotNull GrindMode grindMode) {\n jedis.set(nameSpace + \"grindMode:\" + player.getUuid(), grindMode.name());\n }\n\n /**\n * Get the player's specified grindMode. HUB if none has been set\n * @param player the player to get for\n * @return The selected grindMode\n */\n @NotNull\n public GrindMode getGrindMode(EndercubePlayer player) {\n @Nullable String stringGrindMode = jedis.get(nameSpace + \"grindMode:\" + player.getUuid());\n if (stringGrindMode == null) {\n this.setGrindMode(player, GrindMode.HUB);\n return GrindMode.HUB;\n }\n return GrindMode.valueOf(stringGrindMode);\n }\n}" }, { "identifier": "InventoryPreClick", "path": "Parkour/src/main/java/net/endercube/Parkour/listeners/InventoryPreClick.java", "snippet": "public class InventoryPreClick implements EventListener<InventoryPreClickEvent> {\n @Override\n public @NotNull Class<InventoryPreClickEvent> eventType() {\n return InventoryPreClickEvent.class;\n }\n\n @Override\n public @NotNull Result run(@NotNull InventoryPreClickEvent event) {\n EndercubePlayer player = (EndercubePlayer) event.getPlayer();\n ItemClickHandler.handleClick(event.getClickedItem(), player);\n\n event.setCancelled(true);\n\n return Result.SUCCESS;\n }\n}" }, { "identifier": "MinigamePlayerJoin", "path": "Parkour/src/main/java/net/endercube/Parkour/listeners/MinigamePlayerJoin.java", "snippet": "public class MinigamePlayerJoin implements EventListener<MinigamePlayerJoinEvent> {\n\n\n\n\n @Override\n public @NotNull Class<MinigamePlayerJoinEvent> eventType() {\n return MinigamePlayerJoinEvent.class;\n }\n\n @Override\n public @NotNull Result run(@NotNull MinigamePlayerJoinEvent event) {\n EndercubePlayer player = event.getPlayer();\n String mapName = event.getMap();\n\n // Disable player pushing\n player.setTeam(MinecraftServer.getTeamManager().getTeam(\"parkourTeam\"));\n\n logger.info(\"Sending \" + player.getUsername() + \" To a parkour map\");\n\n InstanceContainer instance = parkourMinigame\n .getInstances()\n .stream()\n .filter(\n (mapInstance) -> mapInstance.getTag(Tag.String(\"name\")).equals(mapName)\n )\n .findFirst()\n .orElse(null);\n\n if (instance == null) {\n logger.error(\"Parkour was given a map name that does not exist. something really broke good...\");\n return Result.INVALID;\n }\n\n player.setInstance(instance, instance.getTag(Tag.Transient(\"spawnPos\")));\n\n // Init tags\n player.setTag(Tag.Integer(\"parkour_checkpoint\"), -1);\n player.setTag(Tag.Boolean(\"parkour_timerStarted\"), false);\n\n addInventoryButtons(player);\n\n return Result.SUCCESS;\n }\n\n private void addInventoryButtons(EndercubePlayer player) {\n player.getInventory().setItemStack(0, InventoryItems.CHECKPOINT_ITEM);\n player.getInventory().setItemStack(1, InventoryItems.RESTART_ITEM);\n player.getInventory().setItemStack(4, InventoryItems.VISIBILITY_ITEM_INVISIBLE);\n player.getInventory().setItemStack(8, InventoryItems.HUB_ITEM);\n\n switch (database.getGrindMode(player)) {\n case HUB -> player.getInventory().setItemStack(17, InventoryItems.GRIND_MODE_HUB);\n case MENU -> player.getInventory().setItemStack(17, InventoryItems.GRIND_MODE_MENU);\n case RESTART -> player.getInventory().setItemStack(17, InventoryItems.GRIND_MODE_RESTART);\n }\n\n }\n}" }, { "identifier": "MinigamePlayerLeave", "path": "Parkour/src/main/java/net/endercube/Parkour/listeners/MinigamePlayerLeave.java", "snippet": "public class MinigamePlayerLeave implements EventListener<MinigamePlayerLeaveEvent> {\n @Override\n public @NotNull Class<MinigamePlayerLeaveEvent> eventType() {\n return MinigamePlayerLeaveEvent.class;\n }\n\n @Override\n public @NotNull Result run(@NotNull MinigamePlayerLeaveEvent event) {\n EndercubePlayer player = event.getPlayer();\n player.getInventory().clear();\n\n // Stop the action bar timer\n Task actionbarTimerTask = player.getTag(Tag.Transient(\"actionbarTimerTask\"));\n actionbarTimerTask.cancel();\n \n // Clean up team\n player.setTeam(null);\n\n // Make sure the player can see hub NPCs\n player.updateViewerRule(playerVisible -> true);\n\n return Result.SUCCESS;\n }\n}" }, { "identifier": "PlayerMove", "path": "Parkour/src/main/java/net/endercube/Parkour/listeners/PlayerMove.java", "snippet": "public class PlayerMove implements EventListener<PlayerMoveEvent> {\n\n private EndercubePlayer player;\n private Pos playerPosition;\n private Instance instance;\n private Pos[] checkpoints;\n private int currentCheckpoint;\n private String mapName;\n private Scheduler scheduler;\n @Override\n public @NotNull Class<PlayerMoveEvent> eventType() {\n return PlayerMoveEvent.class;\n }\n\n @Override\n public @NotNull Result run(@NotNull PlayerMoveEvent event) {\n player = (EndercubePlayer) event.getPlayer();\n playerPosition = player.getPosition();\n instance = player.getInstance();\n checkpoints = instance.getTag(Tag.Transient(\"checkpointsPosArray\"));\n currentCheckpoint = player.getTag(Tag.Integer(\"parkour_checkpoint\"));\n mapName = instance.getTag(Tag.String(\"name\"));\n scheduler = player.scheduler();\n\n // See if player is below the death barrier and if so, teleport them to current checkpoint\n if (player.getPosition().y() < instance.getTag(Tag.Integer(\"death-y\"))) {\n this.handleDeath();\n return Result.SUCCESS;\n }\n\n // Start timer on player move\n if (!player.getTag(Tag.Boolean(\"parkour_timerStarted\"))) {\n startTimer();\n return Result.SUCCESS;\n }\n\n\n // Deal with completing checkpoints\n if (currentCheckpoint < checkpoints.length - 1) { // Stop IndexOutOfBounds errors\n if (player.getPosition().sameBlock(checkpoints[currentCheckpoint + 1])) { // Actually check the checkpoint\n handleCheckpoint();\n return Result.SUCCESS;\n }\n }\n\n // Deal with finish\n if (playerPosition.sameBlock(instance.getTag(Tag.Transient(\"finishPos\")))) {\n if (currentCheckpoint == checkpoints.length - 1) {\n handleFinish();\n\n } else {\n player.sendMessage(parkourMinigame.getChatPrefix()\n .append(Component.text(\"You've missed some checkpoints! Go back and grab them or use the\"))\n .append(Component.text(\" blaze powder \")\n .hoverEvent(HoverEvent.showItem(HoverEvent.ShowItem.showItem(Key.key(\"minecraft:blaze_powder\"), 1)))\n .decorate(TextDecoration.BOLD)\n )\n .append(Component.text(\"to restart the course\"))\n );\n }\n return Result.SUCCESS;\n }\n\n\n return Result.SUCCESS;\n }\n\n private void handleDeath() {\n player.sendMessage(parkourMinigame.getChatPrefix().append(Component.text(\"Ya died :(\"))); // TODO: Random death message\n ParkourMinigame.sendToCheckpoint(player);\n logger.debug(player.getUsername() + \" died on \" + mapName);\n }\n\n private void startTimer() {\n // Toggle the timer started and set the start time\n player.setTag(Tag.Boolean(\"parkour_timerStarted\"), true);\n player.setTag(Tag.Long(\"parkour_startTime\"), System.currentTimeMillis());\n\n // Start the action bar timer task\n player.setTag(Tag.Transient(\"actionbarTimerTask\"),\n scheduler.submitTask(() -> {\n long timeTaken = System.currentTimeMillis() - player.getTag(Tag.Long(\"parkour_startTime\"));\n player.sendActionBar(Component.text(toHumanReadableTime(timeTaken), NamedTextColor.WHITE));\n return TaskSchedule.millis(15);\n })\n );\n }\n\n private void handleCheckpoint() {\n player.setTag(Tag.Integer(\"parkour_checkpoint\"), currentCheckpoint + 1);\n currentCheckpoint = currentCheckpoint + 1; // Increment currentCheckpoint as that hasn't updated and we need it soon\n\n player.sendMessage(parkourMinigame.getChatPrefix().append(Component.text(\"Checkpoint \" + (currentCheckpoint + 1) + \" completed!\")));\n logger.debug(player.getUsername() + \" finished checkpoint \" + (currentCheckpoint + 1) + \"/\" + checkpoints.length);\n\n player.playSound(Sound.sound(SoundEvent.ENTITY_PLAYER_LEVELUP, Sound.Source.PLAYER, 1f, 1f));\n }\n\n private void handleFinish() {\n // Calculate time by taking away the tag we set at the beginning from time now\n long timeTakenMS = System.currentTimeMillis() - player.getTag(Tag.Long(\"parkour_startTime\"));\n\n // Stop the action bar timer\n Task actionbarTimerTask = player.getTag(Tag.Transient(\"actionbarTimerTask\"));\n actionbarTimerTask.cancel();\n\n // Add the player's time to the database\n boolean newPB = database.addTime(player, mapName, timeTakenMS);\n\n // Do what the player's grind mode says\n switch (database.getGrindMode(player)) {\n case HUB -> player.gotoHub();\n case RESTART -> ParkourMinigame.restartMap(player);\n case MENU -> {\n player.gotoHub();\n player.openInventory(ParkourMapInventory.getInventory(false));\n }\n }\n\n player.sendMessage(Component.text(\"\")\n .append(parkourMinigame.getChatPrefix())\n .append(Component.text(\"Well done! You finished \" + mapName + \" in \" + toHumanReadableTime(timeTakenMS) + \". Use \"))\n .append(Component.text(\"/parkour leaderboard\")\n .decorate(TextDecoration.ITALIC)\n .clickEvent(ClickEvent.suggestCommand(\"/parkour leaderboard \"))\n .hoverEvent(HoverEvent.showText(Component.text(\"/parkour leaderboard <map>\"))))\n .append(Component.text(\" to view other's times\"))\n );\n\n logger.debug(player.getUsername() + \" finished \" + mapName);\n\n if (Objects.equals(database.getLeaderboard(mapName, 1).getFirst().getElement(), player.getUsername())) {\n showWRAnimation();\n return;\n }\n if (newPB) {\n player.sendMessage(parkourMinigame.getChatPrefix().append(Component.text(\"That run was a PB! Nice job\")));\n }\n }\n\n private void showWRAnimation() {\n byte totemEffect = (byte) 35;\n player.sendPacket(new EntityStatusPacket(player.getEntityId(), totemEffect));\n\n final Title.Times times = Title.Times.times(Duration.ofMillis(100), Duration.ofMillis(1500), Duration.ofMillis(500));\n final Title title = Title.title(Component.text(\"New world record!\"), Component.empty(), times);\n player.showTitle(title);\n\n player.sendMessage(parkourMinigame.getChatPrefix().append(Component.text(\"That was a new world record!\")));\n }\n}" }, { "identifier": "PlayerUseItem", "path": "Parkour/src/main/java/net/endercube/Parkour/listeners/PlayerUseItem.java", "snippet": "public class PlayerUseItem implements EventListener<PlayerUseItemEvent> {\n @Override\n public @NotNull Class<PlayerUseItemEvent> eventType() {\n return PlayerUseItemEvent.class;\n }\n\n @Override\n public @NotNull Result run(@NotNull PlayerUseItemEvent event) {\n EndercubePlayer player = (EndercubePlayer) event.getPlayer();\n\n ItemClickHandler.handleClick(event.getItemStack(), player);\n\n return Result.SUCCESS;\n }\n\n\n}" } ]
import net.endercube.Common.EndercubeMinigame; import net.endercube.Common.EndercubeServer; import net.endercube.Common.dimensions.FullbrightDimension; import net.endercube.Common.players.EndercubePlayer; import net.endercube.Parkour.commands.LeaderboardCommand; import net.endercube.Parkour.database.ParkourDatabase; import net.endercube.Parkour.listeners.InventoryPreClick; import net.endercube.Parkour.listeners.MinigamePlayerJoin; import net.endercube.Parkour.listeners.MinigamePlayerLeave; import net.endercube.Parkour.listeners.PlayerMove; import net.endercube.Parkour.listeners.PlayerUseItem; import net.hollowcube.polar.PolarLoader; import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.player.PlayerSwapItemEvent; import net.minestom.server.instance.Instance; import net.minestom.server.instance.InstanceContainer; import net.minestom.server.network.packet.server.play.TeamsPacket; import net.minestom.server.scoreboard.Team; import net.minestom.server.tag.Tag; import org.spongepowered.configurate.ConfigurationNode; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList;
8,691
package net.endercube.Parkour; /** * This is the entrypoint for Parkour */ public class ParkourMinigame extends EndercubeMinigame { public static ParkourMinigame parkourMinigame; public static ParkourDatabase database; public static Team parkourTeam; static { parkourTeam = MinecraftServer.getTeamManager().createBuilder("parkourTeam") .collisionRule(TeamsPacket.CollisionRule.NEVER) .build(); } public ParkourMinigame(EndercubeServer endercubeServer) { super(endercubeServer); parkourMinigame = this; // Register events eventNode .addListener(new PlayerMove())
package net.endercube.Parkour; /** * This is the entrypoint for Parkour */ public class ParkourMinigame extends EndercubeMinigame { public static ParkourMinigame parkourMinigame; public static ParkourDatabase database; public static Team parkourTeam; static { parkourTeam = MinecraftServer.getTeamManager().createBuilder("parkourTeam") .collisionRule(TeamsPacket.CollisionRule.NEVER) .build(); } public ParkourMinigame(EndercubeServer endercubeServer) { super(endercubeServer); parkourMinigame = this; // Register events eventNode .addListener(new PlayerMove())
.addListener(new PlayerUseItem())
10
2023-12-10 12:08:18+00:00
12k
lukebemishprojects/Tempest
fabriquilt/src/main/java/dev/lukebemish/tempest/impl/fabriquilt/ModPlatform.java
[ { "identifier": "FastChunkLookup", "path": "common/src/main/java/dev/lukebemish/tempest/impl/FastChunkLookup.java", "snippet": "public interface FastChunkLookup {\n WeatherChunkData tempest$getChunkData();\n void tempest$setChunkData(WeatherChunkData data);\n}" }, { "identifier": "Services", "path": "common/src/main/java/dev/lukebemish/tempest/impl/Services.java", "snippet": "public final class Services {\n private Services() {}\n\n public static final Platform PLATFORM = load(Platform.class);\n\n private static final List<Snower> SNOWERS;\n private static final List<Melter> MELTERS;\n\n public static boolean snow(ServerLevel level, BlockPos pos, BlockState original) {\n for (var snower : SNOWERS) {\n if (snower.snow(level, pos, original)) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean melt(ServerLevel level, BlockPos pos, BlockState original) {\n for (var melter : MELTERS) {\n if (melter.melt(level, pos, original)) {\n return true;\n }\n }\n return false;\n }\n\n public static <T> T load(Class<T> clazz) {\n return ServiceLoader.load(clazz)\n .findFirst()\n .orElseThrow(() -> new NullPointerException(\"Failed to load service for \" + clazz.getName()));\n }\n\n static {\n var melters = new ArrayList<Melter>();\n var snowers = new ArrayList<Snower>();\n for (var provider : ServiceLoader.load(CompatProvider.class)) {\n if (provider.shouldLoad()) {\n var compat = provider.compat();\n melters.add(new Melter() {\n boolean valid = true;\n\n @Override\n public boolean melt(ServerLevel level, BlockPos pos, BlockState original) {\n if (valid) {\n try {\n return compat.melt(level, pos, original);\n } catch (Throwable t) {\n valid = false;\n Constants.LOGGER.error(\"Failed to melt block at {} with provider {}\", pos, provider.getClass().getName(), t);\n }\n }\n return false;\n }\n });\n snowers.add(new Snower() {\n boolean valid = true;\n\n @Override\n public boolean snow(ServerLevel level, BlockPos pos, BlockState original) {\n if (valid) {\n try {\n return compat.snow(level, pos, original);\n } catch (Throwable t) {\n valid = false;\n Constants.LOGGER.error(\"Failed to snow block at {} with provider {}\", pos, provider.getClass().getName(), t);\n }\n }\n return false;\n }\n });\n }\n }\n MELTERS = List.copyOf(melters);\n SNOWERS = List.copyOf(snowers);\n }\n\n public interface Platform {\n WeatherChunkData getChunkData(LevelChunk chunk);\n <S, T extends S> Supplier<T> register(Supplier<T> supplier, ResourceLocation location, Registry<S> registry);\n\n boolean modLoaded(String modId);\n }\n\n @FunctionalInterface\n private interface Melter {\n boolean melt(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n @FunctionalInterface\n private interface Snower {\n boolean snow(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n public interface Compat {\n boolean melt(ServerLevel level, BlockPos pos, BlockState original);\n boolean snow(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n public interface CompatProvider {\n Compat compat();\n\n boolean shouldLoad();\n }\n}" }, { "identifier": "WeatherChunkData", "path": "common/src/main/java/dev/lukebemish/tempest/impl/data/world/WeatherChunkData.java", "snippet": "public class WeatherChunkData {\n final Int2ObjectMap<WeatherData.Concrete> data = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>());\n\n private final LevelChunk chunk;\n\n private final Int2IntMap updateQueue = new Int2IntOpenHashMap();\n private boolean networkingDirty = false;\n\n private float[] precipitation = new float[] {-0.5f, -0.5f, -0.5f, -0.5f};\n private float[] temperature = new float[] {0.5f, 0.5f, 0.5f, 0.5f};\n private float[] windX = new float[4];\n private float[] windZ = new float[4];\n private float[] thunder = new float[4];\n\n private static final int[] XS = new int[] {0, 0, 16, 16};\n private static final int[] ZS = new int[] {0, 16, 0, 16};\n\n private boolean initialized;\n private int visitIndex = -1;\n private final List<BlockPos> windCheckPositions = new ArrayList<>();\n\n private final @Nullable Runnable setDirtyCallback;\n\n public WeatherChunkData(LevelChunk chunk, @Nullable Runnable setDirtyCallback) {\n this.chunk = chunk;\n this.setDirtyCallback = setDirtyCallback;\n }\n\n public WeatherChunkData(LevelChunk chunk) {\n this(chunk, null);\n }\n\n protected void update(int pos, int data) {\n synchronized (updateQueue) {\n updateQueue.put(pos, data);\n markDirty();\n }\n }\n\n private void markDirty() {\n networkingDirty = true;\n if (setDirtyCallback != null) {\n setDirtyCallback.run();\n }\n }\n\n public List<BlockPos> icedInSection(SectionPos pos) {\n List<BlockPos> iced = new ArrayList<>();\n BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos();\n for (var key : data.keySet()) {\n decode(key, mutable);\n var data = query(mutable);\n if (data.blackIce() >= 1 && mutable.getY() >= pos.minBlockY() && mutable.getY() <= pos.maxBlockY()) {\n iced.add(mutable.immutable());\n }\n }\n return iced;\n }\n\n public void update() {\n if (this.networkingDirty) {\n int[] posData;\n int[] weatherData;\n synchronized (updateQueue) {\n posData = new int[updateQueue.size()];\n weatherData = new int[updateQueue.size()];\n int i = 0;\n for (Int2IntMap.Entry entry : updateQueue.int2IntEntrySet()) {\n posData[i] = entry.getIntKey();\n weatherData[i] = entry.getIntValue();\n i++;\n }\n updateQueue.clear();\n this.networkingDirty = false;\n }\n var packet = new UpdateWeatherChunk(LevelIdMap.CURRENT.id(chunk.getLevel().dimension()), chunk.getPos(), posData, weatherData, precipitation, temperature, windX, windZ, thunder);\n UpdateWeatherChunk.Sender.SENDER.send(packet, chunk);\n }\n }\n\n public @Nullable UpdateWeatherChunk full() {\n int[] posData;\n int[] weatherData;\n var entryList = new ArrayList<>(data.int2ObjectEntrySet());\n int size = entryList.size();\n posData = new int[size];\n weatherData = new int[size];\n int i = 0;\n for (Int2ObjectMap.Entry<WeatherData.Concrete> entry : entryList) {\n posData[i] = entry.getIntKey();\n weatherData[i] = entry.getValue().data();\n i++;\n }\n return new UpdateWeatherChunk(LevelIdMap.CURRENT.id(chunk.getLevel().dimension()), chunk.getPos(), posData, weatherData, precipitation, temperature, windX, windZ, thunder);\n }\n\n public WeatherData query(BlockPos pos) {\n int x = (pos.getX() - chunk.getPos().getMinBlockX()) & 0xFF;\n int y = (pos.getY() - chunk.getMinBuildHeight()) & 0xFFFF;\n int z = (pos.getZ() - chunk.getPos().getMinBlockZ()) & 0xFF;\n int key = (y << 16) | (x << 8) | z;\n var found = data.getOrDefault(key, null);\n if (found == null) {\n return new WeatherData.Reference(this, key);\n }\n return found;\n }\n\n void decode(int key, BlockPos.MutableBlockPos pos) {\n int x = (key >> 8) & 0xFF;\n int y = (key >> 16) & 0xFFFF;\n int z = key & 0xFF;\n pos.set(chunk.getPos().getMinBlockX() + x, chunk.getMinBuildHeight() + y, chunk.getPos().getMinBlockZ() + z);\n }\n\n public @NotNull CompoundTag save(CompoundTag tag) {\n List<Integer> keys = new ArrayList<>();\n ListTag values = new ListTag();\n data.forEach((k, v) -> {\n if (!v.boring()) {\n keys.add(k);\n values.add(v.save());\n }\n });\n tag.putIntArray(\"positions\", keys);\n tag.put(\"data\", values);\n CompoundTag stats = new CompoundTag();\n for (int i = 0; i < 4; i++) {\n stats.putFloat(\"precipitation\" + i, precipitation[i]);\n stats.putFloat(\"temperature\" + i, temperature[i]);\n stats.putFloat(\"windX\" + i, windX[i]);\n stats.putFloat(\"windZ\" + i, windZ[i]);\n stats.putFloat(\"thunder\" + i, thunder[i]);\n }\n tag.put(\"stats\", stats);\n return tag;\n }\n\n public void load(CompoundTag tag) {\n int[] keys = tag.getIntArray(\"positions\");\n ListTag values = tag.getList(\"data\", 10);\n if (keys.length != values.size()) {\n throw new IllegalStateException(\"Positions and data are not the same size\");\n }\n for (int i = 0; i < keys.length; i++) {\n var weatherData = new WeatherData.Concrete(this, keys[i]);\n weatherData.load(values.getCompound(i));\n data.put(keys[i], weatherData);\n }\n if (tag.contains(\"stats\", Tag.TAG_COMPOUND)) {\n CompoundTag stats = tag.getCompound(\"stats\");\n for (int i = 0; i < 4; i++) {\n precipitation[i] = stats.getFloat(\"precipitation\" + i);\n temperature[i] = stats.getFloat(\"temperature\" + i);\n windX[i] = stats.getFloat(\"windX\" + i);\n windZ[i] = stats.getFloat(\"windZ\" + i);\n thunder[i] = stats.getFloat(\"thunder\" + i);\n }\n }\n }\n\n public float temperature(BlockPos pos) {\n return relative(pos, temperature);\n }\n\n public float precipitation(BlockPos pos) {\n return relative(pos, precipitation);\n }\n\n public float windX(BlockPos pos) {\n return relative(pos, windX);\n }\n\n public float windZ(BlockPos pos) {\n return relative(pos, windZ);\n }\n\n public float thunder(BlockPos pos) {\n return relative(pos, thunder);\n }\n\n private static float relative(BlockPos pos, float[] corners) {\n float x = (pos.getX() & 0xF) / 15f;\n float z = (pos.getZ() & 0xF) / 15f;\n float x1 = 1 - x;\n float z1 = 1 - z;\n return corners[0] * x1 * z1 + corners[1] * x1 * z + corners[2] * x * z1 + corners[3] * x * z;\n }\n\n public void tick(ServerLevel level, WeatherMapData.Built weatherMap) {\n int x = chunk.getPos().getMinBlockX();\n int z = chunk.getPos().getMinBlockZ();\n\n if (!initialized || level.random.nextInt(8) == 0) {\n initialized = true;\n long gameTime = chunk.getLevel().getGameTime();\n BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos();\n for (int i = 0; i < 4; i++) {\n mutablePos.setX(x+XS[i]);\n mutablePos.setZ(z+ZS[i]);\n var surface = level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, mutablePos);\n var biome = chunk.getLevel().getBiome(surface).value();\n\n float temp = weatherMap.temperature().query(x+XS[i], z+ZS[i], gameTime);\n\n if (!biome.warmEnoughToRain(surface)) {\n temp -= 0.95f;\n } else if (biome.getBaseTemperature() > 1.5f) {\n temp += 0.7f;\n }\n\n temperature[i] = Mth.clamp(temp, -1, 1);\n\n float precip = weatherMap.precipitation().query(x+XS[i], z+ZS[i], gameTime);\n\n if (!biome.hasPrecipitation()) {\n precipitation[i] -= 0.6f;\n }\n\n precipitation[i] = Mth.clamp(precip, -1, 1);\n\n windX[i] = weatherMap.windX().query(x+XS[i], z+ZS[i], gameTime);\n windZ[i] = weatherMap.windZ().query(x+XS[i], z+ZS[i], gameTime);\n thunder[i] = Mth.clamp(weatherMap.thunder().query(x+XS[i], z+ZS[i], gameTime), -1, 1);\n }\n recalculateWindCheckPositions(level);\n this.markDirty();\n }\n\n BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();\n for (int key : new IntArrayList(data.keySet())) {\n var val = this.data.get(key);\n if (val != null) {\n decode(key, pos);\n BlockState state = level.getBlockState(pos);\n if (val.frozenUp() && !state.is(Constants.FREEZES_UP)) {\n val.frozenUp(false);\n }\n //noinspection deprecation\n if (!state.blocksMotion()) {\n if (!val.frozenUp() || !state.is(Constants.FREEZES_UP)) {\n data.remove(key);\n update(key, 0);\n }\n }\n if (meltsAt(level, pos)) {\n int blackIce = val.blackIce();\n blackIce = Math.max(0, blackIce - 2);\n val.levelBlackIce(level, pos, blackIce);\n }\n boolean belowSturdyUp = state.isFaceSturdy(level, pos, Direction.UP);\n pos.setY(pos.getY() + 1);\n state = level.getBlockState(pos);\n boolean aboveSturdyDown = state.isFaceSturdy(level, pos, Direction.DOWN);\n if (belowSturdyUp && aboveSturdyDown) {\n data.remove(key);\n update(key, 0);\n }\n }\n }\n\n if (meltAndFreeze(level)) {\n boolean tryAgain = meltAndFreeze(level);\n if (tryAgain && level.random.nextBoolean()) {\n meltAndFreeze(level);\n }\n }\n\n this.update();\n }\n\n private void recalculateWindCheckPositions(Level level) {\n var centerPos = chunk.getPos().getBlockAt(8, 0, 8);\n float windX = windX(level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, centerPos));\n float windZ = windZ(level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, centerPos));\n float speed = Mth.sqrt(windX * windX + windZ * windZ);\n float angle = Mth.clamp(speed, 0, 1.25F)/ 1.25F;\n float singleX = -(float) Math.cos(angle) * windX / speed;\n float singleY = (float) Math.sin(angle);\n float singleZ = -(float) Math.cos(angle) * windZ / speed;\n windCheckPositions.clear();\n float xOff = 0;\n float yOff = 0;\n float zOff = 0;\n for (int i = 0; i < 12; i++) {\n xOff += singleX;\n yOff += singleY;\n zOff += singleZ;\n windCheckPositions.add(new BlockPos(Math.round(xOff), Math.round(yOff), Math.round(zOff)));\n }\n }\n\n private boolean meltAndFreeze(ServerLevel level) {\n BlockPos waterySurface = level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, QuasiRandomChunkVisitor.INSTANCE.inChunk(chunk, visitIndex, i -> this.visitIndex = i)).below();\n float temp = temperature(waterySurface);\n float precip = precipitation(waterySurface);\n float thunder = thunder(waterySurface);\n\n boolean repeat = false;\n\n if (isHailing(temp, precip, thunder)) {\n if (level.random.nextFloat() < 0.4 * precip) {\n BlockPos hailSurface = level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, waterySurface).below();\n if (canSeeWind(hailSurface)) {\n if (tryHailBreak(level, hailSurface.above())) {\n tryHailBreak(level, hailSurface);\n }\n }\n }\n repeat = level.random.nextFloat() < precip;\n }\n\n if (temp < 0f) {\n BlockPos.MutableBlockPos above = new BlockPos.MutableBlockPos();\n above.set(waterySurface);\n above.setY(above.getY() + 1);\n if (!canSeeWindSnow(above)) {\n above.setY(above.getY() + 1);\n if (level.random.nextBoolean() || !canSeeWindSnow(above)) {\n above.setY(above.getY() + 1);\n if (level.random.nextBoolean() || !canSeeWindSnow(above)) {\n return false;\n }\n }\n }\n // add new black ice or ice\n boolean frozen = tryFreezeBlock(level, waterySurface);\n repeat = frozen || (repeat && level.random.nextBoolean());\n }\n\n if (temp > 0) {\n // melt black ice or ice\n tryMeltBlock(level, waterySurface);\n boolean melted = level.random.nextFloat() < temp;\n repeat = repeat || (melted && level.random.nextBoolean());\n }\n\n return repeat;\n }\n\n private boolean tryFreezeBlock(ServerLevel level, BlockPos toFreeze) {\n float precip = this.precipitation(toFreeze);\n float temp = this.temperature(toFreeze);\n float thunder = this.thunder(toFreeze);\n if (validBlock(level, toFreeze)) {\n if (shouldFreeze(level, toFreeze)) {\n var freezeState = level.getBlockState(toFreeze);\n if (freezeState.getBlock() instanceof LiquidBlock) {\n if (isFreezableWater(level, toFreeze)) {\n level.setBlockAndUpdate(toFreeze, Blocks.ICE.defaultBlockState());\n var data = this.query(toFreeze);\n int current = data.blackIce();\n if (current < 15) {\n data.levelBlackIce(level, toFreeze, current + 3);\n }\n }\n return level.random.nextFloat() < -temp;\n } else {\n if (isSleeting(temp, precip, thunder)) {\n var data = this.query(toFreeze);\n int current = data.blackIce();\n if (current < 15) {\n data.levelBlackIce(level, toFreeze, current + 2);\n var abovePos = toFreeze.above();\n BlockState aboveState;\n while ((aboveState = level.getBlockState(abovePos)).is(Constants.FREEZES_UP)) {\n if (aboveState.is(Constants.FREEZES_UP)) {\n var aboveData = query(abovePos);\n int aboveCurrent = aboveData.blackIce();\n if (aboveCurrent < 15) {\n aboveData.levelBlackIce(level, abovePos, aboveCurrent + 2);\n }\n }\n abovePos = abovePos.above();\n }\n }\n return level.random.nextFloat() < precip;\n } else if (isSnowing(temp, precip, thunder)) {\n BlockPos toSnow = toFreeze.above();\n processSnow(level, toSnow);\n return level.random.nextFloat() < precip;\n }\n }\n }\n }\n return level.random.nextFloat() < (level.random.nextBoolean() ? -temp : precip);\n }\n\n @SuppressWarnings(\"StatementWithEmptyBody\")\n private static void processSnow(ServerLevel level, BlockPos toSnow) {\n var state = level.getBlockState(toSnow);\n if (state.getBlock() == Blocks.SNOW) {\n int levels = state.getValue(SnowLayerBlock.LAYERS);\n BlockState newState;\n if (levels < 7) {\n newState = state.setValue(SnowLayerBlock.LAYERS, levels + 1);\n } else {\n if (level.random.nextFloat() < 0.75f) {\n newState = Blocks.SNOW_BLOCK.defaultBlockState();\n } else {\n newState = Blocks.POWDER_SNOW.defaultBlockState();\n }\n }\n level.setBlockAndUpdate(toSnow, newState);\n Block.pushEntitiesUp(state, newState, level, toSnow);\n } else if (hasSpaceForSnow(level, toSnow) && Services.snow(level, toSnow, state)) {\n\n } else if (hasSpaceForSnow(level, toSnow) && Blocks.SNOW.defaultBlockState().canSurvive(level, toSnow) && state.canBeReplaced()) {\n level.setBlockAndUpdate(toSnow, Blocks.SNOW.defaultBlockState());\n } else if (state.getBlock() == Blocks.POWDER_SNOW) {\n BlockPos aboveSnow = toSnow.above();\n level.setBlockAndUpdate(toSnow, Blocks.SNOW_BLOCK.defaultBlockState());\n processSnow(level, aboveSnow);\n }\n }\n\n public boolean canSeeWindSnow(BlockPos pos) {\n var mutablePos = new BlockPos.MutableBlockPos();\n for (BlockPos check : windCheckPositions) {\n mutablePos.setWithOffset(pos, check);\n if (chunk.getLevel().isLoaded(mutablePos)) {\n BlockState blockState = chunk.getLevel().getBlockState(mutablePos);\n if (isMotionBlocking(blockState) && !(blockState.getBlock() instanceof LeavesBlock) && !(blockState.is(Constants.SNOW_PASSTHROUGH))) {\n return false;\n }\n }\n }\n return true;\n }\n\n public boolean canSeeWind(BlockPos pos) {\n var mutablePos = new BlockPos.MutableBlockPos();\n for (BlockPos check : windCheckPositions) {\n mutablePos.setWithOffset(pos, check);\n if (chunk.getLevel().isLoaded(mutablePos)) {\n BlockState blockState = chunk.getLevel().getBlockState(mutablePos);\n if (isMotionBlocking(blockState)) {\n return false;\n }\n }\n }\n return true;\n }\n\n @SuppressWarnings(\"deprecation\")\n private static boolean isMotionBlocking(BlockState blockState) {\n return (blockState.blocksMotion() || !blockState.getFluidState().isEmpty()) && !(blockState.getBlock() == Blocks.SNOW);\n }\n\n private static boolean hasSpaceForSnow(ServerLevel level, BlockPos pos) {\n for (int i = 0; i < 4; i++) {\n pos = pos.below();\n if (!validBlock(level, pos)) {\n return true;\n }\n var block = level.getBlockState(pos).getBlock();\n if (block != Blocks.SNOW_BLOCK && block != Blocks.POWDER_SNOW) {\n return true;\n }\n }\n return false;\n }\n\n private static boolean tryHailBreak(ServerLevel level, BlockPos toFreeze) {\n var hailEffectState = level.getBlockState(toFreeze);\n if (hailEffectState.is(Constants.BREAKS_WITH_HAIL) && !hailEffectState.is(Constants.SAFE_WITH_HAIL)) {\n level.destroyBlock(toFreeze, true);\n return false;\n }\n return true;\n }\n\n private static boolean isHailing(float temp, float precip, float thunder) {\n return temp < 0.5f && ((precip > 0.75f && temp > -0.5f) || thunder > 0.9f);\n }\n\n private static boolean isSnowing(float temp, float precip, float thunder) {\n return precip > 0f && !isHailing(temp, precip, thunder) && ((temp < -0.6) || (temp < -0.1 && precip > 0.7f));\n }\n\n private static boolean isSleeting(float temp, float precip, float thunder) {\n return precip > 0f && temp < 0 && !isSnowing(temp, precip, thunder) && !isHailing(temp, precip, thunder);\n }\n\n private static boolean isRaining(float temp, float precip, float thunder) {\n return precip > 0f && !isSleeting(temp, precip, thunder) && !isSnowing(temp, precip, thunder) && !isHailing(temp, precip, thunder);\n }\n\n public interface WeatherStatusAssembler {\n WeatherStatus assemble(WeatherStatus.Kind kind, float intensity, float temperature, boolean thunder, Vec2 wind);\n }\n\n public WeatherStatus makeApiStatus(WeatherStatusAssembler assembler, BlockPos pos) {\n float temp = temperature(pos);\n float precip = precipitation(pos);\n float thunder = thunder(pos);\n float windX = windX(pos);\n float windZ = windZ(pos);\n\n WeatherStatus.Kind kind;\n if (isSnowing(temp, precip, thunder)) {\n kind = WeatherStatus.Kind.SNOW;\n } else if (isSleeting(temp, precip, thunder)) {\n kind = WeatherStatus.Kind.SLEET;\n } else if (isHailing(temp, precip, thunder)) {\n kind = WeatherStatus.Kind.HAIL;\n } else if (isRaining(temp, precip, thunder)) {\n kind = WeatherStatus.Kind.RAIN;\n } else {\n kind = WeatherStatus.Kind.CLEAR;\n }\n\n return assembler.assemble(kind, Mth.sqrt(Mth.clamp(precip, 0, 1)), temp, thunder > 0f, new Vec2(windX, windZ));\n }\n\n @SuppressWarnings(\"StatementWithEmptyBody\")\n private void tryMeltBlock(ServerLevel level, BlockPos toMelt) {\n if (validBlock(level, toMelt)) {\n var state = level.getBlockState(toMelt);\n if (state.getBlock() == Blocks.ICE) {\n level.setBlockAndUpdate(toMelt, Blocks.WATER.defaultBlockState());\n var data = query(toMelt);\n int current = data.blackIce();\n if (current > 0) {\n data.levelBlackIce(level, toMelt, 0);\n }\n } else {\n var data = query(toMelt);\n int current = data.blackIce();\n if (current > 0) {\n data.levelBlackIce(level, toMelt, Math.max(0, current - 2));\n var abovePos = toMelt.above();\n BlockState aboveState;\n while ((aboveState = level.getBlockState(abovePos)).is(Constants.FREEZES_UP)) {\n if (aboveState.is(Constants.FREEZES_UP)) {\n var aboveData = query(abovePos);\n int aboveCurrent = aboveData.blackIce();\n if (aboveCurrent > 0) {\n aboveData.levelBlackIce(level, abovePos, Math.max(0, aboveCurrent - 2));\n }\n }\n abovePos = abovePos.above();\n }\n }\n }\n\n var above = toMelt.above();\n var stateAbove = level.getBlockState(above);\n if (stateAbove.getBlock() == Blocks.SNOW) {\n int levels = stateAbove.getValue(SnowLayerBlock.LAYERS);\n if (levels > 1) {\n var newState = stateAbove.setValue(SnowLayerBlock.LAYERS, levels - 1);\n level.setBlockAndUpdate(above, newState);\n } else {\n level.setBlockAndUpdate(above, Blocks.AIR.defaultBlockState());\n }\n } else if (stateAbove.getBlock() == Blocks.POWDER_SNOW) {\n level.setBlockAndUpdate(above, Blocks.SNOW.defaultBlockState().setValue(SnowLayerBlock.LAYERS, 7));\n } else if (Services.melt(level, above, stateAbove)) {\n\n } else if (state.getBlock() == Blocks.SNOW_BLOCK || state.getBlock() == Blocks.POWDER_SNOW) {\n level.setBlockAndUpdate(toMelt, Blocks.SNOW.defaultBlockState().setValue(SnowLayerBlock.LAYERS, 7));\n } else if (Services.melt(level, toMelt, state)) {\n\n }\n }\n }\n\n private boolean meltsAt(ServerLevel level, BlockPos pos) {\n BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos();\n mutable.set(pos);\n for (int i = -1; i <= 1; i++) {\n mutable.setX(pos.getX() + i);\n if (level.getBrightness(LightLayer.BLOCK, mutable) > 11) return true;\n }\n mutable.setX(pos.getX());\n for (int i = -1; i <= 1; i++) {\n mutable.setY(pos.getY() + i);\n if (level.getBrightness(LightLayer.BLOCK, mutable) > 11) return true;\n }\n mutable.setY(pos.getY());\n for (int i = -1; i <= 1; i++) {\n mutable.setZ(pos.getZ() + i);\n if (level.getBrightness(LightLayer.BLOCK, mutable) > 11) return true;\n }\n return level.getBrightness(LightLayer.BLOCK, pos) > 11;\n }\n\n private boolean shouldFreeze(ServerLevel level, BlockPos toFreeze) {\n return level.getBrightness(LightLayer.BLOCK, toFreeze) < 10;\n }\n\n private static boolean validBlock(ServerLevel level, BlockPos toFreeze) {\n return toFreeze.getY() >= level.getMinBuildHeight() && toFreeze.getY() < level.getMaxBuildHeight();\n }\n\n private boolean isFreezableWater(ServerLevel level, BlockPos toFreeze) {\n BlockState blockstate = level.getBlockState(toFreeze);\n FluidState fluidstate = level.getFluidState(toFreeze);\n if (fluidstate.getType() == Fluids.WATER && blockstate.getBlock() instanceof LiquidBlock) {\n if (!level.isLoaded(toFreeze.west()) || !level.isLoaded(toFreeze.east()) || !level.isLoaded(toFreeze.north()) || !level.isLoaded(toFreeze.south())) {\n return false;\n }\n\n boolean flag = level.isWaterAt(toFreeze.west()) && level.isWaterAt(toFreeze.east()) && level.isWaterAt(toFreeze.north()) && level.isWaterAt(toFreeze.south());\n return !flag;\n }\n return false;\n }\n\n void update(UpdateWeatherChunk updateWeatherChunk, Consumer<BlockPos> posUpdater) {\n boolean recalcChecks = this.windX != updateWeatherChunk.windX || this.windZ != updateWeatherChunk.windZ;\n\n this.temperature = updateWeatherChunk.temperature;\n this.precipitation = updateWeatherChunk.precipitation;\n this.windX = updateWeatherChunk.windX;\n this.windZ = updateWeatherChunk.windZ;\n this.thunder = updateWeatherChunk.thunder;\n\n if (recalcChecks) {\n recalculateWindCheckPositions(chunk.getLevel());\n }\n\n BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();\n for (int i = 0; i < updateWeatherChunk.posData.length; i++) {\n int key = updateWeatherChunk.posData[i];\n int value = updateWeatherChunk.weatherData[i];\n decode(key, pos);\n query(pos).data(value);\n posUpdater.accept(pos);\n }\n }\n\n public @Nullable WeatherCategory.WeatherStatus getWeatherStatusWindAware(BlockPos pos) {\n var status = getWeatherStatus(pos);\n if (canSeeWind(pos)) {\n return status;\n }\n return null;\n }\n\n public @Nullable WeatherCategory.WeatherStatus getWeatherStatus(BlockPos pos) {\n float precip = precipitation(pos);\n if (precipitation(pos) > 0f) {\n WeatherCategory category;\n float temp = temperature(pos);\n float thunder = this.thunder(pos);\n if (isSnowing(temp, precip, thunder)) {\n category = WeatherCategory.SNOW;\n } else if (isSleeting(temp, precip, thunder)) {\n category = WeatherCategory.SLEET;\n } else if (isHailing(temp, precip, thunder)) {\n category = WeatherCategory.HAIL;\n } else {\n category = WeatherCategory.RAIN;\n }\n return new WeatherCategory.WeatherStatus(category, precipitation(pos), windX(pos), windZ(pos), thunder(pos));\n }\n return null;\n }\n}" }, { "identifier": "WeatherData", "path": "common/src/main/java/dev/lukebemish/tempest/impl/data/world/WeatherData.java", "snippet": "public sealed interface WeatherData {\n void blackIce(int blackIce);\n\n default void levelBlackIce(ServerLevel level, BlockPos pos, int blackIce) {\n blackIce(blackIce);\n var state = level.getBlockState(pos);\n frozenUp(blackIce > 4 && state.is(Constants.FREEZES_UP));\n }\n\n int blackIce();\n\n void data(int value);\n\n void frozenUp(boolean stuck);\n boolean frozenUp();\n\n final class Empty implements WeatherData {\n public static final Empty INSTANCE = new Empty();\n\n private Empty() {}\n\n\n @Override\n public void blackIce(int blackIce) {}\n\n @Override\n public int blackIce() {\n return 0;\n }\n\n @Override\n public void data(int value) {}\n\n @Override\n public void frozenUp(boolean stuck) {}\n\n @Override\n public boolean frozenUp() {\n return false;\n }\n }\n\n final class Reference implements WeatherData {\n private final WeatherChunkData intrusive;\n private final int pos;\n @Nullable\n private Concrete concrete;\n private final IntFunction<Concrete> factory;\n\n Reference(WeatherChunkData intrusive, int pos) {\n this.intrusive = intrusive;\n this.pos = pos;\n this.factory = key -> new WeatherData.Concrete(intrusive, key);\n }\n\n @Override\n public void blackIce(int blackIce) {\n if (this.concrete == null) {\n this.concrete = intrusive.data.computeIfAbsent(pos, factory);\n }\n concrete.blackIce(blackIce);\n }\n\n @Override\n public int blackIce() {\n if (this.concrete != null) {\n return this.concrete.blackIce();\n }\n var concrete = intrusive.data.getOrDefault(pos, null);\n if (concrete == null) {\n return 0;\n } else {\n this.concrete = concrete;\n return concrete.blackIce();\n }\n }\n\n @Override\n public void data(int value) {\n if (this.concrete == null) {\n this.concrete = intrusive.data.computeIfAbsent(pos, factory);\n }\n concrete.data(value);\n }\n\n @Override\n public void frozenUp(boolean frozenUp) {\n if (this.concrete == null) {\n this.concrete = intrusive.data.computeIfAbsent(pos, factory);\n }\n concrete.frozenUp(frozenUp);\n }\n\n @Override\n public boolean frozenUp() {\n if (this.concrete != null) {\n return this.concrete.frozenUp();\n }\n var concrete = intrusive.data.getOrDefault(pos, null);\n if (concrete == null) {\n return false;\n } else {\n this.concrete = concrete;\n return concrete.frozenUp();\n }\n }\n }\n\n final class Concrete implements WeatherData {\n private final WeatherChunkData intrusive;\n\n // 0b0XXXX: black ice\n // 0bX0000: frozen up\n private int data;\n\n private final int pos;\n\n Concrete(WeatherChunkData intrusive, int pos) {\n this.intrusive = intrusive;\n this.pos = pos;\n }\n\n public CompoundTag save() {\n var tag = new CompoundTag();\n tag.putInt(\"data\", data);\n return tag;\n }\n\n public void load(CompoundTag tag) {\n data = tag.getInt(\"data\");\n }\n\n private void update() {\n if (boring()) {\n intrusive.data.remove(pos);\n intrusive.update(pos, 0);\n } else {\n intrusive.update(pos, data);\n }\n }\n\n @Override\n public void blackIce(int blackIce) {\n this.data = (data & (~0xF)) | (blackIce & 0xF);\n update();\n }\n\n @Override\n public int blackIce() {\n return data & 0xF;\n }\n\n @Override\n public void data(int value) {\n this.data = value;\n update();\n }\n\n @Override\n public void frozenUp(boolean stuck) {\n if (stuck) {\n data |= 0b10000;\n } else {\n data &= ~0b10000;\n }\n update();\n }\n\n @Override\n public boolean frozenUp() {\n return (data & 0b10000) != 0;\n }\n\n int data() {\n return data;\n }\n\n public boolean boring() {\n return data == 0;\n }\n }\n}" } ]
import com.google.auto.service.AutoService; import dev.lukebemish.tempest.impl.FastChunkLookup; import dev.lukebemish.tempest.impl.Services; import dev.lukebemish.tempest.impl.data.WeatherMapData; import dev.lukebemish.tempest.impl.data.world.WeatherChunkData; import dev.lukebemish.tempest.impl.data.world.WeatherData; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; import net.minecraft.core.SectionPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.chunk.EmptyLevelChunk; import net.minecraft.world.level.chunk.LevelChunk; import java.util.List; import java.util.function.Supplier;
9,569
package dev.lukebemish.tempest.impl.fabriquilt; @AutoService(Services.Platform.class) public final class ModPlatform implements Services.Platform { @Override public WeatherChunkData getChunkData(LevelChunk chunk) { var existing = ((FastChunkLookup) chunk).tempest$getChunkData(); if (existing != null) { return existing; } else if (chunk instanceof EmptyLevelChunk emptyChunk) { return new EmptyData(emptyChunk); } else { var data = ComponentRegistration.WEATHER_CHUNK_DATA.get(chunk).data; ((FastChunkLookup) chunk).tempest$setChunkData(data); return data; } } @Override public <S, T extends S> Supplier<T> register(Supplier<T> supplier, ResourceLocation location, Registry<S> registry) { var entry = Registry.register(registry, location, supplier.get()); return () -> entry; } @Override public boolean modLoaded(String modId) { return FabricLoader.getInstance().isModLoaded(modId); } private static final class EmptyData extends WeatherChunkData { public EmptyData(EmptyLevelChunk chunk) { super(chunk); } @Override protected void update(int pos, int data) {} @Override public void update() {} @Override public List<BlockPos> icedInSection(SectionPos pos) { return List.of(); } @Override
package dev.lukebemish.tempest.impl.fabriquilt; @AutoService(Services.Platform.class) public final class ModPlatform implements Services.Platform { @Override public WeatherChunkData getChunkData(LevelChunk chunk) { var existing = ((FastChunkLookup) chunk).tempest$getChunkData(); if (existing != null) { return existing; } else if (chunk instanceof EmptyLevelChunk emptyChunk) { return new EmptyData(emptyChunk); } else { var data = ComponentRegistration.WEATHER_CHUNK_DATA.get(chunk).data; ((FastChunkLookup) chunk).tempest$setChunkData(data); return data; } } @Override public <S, T extends S> Supplier<T> register(Supplier<T> supplier, ResourceLocation location, Registry<S> registry) { var entry = Registry.register(registry, location, supplier.get()); return () -> entry; } @Override public boolean modLoaded(String modId) { return FabricLoader.getInstance().isModLoaded(modId); } private static final class EmptyData extends WeatherChunkData { public EmptyData(EmptyLevelChunk chunk) { super(chunk); } @Override protected void update(int pos, int data) {} @Override public void update() {} @Override public List<BlockPos> icedInSection(SectionPos pos) { return List.of(); } @Override
public WeatherData query(BlockPos pos) {
3
2023-12-06 23:23:31+00:00
12k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/service/impl/SysAreaInfoServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @Schema(description = \"当前页\")\n private long current;\n\n /**\n * 每页显示条数\n */\n @Schema(description = \"每页显示条数\")\n private long size;\n\n /**\n * 总页数\n */\n @Schema(description = \"总页数\")\n private long pages;\n\n /**\n * 总条目数\n */\n @Schema(description = \"总条目数\")\n private long total;\n\n /**\n * 结果集\n */\n @Schema(description = \"结果集\")\n private List<T> list;\n\n}" }, { "identifier": "CommonConstants", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/constant/CommonConstants.java", "snippet": "public interface CommonConstants {\n\n /**\n * 树节点默认值\n */\n String TREE_DEFAULT = \"-1\";\n\n String ERROR_MESSAGE = \"error_message\";\n}" }, { "identifier": "StringUtils", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/support/StringUtils.java", "snippet": "public final class StringUtils extends org.springframework.util.StringUtils {\n\n /**\n * 当字符串空的时候,返回默认值,不为空返回当前值\n */\n public static String emptyDefault(String value) {\n return emptyDefault(value, \"\");\n }\n\n /**\n * 当字符串空的时候,返回默认值\n */\n public static String emptyDefault(String value, String defaultValue) {\n if (hasText(value)) {\n return value;\n }\n return defaultValue;\n }\n\n /**\n * 比较两个字符串(大小写敏感)。\n *\n * <pre>\n * equals(null, null) = true\n * equals(null, &quot;abc&quot;) = false\n * equals(&quot;abc&quot;, null) = false\n * equals(&quot;abc&quot;, &quot;abc&quot;) = true\n * equals(&quot;abc&quot;, &quot;ABC&quot;) = false\n * </pre>\n *\n * @param str1 要比较的字符串1\n * @param str2 要比较的字符串2\n * @return 如果两个字符串相同,或者都是{@code null},则返回{@code true}\n */\n public static boolean equals(CharSequence str1, CharSequence str2) {\n return equals(str1, str2, false);\n }\n\n /**\n * 比较两个字符串(大小写不敏感)。\n *\n * <pre>\n * equalsIgnoreCase(null, null) = true\n * equalsIgnoreCase(null, &quot;abc&quot;) = false\n * equalsIgnoreCase(&quot;abc&quot;, null) = false\n * equalsIgnoreCase(&quot;abc&quot;, &quot;abc&quot;) = true\n * equalsIgnoreCase(&quot;abc&quot;, &quot;ABC&quot;) = true\n * </pre>\n *\n * @param str1 要比较的字符串1\n * @param str2 要比较的字符串2\n * @return 如果两个字符串相同,或者都是{@code null},则返回{@code true}\n */\n public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) {\n return equals(str1, str2, true);\n }\n\n /**\n * 比较两个字符串是否相等,规则如下\n * <ul>\n * <li>str1和str2都为{@code null}</li>\n * <li>忽略大小写使用{@link String#equalsIgnoreCase(String)}判断相等</li>\n * <li>不忽略大小写使用{@link String#contentEquals(CharSequence)}判断相等</li>\n * </ul>\n *\n * @param str1 要比较的字符串1\n * @param str2 要比较的字符串2\n * @param ignoreCase 是否忽略大小写\n * @return 如果两个字符串相同,或者都是{@code null},则返回{@code true}\n * @since 3.2.0\n */\n public static boolean equals(CharSequence str1, CharSequence str2, boolean ignoreCase) {\n if (null == str1) {\n // 只有两个都为null才判断相等\n return str2 == null;\n }\n if (null == str2) {\n // 字符串2空,字符串1非空,直接false\n return false;\n }\n\n if (ignoreCase) {\n return str1.toString().equalsIgnoreCase(str2.toString());\n } else {\n return str1.toString().contentEquals(str2);\n }\n }\n}" }, { "identifier": "INode", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/treenode/INode.java", "snippet": "public interface INode<T> extends Comparable<INode<T>>, Serializable {\n\n /**\n * 获取ID\n *\n * @return ID\n */\n T getId();\n\n /**\n * 设置ID\n *\n * @param id ID\n * @return this\n */\n INode<T> setId(T id);\n\n /**\n * 获取父节点ID\n *\n * @return 父节点ID\n */\n T getParentId();\n\n /**\n * 设置父节点ID\n *\n * @param parentId 父节点ID\n * @return this\n */\n INode<T> setParentId(T parentId);\n\n /**\n * 获取权重\n *\n * @return 权重\n */\n Integer getWeight();\n\n /**\n * 设置权重\n *\n * @param weight 权重\n * @return this\n */\n INode<T> setWeight(int weight);\n\n\n default int compareTo(INode<T> node) {\n if (null == node) {\n return 1;\n }\n return this.getWeight().compareTo(node.getWeight());\n }\n\n void addChildren(INode<T> node);\n\n List<INode<T>> getChildren();\n\n}" }, { "identifier": "TreeNode", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/treenode/TreeNode.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class TreeNode<T> extends LinkedHashMap<String, Object> implements INode<T> {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n public TreeNode() {\n }\n\n\n public TreeNode(T id, T parentId, int weight) {\n this.setId(id).setParentId(parentId).setWeight(weight);\n }\n\n public TreeNode(T id, T parentId) {\n this.setId(id).setParentId(parentId);\n }\n\n /**\n * 权重\n */\n @JsonIgnore\n private int weight;\n\n\n /**\n * 获取ID\n *\n * @return ID\n */\n @Override\n public T getId() {\n return (T) this.get(\"id\");\n }\n\n /**\n * 设置ID\n *\n * @param id ID\n * @return this\n */\n @Override\n public INode<T> setId(T id) {\n this.put(\"id\", id);\n return this;\n }\n\n /**\n * 获取父节点ID\n *\n * @return 父节点ID\n */\n @Override\n public T getParentId() {\n return (T) this.get(\"parentId\");\n }\n\n /**\n * 设置父节点ID\n *\n * @param parentId 父节点ID\n * @return this\n */\n @Override\n public INode<T> setParentId(T parentId) {\n this.put(\"parentId\", parentId);\n return this;\n }\n\n /**\n * 获取权重\n *\n * @return 权重\n */\n @Override\n public Integer getWeight() {\n return this.weight;\n }\n\n /**\n * 设置权重\n *\n * @param weight 权重\n * @return this\n */\n @Override\n public INode<T> setWeight(int weight) {\n this.weight = weight;\n return this;\n }\n\n /**\n * @param node {@link INode}\n */\n @Override\n public void addChildren(INode<T> node) {\n List<INode<T>> children = this.getChildren();\n if (CollectionUtils.isEmpty(children)) {\n children = new ArrayList<>();\n }\n children.add(node);\n this.setChildren(children);\n }\n\n /**\n * 子节点\n */\n @Override\n public List<INode<T>> getChildren() {\n return (List<INode<T>>) this.get(\"children\");\n }\n\n /**\n * 设置子节点,设置后会覆盖所有原有子节点\n *\n * @param children 子节点列表\n */\n public void setChildren(List<INode<T>> children) {\n this.put(\"children\", children);\n }\n\n public TreeNode<T> setExtra(Map<String, Object> beanToMap) {\n Assert.notNull(beanToMap);\n this.putAll(beanToMap);\n return this;\n }\n}" }, { "identifier": "TreeUtils", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/treenode/TreeUtils.java", "snippet": "public final class TreeUtils {\n\n\n /**\n * 把树给拆解成list集合\n *\n * @param node {@link Tree<T>}\n * @param includeCurrentNode 否包含当前节点的名称\n * @return {@link List<TreeNode> }\n */\n public static <T> List<INode<T>> dismantle(INode<T> node, boolean includeCurrentNode) {\n List<INode<T>> result = new ArrayList<>();\n if (Objects.nonNull(node)) {\n if (includeCurrentNode) {\n result.add(node);\n }\n List<INode<T>> children = node.getChildren();\n if (!CollectionUtils.isEmpty(children)) {\n for (INode<T> child : children) {\n dismantle(child, true);\n }\n }\n }\n return result;\n }\n\n\n /**\n * 把树给拆解成list集合\n *\n * @param nodes {@link List<TreeNode>}\n * @return {@link List<TreeNode> }\n */\n public static <T> List<INode<T>> dismantle(List<INode<T>> nodes) {\n List<INode<T>> result = new ArrayList<>();\n if (!CollectionUtils.isEmpty(nodes)) {\n for (INode<T> node : nodes) {\n List<INode<T>> dismantle = dismantle(node, true);\n if (!CollectionUtils.isEmpty(dismantle)) {\n result.addAll(dismantle);\n }\n }\n }\n return result;\n }\n\n public static <T> List<INode<T>> buildList(List<INode<T>> result) {\n TreeBuilder<T> of = TreeBuilder.of();\n return of.appendList(result).buildList();\n }\n}" }, { "identifier": "Assert", "path": "xht-cloud-framework/xht-cloud-framework-exception/src/main/java/com/xht/cloud/framework/exception/Assert.java", "snippet": "public abstract class Assert {\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n */\n public static void hasText(String str) {\n hasText(str, \"[Assertion failed] Must not empty\");\n }\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n * @param errorCode 异常状态码\n */\n public static void hasText(String str, IErrorStatusCode errorCode) {\n if (!StringUtils.hasText(str)) {\n fail(errorCode);\n }\n }\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n * @param errMessage 异常描述\n */\n public static void hasText(String str, String errMessage) {\n if (!StringUtils.hasText(str)) {\n fail(errMessage);\n }\n }\n\n /**\n * 对象不为空抛出异常\n *\n * @param object 对象\n * @param errorCode 异常状态码\n */\n public static void notNull(Object object, IErrorStatusCode errorCode) {\n if (Objects.isNull(object)) {\n fail(errorCode);\n }\n }\n\n /**\n * 对象不为空抛出异常\n *\n * @param object 对象\n * @param errMessage 异常描述\n */\n public static void notNull(Object object, String errMessage) {\n if (Objects.isNull(object)) {\n fail(errMessage);\n }\n }\n\n /**\n * 对象不为空抛出异常\n *\n * @param object 对象\n */\n public static void notNull(Object object) {\n notNull(object, \"[Assertion failed] Must not null\");\n }\n\n\n /**\n * 集合为空排除异常\n *\n * @param collection 集合\n * @param errorCode 异常状态码\n */\n public static void notEmpty(Collection<?> collection, IErrorStatusCode errorCode) {\n if (Objects.isNull(collection) || collection.isEmpty()) {\n fail(errorCode);\n }\n }\n\n /**\n * 集合为空排除异常\n *\n * @param collection 集合\n * @param errMessage 异常信息\n */\n public static void notEmpty(Collection<?> collection, String errMessage) {\n if (Objects.isNull(collection) || collection.isEmpty()) {\n fail(errMessage);\n }\n }\n\n /**\n * 集合为空排除异常\n *\n * @param collection 集合\n */\n public static void notEmpty(Collection<?> collection) {\n notEmpty(collection, \"[Assertion failed] Collection must not be empty: it must contain at least 1 element\");\n }\n\n /**\n * map集合为空排除异常\n *\n * @param map map集合\n * @param errorCode 异常状态码\n */\n public static void notEmpty(Map<?, ?> map, IErrorStatusCode errorCode) {\n if (Objects.isNull(map) || map.isEmpty()) {\n fail(errorCode);\n }\n }\n\n /**\n * map集合为空排除异常\n *\n * @param map map集合\n * @param errMessage 异常信息\n */\n public static void notEmpty(Map<?, ?> map, String errMessage) {\n if (Objects.isNull(map) || map.isEmpty()) {\n fail(errMessage);\n }\n }\n\n /**\n * map集合为空排除异常\n *\n * @param map map集合\n */\n public static void notEmpty(Map<?, ?> map) {\n notEmpty(map, \"[Assertion failed] Map must not be empty: it must contain at least one entry\");\n }\n\n /**\n * 直接抛出异常\n *\n * @param s 异常描述信息\n */\n public static void fail(String s) {\n throw ExceptionFactory.bizException(s);\n }\n\n /**\n * 直接抛出异常\n *\n * @param errorStatusCode 异常状态码\n */\n public static void fail(IErrorStatusCode errorStatusCode) {\n throw ExceptionFactory.bizException(errorStatusCode);\n }\n\n\n /**\n * 断言是否为假,如果为 true 抛出{@link BizException}\n *\n * @param flag 布尔值\n * @param message 错误信息\n */\n public static void isFalse(boolean flag, String message) {\n isFalse(flag, () -> ExceptionFactory.bizException(message));\n }\n\n\n /**\n * 断言是否为假,如果为 {@code true} 抛出指定类型异常<br>\n * 并使用指定的函数获取错误信息返回\n * <pre class=\"code\">\n * Assert.isFalse(i &gt; 0, ()-&gt;{\n * // to query relation message\n * return new IllegalArgumentException(\"relation message to return\");\n * });\n * </pre>\n *\n * @param <X> 异常类型\n * @param expression 布尔值\n * @param errorSupplier 指定断言不通过时抛出的异常\n * @throws X if expression is {@code false}\n */\n public static <X extends Throwable> void isFalse(boolean expression, Supplier<X> errorSupplier) throws X {\n if (expression) {\n throw errorSupplier.get();\n }\n }\n}" }, { "identifier": "BizException", "path": "xht-cloud-framework/xht-cloud-framework-exception/src/main/java/com/xht/cloud/framework/exception/business/BizException.java", "snippet": "public class BizException extends GlobalException {\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * @param message 异常描述\n */\n public BizException(String message) {\n super(message);\n }\n public BizException(Throwable cause) {\n super(cause);\n }\n\n /**\n * @param code 异常状态码\n * @param message 异常描述\n */\n public BizException(Integer code, String message) {\n super(code, message);\n }\n\n /**\n * @param statusCode 业务异常状态码 {@link IErrorStatusCode}\n */\n public BizException(IErrorStatusCode statusCode) {\n super(statusCode.code(), statusCode.desc());\n }\n\n public BizException(Integer errorCode, String errMessage, Throwable e) {\n super(errorCode, errMessage, e);\n }\n}" }, { "identifier": "SysAreaInfoAddRequest", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/controller/request/SysAreaInfoAddRequest.java", "snippet": "@Data\n@Schema(name = \"SysAreaInfoRequest(地区信息-增加请求信息)\", description = \"地区信息-增加请求信息\")\npublic class SysAreaInfoAddRequest extends SysAreaInfoRequest {\n\n}" }, { "identifier": "SysAreaInfoQueryRequest", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/controller/request/SysAreaInfoQueryRequest.java", "snippet": "@Data\n@Schema(name = \"SysAreaInfoRequest(地区信息-查询请求信息)\", description = \"地区信息-查询请求信息\")\npublic class SysAreaInfoQueryRequest extends SysAreaInfoRequest {\n\n}" }, { "identifier": "SysAreaInfoUpdateRequest", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/controller/request/SysAreaInfoUpdateRequest.java", "snippet": "@Data\n@Schema(name = \"SysAreaInfoRequest(地区信息-修改请求信息)\", description = \"地区信息-修改请求信息\")\npublic class SysAreaInfoUpdateRequest extends SysAreaInfoRequest {\n\n /**\n * 主键\n */\n @Schema(description = \"主键\")\n @NotBlank(message = \"主键 `id` 校验不通过\", groups = {Create.class, Update.class})\n private String id;\n\n}" }, { "identifier": "SysAreaInfoResponse", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/controller/response/SysAreaInfoResponse.java", "snippet": "@Data\n@Schema(name = \"SysAreaInfoResponse(地区信息-响应信息)\", description = \"地区信息\")\npublic class SysAreaInfoResponse extends Response {\n\n /**\n * 主键\n */\n @Schema(description = \"主键\")\n private String id;\n\n /**\n * 父级区划代码\n */\n @Schema(description = \"父级区划代码\")\n private String parentId;\n\n /**\n * 名称\n */\n @Schema(description = \"名称\")\n private String name;\n\n /**\n * 级别1-5,省市县镇村1级:省、直辖市、自治区2级:地级市3级:市辖区、县(旗)、县级市、自治县(自治旗)、特区、林区4级:镇、乡、民族乡、县辖区、街道5级:村、居委会\n */\n @Getter\n @Schema(description = \"级别1-5,省市县镇村1级:省、直辖市、自治区2级:地级市3级:市辖区、县(旗)、县级市、自治县(自治旗)、特区、林区4级:镇、乡、民族乡、县辖区、街道5级:村、居委会\")\n private String level;\n\n /**\n * 区划代码\n */\n @Schema(description = \"区划代码\")\n private String areaNo;\n\n /**\n * 城乡分类111表示主城区;112表示城乡接合区;121表示镇中心区;122表示镇乡接合区;123表示特殊区域;210表示乡中心区;220表示村庄\n */\n @Schema(description = \"城乡分类111表示主城区;112表示城乡接合区;121表示镇中心区;122表示镇乡接合区;123表示特殊区域;210表示乡中心区;220表示村庄\")\n private String category;\n\n /**\n * 描述\n */\n @Schema(description = \"描述\")\n private String msg;\n\n /**\n * 此字段数据冗余字段\n */\n @Schema(description = \"数据冗余字段\")\n private boolean leaf;\n\n}" }, { "identifier": "SysAreaInfoConvert", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/convert/SysAreaInfoConvert.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface SysAreaInfoConvert {\n\n /**\n * {@link SysAreaInfoAddRequest} to {@link SysAreaInfoDO}\n */\n @Named(value = \"addRequestToDo\")\n SysAreaInfoDO toDO(SysAreaInfoAddRequest addRequest);\n\n /**\n * {@link SysAreaInfoUpdateRequest} to {@link SysAreaInfoDO}\n */\n @Named(value = \"updateRequestToDo\")\n SysAreaInfoDO toDO(SysAreaInfoUpdateRequest updateRequest);\n\n /**\n * {@link SysAreaInfoQueryRequest} to {@link SysAreaInfoDO}\n */\n @Named(value = \"queryRequestToDo\")\n SysAreaInfoDO toDO(SysAreaInfoQueryRequest queryRequest);\n\n /**\n * {@link SysAreaInfoDO} to {@link SysAreaInfoResponse}\n */\n @Named(value = \"DoToResponse\")\n @Mapping(target = \"leaf\", expression = \"java(com.xht.cloud.system.module.area.convert.AreaLeafConvert.convert(testDO.getLeaf()))\")\n SysAreaInfoResponse toResponse(SysAreaInfoDO testDO);\n\n\n /**\n * list转换 {@link SysAreaInfoDO} to {@link SysAreaInfoResponse}\n */\n @Named(value = \"DoToResponseCollection\")\n @IterableMapping(qualifiedByName = \"DoToResponse\")\n List<SysAreaInfoResponse> toResponse(List<SysAreaInfoDO> testDO);\n\n\n /**\n * 分页转换 {@link SysAreaInfoDO} to {@link SysAreaInfoResponse}\n */\n default PageResponse<SysAreaInfoResponse> toPageResponse(IPage<SysAreaInfoDO> iPage) {\n if (Objects.nonNull(iPage)) {\n PageResponse<SysAreaInfoResponse> pageResponse = PageTool.cloneEmpty(iPage);\n pageResponse.setList(toResponse(iPage.getRecords()));\n return pageResponse;\n }\n return PageTool.empty();\n }\n\n}" }, { "identifier": "SysAreaInfoDO", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/dao/dataobject/SysAreaInfoDO.java", "snippet": "@Data\n@TableName(value = \"sys_area_info\")\npublic class SysAreaInfoDO extends BaseDO {\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n private String id;\n\n /**\n * 父级区划代码\n */\n @TableField(value = \"parent_id\")\n private String parentId;\n\n /**\n * 名称\n */\n @TableField(value = \"name\")\n private String name;\n\n /**\n * 级别1-5,省市县镇村1级:省、直辖市、自治区2级:地级市3级:市辖区、县(旗)、县级市、自治县(自治旗)、特区、林区4级:镇、乡、民族乡、县辖区、街道5级:村、居委会\n */\n @TableField(value = \"level\")\n private String level;\n\n /**\n * 区划代码\n */\n @TableField(value = \"area_no\")\n private String areaNo;\n\n /**\n * 城乡分类111表示主城区;112表示城乡接合区;121表示镇中心区;122表示镇乡接合区;123表示特殊区域;210表示乡中心区;220表示村庄\n */\n @TableField(value = \"category\")\n private String category;\n\n /**\n * 描述\n */\n @TableField(value = \"msg\")\n private String msg;\n\n /**\n * 此字段数据冗余字段\n */\n @TableField(exist = false, value = \"leaf\")\n private String leaf;\n\n}" }, { "identifier": "SysAreaInfoMapper", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/dao/mapper/SysAreaInfoMapper.java", "snippet": "@Mapper\npublic interface SysAreaInfoMapper extends BaseMapperX<SysAreaInfoDO> {\n\n List<SysAreaInfoDO> selectListByRequest(SysAreaInfoQueryRequest queryRequest);\n}" }, { "identifier": "SysAreaInfoWrapper", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/dao/wrapper/SysAreaInfoWrapper.java", "snippet": "public final class SysAreaInfoWrapper implements EntityWrapper<SysAreaInfoDO> {\n\n /**\n * 私有化构造器\n */\n private SysAreaInfoWrapper() {\n }\n\n /**\n * 获取实例\n */\n public static SysAreaInfoWrapper getInstance() {\n return Instance.INSTANCE.getInstance();\n }\n\n /**\n * 实例处理化\n */\n private enum Instance {\n\n INSTANCE;\n\n private final SysAreaInfoWrapper wrapper;\n\n Instance() {\n wrapper = new SysAreaInfoWrapper();\n }\n\n public SysAreaInfoWrapper getInstance() {\n return wrapper;\n }\n }\n\n /**\n * 获取 {@link LambdaQueryWrapper}\n *\n * @param entity 实体类\n * @return {@link LambdaQueryWrapper}\n */\n @Override\n public LambdaQueryWrapper<SysAreaInfoDO> lambdaQuery(SysAreaInfoDO entity) {\n if (Objects.isNull(entity)) {\n return lambdaQuery();\n }\n LambdaQueryWrapper<SysAreaInfoDO> wrapper = new LambdaQueryWrapper<>();\n return wrapper\n .eq(StringUtils.hasText(entity.getId()), SysAreaInfoDO::getId, entity.getId())\n .eq(StringUtils.hasText(entity.getParentId()), SysAreaInfoDO::getParentId, entity.getParentId())\n .like(StringUtils.hasText(entity.getName()), SysAreaInfoDO::getName, entity.getName())\n .eq(StringUtils.hasText(entity.getLevel()), SysAreaInfoDO::getLevel, entity.getLevel())\n .like(StringUtils.hasText(entity.getAreaNo()), SysAreaInfoDO::getAreaNo, entity.getAreaNo())\n .eq(StringUtils.hasText(entity.getCategory()), SysAreaInfoDO::getCategory, entity.getCategory())\n .eq(StringUtils.hasText(entity.getMsg()), SysAreaInfoDO::getMsg, entity.getMsg())\n ;\n }\n\n /**\n * 获取 {@link LambdaUpdateWrapper}\n *\n * @param entity 实体类\n * @return {@link LambdaUpdateWrapper}\n */\n @Override\n public LambdaUpdateWrapper<SysAreaInfoDO> lambdaUpdate(SysAreaInfoDO entity) {\n if (Objects.isNull(entity)) {\n return lambdaUpdate();\n }\n LambdaUpdateWrapper<SysAreaInfoDO> wrapper = new LambdaUpdateWrapper<>();\n return wrapper\n .set(SysAreaInfoDO::getParentId, entity.getParentId())\n .set(SysAreaInfoDO::getName, entity.getName())\n .set(SysAreaInfoDO::getLevel, entity.getLevel())\n .set(SysAreaInfoDO::getAreaNo, entity.getAreaNo())\n .set(SysAreaInfoDO::getCategory, entity.getCategory())\n .set(SysAreaInfoDO::getMsg, entity.getMsg())\n ;\n }\n\n\n}" }, { "identifier": "ISysAreaInfoService", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/service/ISysAreaInfoService.java", "snippet": "public interface ISysAreaInfoService{\n\n /**\n * 创建\n *\n * @param addRequest {@link SysAreaInfoAddRequest}\n * @return {@link String} 主键\n */\n String create(SysAreaInfoAddRequest addRequest);\n\n /**\n * 根据id修改\n *\n * @param updateRequest {@link SysAreaInfoUpdateRequest}\n */\n void update(SysAreaInfoUpdateRequest updateRequest);\n\n /**\n * 删除\n *\n * @param ids {@link List<String>} id集合\n */\n void remove(List<String> ids);\n\n /**\n * 根据id查询详细\n *\n * @param id {@link String} 数据库主键\n * @return {@link SysAreaInfoResponse}\n */\n SysAreaInfoResponse findById(String id);\n\n /**\n * 按条件查询全部\n *\n * @param queryRequest {@link SysAreaInfoQueryRequest}\n * @return {@link PageResponse<SysAreaInfoResponse>} 详情\n */\n List<SysAreaInfoResponse> list(SysAreaInfoQueryRequest queryRequest);\n\n /**\n * 地区 转换成树结构\n *\n * @param queryRequest {@link SysAreaInfoQueryRequest}\n * @return 树结构\n */\n List<INode<String>> convert(SysAreaInfoQueryRequest queryRequest);\n\n}" } ]
import cn.hutool.core.bean.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.core.constant.CommonConstants; import com.xht.cloud.framework.core.support.StringUtils; import com.xht.cloud.framework.core.treenode.INode; import com.xht.cloud.framework.core.treenode.TreeNode; import com.xht.cloud.framework.core.treenode.TreeUtils; import com.xht.cloud.framework.exception.Assert; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.system.module.area.controller.request.SysAreaInfoAddRequest; import com.xht.cloud.system.module.area.controller.request.SysAreaInfoQueryRequest; import com.xht.cloud.system.module.area.controller.request.SysAreaInfoUpdateRequest; import com.xht.cloud.system.module.area.controller.response.SysAreaInfoResponse; import com.xht.cloud.system.module.area.convert.SysAreaInfoConvert; import com.xht.cloud.system.module.area.dao.dataobject.SysAreaInfoDO; import com.xht.cloud.system.module.area.dao.mapper.SysAreaInfoMapper; import com.xht.cloud.system.module.area.dao.wrapper.SysAreaInfoWrapper; import com.xht.cloud.system.module.area.service.ISysAreaInfoService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects;
8,828
package com.xht.cloud.system.module.area.service.impl; /** * 描述 :地区信息 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysAreaInfoServiceImpl implements ISysAreaInfoService { private final SysAreaInfoMapper sysAreaInfoMapper; private final SysAreaInfoConvert sysAreaInfoConvert; /** * 创建 * * @param addRequest {@link SysAreaInfoAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysAreaInfoAddRequest addRequest) { SysAreaInfoDO entity = sysAreaInfoConvert.toDO(addRequest); sysAreaInfoMapper.insert(entity); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysAreaInfoUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysAreaInfoUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } sysAreaInfoMapper.updateById(sysAreaInfoConvert.toDO(updateRequest)); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { List<SysAreaInfoDO> sysAreaInfoDOS = sysAreaInfoMapper.selectList(SysAreaInfoWrapper.getInstance().lambdaQuery().in(SysAreaInfoDO::getParentId, ids)); if (!CollectionUtils.isEmpty(sysAreaInfoDOS)) { Assert.fail("删除数据中含有下级城市数据,禁止删除!"); } sysAreaInfoMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysAreaInfoResponse} */ @Override public SysAreaInfoResponse findById(String id) { return sysAreaInfoConvert.toResponse(sysAreaInfoMapper.findById(id).orElse(null)); } /** * 按条件查询全部 * * @param queryRequest {@link SysAreaInfoQueryRequest} * @return {@link PageResponse<SysAreaInfoResponse>} 详情 */ @Override public List<SysAreaInfoResponse> list(SysAreaInfoQueryRequest queryRequest) { if (!StringUtils.hasText(queryRequest.getParentId()) && !StringUtils.hasText(queryRequest.getAreaNo()) && !StringUtils.hasText(queryRequest.getAreaNo())) { queryRequest.setParentId(CommonConstants.TREE_DEFAULT); } return sysAreaInfoConvert.toResponse(sysAreaInfoMapper.selectListByRequest(queryRequest)); } /** * 地区 转换成树结构 * * @param queryRequest {@link SysAreaInfoQueryRequest} * @return 树结构 */ @Override public List<INode<String>> convert(SysAreaInfoQueryRequest queryRequest) { Assert.notNull(queryRequest); SysAreaInfoDO sysAreaInfoDO = sysAreaInfoConvert.toDO(queryRequest); LambdaQueryWrapper<SysAreaInfoDO> sysAreaInfoDOLambdaQueryWrapper = SysAreaInfoWrapper.getInstance().lambdaQuery(sysAreaInfoDO); List<SysAreaInfoResponse> areaInfoResponses = sysAreaInfoConvert.toResponse(sysAreaInfoMapper.selectList(sysAreaInfoDOLambdaQueryWrapper)); if (CollectionUtils.isEmpty(areaInfoResponses)) { return Collections.emptyList(); } List<INode<String>> result = new ArrayList<>(areaInfoResponses.size()); for (int i = 0; i < areaInfoResponses.size(); i++) { SysAreaInfoResponse item = areaInfoResponses.get(i);
package com.xht.cloud.system.module.area.service.impl; /** * 描述 :地区信息 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysAreaInfoServiceImpl implements ISysAreaInfoService { private final SysAreaInfoMapper sysAreaInfoMapper; private final SysAreaInfoConvert sysAreaInfoConvert; /** * 创建 * * @param addRequest {@link SysAreaInfoAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysAreaInfoAddRequest addRequest) { SysAreaInfoDO entity = sysAreaInfoConvert.toDO(addRequest); sysAreaInfoMapper.insert(entity); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysAreaInfoUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysAreaInfoUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } sysAreaInfoMapper.updateById(sysAreaInfoConvert.toDO(updateRequest)); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { List<SysAreaInfoDO> sysAreaInfoDOS = sysAreaInfoMapper.selectList(SysAreaInfoWrapper.getInstance().lambdaQuery().in(SysAreaInfoDO::getParentId, ids)); if (!CollectionUtils.isEmpty(sysAreaInfoDOS)) { Assert.fail("删除数据中含有下级城市数据,禁止删除!"); } sysAreaInfoMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysAreaInfoResponse} */ @Override public SysAreaInfoResponse findById(String id) { return sysAreaInfoConvert.toResponse(sysAreaInfoMapper.findById(id).orElse(null)); } /** * 按条件查询全部 * * @param queryRequest {@link SysAreaInfoQueryRequest} * @return {@link PageResponse<SysAreaInfoResponse>} 详情 */ @Override public List<SysAreaInfoResponse> list(SysAreaInfoQueryRequest queryRequest) { if (!StringUtils.hasText(queryRequest.getParentId()) && !StringUtils.hasText(queryRequest.getAreaNo()) && !StringUtils.hasText(queryRequest.getAreaNo())) { queryRequest.setParentId(CommonConstants.TREE_DEFAULT); } return sysAreaInfoConvert.toResponse(sysAreaInfoMapper.selectListByRequest(queryRequest)); } /** * 地区 转换成树结构 * * @param queryRequest {@link SysAreaInfoQueryRequest} * @return 树结构 */ @Override public List<INode<String>> convert(SysAreaInfoQueryRequest queryRequest) { Assert.notNull(queryRequest); SysAreaInfoDO sysAreaInfoDO = sysAreaInfoConvert.toDO(queryRequest); LambdaQueryWrapper<SysAreaInfoDO> sysAreaInfoDOLambdaQueryWrapper = SysAreaInfoWrapper.getInstance().lambdaQuery(sysAreaInfoDO); List<SysAreaInfoResponse> areaInfoResponses = sysAreaInfoConvert.toResponse(sysAreaInfoMapper.selectList(sysAreaInfoDOLambdaQueryWrapper)); if (CollectionUtils.isEmpty(areaInfoResponses)) { return Collections.emptyList(); } List<INode<String>> result = new ArrayList<>(areaInfoResponses.size()); for (int i = 0; i < areaInfoResponses.size(); i++) { SysAreaInfoResponse item = areaInfoResponses.get(i);
result.add(new TreeNode<>(item.getId(), item.getParentId(), i).setExtra(BeanUtil.beanToMap(item)));
4
2023-12-12 08:16:30+00:00
12k
serendipitk/LunarCore
src/main/java/emu/lunarcore/game/battle/skills/MazeSkillAddBuff.java
[ { "identifier": "GameAvatar", "path": "src/main/java/emu/lunarcore/game/avatar/GameAvatar.java", "snippet": "@Getter\n@Entity(value = \"avatars\", useDiscriminator = false)\npublic class GameAvatar implements GameEntity {\n @Id private ObjectId id;\n @Indexed @Getter private int ownerUid; // Uid of player that this avatar belongs to\n\n private transient Player owner;\n private transient AvatarExcel excel;\n \n private int avatarId; // Id of avatar in the excels\n private AvatarData data;\n @Setter private int level;\n @Setter private int exp;\n @Setter private int promotion;\n \n private int rewards; // Previously known as \"taken rewards\"\n private long timestamp;\n \n @Getter(AccessLevel.NONE) private int currentHp;\n @Getter(AccessLevel.NONE) private int currentSp;\n @Getter(AccessLevel.NONE) private int extraLineupHp;\n @Getter(AccessLevel.NONE) private int extraLineupSp;\n\n private transient int entityId;\n private transient Int2ObjectMap<GameItem> equips;\n private transient Int2LongMap buffs;\n private transient AvatarHeroPath heroPath;\n\n @Deprecated // Morphia only\n public GameAvatar() {\n this.equips = new Int2ObjectOpenHashMap<>();\n this.buffs = Int2LongMaps.synchronize(new Int2LongOpenHashMap());\n this.level = 1;\n this.currentHp = 10000;\n this.currentSp = 0;\n }\n \n public GameAvatar(int avatarId) {\n this(GameData.getAvatarExcelMap().get(avatarId));\n }\n\n public GameAvatar(AvatarExcel excel) {\n this();\n this.avatarId = excel.getId();\n this.timestamp = System.currentTimeMillis() / 1000;\n this.setExcel(excel);\n }\n \n public GameAvatar(AvatarHeroPath path) {\n this();\n this.avatarId = GameConstants.TRAILBLAZER_AVATAR_ID;\n this.timestamp = System.currentTimeMillis() / 1000;\n this.setHeroPath(path);\n }\n \n @Override\n public Scene getScene() {\n return this.getOwner().getScene();\n }\n \n public void setExcel(AvatarExcel excel) {\n if (this.excel == null) {\n this.excel = excel;\n }\n if (this.data == null) {\n this.data = new AvatarData(excel);\n }\n }\n\n public void setOwner(Player player) {\n this.owner = player;\n this.ownerUid = player.getUid();\n }\n \n @Override\n public void setEntityId(int entityId) {\n this.entityId = entityId;\n }\n \n @Override\n public Position getPos() {\n return this.getOwner().getPos();\n }\n \n @Override\n public Position getRot() {\n return this.getOwner().getRot();\n }\n \n public int getHeadIconId() {\n return 200000 + this.getAvatarId();\n }\n \n public boolean isHero() {\n return GameData.getHeroExcelMap().containsKey(this.getAvatarId());\n }\n\n public int getMaxSp() {\n return 10000;\n }\n \n public int getCurrentHp(PlayerLineup lineup) {\n return !lineup.isExtraLineup() ? this.currentHp : this.extraLineupHp;\n }\n \n public int getCurrentSp(PlayerLineup lineup) {\n return !lineup.isExtraLineup() ? this.currentSp : this.extraLineupSp;\n }\n \n public void setCurrentHp(PlayerLineup lineup, int amount) {\n amount = Math.max(Math.min(amount, 10000), 0);\n if (!lineup.isExtraLineup()) {\n this.currentHp = amount; \n } else {\n this.extraLineupHp = amount; \n }\n }\n\n public void setCurrentSp(PlayerLineup lineup, int amount) {\n amount = Math.max(Math.min(amount, getMaxSp()), 0);\n if (!lineup.isExtraLineup()) {\n this.currentSp = amount; \n } else {\n this.extraLineupSp = amount; \n }\n }\n \n public boolean isAlive() {\n return this.isAlive(this.getOwner().getCurrentLineup());\n }\n\n public boolean isAlive(PlayerLineup lineup) {\n return this.getCurrentHp(lineup) > 0;\n }\n \n public int getRank() {\n return this.getData().getRank();\n }\n \n public void setRank(int rank) {\n this.getData().setRank(rank);\n }\n \n public Map<Integer, Integer> getSkills() {\n return this.getData().getSkills();\n }\n \n public void setHeroPath(AvatarHeroPath heroPath) {\n // Clear prev set hero path from avatar\n if (this.getHeroPath() != null) {\n this.getHeroPath().setAvatar(null);\n }\n \n this.data = heroPath.getData();\n this.excel = heroPath.getExcel(); // DO NOT USE GameAvatar::setExcel for this\n this.heroPath = heroPath;\n this.heroPath.setAvatar(this);\n }\n \n // Rewards\n \n public boolean setRewards(int flag) {\n if (this.rewards != flag) {\n this.rewards = flag;\n return true;\n }\n \n return false;\n }\n \n public boolean hasTakenReward(int promotion) {\n return (this.rewards & (1 << promotion)) != 0;\n }\n \n public void takeReward(int promotion) {\n this.rewards |= 1 << promotion;\n }\n \n // Buffs\n \n public void addBuff(int buffId, int duration) {\n this.buffs.put(buffId, System.currentTimeMillis() + (duration * 1000));\n }\n\n // Equips\n\n public GameItem getEquipBySlot(int slot) {\n return this.getEquips().get(slot);\n }\n\n public GameItem getEquipment() {\n return this.getEquips().get(GameConstants.EQUIPMENT_SLOT_ID);\n }\n\n public boolean equipItem(GameItem item) {\n // Sanity check\n int slot = item.getEquipSlot();\n if (slot == 0) return false;\n\n // Check if other avatars have this item equipped\n GameAvatar otherAvatar = getOwner().getAvatarById(item.getEquipAvatar());\n if (otherAvatar != null) {\n // Unequip this item from the other avatar\n if (otherAvatar.unequipItem(slot) != null) {\n getOwner().sendPacket(new PacketPlayerSyncScNotify(otherAvatar));\n }\n // Swap with other avatar\n if (getEquips().containsKey(slot)) {\n GameItem toSwap = this.getEquipBySlot(slot);\n otherAvatar.equipItem(toSwap);\n }\n } else if (getEquips().containsKey(slot)) {\n // Unequip item in current slot if it exists\n GameItem unequipped = unequipItem(slot);\n if (unequipped != null) {\n getOwner().sendPacket(new PacketPlayerSyncScNotify(unequipped));\n }\n }\n\n // Set equip\n getEquips().put(slot, item);\n\n // Save equip if equipped avatar was changed\n if (item.setEquipAvatar(this.getAvatarId())) {\n item.save();\n }\n\n // Send packet\n getOwner().sendPacket(new PacketPlayerSyncScNotify(this, item));\n\n return true;\n }\n\n public GameItem unequipItem(int slot) {\n GameItem item = getEquips().remove(slot);\n\n if (item != null) {\n item.setEquipAvatar(0);\n item.save();\n return item;\n }\n\n return null;\n }\n\n // Proto\n\n public Avatar toProto() {\n var proto = Avatar.newInstance()\n .setBaseAvatarId(this.getAvatarId())\n .setLevel(this.getLevel())\n .setExp(this.getExp())\n .setPromotion(this.getPromotion())\n .setRank(this.getRank())\n .setFirstMetTimestamp(this.getTimestamp());\n\n for (var equip : this.getEquips().values()) {\n if (equip.getItemMainType() == ItemMainType.Relic) {\n proto.addEquipRelicList(EquipRelic.newInstance().setSlot(equip.getEquipSlot()).setRelicUniqueId(equip.getInternalUid()));\n } else if (equip.getItemMainType() == ItemMainType.Equipment) {\n proto.setEquipmentUniqueId(equip.getInternalUid());\n }\n }\n\n for (var skill : getSkills().entrySet()) {\n proto.addSkilltreeList(AvatarSkillTree.newInstance().setPointId(skill.getKey()).setLevel(skill.getValue()));\n }\n \n for (int i = 0; i < this.getPromotion(); i++) {\n if (this.hasTakenReward(i)) {\n proto.addTakenRewards(i);\n }\n }\n \n return proto;\n }\n\n public LineupAvatar toLineupAvatarProto(PlayerLineup lineup, int slot) {\n var proto = LineupAvatar.newInstance()\n .setAvatarType(AvatarType.AVATAR_FORMAL_TYPE)\n .setId(this.getAvatarId())\n .setSpBar(SpBarInfo.newInstance().setCurSp(this.getCurrentSp(lineup)).setMaxSp(this.getMaxSp()))\n .setHp(this.getCurrentHp(lineup))\n .setSlot(slot);\n \n return proto;\n }\n\n @Override\n public SceneEntityInfo toSceneEntityProto() {\n var proto = SceneEntityInfo.newInstance()\n .setEntityId(this.getEntityId())\n .setMotion(MotionInfo.newInstance().setPos(this.getPos().toProto()).setRot(this.getRot().toProto()))\n .setActor(SceneActorInfo.newInstance().setBaseAvatarId(this.getAvatarId()).setAvatarType(AvatarType.AVATAR_FORMAL_TYPE));\n\n return proto;\n }\n\n public BattleAvatar toBattleProto(PlayerLineup lineup, int index) {\n var proto = BattleAvatar.newInstance()\n .setAvatarType(AvatarType.AVATAR_FORMAL_TYPE)\n .setId(this.getExcel().getAvatarID())\n .setLevel(this.getLevel())\n .setPromotion(this.getPromotion())\n .setRank(this.getRank())\n .setIndex(index)\n .setHp(this.getCurrentHp(lineup))\n .setSpBar(SpBarInfo.newInstance().setCurSp(this.getCurrentSp(lineup)).setMaxSp(this.getMaxSp()))\n .setWorldLevel(this.getOwner().getWorldLevel());\n\n // Skill tree\n for (var skill : getSkills().entrySet()) {\n proto.addSkilltreeList(AvatarSkillTree.newInstance().setPointId(skill.getKey()).setLevel(skill.getValue()));\n }\n\n // Build equips\n for (var equip : this.getEquips().values()) {\n if (equip.getItemMainType() == ItemMainType.Relic) {\n // Build battle relic proto\n var relic = BattleRelic.newInstance()\n .setId(equip.getItemId())\n .setLevel(equip.getLevel())\n .setUniqueId(equip.getInternalUid())\n .setMainAffixId(equip.getMainAffix());\n\n if (equip.getSubAffixes() != null) {\n for (var subAffix : equip.getSubAffixes()) {\n relic.addSubAffixList(subAffix.toProto());\n }\n }\n\n proto.addRelicList(relic);\n } else if (equip.getItemMainType() == ItemMainType.Equipment) {\n // Build battle equipment proto\n var equipment = BattleEquipment.newInstance()\n .setId(equip.getItemId())\n .setLevel(equip.getLevel())\n .setPromotion(equip.getPromotion())\n .setRank(equip.getRank());\n\n proto.addEquipmentList(equipment);\n }\n }\n\n return proto;\n }\n\n // Database\n\n public void save() {\n // Save avatar\n LunarCore.getGameDatabase().save(this);\n // Save hero path\n if (this.getHeroPath() != null) {\n this.getHeroPath().save();\n }\n }\n}" }, { "identifier": "SceneBuff", "path": "src/main/java/emu/lunarcore/game/scene/SceneBuff.java", "snippet": "@Getter\npublic class SceneBuff {\n private int casterAvatarId; // Owner avatar id\n private int buffId;\n private int buffLevel;\n @Setter private int count;\n \n private float duration;\n private long createTime;\n private long expiry;\n \n public SceneBuff(int buffId) {\n this.buffId = buffId;\n this.buffLevel = 1;\n this.count = 1;\n this.createTime = System.currentTimeMillis();\n this.duration = -1;\n }\n \n public SceneBuff(int casterAvatarId, int buffId) {\n this(buffId);\n this.casterAvatarId = casterAvatarId;\n this.expiry = Long.MAX_VALUE;\n }\n \n public SceneBuff(int casterAvatarId, int buffId, int seconds) {\n this(buffId);\n this.casterAvatarId = casterAvatarId;\n this.duration = seconds * 1000;\n this.expiry = this.createTime + (long) duration;\n }\n \n public int decrementAndGet() {\n this.count--;\n return this.count;\n }\n \n public boolean isExpired(long timestamp) {\n return timestamp > this.expiry;\n }\n \n // Serialization\n \n public BuffInfo toProto() {\n var proto = BuffInfo.newInstance()\n .setBuffId(this.getBuffId())\n .setLevel(this.getBuffLevel())\n .setBaseAvatarId(this.getCasterAvatarId())\n .setAddTimeMs(LunarCore.convertToServerTime(this.getCreateTime()))\n .setLifeTime(this.getDuration())\n .setCount(this.getCount());\n \n return proto;\n }\n}" }, { "identifier": "EntityMonster", "path": "src/main/java/emu/lunarcore/game/scene/entity/EntityMonster.java", "snippet": "@Getter\npublic class EntityMonster implements GameEntity, Tickable {\n @Setter private NpcMonsterExcel excel;\n @Setter private int entityId;\n @Setter private int worldLevel;\n @Setter private int groupId;\n @Setter private int instId;\n @Setter private int eventId;\n \n private final Scene scene;\n private final Position pos;\n private final Position rot;\n \n private Int2ObjectMap<SceneBuff> buffs;\n @Setter private SceneBuff tempBuff;\n \n private int farmElementId;\n @Setter private int customStageId;\n @Setter private int customLevel;\n \n public EntityMonster(Scene scene, NpcMonsterExcel excel, GroupInfo group, MonsterInfo monsterInfo) {\n this.scene = scene;\n this.excel = excel;\n this.pos = monsterInfo.getPos().clone();\n this.rot = monsterInfo.getRot().clone();\n this.groupId = group.getId();\n this.instId = monsterInfo.getID();\n this.farmElementId = monsterInfo.getFarmElementID();\n }\n \n public boolean isFarmElement() {\n return this.farmElementId > 0;\n }\n \n public int getStageId() {\n if (this.customStageId == 0) {\n return (this.getEventId() * 10) + worldLevel;\n } else {\n return this.customStageId;\n }\n }\n \n public synchronized SceneBuff addBuff(int caster, int buffId, int duration) {\n if (this.buffs == null) {\n this.buffs = new Int2ObjectOpenHashMap<>();\n }\n \n // Create buff\n var buff = new SceneBuff(caster, buffId, duration);\n \n // Add to buff map\n this.buffs.put(buffId, buff);\n return buff;\n }\n \n public synchronized void applyBuffs(Battle battle, int waveIndex) {\n if (this.buffs != null) {\n for (var entry : this.buffs.int2ObjectEntrySet()) {\n // Check expiry for buff\n if (entry.getValue().isExpired(battle.getTimestamp())) {\n continue;\n }\n \n // Add buff to battle\n this.applyBuff(battle, entry.getValue(), waveIndex);\n }\n }\n \n if (this.getTempBuff() != null) {\n this.applyBuff(battle, this.getTempBuff(), waveIndex);\n this.tempBuff = null;\n }\n }\n \n private boolean applyBuff(Battle battle, SceneBuff buff, int waveIndex) {\n // Get index of owner in lineup\n int ownerIndex = battle.getLineup().indexOf(buff.getCasterAvatarId());\n \n // Add buff to battle if owner exists\n if (ownerIndex != -1) {\n battle.addBuff(buff.getBuffId(), ownerIndex, 1 << waveIndex);\n return true;\n }\n \n // Failure\n return false;\n }\n \n @Override\n public void onRemove() {\n // Try to fire any triggers\n getScene().invokePropTrigger(PropTriggerType.MONSTER_DIE, this.getGroupId(), this.getInstId());\n }\n \n @Override\n public synchronized void onTick(long timestamp, long delta) {\n // Check if we need to remove any buffs\n if (this.buffs != null && this.buffs.size() > 0) {\n var it = this.buffs.values().iterator();\n \n while (it.hasNext()) {\n var buff = it.next();\n \n if (buff.isExpired(timestamp)) {\n // Safely remove from iterator\n it.remove();\n \n // Send packet to notify the client that we are removing the buff\n getScene().getPlayer().sendPacket(new PacketSyncEntityBuffChangeListScNotify(this.getEntityId(), buff.getBuffId()));\n }\n }\n }\n }\n\n @Override\n public SceneEntityInfo toSceneEntityProto() {\n var monster = SceneNpcMonsterInfo.newInstance()\n .setWorldLevel(this.getWorldLevel())\n .setMonsterId(excel.getId())\n .setEventId(this.getEventId());\n\n var proto = SceneEntityInfo.newInstance()\n .setEntityId(this.getEntityId())\n .setGroupId(this.getGroupId())\n .setInstId(this.getInstId())\n .setMotion(MotionInfo.newInstance().setPos(getPos().toProto()).setRot(getRot().toProto()))\n .setNpcMonster(monster);\n\n return proto;\n }\n}" }, { "identifier": "GameEntity", "path": "src/main/java/emu/lunarcore/game/scene/entity/GameEntity.java", "snippet": "public interface GameEntity {\n\n public int getEntityId();\n\n public void setEntityId(int id);\n \n public Scene getScene();\n \n public Position getPos();\n \n public Position getRot();\n\n public default int getGroupId() {\n return 0;\n }\n \n public default int getInstId() {\n return 0;\n }\n \n public default void onAdd() {\n \n }\n\n public default void onRemove() {\n \n }\n\n public SceneEntityInfo toSceneEntityProto();\n}" }, { "identifier": "MotionInfo", "path": "src/generated/main/emu/lunarcore/proto/MotionInfoOuterClass.java", "snippet": "public static final class MotionInfo extends ProtoMessage<MotionInfo> implements Cloneable {\n private static final long serialVersionUID = 0L;\n\n /**\n * <code>optional .Vector rot = 9;</code>\n */\n private final VectorOuterClass.Vector rot = VectorOuterClass.Vector.newInstance();\n\n /**\n * <code>optional .Vector pos = 12;</code>\n */\n private final VectorOuterClass.Vector pos = VectorOuterClass.Vector.newInstance();\n\n private MotionInfo() {\n }\n\n /**\n * @return a new empty instance of {@code MotionInfo}\n */\n public static MotionInfo newInstance() {\n return new MotionInfo();\n }\n\n /**\n * <code>optional .Vector rot = 9;</code>\n * @return whether the rot field is set\n */\n public boolean hasRot() {\n return (bitField0_ & 0x00000001) != 0;\n }\n\n /**\n * <code>optional .Vector rot = 9;</code>\n * @return this\n */\n public MotionInfo clearRot() {\n bitField0_ &= ~0x00000001;\n rot.clear();\n return this;\n }\n\n /**\n * <code>optional .Vector rot = 9;</code>\n *\n * This method returns the internal storage object without modifying any has state.\n * The returned object should not be modified and be treated as read-only.\n *\n * Use {@link #getMutableRot()} if you want to modify it.\n *\n * @return internal storage object for reading\n */\n public VectorOuterClass.Vector getRot() {\n return rot;\n }\n\n /**\n * <code>optional .Vector rot = 9;</code>\n *\n * This method returns the internal storage object and sets the corresponding\n * has state. The returned object will become part of this message and its\n * contents may be modified as long as the has state is not cleared.\n *\n * @return internal storage object for modifications\n */\n public VectorOuterClass.Vector getMutableRot() {\n bitField0_ |= 0x00000001;\n return rot;\n }\n\n /**\n * <code>optional .Vector rot = 9;</code>\n * @param value the rot to set\n * @return this\n */\n public MotionInfo setRot(final VectorOuterClass.Vector value) {\n bitField0_ |= 0x00000001;\n rot.copyFrom(value);\n return this;\n }\n\n /**\n * <code>optional .Vector pos = 12;</code>\n * @return whether the pos field is set\n */\n public boolean hasPos() {\n return (bitField0_ & 0x00000002) != 0;\n }\n\n /**\n * <code>optional .Vector pos = 12;</code>\n * @return this\n */\n public MotionInfo clearPos() {\n bitField0_ &= ~0x00000002;\n pos.clear();\n return this;\n }\n\n /**\n * <code>optional .Vector pos = 12;</code>\n *\n * This method returns the internal storage object without modifying any has state.\n * The returned object should not be modified and be treated as read-only.\n *\n * Use {@link #getMutablePos()} if you want to modify it.\n *\n * @return internal storage object for reading\n */\n public VectorOuterClass.Vector getPos() {\n return pos;\n }\n\n /**\n * <code>optional .Vector pos = 12;</code>\n *\n * This method returns the internal storage object and sets the corresponding\n * has state. The returned object will become part of this message and its\n * contents may be modified as long as the has state is not cleared.\n *\n * @return internal storage object for modifications\n */\n public VectorOuterClass.Vector getMutablePos() {\n bitField0_ |= 0x00000002;\n return pos;\n }\n\n /**\n * <code>optional .Vector pos = 12;</code>\n * @param value the pos to set\n * @return this\n */\n public MotionInfo setPos(final VectorOuterClass.Vector value) {\n bitField0_ |= 0x00000002;\n pos.copyFrom(value);\n return this;\n }\n\n @Override\n public MotionInfo copyFrom(final MotionInfo other) {\n cachedSize = other.cachedSize;\n if ((bitField0_ | other.bitField0_) != 0) {\n bitField0_ = other.bitField0_;\n rot.copyFrom(other.rot);\n pos.copyFrom(other.pos);\n }\n return this;\n }\n\n @Override\n public MotionInfo mergeFrom(final MotionInfo other) {\n if (other.isEmpty()) {\n return this;\n }\n cachedSize = -1;\n if (other.hasRot()) {\n getMutableRot().mergeFrom(other.rot);\n }\n if (other.hasPos()) {\n getMutablePos().mergeFrom(other.pos);\n }\n return this;\n }\n\n @Override\n public MotionInfo clear() {\n if (isEmpty()) {\n return this;\n }\n cachedSize = -1;\n bitField0_ = 0;\n rot.clear();\n pos.clear();\n return this;\n }\n\n @Override\n public MotionInfo clearQuick() {\n if (isEmpty()) {\n return this;\n }\n cachedSize = -1;\n bitField0_ = 0;\n rot.clearQuick();\n pos.clearQuick();\n return this;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof MotionInfo)) {\n return false;\n }\n MotionInfo other = (MotionInfo) o;\n return bitField0_ == other.bitField0_\n && (!hasRot() || rot.equals(other.rot))\n && (!hasPos() || pos.equals(other.pos));\n }\n\n @Override\n public void writeTo(final ProtoSink output) throws IOException {\n if ((bitField0_ & 0x00000001) != 0) {\n output.writeRawByte((byte) 74);\n output.writeMessageNoTag(rot);\n }\n if ((bitField0_ & 0x00000002) != 0) {\n output.writeRawByte((byte) 98);\n output.writeMessageNoTag(pos);\n }\n }\n\n @Override\n protected int computeSerializedSize() {\n int size = 0;\n if ((bitField0_ & 0x00000001) != 0) {\n size += 1 + ProtoSink.computeMessageSizeNoTag(rot);\n }\n if ((bitField0_ & 0x00000002) != 0) {\n size += 1 + ProtoSink.computeMessageSizeNoTag(pos);\n }\n return size;\n }\n\n @Override\n @SuppressWarnings(\"fallthrough\")\n public MotionInfo mergeFrom(final ProtoSource input) throws IOException {\n // Enabled Fall-Through Optimization (QuickBuffers)\n int tag = input.readTag();\n while (true) {\n switch (tag) {\n case 74: {\n // rot\n input.readMessage(rot);\n bitField0_ |= 0x00000001;\n tag = input.readTag();\n if (tag != 98) {\n break;\n }\n }\n case 98: {\n // pos\n input.readMessage(pos);\n bitField0_ |= 0x00000002;\n tag = input.readTag();\n if (tag != 0) {\n break;\n }\n }\n case 0: {\n return this;\n }\n default: {\n if (!input.skipField(tag)) {\n return this;\n }\n tag = input.readTag();\n break;\n }\n }\n }\n }\n\n @Override\n public void writeTo(final JsonSink output) throws IOException {\n output.beginObject();\n if ((bitField0_ & 0x00000001) != 0) {\n output.writeMessage(FieldNames.rot, rot);\n }\n if ((bitField0_ & 0x00000002) != 0) {\n output.writeMessage(FieldNames.pos, pos);\n }\n output.endObject();\n }\n\n @Override\n public MotionInfo mergeFrom(final JsonSource input) throws IOException {\n if (!input.beginObject()) {\n return this;\n }\n while (!input.isAtEnd()) {\n switch (input.readFieldHash()) {\n case 113111: {\n if (input.isAtField(FieldNames.rot)) {\n if (!input.trySkipNullValue()) {\n input.readMessage(rot);\n bitField0_ |= 0x00000001;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case 111188: {\n if (input.isAtField(FieldNames.pos)) {\n if (!input.trySkipNullValue()) {\n input.readMessage(pos);\n bitField0_ |= 0x00000002;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n default: {\n input.skipUnknownField();\n break;\n }\n }\n }\n input.endObject();\n return this;\n }\n\n @Override\n public MotionInfo clone() {\n return new MotionInfo().copyFrom(this);\n }\n\n @Override\n public boolean isEmpty() {\n return ((bitField0_) == 0);\n }\n\n public static MotionInfo parseFrom(final byte[] data) throws InvalidProtocolBufferException {\n return ProtoMessage.mergeFrom(new MotionInfo(), data).checkInitialized();\n }\n\n public static MotionInfo parseFrom(final ProtoSource input) throws IOException {\n return ProtoMessage.mergeFrom(new MotionInfo(), input).checkInitialized();\n }\n\n public static MotionInfo parseFrom(final JsonSource input) throws IOException {\n return ProtoMessage.mergeFrom(new MotionInfo(), input).checkInitialized();\n }\n\n /**\n * @return factory for creating MotionInfo messages\n */\n public static MessageFactory<MotionInfo> getFactory() {\n return MotionInfoFactory.INSTANCE;\n }\n\n private enum MotionInfoFactory implements MessageFactory<MotionInfo> {\n INSTANCE;\n\n @Override\n public MotionInfo create() {\n return MotionInfo.newInstance();\n }\n }\n\n /**\n * Contains name constants used for serializing JSON\n */\n static class FieldNames {\n static final FieldName rot = FieldName.forField(\"rot\");\n\n static final FieldName pos = FieldName.forField(\"pos\");\n }\n}" }, { "identifier": "PacketSyncEntityBuffChangeListScNotify", "path": "src/main/java/emu/lunarcore/server/packet/send/PacketSyncEntityBuffChangeListScNotify.java", "snippet": "public class PacketSyncEntityBuffChangeListScNotify extends BasePacket {\n\n public PacketSyncEntityBuffChangeListScNotify(int entityId, SceneBuff buff) {\n super(CmdId.SyncEntityBuffChangeListScNotify);\n \n var buffChange = EntityBuffChangeInfo.newInstance().setEntityId(entityId)\n .setAddBuffInfo(buff.toProto())\n .setEntityId(entityId);\n \n var data = SyncEntityBuffChangeListScNotify.newInstance()\n .addEntityBuffInfoList(buffChange);\n \n this.setData(data);\n }\n\n public PacketSyncEntityBuffChangeListScNotify(int entityId, int removeBuffId) {\n super(CmdId.SyncEntityBuffChangeListScNotify);\n \n var buffChange = EntityBuffChangeInfo.newInstance().setEntityId(entityId)\n .setRemoveBuffId(removeBuffId)\n .setEntityId(entityId);\n \n var data = SyncEntityBuffChangeListScNotify.newInstance()\n .addEntityBuffInfoList(buffChange);\n \n this.setData(data);\n }\n}" } ]
import java.util.List; import emu.lunarcore.game.avatar.GameAvatar; import emu.lunarcore.game.scene.SceneBuff; import emu.lunarcore.game.scene.entity.EntityMonster; import emu.lunarcore.game.scene.entity.GameEntity; import emu.lunarcore.proto.MotionInfoOuterClass.MotionInfo; import emu.lunarcore.server.packet.send.PacketSyncEntityBuffChangeListScNotify; import lombok.Getter; import lombok.Setter;
7,885
package emu.lunarcore.game.battle.skills; @Getter public class MazeSkillAddBuff extends MazeSkillAction { private int buffId; private int duration; @Setter private boolean sendBuffPacket; public MazeSkillAddBuff(int buffId, int duration) { this.buffId = buffId; this.duration = duration; } @Override public void onCast(GameAvatar caster, MotionInfo castPosition) { caster.addBuff(buffId, duration); } @Override public void onCastHit(GameAvatar caster, List<? extends GameEntity> entities) { for (GameEntity entity : entities) { if (entity instanceof EntityMonster monster) { // Add buff to monster var buff = monster.addBuff(caster.getAvatarId(), buffId, duration); // Send packet if (buff != null && this.sendBuffPacket) {
package emu.lunarcore.game.battle.skills; @Getter public class MazeSkillAddBuff extends MazeSkillAction { private int buffId; private int duration; @Setter private boolean sendBuffPacket; public MazeSkillAddBuff(int buffId, int duration) { this.buffId = buffId; this.duration = duration; } @Override public void onCast(GameAvatar caster, MotionInfo castPosition) { caster.addBuff(buffId, duration); } @Override public void onCastHit(GameAvatar caster, List<? extends GameEntity> entities) { for (GameEntity entity : entities) { if (entity instanceof EntityMonster monster) { // Add buff to monster var buff = monster.addBuff(caster.getAvatarId(), buffId, duration); // Send packet if (buff != null && this.sendBuffPacket) {
caster.getOwner().sendPacket(new PacketSyncEntityBuffChangeListScNotify(entity.getEntityId(), buff));
5
2023-12-08 14:13:04+00:00
12k
zhaw-iwi/promise
src/test/java/ch/zhaw/statefulconversation/paper/MultiStateInteraction.java
[ { "identifier": "Agent", "path": "src/main/java/ch/zhaw/statefulconversation/model/Agent.java", "snippet": "@Entity\npublic class Agent {\n\n // @TODO: maybe have an attribute or getter method is active?\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getId() {\n return this.id;\n }\n\n protected Agent() {\n\n }\n\n private String name;\n private String description;\n\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State initialState;\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State currentState;\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private Storage storage;\n\n public Agent(String name, String description, State initialState) {\n this(name, description, initialState, null);\n }\n\n public Agent(String name, String description, State initialState, Storage storage) {\n this.name = name;\n this.description = description;\n this.initialState = initialState;\n this.storage = storage;\n this.currentState = this.initialState;\n }\n\n public String name() {\n return this.name;\n }\n\n public String description() {\n return this.description;\n }\n\n public Map<String, JsonElement> storage() {\n return this.storage.toMap();\n }\n\n public boolean isActive() {\n return this.currentState.isActive();\n }\n\n public List<Utterance> conversation() {\n if (this.isActive()) {\n return this.currentState.getUtterances().toList();\n }\n return this.initialState.getUtterances().toList();\n }\n\n public String summarise() {\n if (this.isActive()) {\n return this.currentState.summarise();\n }\n return this.initialState.summarise();\n }\n\n public String start() {\n return this.currentState.start();\n }\n\n public String respond(String userSays) {\n try {\n return this.currentState.respond(userSays);\n } catch (TransitionException e) {\n this.currentState = e.getSubsequentState();\n if (this.currentState.isStarting()) {\n return this.start();\n }\n return this.respond(userSays);\n }\n }\n\n public String reRespond() {\n\n if (!this.isActive()) {\n throw new RuntimeException(\"cannot rerespond if agent is inactive.\");\n }\n\n String lastUserSays = this.currentState.getUtterances().removeLastTwoUtterances();\n return this.respond(lastUserSays);\n }\n\n public void reset() {\n this.currentState = this.initialState;\n this.currentState.reset();\n }\n\n public void resetCurrentState() {\n this.currentState.reset();\n }\n\n @Override\n public String toString() {\n return \"Agent with current state \" + this.currentState;\n }\n}" }, { "identifier": "Final", "path": "src/main/java/ch/zhaw/statefulconversation/model/Final.java", "snippet": "@Entity\npublic class Final extends State {\n\n private static final String FINAL_PROMPT = \"Provide a brief reply, no more than 12 tokens, acknowledging the user and leading to a goodbye.\";\n private static final String FINAL_STARTER_PROMPT = \"Give a very brief, courteous goodbye to end on a positive and respectful note.\";\n \n public Final() {\n super(Final.FINAL_PROMPT, \"FINAL\", Final.FINAL_STARTER_PROMPT, List.of());\n }\n\n public Final(boolean isStarting, String summarisePrompt) {\n super(Final.FINAL_PROMPT, \"FINAL\", Final.FINAL_STARTER_PROMPT, List.of(), summarisePrompt, isStarting, false);\n }\n\n public Final(String prompt) {\n super(prompt, \"FINAL\", Final.FINAL_STARTER_PROMPT, List.of());\n }\n\n public Final(String prompt, boolean isStarting, String summarisePrompt) {\n super(prompt, \"FINAL\", Final.FINAL_STARTER_PROMPT, List.of(), summarisePrompt, isStarting, false);\n }\n\n public Final(String prompt, String starterPrompt) {\n super(prompt, \"FINAL\", starterPrompt, List.of());\n }\n\n public Final(String prompt, String starterPrompt, boolean isStarting, String summarisePrompt) {\n super(prompt, \"FINAL\", starterPrompt, List.of(), summarisePrompt, isStarting, false);\n }\n\n @Override\n public boolean isActive() {\n return false;\n }\n\n @Override\n public String toString() {\n return \"Final IS-A \" + super.toString();\n }\n}" }, { "identifier": "OuterState", "path": "src/main/java/ch/zhaw/statefulconversation/model/OuterState.java", "snippet": "@Entity\npublic class OuterState extends State {\n\n protected OuterState() {\n\n }\n\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State innerInitial;\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State innerCurrent;\n\n public OuterState(String prompt, String name, List<Transition> transitions, State innerInitial) {\n super(prompt, name, null, transitions);\n this.innerInitial = innerInitial;\n this.innerCurrent = this.innerInitial;\n }\n\n public OuterState(String prompt, String name, List<Transition> transitions, State innerInitial,\n String summarisePrompt) {\n super(prompt, name, null, transitions, summarisePrompt, true, false);\n this.innerInitial = innerInitial;\n this.innerCurrent = this.innerInitial;\n }\n\n @Override\n public boolean isActive() {\n return this.innerCurrent.isActive();\n }\n\n public String start() {\n return this.start(null);\n }\n\n public String start(String outerPrompt) {\n String totalPrompt = (this.composeTotalPrompt(outerPrompt).isEmpty() ? null\n : this.composeTotalPrompt(outerPrompt));\n\n String assistantSays = this.innerCurrent.start(totalPrompt);\n this.utterances.appendAssistantSays(assistantSays);\n return assistantSays;\n }\n\n public String respond(String userSays) throws TransitionException {\n return this.respond(userSays, null);\n }\n\n public String respond(String userSays, String outerPrompt) throws TransitionException {\n this.utterances.appendUserSays(userSays);\n this.raiseIfTransit();\n String totalPrompt = this.composeTotalPrompt(outerPrompt);\n String assistantSays = null;\n try {\n assistantSays = this.innerCurrent.respond(userSays, totalPrompt);\n this.utterances.appendAssistantSays(assistantSays);\n return assistantSays;\n } catch (TransitionException e) {\n this.innerCurrent = e.getSubsequentState();\n if (this.innerCurrent.isStarting()) {\n assistantSays = this.start(totalPrompt);\n } else {\n assistantSays = this.innerCurrent.respond(userSays, totalPrompt);\n this.utterances.appendAssistantSays(assistantSays);\n }\n return assistantSays;\n }\n }\n\n @Override\n public void reset() {\n this.reset(new HashSet<State>());\n }\n\n @Override\n protected void reset(Set<State> statesAlreadyReseted) {\n if (statesAlreadyReseted.contains(this)) {\n return;\n }\n super.reset(statesAlreadyReseted);\n this.innerCurrent = this.innerInitial;\n this.innerCurrent.reset(statesAlreadyReseted);\n }\n\n @Override\n public String toString() {\n return \"OuterState IS-A \" + super.toString() + \" with inner initial \" + this.innerInitial\n + \" and inner current \" + this.innerCurrent;\n }\n\n}" }, { "identifier": "State", "path": "src/main/java/ch/zhaw/statefulconversation/model/State.java", "snippet": "@Entity\npublic class State extends Prompt {\n private static final Logger LOGGER = LoggerFactory.getLogger(State.class);\n protected static final String SUMMARISE_PROMPT = \"Please summarise the following conversation. Be concise, but ensure that the key points and issues are included. \";\n\n protected State() {\n\n }\n\n private String name;\n private String starterPrompt;\n private String summarisePrompt;\n private boolean isStarting;\n private boolean isOblivious;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n @OrderColumn(name = \"transition_index\")\n private List<Transition> transitions;\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n protected Utterances utterances;\n\n public State(String prompt, String name, String starterPrompt, List<Transition> transitions) {\n super(prompt);\n this.name = name;\n this.starterPrompt = starterPrompt;\n this.transitions = new ArrayList<Transition>(transitions);\n this.summarisePrompt = State.SUMMARISE_PROMPT;\n this.isStarting = true;\n this.isOblivious = false;\n this.utterances = new Utterances();\n }\n\n public State(String prompt, String name, String starterPrompt, List<Transition> transitions, String summarisePrompt,\n boolean isStarting,\n boolean isOblivious) {\n this(prompt, name, starterPrompt, transitions);\n this.summarisePrompt = summarisePrompt;\n this.isStarting = isStarting;\n this.isOblivious = isOblivious;\n }\n\n public State(String prompt, String name, String starterPrompt, List<Transition> transitions, Storage storage,\n List<String> storageKeysFrom) {\n super(prompt, storage, storageKeysFrom);\n this.name = name;\n this.starterPrompt = starterPrompt;\n this.transitions = new ArrayList<Transition>(transitions);\n this.summarisePrompt = SUMMARISE_PROMPT;\n this.isStarting = true;\n this.isOblivious = false;\n this.utterances = new Utterances();\n }\n\n public State(String prompt, String name, String starterPrompt, List<Transition> transitions, String summarisePrompt,\n boolean isStarting,\n boolean isOblivious,\n Storage storage, List<String> storageKeysFrom) {\n this(prompt, name, starterPrompt, transitions, storage, storageKeysFrom);\n this.summarisePrompt = summarisePrompt;\n this.isStarting = isStarting;\n this.isOblivious = isOblivious;\n }\n\n public String getName() {\n return this.name;\n }\n\n public boolean isStarting() {\n return this.isStarting;\n }\n\n public Utterances getUtterances() {\n return this.utterances;\n }\n\n public boolean isActive() {\n return true;\n }\n\n public void addTransition(Transition transition) {\n this.transitions.add(transition);\n }\n\n protected List<Transition> getTransitions() {\n return List.copyOf(this.transitions);\n }\n\n protected void raiseIfTransit() throws TransitionException {\n State subsequentState = this.transit();\n if (subsequentState != null) {\n throw new TransitionException(subsequentState);\n }\n }\n\n private State transit() {\n State.LOGGER.warn(this.getClass() + \" \\\"\" + this.getName() + \"\\\".transit()\");\n for (Transition current : this.transitions) {\n if (this.transitThisOne(current)) {\n return current.getSubsequentState();\n }\n }\n return null;\n }\n\n private boolean transitThisOne(Transition transition) {\n if (transition.decide(this.utterances)) {\n transition.action(this.utterances);\n return true;\n }\n return false;\n }\n\n public String start() {\n return this.start(null);\n }\n\n public String start(String outerPrompt) {\n if (this.isOblivious) {\n this.utterances.reset();\n }\n String totalPromptPrepend = this.composeTotalPrompt(outerPrompt);\n // @todo: is it ok to avoid completion if there's no prompt?\n if (totalPromptPrepend.isEmpty()) {\n return null;\n }\n String assistantSays = LMOpenAI.complete(this.utterances, totalPromptPrepend, this.starterPrompt);\n this.utterances.appendAssistantSays(assistantSays);\n return assistantSays;\n }\n\n public String respond(String userSays) throws TransitionException {\n return this.respond(userSays, null);\n }\n\n public String respond(String userSays, String outerPrompt) throws TransitionException {\n State.LOGGER\n .info(this.getClass() + \" \\\"\" + this.getName() + \"\\\".respond(\" + userSays + \", \" + outerPrompt + \")\");\n this.utterances.appendUserSays(userSays);\n // check if there's a transition to be followed\n this.raiseIfTransit();\n // no transition, compose prompt\n String totalPrompt = this.composeTotalPrompt(outerPrompt);\n // @todo: is it ok to avoid completion if there's no prompt?\n if (totalPrompt.isEmpty()) {\n return null;\n }\n String assistantSays = LMOpenAI.complete(this.utterances, totalPrompt);\n this.utterances.appendAssistantSays(assistantSays);\n return assistantSays;\n }\n\n protected String composeTotalPrompt(String outerPrompt) {\n String totalPrompt = (this.getPrompt() != null ? this.getPrompt() : \"\");\n if (outerPrompt != null) {\n totalPrompt = outerPrompt + \" \" + totalPrompt;\n }\n return totalPrompt.trim();\n }\n\n public String summarise() {\n String result = LMOpenAI.summarise(this.utterances, this.summarisePrompt);\n return result;\n }\n\n public void reset() {\n this.reset(new HashSet<State>());\n }\n\n protected void reset(Set<State> statesAlreadyReseted) {\n if (statesAlreadyReseted.contains(this)) {\n return;\n }\n this.utterances.reset();\n statesAlreadyReseted.add(this);\n for (Transition current : this.transitions) {\n current.getSubsequentState().reset(statesAlreadyReseted);\n }\n }\n\n @Override\n public String toString() {\n return \"State IS-A \" + super.toString() + \" with name \" + this.getName();\n }\n\n}" }, { "identifier": "Storage", "path": "src/main/java/ch/zhaw/statefulconversation/model/Storage.java", "snippet": "@Entity\npublic class Storage {\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getID() {\n return this.id;\n }\n\n @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true)\n private List<StorageEntry> entries;\n\n public Storage() {\n this.entries = new ArrayList<StorageEntry>();\n }\n\n public void put(String key, JsonElement value) {\n for (StorageEntry current : this.entries) {\n if (current.getKey().equals(key)) {\n current.setValue(value);\n return;\n }\n }\n\n StorageEntry entry = new StorageEntry(key, value);\n this.entries.add(entry);\n }\n\n public boolean containsKey(String key) {\n for (StorageEntry current : this.entries) {\n if (current.getKey().equals(key)) {\n return true;\n }\n }\n return false;\n }\n\n public JsonElement get(String key) {\n for (StorageEntry candiate : this.entries) {\n if (candiate.getKey().equals(key)) {\n return candiate.getValue();\n }\n }\n throw new RuntimeException(\"this storage does not contain an entry with key = \" + key);\n }\n\n public StorageEntry remove(String key) {\n for (StorageEntry current : this.entries) {\n if (current.getKey().equals(key)) {\n this.entries.remove(current);\n return current;\n }\n }\n throw new RuntimeException(\"this storage does not contain an entry with key = \" + key);\n }\n\n public Map<String, JsonElement> toMap() {\n Map<String, JsonElement> result = new HashMap<>();\n for (StorageEntry current : this.entries) {\n result.put(current.getKey(), current.getValue());\n }\n return result;\n }\n\n @Override\n public String toString() {\n return \"Storage containing \" + this.entries;\n }\n\n // @TODO utility serialisation/deserialisation methods\n public static List<String> toListOfString(JsonElement jsonListOfStrings) {\n List<JsonElement> listOfJsonElements = jsonListOfStrings.getAsJsonArray().asList();\n List<String> result = new ArrayList<String>();\n for (JsonElement current : listOfJsonElements) {\n result.add(current.getAsString());\n }\n return result;\n }\n\n private static Gson GSON = new Gson();\n\n public static JsonElement toJsonElement(Object javaObject) {\n return Storage.GSON.toJsonTree(javaObject);\n }\n\n}" }, { "identifier": "Transition", "path": "src/main/java/ch/zhaw/statefulconversation/model/Transition.java", "snippet": "@Entity\npublic class Transition {\n private static final Logger LOGGER = LoggerFactory.getLogger(Transition.class);\n\n @Id\n @GeneratedValue\n private UUID id;\n\n protected Transition() {\n\n }\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n @OrderColumn(name = \"decision_index\")\n private List<Decision> decisions;\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n @OrderColumn(name = \"action_index\")\n private List<Action> actions;\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State subsequentState;\n\n public Transition(List<Decision> decisions, List<Action> actions, State subsequentState) {\n this.decisions = new ArrayList<Decision>(decisions);\n this.actions = new ArrayList<Action>(actions);\n this.subsequentState = subsequentState;\n }\n\n public Transition(Decision decision, Action action, State subsequentState) {\n this(List.of(decision), List.of(action), subsequentState);\n }\n\n public Transition(Decision decision, State subsequentState) {\n this(List.of(decision), List.of(), subsequentState);\n }\n\n public Transition(Action action, State subsequentState) {\n this(List.of(), List.of(action), subsequentState);\n }\n\n public Transition(State subsequentState) {\n this(List.of(), List.of(), subsequentState);\n }\n\n public State getSubsequentState() {\n return this.subsequentState;\n }\n\n public void addDecision(Decision decision) {\n this.decisions.add(decision);\n }\n\n public void addAction(Action action) {\n this.actions.add(action);\n }\n\n public void setSubsequenState(State subsequentState) {\n this.subsequentState = subsequentState;\n }\n\n public boolean decide(Utterances utterances) {\n Transition.LOGGER.warn(\"decisions if transition to \" + this.subsequentState.getName());\n if (this.decisions.isEmpty()) {\n Transition.LOGGER.warn(\"no decisions present\");\n return true;\n }\n String currentDecisionPrompt;\n boolean currentDecision;\n for (Decision current : this.decisions) {\n currentDecisionPrompt = current.getPrompt();\n currentDecision = LMOpenAI.decide(utterances, currentDecisionPrompt);\n if (!currentDecision) {\n return false;\n }\n }\n return true;\n }\n\n public void action(Utterances utterances) {\n Transition.LOGGER.warn(\"actions while transitioning to \" + this.subsequentState.getName());\n if (this.actions.isEmpty()) {\n Transition.LOGGER.warn(\"no action present\");\n return;\n }\n for (Action current : this.actions) {\n current.execute(utterances);\n }\n }\n\n @Override\n public String toString() {\n return \"Transition to \" + this.subsequentState + \" decided by \" + this.decisions + \" and affected by \"\n + this.actions;\n }\n}" }, { "identifier": "StaticExtractionAction", "path": "src/main/java/ch/zhaw/statefulconversation/model/commons/actions/StaticExtractionAction.java", "snippet": "@Entity\npublic class StaticExtractionAction extends Action {\n\n protected StaticExtractionAction() {\n\n }\n\n public StaticExtractionAction(String actionPrompt, Storage storage, String storageKeyTo) {\n super(actionPrompt, storage, storageKeyTo);\n }\n\n @Override\n public void execute(Utterances utterances) {\n JsonElement result = LMOpenAI.extract(utterances, this.getPrompt());\n this.getStorage().put(this.getStorageKeyTo(), result);\n }\n\n @Override\n public String toString() {\n return \"StaticExtractionAction IS-A \" + super.toString();\n }\n}" }, { "identifier": "StaticDecision", "path": "src/main/java/ch/zhaw/statefulconversation/model/commons/decisions/StaticDecision.java", "snippet": "@Entity\npublic class StaticDecision extends Decision {\n\n protected StaticDecision() {\n\n }\n\n public StaticDecision(String decisionPrompt) {\n super(decisionPrompt);\n }\n\n @Override\n public String toString() {\n return \"StaticDecision IS-A \" + super.toString();\n }\n}" }, { "identifier": "DynamicSingleChoiceState", "path": "src/main/java/ch/zhaw/statefulconversation/model/commons/states/DynamicSingleChoiceState.java", "snippet": "@Entity\npublic class DynamicSingleChoiceState extends State {\n\n private static final String SINGLECHOICE_PROMPT = \"Ask the user to choose one item out of the following list of items: \";\n private static final String SINGLECHOICE_STARTER_PROMPT = \"Ask the user.\";\n private static final String SINGLECHOICE_TRIGGER = \"Examine the following chat and decide if the user indicates one choice among the following choices: \";\n private static final String SINGLECHOICE_ACTION = \"Examine the following chat and extract extract the one choice the user made among the following choices: \";\n private static final String SUMMARISE_PROMPT = \"Please summarise the following conversation. Be concise, but ensure that the key points and issues are included. \";\n\n protected DynamicSingleChoiceState() {\n\n }\n\n public DynamicSingleChoiceState(String name, State subsequentState, Storage storage, String storageKeyFrom,\n String storageKeyTo) {\n this(name, subsequentState, storage, storageKeyFrom, storageKeyTo, true, false);\n }\n\n public DynamicSingleChoiceState(String name, State subsequentState, Storage storage, String storageKeyFrom,\n String storageKeyTo,\n boolean isStarting,\n boolean isOblivious) {\n super(DynamicSingleChoiceState.SINGLECHOICE_PROMPT + \"${\" + storageKeyFrom + \"}\",\n name,\n DynamicSingleChoiceState.SINGLECHOICE_STARTER_PROMPT,\n List.of(),\n SUMMARISE_PROMPT,\n isStarting,\n isOblivious,\n storage,\n List.of(storageKeyFrom));\n Decision trigger = new DynamicDecision(\n DynamicSingleChoiceState.SINGLECHOICE_TRIGGER + \"${\" + storageKeyFrom + \"}\", storage,\n storageKeyFrom);\n Action action = new DynamicExtractionAction(\n DynamicSingleChoiceState.SINGLECHOICE_ACTION + \"${\" + storageKeyFrom + \"}\", storage,\n storageKeyFrom, storageKeyTo);\n Transition transition = new Transition(List.of(trigger), List.of(action), subsequentState);\n this.addTransition(transition);\n }\n\n @Override\n protected String getPrompt() {\n Map<String, JsonElement> valuesForKeys = this.getValuesForKeys();\n if (!(valuesForKeys.values().iterator().next() instanceof JsonArray)) {\n throw new RuntimeException(\n \"expected storageKeyFrom being associated to a list (JsonArray) but enountered \"\n + valuesForKeys.values().iterator().next().getClass()\n + \" instead\");\n }\n\n return NamedParametersFormatter.format(super.getPrompt(), valuesForKeys);\n }\n\n @Override\n public String toString() {\n return \"DynamicSingleChoiceState IS-A \" + super.toString();\n }\n}" }, { "identifier": "EN_DynamicCauseAssessmentState", "path": "src/main/java/ch/zhaw/statefulconversation/model/commons/states/EN_DynamicCauseAssessmentState.java", "snippet": "@Entity\npublic class EN_DynamicCauseAssessmentState extends State {\n\n private static final String CAUSEASSESSMENT_PROMPT_PREFIX = \"Initiate a conversation to inquire about the patient's reasons for: \";\n private static final String CAUSEASSESSMENT_PROMPT_POSTFIX = \"Encourage them to openly discuss any obstacles they faced.\";\n private static final String CAUSEASSESSMENT_STARTER_PROMPT = \"Compose a single, very short message that the therapy coach would use to initiate the inquiry.\";\n private static final String CAUSEASSESSMENT_TRIGGER_PREFIX = \"Examine the following conversation and confirm that the patient has provided a reason for each one of: \";\n private static final String CAUSEASSESSMENT_TRIGGER_POSTFIX = \"Ensure the reasons provided are detailed enough to understand each one of the patient's specific barriers to adherence, allowing for a tailored suggestion to improve their commitment to the therapy plan.\";\n private static final String CAUSEASSESSMENT_GUARD_PREFIX = \"Review the conversation and verify whether the patient has articulated a clear and extractable reason for not adhering to: \";\n private static final String CAUSEASSESSMENT_GUARD_POSTFIX = \"The reason should be explicit enough to allow for an accurate GPT-based extraction and subsequent analysis.\";\n private static final String CAUSEASSESSMENT_ACTION_PREFIX = \"Identify and extract the specific reason the patient has given for not adhering to: \";\n private static final String CAUSEASSESSMENT_ACTION_POSTFIX = \"Respond with a JSON-Object with the format {reason: reason extracted}.\";\n private static final String SUMMARISE_PROMPT = \"Please summarise the following conversation. Be concise, but ensure that the key points and issues are included. \";\n\n protected EN_DynamicCauseAssessmentState() {\n\n }\n\n public EN_DynamicCauseAssessmentState(String name, State subsequentState, Storage storage,\n String storageKeyFrom,\n String storageKeyTo) {\n this(name, subsequentState, storage, storageKeyFrom, storageKeyTo, true, false);\n }\n\n public EN_DynamicCauseAssessmentState(String name, State subsequentState, Storage storage,\n String storageKeyFrom,\n String storageKeyTo,\n boolean isStarting,\n boolean isOblivious) {\n super(EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_PROMPT_PREFIX + \"${\" + storageKeyFrom + \"} \"\n + EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_PROMPT_POSTFIX,\n name,\n EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_STARTER_PROMPT,\n List.of(),\n SUMMARISE_PROMPT,\n isStarting,\n isOblivious,\n storage,\n List.of(storageKeyFrom));\n Decision trigger = new DynamicDecision(\n EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_TRIGGER_PREFIX + \"${\" + storageKeyFrom\n + \"}\"\n + EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_TRIGGER_POSTFIX,\n storage, storageKeyFrom);\n Decision guard = new DynamicDecision(\n EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_GUARD_PREFIX + \"${\" + storageKeyFrom\n + \"}\" + EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_GUARD_POSTFIX,\n storage, storageKeyFrom);\n Action action = new DynamicExtractionAction(\n EN_DynamicCauseAssessmentState.CAUSEASSESSMENT_ACTION_PREFIX + \"${\" + storageKeyFrom\n + \"} \"\n + CAUSEASSESSMENT_ACTION_POSTFIX,\n storage,\n storageKeyFrom,\n storageKeyTo);\n Transition transition = new Transition(List.of(trigger, guard), List.of(action), subsequentState);\n this.addTransition(transition);\n }\n\n public void setSubsequentState(State subsequentState) {\n List<Transition> transitions = this.getTransitions();\n if (transitions.size() != 1) {\n throw new RuntimeException(\"expected number of transitions to be 1 but encountered \"\n + transitions.size());\n }\n transitions.iterator().next().setSubsequenState(subsequentState);\n }\n\n @Override\n protected String getPrompt() {\n Map<String, JsonElement> valuesForKeys = this.getValuesForKeys();\n if (!(valuesForKeys.values().iterator().next() instanceof JsonArray)) {\n throw new RuntimeException(\n \"expected storageKeyFrom being associated to a list (JasonArray) but enountered \"\n + valuesForKeys.values().iterator().next().getClass()\n + \" instead\");\n }\n\n return NamedParametersFormatter.format(super.getPrompt(), valuesForKeys);\n }\n\n @Override\n public String toString() {\n return \"DynamicCauseAssessmentState IS-A \" + super.toString();\n }\n}" }, { "identifier": "AgentRepository", "path": "src/main/java/ch/zhaw/statefulconversation/repositories/AgentRepository.java", "snippet": "public interface AgentRepository extends JpaRepository<Agent, UUID> {\n\n}" } ]
import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.google.gson.Gson; import ch.zhaw.statefulconversation.model.Agent; import ch.zhaw.statefulconversation.model.Final; import ch.zhaw.statefulconversation.model.OuterState; import ch.zhaw.statefulconversation.model.State; import ch.zhaw.statefulconversation.model.Storage; import ch.zhaw.statefulconversation.model.Transition; import ch.zhaw.statefulconversation.model.commons.actions.StaticExtractionAction; import ch.zhaw.statefulconversation.model.commons.decisions.StaticDecision; import ch.zhaw.statefulconversation.model.commons.states.DynamicSingleChoiceState; import ch.zhaw.statefulconversation.model.commons.states.EN_DynamicCauseAssessmentState; import ch.zhaw.statefulconversation.repositories.AgentRepository;
7,520
package ch.zhaw.statefulconversation.paper; @SpringBootTest class MultiStateInteraction { private static final String PROMPT_THERAPYCOACH = """ As a digital therapy coach, your role is to support and enhance patient adherence to their therapy plans. Always respond with very brief, succinct answers, keeping them to a maximum of one or two sentences. """; private static final String PROMPT_THERAPYCOACH_TRIGGER = """ Review the patient's latest messages in the following conversation. Decide if there are any statements or cues suggesting they wish to pause or stop the conversation, such as explicit requests for a break, indications of needing time, or other phrases implying a desire to end the chat. """; private static final String PROMPT_THERAPYCOACH_GUARD = """ Examine the following conversation and confirm that the patient has not reported any issues like physical or mental discomfort that need addressing. """; private static final String PROMPT_THERAPYCOACH_ACTION = """ Summarize the coach-patient conversation, highlighting adherence to the therapy plan, issues reported, and suggestions for improvements accepted for the physician's review. """; @Autowired private AgentRepository repository; @Test void setUp() { String storageKeyFromActivityMissed = "ActivityMissed"; String storageKeyToReasonProvided = "ReasonProvided"; String storageKeyFromSuggestionsOffered = "SuggestionsOffered"; String storageKeyToSuggestionChosen = "SuggestionChosen"; Gson gson = new Gson(); Storage storage = new Storage(); storage.put(storageKeyFromActivityMissed, gson.toJsonTree(List.of("Patient missed 30 minutes of swimming yesterday evening."))); storage.put(storageKeyFromSuggestionsOffered, gson.toJsonTree(List.of( "Less Crowded Swim Sessions: Recommend that the patient look for less busy times to swim at the public pool.", "Alternative Water Exercises: Propose looking into water aerobics classes which often attract people of all body types, promoting a more inclusive and less self-conscious atmosphere.")));
package ch.zhaw.statefulconversation.paper; @SpringBootTest class MultiStateInteraction { private static final String PROMPT_THERAPYCOACH = """ As a digital therapy coach, your role is to support and enhance patient adherence to their therapy plans. Always respond with very brief, succinct answers, keeping them to a maximum of one or two sentences. """; private static final String PROMPT_THERAPYCOACH_TRIGGER = """ Review the patient's latest messages in the following conversation. Decide if there are any statements or cues suggesting they wish to pause or stop the conversation, such as explicit requests for a break, indications of needing time, or other phrases implying a desire to end the chat. """; private static final String PROMPT_THERAPYCOACH_GUARD = """ Examine the following conversation and confirm that the patient has not reported any issues like physical or mental discomfort that need addressing. """; private static final String PROMPT_THERAPYCOACH_ACTION = """ Summarize the coach-patient conversation, highlighting adherence to the therapy plan, issues reported, and suggestions for improvements accepted for the physician's review. """; @Autowired private AgentRepository repository; @Test void setUp() { String storageKeyFromActivityMissed = "ActivityMissed"; String storageKeyToReasonProvided = "ReasonProvided"; String storageKeyFromSuggestionsOffered = "SuggestionsOffered"; String storageKeyToSuggestionChosen = "SuggestionChosen"; Gson gson = new Gson(); Storage storage = new Storage(); storage.put(storageKeyFromActivityMissed, gson.toJsonTree(List.of("Patient missed 30 minutes of swimming yesterday evening."))); storage.put(storageKeyFromSuggestionsOffered, gson.toJsonTree(List.of( "Less Crowded Swim Sessions: Recommend that the patient look for less busy times to swim at the public pool.", "Alternative Water Exercises: Propose looking into water aerobics classes which often attract people of all body types, promoting a more inclusive and less self-conscious atmosphere.")));
State patientChoosesSuggestion = new DynamicSingleChoiceState("PatientChoosesSuggestion", new Final(),
3
2023-12-06 09:36:58+00:00
12k
SkyDynamic/QuickBackupM-Fabric
src/main/java/dev/skydynamic/quickbackupmulti/command/QuickBackupMultiCommand.java
[ { "identifier": "RestoreTask", "path": "src/main/java/dev/skydynamic/quickbackupmulti/backup/RestoreTask.java", "snippet": "public class RestoreTask extends TimerTask {\n\n private final EnvType env;\n private final List<ServerPlayerEntity> playerList;\n private final int slot;\n\n public RestoreTask(EnvType env, List<ServerPlayerEntity> playerList, int slot) {\n this.env = env;\n this.playerList = playerList;\n this.slot = slot;\n }\n\n @Override\n public void run() {\n QbDataHashMap.clear();\n if (env == EnvType.SERVER) {\n for (ServerPlayerEntity player : playerList) {\n player.networkHandler.disconnect(Text.of(\"Server restore backup\"));\n }\n Config.TEMP_CONFIG.setIsBackupValue(true);\n Config.TEMP_CONFIG.server.stop(true);\n } else {\n //不分到另一个class中执行 会找不到Screen然后炸(\n new ClientRestoreDelegate(playerList, slot).run();\n }\n }\n}" }, { "identifier": "LangSuggestionProvider", "path": "src/main/java/dev/skydynamic/quickbackupmulti/i18n/LangSuggestionProvider.java", "snippet": "public class LangSuggestionProvider implements SuggestionProvider<ServerCommandSource> {\n @Override\n public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) {\n for (String lang : Translate.supportLanguage) {\n builder.suggest(lang);\n }\n return builder.buildFuture();\n }\n}" }, { "identifier": "Translate", "path": "src/main/java/dev/skydynamic/quickbackupmulti/i18n/Translate.java", "snippet": "public class Translate {\n\n private static Map<String, String> translateMap = new HashMap<>();\n public static final Collection<String> supportLanguage = List.of(\"zh_cn\", \"en_us\");\n\n public static Map<String, String> getTranslationFromResourcePath(String lang) {\n InputStream langFile = Translate.class.getClassLoader().getResourceAsStream(\"assets/quickbackupmulti/lang/%s.yml\".formatted(lang));\n if (langFile == null) {\n return Collections.emptyMap();\n }\n String yamlData;\n try {\n yamlData = IOUtils.toString(langFile, StandardCharsets.UTF_8);\n } catch (IOException e) {\n return Collections.emptyMap();\n }\n Yaml yaml = new Yaml();\n Map<String, Object> obj = yaml.load(yamlData);\n return addMapToResult(\"\", obj);\n }\n\n public static void handleResourceReload(String lang) {\n translateMap = getTranslationFromResourcePath(lang);\n }\n\n public static String translate(String key, Object... args) {\n String fmt = translateMap.getOrDefault(key, key);\n if (!translateMap.containsKey(key)) return key;\n return String.format(fmt, args);\n }\n\n public static String tr(String k, Object... o) {\n return translate(k, o);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static Map<String, String> addMapToResult(String prefix, Map<String, Object> map) {\n Map<String, String> resultMap = new HashMap<>();\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n String newPrefix = prefix.isEmpty() ? key : prefix + \".\" + key;\n if (value instanceof Map) {\n resultMap.putAll(addMapToResult(newPrefix, (Map<String, Object>) value));\n } else {\n resultMap.put(newPrefix, value.toString());\n }\n }\n return resultMap;\n }\n\n}" }, { "identifier": "Messenger", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/Messenger.java", "snippet": "public class Messenger {\n\n public static void sendMessage(ServerCommandSource commandSource, Text text) {\n //#if MC>=11900\n commandSource.sendMessage(text);\n //#else\n //$$ commandSource.sendFeedback(text, false);\n //#endif\n }\n\n public static MutableText literal(String string) {\n //#if MC>=11900\n return Text.literal(string);\n //#else\n //$$ return new LiteralText(string);\n //#endif\n }\n\n}" }, { "identifier": "Config", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/config/Config.java", "snippet": "public class Config {\n public static QuickBackupMultiConfig INSTANCE = new QuickBackupMultiConfig();\n public static QbmTempConfig TEMP_CONFIG = new QbmTempConfig();\n}" }, { "identifier": "QbmManager", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/QbmManager.java", "snippet": "public class QbmManager {\n public static Path backupDir = Path.of(System.getProperty(\"user.dir\") + \"/QuickBackupMulti/\");\n public static Path savePath = Config.TEMP_CONFIG.server.getSavePath(WorldSavePath.ROOT);\n public static IOFileFilter fileFilter = new NotFileFilter(new NameFileFilter(Config.INSTANCE.getIgnoredFiles()));\n\n static Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();\n\n public static Path getBackupDir() {\n if (Config.TEMP_CONFIG.env == EnvType.SERVER) {\n return backupDir;\n } else {\n return backupDir.resolve(Config.TEMP_CONFIG.worldName);\n }\n }\n\n private static class SlotInfoStorage {\n String desc;\n long timestamp;\n\n public String getDesc() {\n return this.desc;\n }\n\n public long getTimestamp() {\n return this.timestamp;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getDesc(), getTimestamp());\n }\n }\n\n private static void writeBackupInfo(int slot, String desc) {\n try {\n ConcurrentHashMap<String, Object> data = new ConcurrentHashMap<>();\n data.put(\"desc\", desc);\n data.put(\"timestamp\", System.currentTimeMillis());\n var writer = new FileWriter(getBackupDir().resolve(\"Slot\" + slot + \"_info.json\").toFile());\n gson.toJson(data, writer);\n writer.close();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n }\n\n private static long getDirSize(File dir) {\n return FileUtils.sizeOf(dir);\n }\n\n private static boolean checkSlotExist(int slot) {\n return getBackupDir().resolve(\"Slot\" + slot + \"_info.json\").toFile().exists();\n }\n\n public static void restoreClient(int slot) {\n File targetBackupSlot = getBackupDir().resolve(\"Slot\" + slot).toFile();\n try {\n savePath.resolve(\"level.dat\").toFile().delete();\n savePath.resolve(\"level.dat_old\").toFile().delete();\n File[] fileList = savePath.toFile().listFiles((FilenameFilter) fileFilter);\n if (fileList != null) {\n Arrays.sort(fileList, ((o1, o2) -> {\n if (o1.isDirectory() && o2.isDirectory()) {\n return -1;\n } else if (!o1.isDirectory() && o2.isDirectory()) {\n return 1;\n } else {\n return o1.compareTo(o2);\n }\n }));\n for (File file : fileList) {\n FileUtils.forceDelete(file);\n }\n }\n FileUtils.copyDirectory(targetBackupSlot, savePath.toFile());\n } catch (IOException e) {\n restoreClient(slot);\n }\n }\n\n public static void restore(int slot) {\n File targetBackupSlot = getBackupDir().resolve(\"Slot\" + slot).toFile();\n try {\n// var it = Files.walk(savePath,5).sorted(Comparator.reverseOrder()).iterator();\n// while (it.hasNext()){\n// Files.delete(it.next());\n// }\n for (File file : Objects.requireNonNull(savePath.toFile().listFiles((FilenameFilter) fileFilter))) {\n FileUtils.forceDelete(file);\n }\n FileUtils.copyDirectory(targetBackupSlot, savePath.toFile());\n } catch (IOException e) {\n restore(slot);\n }\n }\n\n private static int getSlot(int slot) {\n if (slot == -1) {\n for (int j=1;j<=Config.INSTANCE.getNumOfSlot();j++) {\n if (!checkSlotExist(j)) {\n slot = j;\n break;\n }\n }\n if (slot == -1) slot = 1;\n }\n return slot;\n }\n\n public static boolean scheduleMake(ServerCommandSource commandSource, int slot) {\n slot = getSlot(slot);\n try {\n MinecraftServer server = commandSource.getServer();\n //#if MC>11800\n server.saveAll(true, true, true);\n //#else\n //$$ server.save(true, true, true);\n //#endif\n for (ServerWorld serverWorld : server.getWorlds()) {\n if (serverWorld == null || serverWorld.savingDisabled) continue;\n serverWorld.savingDisabled = true;\n }\n if (!getBackupDir().resolve(\"Slot\" + slot).toFile().exists()) getBackupDir().resolve(\"Slot\" + slot).toFile().mkdir();\n if (Objects.requireNonNull(getBackupDir().resolve(\"Slot\" + slot).toFile().listFiles()).length > 0) FileUtils.deleteDirectory(getBackupDir().resolve(\"Slot\" + slot).toFile());\n FileUtils.copyDirectory(savePath.toFile(), getBackupDir().resolve(\"Slot\" + slot).toFile(), fileFilter);\n writeBackupInfo(slot, \"Scheduled Backup\");\n for (ServerWorld serverWorld : server.getWorlds()) {\n if (serverWorld == null || !serverWorld.savingDisabled) continue;\n serverWorld.savingDisabled = false;\n }\n return true;\n } catch (IOException e) {\n return false;\n }\n }\n\n public static int make(ServerCommandSource commandSource, int slot, String desc) {\n long startTime = System.currentTimeMillis();\n slot = getSlot(slot);\n if (slot > Config.INSTANCE.getNumOfSlot() || slot < 1) {\n Messenger.sendMessage(commandSource, Text.of(tr(\"quickbackupmulti.make.no_slot\")));\n return 0;\n }\n try {\n Messenger.sendMessage(commandSource, Text.of(tr(\"quickbackupmulti.make.start\")));\n MinecraftServer server = commandSource.getServer();\n //#if MC>11800\n server.saveAll(true, true, true);\n //#else\n //$$ server.save(true, true, true);\n //#endif\n for (ServerWorld serverWorld : server.getWorlds()) {\n if (serverWorld == null || serverWorld.savingDisabled) continue;\n serverWorld.savingDisabled = true;\n }\n if (!getBackupDir().resolve(\"Slot\" + slot).toFile().exists()) getBackupDir().resolve(\"Slot\" + slot).toFile().mkdir();\n if (Objects.requireNonNull(getBackupDir().resolve(\"Slot\" + slot).toFile().listFiles()).length > 0) FileUtils.deleteDirectory(getBackupDir().resolve(\"Slot\" + slot).toFile());\n FileUtils.copyDirectory(savePath.toFile(), getBackupDir().resolve(\"Slot\" + slot).toFile(), fileFilter);\n long endTime = System.currentTimeMillis();\n double intervalTime = (endTime - startTime) / 1000.0;\n Messenger.sendMessage(commandSource, Text.of(tr(\"quickbackupmulti.make.success\", intervalTime)));\n writeBackupInfo(slot, desc);\n startSchedule(commandSource);\n for (ServerWorld serverWorld : server.getWorlds()) {\n if (serverWorld == null || !serverWorld.savingDisabled) continue;\n serverWorld.savingDisabled = false;\n }\n } catch (IOException e) {\n Messenger.sendMessage(commandSource, Text.of(tr(\"quickbackupmulti.make.fail\", e.getMessage())));\n }\n return 1;\n }\n\n public static MutableText list() {\n MutableText resultText = Messenger.literal(tr(\"quickbackupmulti.list_backup.title\"));\n long totalBackupSizeB = 0;\n for (int j=1;j<=Config.INSTANCE.getNumOfSlot();j++) {\n try {\n MutableText backText = Messenger.literal(\"§2[▷] \");\n MutableText deleteText = Messenger.literal(\"§c[×] \");\n var reader = new FileReader(getBackupDir().resolve(\"Slot\" + j + \"_info.json\").toFile());\n var result = gson.fromJson(reader, SlotInfoStorage.class);\n reader.close();\n int finalJ = j;\n backText.styled(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, \"/qb back \" + finalJ)))\n .styled(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.of(tr(\"quickbackupmulti.list_backup.slot.restore\", finalJ)))));\n deleteText.styled(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, \"/qb delete \" + finalJ)))\n .styled(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.of(tr(\"quickbackupmulti.list_backup.slot.delete\", finalJ)))));\n String desc = result.desc;\n if (Objects.equals(result.desc, \"\")) desc = tr(\"quickbackupmulti.empty_comment\");\n long backupSizeB = getDirSize(getBackupDir().resolve(\"Slot\" + j).toFile());\n totalBackupSizeB += backupSizeB;\n double backupSizeMB = (double) backupSizeB / FileUtils.ONE_MB;\n double backupSizeGB = (double) backupSizeB / FileUtils.ONE_GB;\n String sizeString = (backupSizeMB >= 1000) ? String.format(\"%.2fGB\", backupSizeGB) : String.format(\"%.2fMB\", backupSizeMB);\n resultText.append(\"\\n\" + tr(\"quickbackupmulti.list_backup.slot.header\", finalJ) + \" \")\n .append(backText)\n .append(deleteText)\n .append(\"§a\" + sizeString)\n .append(String.format(\" §b%s§7: §r%s\", new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\").format(result.timestamp), desc));\n } catch (IOException e) {\n resultText.append(\"\\n\"+ tr(\"quickbackupmulti.list_backup.slot.header\", j) + \" §2[▷] §c[×] §r\" + tr(\"quickbackupmulti.empty_comment\"));\n }\n }\n double totalBackupSizeMB = (double) totalBackupSizeB / FileUtils.ONE_MB;\n double totalBackupSizeGB = (double) totalBackupSizeB / FileUtils.ONE_GB;\n String sizeString = (totalBackupSizeMB >= 1000) ? String.format(\"%.2fGB\", totalBackupSizeGB) : String.format(\"%.2fMB\", totalBackupSizeMB);\n resultText.append(\"\\n\" + tr(\"quickbackupmulti.list_backup.slot.total_space\", sizeString));\n return resultText;\n }\n\n public static boolean delete(int slot) {\n if (getBackupDir().resolve(\"Slot\" + slot + \"_info.json\").toFile().exists() || getBackupDir().resolve(\"Slot\" + slot).toFile().exists()) {\n try {\n getBackupDir().resolve(\"Slot\" + slot + \"_info.json\").toFile().delete();\n FileUtils.deleteDirectory(getBackupDir().resolve(\"Slot\" + slot).toFile());\n return true;\n } catch (SecurityException | IOException e) {\n return false;\n }\n } else return false;\n }\n\n public static void createBackupDir(Path path) {\n if (!path.toFile().exists()) {\n LOGGER.info(tr(\"quickbackupmulti.init.start\"));\n path.toFile().mkdirs();\n LOGGER.info(tr(\"quickbackupmulti.init.finish\"));\n }\n for(int j = 1; j<= Config.INSTANCE.getNumOfSlot(); j++) {\n if (!path.resolve(\"Slot\" + j).toFile().exists()) path.resolve(\"Slot\" + j).toFile().mkdir();\n }\n }\n\n public static void startSchedule(ServerCommandSource commandSource) {\n String nextBackupTimeString = \"\";\n try {\n switch (Config.INSTANCE.getScheduleMode()) {\n case \"cron\" -> nextBackupTimeString = getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false);\n case \"interval\" -> nextBackupTimeString = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\").format(System.currentTimeMillis() + Config.INSTANCE.getScheduleInrerval() * 1000L);\n }\n buildScheduler();\n Config.TEMP_CONFIG.scheduler.start();\n Messenger.sendMessage(commandSource, Messenger.literal(tr(\"quickbackupmulti.schedule.enable.success\", nextBackupTimeString)));\n } catch (SchedulerException e) {\n Messenger.sendMessage(commandSource, Messenger.literal(tr(\"quickbackupmulti.schedule.enable.fail\", e)));\n }\n }\n}" }, { "identifier": "tr", "path": "src/main/java/dev/skydynamic/quickbackupmulti/i18n/Translate.java", "snippet": "public static String tr(String k, Object... o) {\n return translate(k, o);\n}" }, { "identifier": "CronUtil", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/schedule/CronUtil.java", "snippet": "public class CronUtil {\n\n public static Trigger buildTrigger() {\n try {\n if (Config.INSTANCE.getScheduleMode().equals(\"cron\")) {\n return TriggerBuilder.newTrigger()\n .withSchedule(CronScheduleBuilder.cronSchedule(Config.INSTANCE.getScheduleCron()))\n .startAt(new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\").parse(getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false)))\n .build();\n } else {\n return TriggerBuilder.newTrigger()\n .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(Config.INSTANCE.getScheduleInrerval()).repeatForever())\n .startAt(new Date(System.currentTimeMillis() + Config.INSTANCE.getScheduleInrerval() * 1000L))\n .build();\n }\n } catch (ParseException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void buildScheduler() {\n try {\n JobDetail jb = JobBuilder.newJob(ScheduleBackup.class).withIdentity(\"ScheduleBackup\").build();\n Trigger t = buildTrigger();\n StdSchedulerFactory sf = new StdSchedulerFactory();\n Config.TEMP_CONFIG.setScheduler(sf.getScheduler());\n Config.TEMP_CONFIG.scheduler.scheduleJob(jb, t);\n } catch (SchedulerException e) {\n LOGGER.error(e.toString());\n }\n }\n\n public static int getSeconds(int minute, int hour, int day) {\n return minute*60 + hour*3600 + day*3600*24;\n }\n\n public static String getNextExecutionTime(String cronExpress, boolean get) {\n CronExpression cronExpression;\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n try {\n cronExpression = new CronExpression(cronExpress);\n if (get) {\n return simpleDateFormat.format(cronExpression.getNextValidTimeAfter(new Date(Config.TEMP_CONFIG.latestScheduleExecuteTime)));\n }\n Date nextValidTime = cronExpression.getNextValidTimeAfter(new Date());\n return simpleDateFormat.format(nextValidTime);\n } catch (ParseException e) {\n return simpleDateFormat.format(new Date());\n }\n }\n\n public static boolean cronIsValid(String cronExpression) {\n try {\n new CronExpression(cronExpression);\n return true;\n } catch (Exception e) {\n return false;\n }\n }\n\n}" } ]
import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.tree.LiteralCommandNode; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import dev.skydynamic.quickbackupmulti.backup.RestoreTask; import dev.skydynamic.quickbackupmulti.i18n.LangSuggestionProvider; import dev.skydynamic.quickbackupmulti.i18n.Translate; import dev.skydynamic.quickbackupmulti.utils.Messenger; import net.fabricmc.api.EnvType; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.ClickEvent; import net.minecraft.text.HoverEvent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import dev.skydynamic.quickbackupmulti.utils.config.Config; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.List; import java.util.Timer; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static dev.skydynamic.quickbackupmulti.utils.QbmManager.*; import static dev.skydynamic.quickbackupmulti.i18n.Translate.tr; import static dev.skydynamic.quickbackupmulti.utils.schedule.CronUtil.*; import static net.minecraft.server.command.CommandManager.literal;
7,701
private static int enableScheduleBackup(ServerCommandSource commandSource) { try { Config.INSTANCE.setScheduleBackup(true); if (Config.TEMP_CONFIG.scheduler != null) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.enable.fail", e))); return 0; } } public static int getScheduleMode(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.schedule.mode.get", Config.INSTANCE.getScheduleMode()))); return 1; } public static int getNextBackupTime(ServerCommandSource commandSource) { if (Config.INSTANCE.getScheduleBackup()) { String nextBackupTimeString = ""; switch (Config.INSTANCE.getScheduleMode()) { case "cron" -> nextBackupTimeString = getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false); case "interval" -> nextBackupTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Config.TEMP_CONFIG.latestScheduleExecuteTime + Config.INSTANCE.getScheduleInrerval() * 1000L); } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get", nextBackupTimeString))); return 1; } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get_fail"))); return 0; } } private static int getLang(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.get", Config.INSTANCE.getLang()))); return 1; } private static int setLang(ServerCommandSource commandSource, String lang) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.set", lang))); Translate.handleResourceReload(lang); Config.INSTANCE.setLang(lang); return 1; } private static int makeSaveBackup(ServerCommandSource commandSource, int slot, String desc) { return make(commandSource, slot, desc); } private static int deleteSaveBackup(ServerCommandSource commandSource, int slot) { if (delete(slot)) Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.delete.success", slot))); else Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.delete.fail", slot))); return 1; } private static int restoreSaveBackup(ServerCommandSource commandSource, int slot) { if (!getBackupDir().resolve("Slot" + slot + "_info.json").toFile().exists()) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.fail"))); return 0; } ConcurrentHashMap<String, Object> restoreDataHashMap = new ConcurrentHashMap<>(); restoreDataHashMap.put("Slot", slot); restoreDataHashMap.put("Timer", new Timer()); restoreDataHashMap.put("Countdown", Executors.newSingleThreadScheduledExecutor()); synchronized (QbDataHashMap) { QbDataHashMap.put("QBM", restoreDataHashMap); Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.confirm_hint"))); return 1; } } //#if MC>11900 private static void executeRestore(ServerCommandSource commandSource) { //#else //$$ private static void executeRestore(ServerCommandSource commandSource) throws CommandSyntaxException { //#endif synchronized (QbDataHashMap) { if (QbDataHashMap.containsKey("QBM")) { if (!getBackupDir().resolve("Slot" + QbDataHashMap.get("QBM").get("Slot") + "_info.json").toFile().exists()) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.fail"))); QbDataHashMap.clear(); return; } EnvType env = FabricLoader.getInstance().getEnvironmentType(); String executePlayerName; if (commandSource.getPlayer() != null) { executePlayerName = commandSource.getPlayer().getGameProfile().getName(); } else { executePlayerName = "Console"; } Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.abort_hint"))); MinecraftServer server = commandSource.getServer(); for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) { player.sendMessage(Text.of(tr("quickbackupmulti.restore.countdown.intro", executePlayerName)), false); } int slot = (int) QbDataHashMap.get("QBM").get("Slot"); Config.TEMP_CONFIG.setBackupSlot(slot); Timer timer = (Timer) QbDataHashMap.get("QBM").get("Timer"); ScheduledExecutorService countdown = (ScheduledExecutorService) QbDataHashMap.get("QBM").get("Countdown"); AtomicInteger countDown = new AtomicInteger(11); final List<ServerPlayerEntity> playerList = server.getPlayerManager().getPlayerList(); countdown.scheduleAtFixedRate(() -> { int remaining = countDown.decrementAndGet(); if (remaining >= 1) { for (ServerPlayerEntity player : playerList) { //#if MC>11900 MutableText content = Messenger.literal(tr("quickbackupmulti.restore.countdown.text", remaining, slot)) //#else //$$ BaseText content = (BaseText) Messenger.literal(tr("quickbackupmulti.restore.countdown.text", remaining, slot)) //#endif .append(Messenger.literal(tr("quickbackupmulti.restore.countdown.hover")) .styled(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qb cancel"))) .styled(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.of(tr("quickbackupmulti.restore.countdown.hover")))))); player.sendMessage(content, false); logger.info(content.getString()); } } else { countdown.shutdown(); } }, 0, 1, TimeUnit.SECONDS);
package dev.skydynamic.quickbackupmulti.command; //#if MC<11900 //$$ import com.mojang.brigadier.exceptions.CommandSyntaxException; //#endif public class QuickBackupMultiCommand { private static final Logger logger = LoggerFactory.getLogger("Command"); public static void RegisterCommand(CommandDispatcher<ServerCommandSource> dispatcher) { LiteralCommandNode<ServerCommandSource> QuickBackupMultiShortCommand = dispatcher.register(literal("qb") .then(literal("list").executes(it -> listSaveBackups(it.getSource()))) .then(literal("make").requires(me -> me.hasPermissionLevel(2)) .executes(it -> makeSaveBackup(it.getSource(), -1, "")) .then(CommandManager.argument("slot", IntegerArgumentType.integer(1)) .executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), "")) .then(CommandManager.argument("desc", StringArgumentType.string()) .executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), StringArgumentType.getString(it, "desc")))) ) .then(CommandManager.argument("desc", StringArgumentType.string()) .executes(it -> makeSaveBackup(it.getSource(), -1, StringArgumentType.getString(it, "desc")))) ) .then(literal("back").requires(me -> me.hasPermissionLevel(2)) .executes(it -> restoreSaveBackup(it.getSource(), 1)) .then(CommandManager.argument("slot", IntegerArgumentType.integer(1)) .executes(it -> restoreSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"))))) .then(literal("confirm").requires(me -> me.hasPermissionLevel(2)) .executes(it -> { try { executeRestore(it.getSource()); } catch (Exception e) { e.printStackTrace(); } return 0; })) .then(literal("cancel").requires(me -> me.hasPermissionLevel(2)) .executes(it -> cancelRestore(it.getSource()))) .then(literal("delete").requires(me -> me.hasPermissionLevel(2)) .then(CommandManager.argument("slot", IntegerArgumentType.integer(1)) .executes(it -> deleteSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"))))) .then(literal("setting").requires(me -> me.hasPermissionLevel(2)) .then(literal("lang") .then(literal("get").executes(it -> getLang(it.getSource()))) .then(literal("set").requires(me -> me.hasPermissionLevel(2)) .then(CommandManager.argument("lang", StringArgumentType.string()) .suggests(new LangSuggestionProvider()) .executes(it -> setLang(it.getSource(), StringArgumentType.getString(it, "lang")))))) .then(literal("schedule") .then(literal("enable").executes(it -> enableScheduleBackup(it.getSource()))) .then(literal("disable").executes(it -> disableScheduleBackup(it.getSource()))) .then(literal("set") .then(literal("interval") .then(literal("second") .then(CommandManager.argument("second", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "second"), "s")) ) ).then(literal("minute") .then(CommandManager.argument("minute", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "minute"), "m")) ) ).then(literal("hour") .then(CommandManager.argument("hour", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "hour"), "h")) ) ).then(literal("day") .then(CommandManager.argument("day", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "day"), "d")) ) ) ) .then(literal("cron") .then(CommandManager.argument("cron", StringArgumentType.string()) .executes(it -> setScheduleCron(it.getSource(), StringArgumentType.getString(it, "cron"))))) .then(literal("mode") .then(literal("switch") .then(literal("interval") .executes(it -> switchMode(it.getSource(), "interval"))) .then(literal("cron") .executes(it -> switchMode(it.getSource(), "cron")))) .then(literal("get").executes(it -> getScheduleMode(it.getSource())))) ) .then(literal("get") .executes(it -> getNextBackupTime(it.getSource()))) ) ) ); dispatcher.register(literal("quickbackupm").redirect(QuickBackupMultiShortCommand)); } public static final ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> QbDataHashMap = new ConcurrentHashMap<>(); private static int switchMode(ServerCommandSource commandSource, String mode) { Config.INSTANCE.setScheduleMode(mode); try { if (Config.INSTANCE.getScheduleBackup()) { if (Config.TEMP_CONFIG.scheduler.isStarted()) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); } } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.switch.fail", e))); return 0; } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.switch.set", mode))); return 1; } private static int setScheduleCron(ServerCommandSource commandSource, String value) { try { if (cronIsValid(value)) { if (Config.TEMP_CONFIG.scheduler.isStarted()) Config.TEMP_CONFIG.scheduler.shutdown(); if (Config.INSTANCE.getScheduleBackup()) { Config.INSTANCE.setScheduleCron(value); startSchedule(commandSource); if (Config.INSTANCE.getScheduleMode().equals("cron")) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_custom_success", getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false)))); } } else { Config.INSTANCE.setScheduleCron(value); Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_custom_success_only"))); } } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.expression_error"))); return 0; } return 1; } catch (SchedulerException e) { return 0; } } private static int setScheduleInterval(ServerCommandSource commandSource, int value, String type) { try { Config.TEMP_CONFIG.scheduler.shutdown(); switch (type) { case "s" -> Config.INSTANCE.setScheduleInterval(value); case "m" -> Config.INSTANCE.setScheduleInterval(getSeconds(value, 0, 0)); case "h" -> Config.INSTANCE.setScheduleInterval(getSeconds(0, value, 0)); case "d" -> Config.INSTANCE.setScheduleInterval(getSeconds(0, 0, value)); } if (Config.INSTANCE.getScheduleBackup()) { startSchedule(commandSource); if (Config.INSTANCE.getScheduleMode().equals("interval")) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_success", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis() + Config.INSTANCE.getScheduleInrerval() * 1000L)))); } } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_success_only"))); } return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_fail", e))); return 0; } } private static int disableScheduleBackup(ServerCommandSource commandSource) { try { Config.TEMP_CONFIG.scheduler.shutdown(); Config.INSTANCE.setScheduleBackup(false); Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.disable.success"))); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.disable.fail", e))); return 0; } } private static int enableScheduleBackup(ServerCommandSource commandSource) { try { Config.INSTANCE.setScheduleBackup(true); if (Config.TEMP_CONFIG.scheduler != null) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.enable.fail", e))); return 0; } } public static int getScheduleMode(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.schedule.mode.get", Config.INSTANCE.getScheduleMode()))); return 1; } public static int getNextBackupTime(ServerCommandSource commandSource) { if (Config.INSTANCE.getScheduleBackup()) { String nextBackupTimeString = ""; switch (Config.INSTANCE.getScheduleMode()) { case "cron" -> nextBackupTimeString = getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false); case "interval" -> nextBackupTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Config.TEMP_CONFIG.latestScheduleExecuteTime + Config.INSTANCE.getScheduleInrerval() * 1000L); } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get", nextBackupTimeString))); return 1; } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get_fail"))); return 0; } } private static int getLang(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.get", Config.INSTANCE.getLang()))); return 1; } private static int setLang(ServerCommandSource commandSource, String lang) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.set", lang))); Translate.handleResourceReload(lang); Config.INSTANCE.setLang(lang); return 1; } private static int makeSaveBackup(ServerCommandSource commandSource, int slot, String desc) { return make(commandSource, slot, desc); } private static int deleteSaveBackup(ServerCommandSource commandSource, int slot) { if (delete(slot)) Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.delete.success", slot))); else Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.delete.fail", slot))); return 1; } private static int restoreSaveBackup(ServerCommandSource commandSource, int slot) { if (!getBackupDir().resolve("Slot" + slot + "_info.json").toFile().exists()) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.fail"))); return 0; } ConcurrentHashMap<String, Object> restoreDataHashMap = new ConcurrentHashMap<>(); restoreDataHashMap.put("Slot", slot); restoreDataHashMap.put("Timer", new Timer()); restoreDataHashMap.put("Countdown", Executors.newSingleThreadScheduledExecutor()); synchronized (QbDataHashMap) { QbDataHashMap.put("QBM", restoreDataHashMap); Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.confirm_hint"))); return 1; } } //#if MC>11900 private static void executeRestore(ServerCommandSource commandSource) { //#else //$$ private static void executeRestore(ServerCommandSource commandSource) throws CommandSyntaxException { //#endif synchronized (QbDataHashMap) { if (QbDataHashMap.containsKey("QBM")) { if (!getBackupDir().resolve("Slot" + QbDataHashMap.get("QBM").get("Slot") + "_info.json").toFile().exists()) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.fail"))); QbDataHashMap.clear(); return; } EnvType env = FabricLoader.getInstance().getEnvironmentType(); String executePlayerName; if (commandSource.getPlayer() != null) { executePlayerName = commandSource.getPlayer().getGameProfile().getName(); } else { executePlayerName = "Console"; } Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.restore.abort_hint"))); MinecraftServer server = commandSource.getServer(); for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) { player.sendMessage(Text.of(tr("quickbackupmulti.restore.countdown.intro", executePlayerName)), false); } int slot = (int) QbDataHashMap.get("QBM").get("Slot"); Config.TEMP_CONFIG.setBackupSlot(slot); Timer timer = (Timer) QbDataHashMap.get("QBM").get("Timer"); ScheduledExecutorService countdown = (ScheduledExecutorService) QbDataHashMap.get("QBM").get("Countdown"); AtomicInteger countDown = new AtomicInteger(11); final List<ServerPlayerEntity> playerList = server.getPlayerManager().getPlayerList(); countdown.scheduleAtFixedRate(() -> { int remaining = countDown.decrementAndGet(); if (remaining >= 1) { for (ServerPlayerEntity player : playerList) { //#if MC>11900 MutableText content = Messenger.literal(tr("quickbackupmulti.restore.countdown.text", remaining, slot)) //#else //$$ BaseText content = (BaseText) Messenger.literal(tr("quickbackupmulti.restore.countdown.text", remaining, slot)) //#endif .append(Messenger.literal(tr("quickbackupmulti.restore.countdown.hover")) .styled(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qb cancel"))) .styled(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.of(tr("quickbackupmulti.restore.countdown.hover")))))); player.sendMessage(content, false); logger.info(content.getString()); } } else { countdown.shutdown(); } }, 0, 1, TimeUnit.SECONDS);
timer.schedule(new RestoreTask(env, playerList, slot), 10000);
0
2023-12-09 13:51:17+00:00
12k
quentin452/Garden-Stuff-Continuation
src/main/java/com/jaquadro/minecraft/gardencore/core/ClientProxy.java
[ { "identifier": "CompostBinRenderer", "path": "src/main/java/com/jaquadro/minecraft/gardencore/client/renderer/CompostBinRenderer.java", "snippet": "public class CompostBinRenderer implements ISimpleBlockRenderingHandler {\n\n private ModularBoxRenderer boxRenderer = new ModularBoxRenderer();\n\n public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {\n if (block instanceof BlockCompostBin) {\n this.renderInventoryBlock((BlockCompostBin) block, metadata, modelId, renderer);\n }\n }\n\n private void renderInventoryBlock(BlockCompostBin block, int metadata, int modelId, RenderBlocks renderer) {\n GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);\n GL11.glTranslatef(-0.5F, -0.5F, -0.5F);\n this.boxRenderer.setUnit(0.0625D);\n this.boxRenderer.setColor(ModularBoxRenderer.COLOR_WHITE);\n this.boxRenderer.setCutIcon(block.getInnerIcon());\n\n for (int side = 0; side < 6; ++side) {\n this.boxRenderer.setExteriorIcon(block.getIcon(side, metadata), side);\n this.boxRenderer.setInteriorIcon(block.getIcon(side, metadata), side);\n }\n\n this.boxRenderer\n .renderBox((IBlockAccess) null, block, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D, 0, 2);\n this.boxRenderer.setUnit(0.0D);\n this.boxRenderer.setInteriorIcon(block.getIcon(1, metadata));\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.125D,\n 0.625D,\n 0.9375D,\n 0.875D,\n 0.75D,\n 1.0D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.125D,\n 0.25D,\n 0.9375D,\n 0.875D,\n 0.375D,\n 1.0D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.125D,\n 0.625D,\n 0.0D,\n 0.875D,\n 0.75D,\n 0.0625D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.125D,\n 0.25D,\n 0.0D,\n 0.875D,\n 0.375D,\n 0.0625D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.9375D,\n 0.625D,\n 0.125D,\n 1.0D,\n 0.75D,\n 0.875D,\n 0,\n 48);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.9375D,\n 0.25D,\n 0.125D,\n 1.0D,\n 0.375D,\n 0.875D,\n 0,\n 48);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.625D,\n 0.125D,\n 0.0625D,\n 0.75D,\n 0.875D,\n 0,\n 48);\n this.boxRenderer.renderInterior(\n (IBlockAccess) null,\n block,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.0D,\n 0.25D,\n 0.125D,\n 0.0625D,\n 0.375D,\n 0.875D,\n 0,\n 48);\n GL11.glTranslatef(0.5F, 0.5F, 0.5F);\n }\n\n public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId,\n RenderBlocks renderer) {\n return !(block instanceof BlockCompostBin) ? false\n : this.renderWorldBlock(world, x, y, z, (BlockCompostBin) block, modelId, renderer);\n }\n\n private boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, BlockCompostBin block, int modelId,\n RenderBlocks renderer) {\n Tessellator tessellator = Tessellator.instance;\n tessellator.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z));\n this.boxRenderer.setUnit(0.0625D);\n this.boxRenderer.setColor(ModularBoxRenderer.COLOR_WHITE);\n this.boxRenderer.setCutIcon(block.getInnerIcon());\n\n for (int side = 0; side < 6; ++side) {\n this.boxRenderer.setExteriorIcon(block.getIcon(world, x, y, z, side), side);\n this.boxRenderer.setInteriorIcon(block.getIcon(world, x, y, z, side), side);\n }\n\n this.boxRenderer\n .renderBox(world, block, (double) x, (double) y, (double) z, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D, 0, 2);\n this.boxRenderer.setUnit(0.0D);\n this.boxRenderer.setInteriorIcon(block.getIcon(world, x, y, z, 1));\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.125D,\n 0.625D,\n 0.9375D,\n 0.875D,\n 0.75D,\n 1.0D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.125D,\n 0.25D,\n 0.9375D,\n 0.875D,\n 0.375D,\n 1.0D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.125D,\n 0.625D,\n 0.0D,\n 0.875D,\n 0.75D,\n 0.0625D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.125D,\n 0.25D,\n 0.0D,\n 0.875D,\n 0.375D,\n 0.0625D,\n 0,\n 12);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.9375D,\n 0.625D,\n 0.125D,\n 1.0D,\n 0.75D,\n 0.875D,\n 0,\n 48);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.9375D,\n 0.25D,\n 0.125D,\n 1.0D,\n 0.375D,\n 0.875D,\n 0,\n 48);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.0D,\n 0.625D,\n 0.125D,\n 0.0625D,\n 0.75D,\n 0.875D,\n 0,\n 48);\n this.boxRenderer.renderInterior(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.0D,\n 0.25D,\n 0.125D,\n 0.0625D,\n 0.375D,\n 0.875D,\n 0,\n 48);\n TileEntityCompostBin te = (TileEntityCompostBin) world.getTileEntity(x, y, z);\n if (te != null) {\n if (te.hasInputItems()) {\n this.boxRenderer.setExteriorIcon(Blocks.dirt.getIcon(1, 2));\n this.boxRenderer.renderSolidBox(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.0625D,\n 0.0625D,\n 0.0625D,\n 0.9375D,\n 0.9375D,\n 0.9375D);\n } else if (te.hasOutputItems()) {\n this.boxRenderer.setExteriorIcon(ModBlocks.gardenSoil.getIcon(1, 0));\n this.boxRenderer.renderSolidBox(\n world,\n block,\n (double) x,\n (double) y,\n (double) z,\n 0.0625D,\n 0.0625D,\n 0.0625D,\n 0.9375D,\n 0.9375D,\n 0.9375D);\n }\n }\n\n return true;\n }\n\n public boolean shouldRender3DInInventory(int modelId) {\n return true;\n }\n\n public int getRenderId() {\n return 0;\n }\n}" }, { "identifier": "GardenProxyRenderer", "path": "src/main/java/com/jaquadro/minecraft/gardencore/client/renderer/GardenProxyRenderer.java", "snippet": "public class GardenProxyRenderer implements ISimpleBlockRenderingHandler {\n\n public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {}\n\n public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId,\n RenderBlocks renderer) {\n return !(block instanceof BlockGardenProxy) ? false\n : this.renderWorldBlock(world, x, y, z, (BlockGardenProxy) block, modelId, renderer);\n }\n\n public boolean shouldRender3DInInventory(int modelId) {\n return false;\n }\n\n public int getRenderId() {\n return ClientProxy.gardenProxyRenderID;\n }\n\n private boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, BlockGardenProxy block, int modelId,\n RenderBlocks renderer) {\n TileEntityGarden te = block.getGardenEntity(world, x, y, z);\n BlockGarden garden = block.getGardenBlock(world, x, y, z);\n if (te != null && garden != null) {\n int section = y - te.yCoord;\n Tessellator tessellator = Tessellator.instance;\n int[] var12 = garden.getSlotProfile()\n .getPlantSlots();\n int var13 = var12.length;\n\n for (int var14 = 0; var14 < var13; ++var14) {\n int slot = var12[var14];\n Block subBlock = block.getPlantBlockRestricted(te, slot);\n int subBlockData = block.getPlantData(te, slot);\n if (subBlock != null) {\n block.bindSlot(te.getWorldObj(), x, y, z, te, slot);\n float offsetX = block.getPlantOffsetX(world, x, y, z, slot);\n float offsetY = block.getPlantOffsetY(world, x, y, z, slot);\n float offsetZ = block.getPlantOffsetZ(world, x, y, z, slot);\n AxisAlignedBB[] clippingBounds = garden.getSlotProfile()\n .getClippingBounds(world, x, te.yCoord, z, slot);\n int color = subBlock.colorMultiplier(world, x, y, z);\n if (color == world.getBiomeGenForCoords(x, z)\n .getBiomeGrassColor(x, y, z)) {\n color = ColorizerGrass\n .getGrassColor((double) te.getBiomeTemperature(), (double) te.getBiomeHumidity());\n }\n\n float r = (float) (color >> 16 & 255) / 255.0F;\n float g = (float) (color >> 8 & 255) / 255.0F;\n float b = (float) (color & 255) / 255.0F;\n if (EntityRenderer.anaglyphEnable) {\n float gray = (r * 30.0F + g * 59.0F + b * 11.0F) / 100.0F;\n float ra = (r * 30.0F + g * 70.0F) / 100.0F;\n float ba = (r * 30.0F + b * 70.0F) / 100.0F;\n r = gray;\n g = ra;\n b = ba;\n }\n\n tessellator.setColorOpaque_F(r, g, b);\n tessellator.setBrightness(subBlock.getMixedBrightnessForBlock(renderer.blockAccess, x, y, z));\n tessellator.addTranslation(offsetX, offsetY, offsetZ);\n\n try {\n IPlantRenderer plantRenderer = PlantRegistry.instance()\n .getPlantRenderer(subBlock, subBlockData);\n if (plantRenderer != null) {\n IPlantMetaResolver resolver = PlantRegistry.instance()\n .getPlantMetaResolver(subBlock, subBlockData);\n boolean shouldRender = section == 1;\n if (resolver != null && section <= resolver.getPlantHeight(subBlock, subBlockData)) {\n shouldRender = true;\n }\n\n if (shouldRender) {\n plantRenderer\n .render(world, x, y, z, renderer, subBlock, subBlockData, section, clippingBounds);\n }\n } else {\n renderer.renderBlockByRenderType(subBlock, x, y, z);\n }\n } catch (Exception var32) {} finally {\n block.unbindSlot(te.getWorldObj(), x, y, z, te);\n tessellator.addTranslation(-offsetX, -offsetY, -offsetZ);\n }\n }\n }\n\n return true;\n } else {\n return true;\n }\n }\n\n private boolean renderCrossedSquares(IBlockAccess world, RenderBlocks renderer, Block block, int x, int y, int z,\n TileEntityGarden te) {\n Tessellator tessellator = Tessellator.instance;\n tessellator.setBrightness(block.getMixedBrightnessForBlock(renderer.blockAccess, x, y, z));\n int l = block.colorMultiplier(renderer.blockAccess, x, y, z);\n float f = (float) (l >> 16 & 255) / 255.0F;\n float f1 = (float) (l >> 8 & 255) / 255.0F;\n float f2 = (float) (l & 255) / 255.0F;\n if (EntityRenderer.anaglyphEnable) {\n float f3 = (f * 30.0F + f1 * 59.0F + f2 * 11.0F) / 100.0F;\n float f4 = (f * 30.0F + f1 * 70.0F) / 100.0F;\n float f5 = (f * 30.0F + f2 * 70.0F) / 100.0F;\n f = f3;\n f1 = f4;\n f2 = f5;\n }\n\n tessellator.setColorOpaque_F(f, f1, f2);\n double d1 = (double) x;\n double d2 = (double) y;\n double d0 = (double) z;\n IIcon iicon = renderer\n .getBlockIconFromSideAndMetadata(block, 0, renderer.blockAccess.getBlockMetadata(x, y, z));\n renderer.drawCrossedSquares(iicon, d1, d2, d0, 1.0F);\n return true;\n }\n\n private boolean renderBlockDoublePlant(IBlockAccess world, RenderBlocks renderer, BlockDoublePlant block, int x,\n int y, int z, TileEntityGarden potData) {\n Tessellator tessellator = Tessellator.instance;\n tessellator.setBrightness(block.getMixedBrightnessForBlock(renderer.blockAccess, x, y, z));\n int l = block.colorMultiplier(renderer.blockAccess, x, y, z);\n float f = (float) (l >> 16 & 255) / 255.0F;\n float f1 = (float) (l >> 8 & 255) / 255.0F;\n float f2 = (float) (l & 255) / 255.0F;\n if (EntityRenderer.anaglyphEnable) {\n float f3 = (f * 30.0F + f1 * 59.0F + f2 * 11.0F) / 100.0F;\n float f4 = (f * 30.0F + f1 * 70.0F) / 100.0F;\n float f5 = (f * 30.0F + f2 * 70.0F) / 100.0F;\n f = f3;\n f1 = f4;\n f2 = f5;\n }\n\n tessellator.setColorOpaque_F(f, f1, f2);\n long j1 = (long) (x * 3129871) ^ (long) z * 116129781L;\n j1 = j1 * j1 * 42317861L + j1 * 11L;\n double d19 = (double) x;\n double d0 = (double) y;\n double d1 = (double) z;\n int i1 = renderer.blockAccess.getBlockMetadata(x, y, z);\n boolean flag = false;\n boolean flag1 = BlockDoublePlant.func_149887_c(i1);\n int k1;\n if (flag1) {\n k1 = BlockDoublePlant.func_149890_d(renderer.blockAccess.getBlockMetadata(x, y - 1, z));\n } else {\n k1 = BlockDoublePlant.func_149890_d(i1);\n }\n\n IIcon iicon = block.func_149888_a(flag1, k1);\n renderer.drawCrossedSquares(iicon, d19, d0, d1, 1.0F);\n if (flag1 && k1 == 0) {\n IIcon iicon1 = block.sunflowerIcons[0];\n double d2 = Math.cos((double) j1 * 0.8D) * 3.141592653589793D * 0.1D;\n double d3 = Math.cos(d2);\n double d4 = Math.sin(d2);\n double d5 = (double) iicon1.getMinU();\n double d6 = (double) iicon1.getMinV();\n double d7 = (double) iicon1.getMaxU();\n double d8 = (double) iicon1.getMaxV();\n double d9 = 0.3D;\n double d10 = -0.05D;\n double d11 = 0.5D + 0.3D * d3 - 0.5D * d4;\n double d12 = 0.5D + 0.5D * d3 + 0.3D * d4;\n double d13 = 0.5D + 0.3D * d3 + 0.5D * d4;\n double d14 = 0.5D + -0.5D * d3 + 0.3D * d4;\n double d15 = 0.5D + -0.05D * d3 + 0.5D * d4;\n double d16 = 0.5D + -0.5D * d3 + -0.05D * d4;\n double d17 = 0.5D + -0.05D * d3 - 0.5D * d4;\n double d18 = 0.5D + 0.5D * d3 + -0.05D * d4;\n tessellator.addVertexWithUV(d19 + d15, d0 + 1.0D, d1 + d16, d5, d8);\n tessellator.addVertexWithUV(d19 + d17, d0 + 1.0D, d1 + d18, d7, d8);\n tessellator.addVertexWithUV(d19 + d11, d0 + 0.0D, d1 + d12, d7, d6);\n tessellator.addVertexWithUV(d19 + d13, d0 + 0.0D, d1 + d14, d5, d6);\n IIcon iicon2 = block.sunflowerIcons[1];\n d5 = (double) iicon2.getMinU();\n d6 = (double) iicon2.getMinV();\n d7 = (double) iicon2.getMaxU();\n d8 = (double) iicon2.getMaxV();\n tessellator.addVertexWithUV(d19 + d17, d0 + 1.0D, d1 + d18, d5, d8);\n tessellator.addVertexWithUV(d19 + d15, d0 + 1.0D, d1 + d16, d7, d8);\n tessellator.addVertexWithUV(d19 + d13, d0 + 0.0D, d1 + d14, d7, d6);\n tessellator.addVertexWithUV(d19 + d11, d0 + 0.0D, d1 + d12, d5, d6);\n }\n\n return true;\n }\n}" }, { "identifier": "SmallFireRenderer", "path": "src/main/java/com/jaquadro/minecraft/gardencore/client/renderer/SmallFireRenderer.java", "snippet": "public class SmallFireRenderer implements ISimpleBlockRenderingHandler {\n\n public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {}\n\n public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId,\n RenderBlocks renderer) {\n return block instanceof BlockSmallFire\n ? this.renderWorldBlock(world, x, y, z, (BlockSmallFire) block, modelId, renderer)\n : false;\n }\n\n private boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, BlockSmallFire block, int modelId,\n RenderBlocks renderer) {\n Tessellator tessellator = Tessellator.instance;\n IIcon icon0 = block.getFireIcon(0);\n IIcon icon1 = block.getFireIcon(1);\n IIcon icon2 = icon0;\n if (renderer.hasOverrideBlockTexture()) {\n icon2 = renderer.overrideBlockTexture;\n }\n\n tessellator.setColorOpaque_F(1.0F, 1.0F, 1.0F);\n tessellator.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z));\n double uMin = (double) icon2.getMinU();\n double vMin = (double) icon2.getMinV();\n double uMax = (double) icon2.getMaxU();\n double vMax = (double) icon2.getMaxV();\n double y0 = (double) y - 0.0625D;\n double y1 = (double) (y + 1);\n double x0 = (double) x + 0.5D + 0.2D;\n double x1 = (double) x + 0.5D - 0.2D;\n double x2 = (double) x + 0.5D - 0.3D;\n double x3 = (double) x + 0.5D + 0.3D;\n double z0 = (double) z + 0.5D + 0.2D;\n double z1 = (double) z + 0.5D - 0.2D;\n double z2 = (double) z + 0.5D - 0.3D;\n double z3 = (double) z + 0.5D + 0.3D;\n tessellator.addVertexWithUV(x2, y1, (double) ((float) (z + 1) - 0.0625F), uMax, vMin);\n tessellator.addVertexWithUV(x0, y0, (double) ((float) (z + 1) - 0.0625F), uMax, vMax);\n tessellator.addVertexWithUV(x0, y0, (double) ((float) (z + 0) + 0.0625F), uMin, vMax);\n tessellator.addVertexWithUV(x2, y1, (double) ((float) (z + 0) + 0.0625F), uMin, vMin);\n tessellator.addVertexWithUV(x3, y1, (double) ((float) (z + 0) + 0.0625F), uMax, vMin);\n tessellator.addVertexWithUV(x1, y0, (double) ((float) (z + 0) + 0.0625F), uMax, vMax);\n tessellator.addVertexWithUV(x1, y0, (double) ((float) (z + 1) - 0.0625F), uMin, vMax);\n tessellator.addVertexWithUV(x3, y1, (double) ((float) (z + 1) - 0.0625F), uMin, vMin);\n uMin = (double) icon1.getMinU();\n vMin = (double) icon1.getMinV();\n uMax = (double) icon1.getMaxU();\n vMax = (double) icon1.getMaxV();\n tessellator.addVertexWithUV((double) ((float) (x + 1) - 0.0625F), y1, z3, uMax, vMin);\n tessellator.addVertexWithUV((double) ((float) (x + 1) - 0.0625F), y0, z1, uMax, vMax);\n tessellator.addVertexWithUV((double) ((float) (x + 0) + 0.0625F), y0, z1, uMin, vMax);\n tessellator.addVertexWithUV((double) ((float) (x + 0) + 0.0625F), y1, z3, uMin, vMin);\n tessellator.addVertexWithUV((double) ((float) (x + 0) + 0.0625F), y1, z2, uMax, vMin);\n tessellator.addVertexWithUV((double) ((float) (x + 0) + 0.0625F), y0, z0, uMax, vMax);\n tessellator.addVertexWithUV((double) ((float) (x + 1) - 0.0625F), y0, z0, uMin, vMax);\n tessellator.addVertexWithUV((double) ((float) (x + 1) - 0.0625F), y1, z2, uMin, vMin);\n x0 = (double) x + 0.5D - 0.5D + 0.125D;\n x1 = (double) x + 0.5D + 0.5D - 0.125D;\n x2 = (double) x + 0.5D - 0.4D + 0.125D;\n x3 = (double) x + 0.5D + 0.4D - 0.125D;\n z0 = (double) z + 0.5D - 0.5D + 0.125D;\n z1 = (double) z + 0.5D + 0.5D - 0.125D;\n z2 = (double) z + 0.5D - 0.4D + 0.125D;\n z3 = (double) z + 0.5D + 0.4D - 0.125D;\n tessellator.addVertexWithUV(x2, y1, (double) (z + 0), uMax, vMin);\n tessellator.addVertexWithUV(x0, y0, (double) (z + 0), uMax, vMax);\n tessellator.addVertexWithUV(x0, y0, (double) (z + 1), uMin, vMax);\n tessellator.addVertexWithUV(x2, y1, (double) (z + 1), uMin, vMin);\n tessellator.addVertexWithUV(x3, y1, (double) (z + 1), uMax, vMin);\n tessellator.addVertexWithUV(x1, y0, (double) (z + 1), uMax, vMax);\n tessellator.addVertexWithUV(x1, y0, (double) (z + 0), uMin, vMax);\n tessellator.addVertexWithUV(x3, y1, (double) (z + 0), uMin, vMin);\n uMin = (double) icon0.getMinU();\n vMin = (double) icon0.getMinV();\n uMax = (double) icon0.getMaxU();\n vMax = (double) icon0.getMaxV();\n tessellator.addVertexWithUV((double) (x + 0), y1, z3, uMax, vMin);\n tessellator.addVertexWithUV((double) (x + 0), y0, z1, uMax, vMax);\n tessellator.addVertexWithUV((double) (x + 1), y0, z1, uMin, vMax);\n tessellator.addVertexWithUV((double) (x + 1), y1, z3, uMin, vMin);\n tessellator.addVertexWithUV((double) (x + 1), y1, z2, uMax, vMin);\n tessellator.addVertexWithUV((double) (x + 1), y0, z0, uMax, vMax);\n tessellator.addVertexWithUV((double) (x + 0), y0, z0, uMin, vMax);\n tessellator.addVertexWithUV((double) (x + 0), y1, z2, uMin, vMin);\n return true;\n }\n\n public boolean shouldRender3DInInventory(int modelId) {\n return false;\n }\n\n public int getRenderId() {\n return ClientProxy.smallFireRenderID;\n }\n}" } ]
import com.jaquadro.minecraft.gardencore.client.renderer.CompostBinRenderer; import com.jaquadro.minecraft.gardencore.client.renderer.GardenProxyRenderer; import com.jaquadro.minecraft.gardencore.client.renderer.SmallFireRenderer; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.client.registry.RenderingRegistry;
8,034
package com.jaquadro.minecraft.gardencore.core; public class ClientProxy extends CommonProxy { public static int renderPass = 0; public static int gardenProxyRenderID; public static int smallFireRenderID; public static int compostBinRenderID; public static ISimpleBlockRenderingHandler gardenProxyRenderer; public static ISimpleBlockRenderingHandler smallFireRenderer; public static ISimpleBlockRenderingHandler compostBinRenderer; public void registerRenderers() { gardenProxyRenderID = RenderingRegistry.getNextAvailableRenderId(); smallFireRenderID = RenderingRegistry.getNextAvailableRenderId(); compostBinRenderID = RenderingRegistry.getNextAvailableRenderId(); gardenProxyRenderer = new GardenProxyRenderer(); smallFireRenderer = new SmallFireRenderer();
package com.jaquadro.minecraft.gardencore.core; public class ClientProxy extends CommonProxy { public static int renderPass = 0; public static int gardenProxyRenderID; public static int smallFireRenderID; public static int compostBinRenderID; public static ISimpleBlockRenderingHandler gardenProxyRenderer; public static ISimpleBlockRenderingHandler smallFireRenderer; public static ISimpleBlockRenderingHandler compostBinRenderer; public void registerRenderers() { gardenProxyRenderID = RenderingRegistry.getNextAvailableRenderId(); smallFireRenderID = RenderingRegistry.getNextAvailableRenderId(); compostBinRenderID = RenderingRegistry.getNextAvailableRenderId(); gardenProxyRenderer = new GardenProxyRenderer(); smallFireRenderer = new SmallFireRenderer();
compostBinRenderer = new CompostBinRenderer();
0
2023-12-12 08:13:16+00:00
12k
Zergatul/java-scripting-language
src/main/java/com/zergatul/scripting/compiler/ScriptingLanguageCompiler.java
[ { "identifier": "BinaryOperation", "path": "src/main/java/com/zergatul/scripting/compiler/operations/BinaryOperation.java", "snippet": "public abstract class BinaryOperation {\r\n\r\n public abstract SType getType();\r\n public abstract void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException;\r\n\r\n public static final BinaryOperation BOOLEAN_OR_BOOLEAN = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(IOR);\r\n }\r\n };\r\n\r\n public static final BinaryOperation BOOLEAN_AND_BOOLEAN = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(IAND);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_ADD_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(IADD);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_SUBTRACT_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(ISUB);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_MULTIPLY_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(IMUL);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_DIVIDE_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(IDIV);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_MODULO_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(IREM);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_FLOORDIV_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n\r\n Method method;\r\n try {\r\n method = Math.class.getDeclaredMethod(\"floorDiv\", int.class, int.class);\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"Cannot find Math.floorDiv(int, int) method.\");\r\n }\r\n left.visitMethodInsn(\r\n INVOKESTATIC,\r\n Type.getInternalName(Math.class),\r\n method.getName(),\r\n Type.getMethodDescriptor(method),\r\n false);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_FLOORMOD_INT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n\r\n Method method;\r\n try {\r\n method = Math.class.getDeclaredMethod(\"floorMod\", int.class, int.class);\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"Cannot find Math.floorMod(int, int) method.\");\r\n }\r\n left.visitMethodInsn(\r\n INVOKESTATIC,\r\n Type.getInternalName(Math.class),\r\n method.getName(),\r\n Type.getMethodDescriptor(method),\r\n false);\r\n }\r\n };\r\n\r\n public static final BinaryOperation INT_LESS_INT = new IntCompare(IF_ICMPLT);\r\n\r\n public static final BinaryOperation INT_GREATER_INT = new IntCompare(IF_ICMPGT);\r\n\r\n public static final BinaryOperation INT_LESS_EQUALS_INT = new IntCompare(IF_ICMPLE);\r\n\r\n public static final BinaryOperation INT_GREATER_EQUALS_INT = new IntCompare(IF_ICMPGE);\r\n\r\n public static final BinaryOperation INT_EQUALS_INT = new IntCompare(IF_ICMPEQ);\r\n\r\n public static final BinaryOperation INT_NOT_EQUALS_INT = new IntCompare(IF_ICMPNE);\r\n\r\n public static final BinaryOperation FLOAT_ADD_FLOAT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(DADD);\r\n }\r\n };\r\n\r\n public static final BinaryOperation FLOAT_SUBTRACT_FLOAT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(DSUB);\r\n }\r\n };\r\n\r\n public static final BinaryOperation FLOAT_MULTIPLY_FLOAT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(DMUL);\r\n }\r\n };\r\n\r\n public static final BinaryOperation FLOAT_DIVIDE_FLOAT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(DDIV);\r\n }\r\n };\r\n\r\n public static final BinaryOperation FLOAT_MODULO_FLOAT = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n left.visitInsn(DREM);\r\n }\r\n };\r\n\r\n public static final BinaryOperation FLOAT_LESS_FLOAT = new FloatCompare(IF_ICMPLT);\r\n\r\n public static final BinaryOperation FLOAT_GREATER_FLOAT = new FloatCompare(IF_ICMPGT);\r\n\r\n public static final BinaryOperation FLOAT_LESS_EQUALS_FLOAT = new FloatCompare(IF_ICMPLE);\r\n\r\n public static final BinaryOperation FLOAT_GREATER_EQUALS_FLOAT = new FloatCompare(IF_ICMPGE);\r\n\r\n public static final BinaryOperation FLOAT_EQUALS_FLOAT = new FloatCompare(IF_ICMPEQ);\r\n\r\n public static final BinaryOperation FLOAT_NOT_EQUALS_FLOAT = new FloatCompare(IF_ICMPNE);\r\n\r\n public static final BinaryOperation INT_ADD_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_ADD_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_ADD_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_ADD_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_SUBTRACT_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_SUBTRACT_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_SUBTRACT_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_SUBTRACT_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_MULTIPLY_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_MULTIPLY_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_MULTIPLY_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_MULTIPLY_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_DIVIDE_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_DIVIDE_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_DIVIDE_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_DIVIDE_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_MODULO_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_MODULO_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_MODULO_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_MODULO_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_LESS_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_LESS_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_LESS_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_LESS_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_GREATER_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_GREATER_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_GREATER_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_GREATER_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_LESS_EQUALS_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_LESS_EQUALS_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_LESS_EQUALS_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_LESS_EQUALS_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_GREATER_EQUALS_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_GREATER_EQUALS_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_GREATER_EQUALS_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_GREATER_EQUALS_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_EQUALS_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_EQUALS_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_EQUALS_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_EQUALS_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation INT_NOT_EQUALS_FLOAT = new CombinedBinaryOperation(\r\n UnaryOperation.INT_TO_FLOAT,\r\n FLOAT_NOT_EQUALS_FLOAT,\r\n UnaryOperation.NONE);\r\n\r\n public static final BinaryOperation FLOAT_NOT_EQUALS_INT = new CombinedBinaryOperation(\r\n UnaryOperation.NONE,\r\n FLOAT_NOT_EQUALS_FLOAT,\r\n UnaryOperation.INT_TO_FLOAT);\r\n\r\n public static final BinaryOperation STRING_ADD_STRING = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SStringType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n Constructor<StringBuilder> constructor;\r\n try {\r\n constructor = StringBuilder.class.getConstructor();\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"ASTAdditiveExpression cannot find StringBuilder constructor.\");\r\n }\r\n\r\n left.visitTypeInsn(NEW, Type.getInternalName(StringBuilder.class));\r\n left.visitInsn(DUP);\r\n\r\n left.visitMethodInsn(\r\n INVOKESPECIAL,\r\n Type.getInternalName(StringBuilder.class),\r\n \"<init>\",\r\n Type.getConstructorDescriptor(constructor),\r\n false);\r\n\r\n left.visitInsn(SWAP);\r\n\r\n Method method;\r\n try {\r\n method = StringBuilder.class.getDeclaredMethod(\"append\", String.class);\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"ASTAdditiveExpression cannot find StringBuilder.list method.\");\r\n }\r\n\r\n left.visitMethodInsn(\r\n INVOKEVIRTUAL,\r\n Type.getInternalName(StringBuilder.class),\r\n method.getName(),\r\n Type.getMethodDescriptor(method),\r\n false);\r\n\r\n right.releaseBuffer(left);\r\n\r\n left.visitMethodInsn(\r\n INVOKEVIRTUAL,\r\n Type.getInternalName(StringBuilder.class),\r\n method.getName(),\r\n Type.getMethodDescriptor(method),\r\n false);\r\n\r\n try {\r\n method = StringBuilder.class.getDeclaredMethod(\"toString\");\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"ASTAdditiveExpression cannot find StringBuilder.toString method.\");\r\n }\r\n\r\n left.visitMethodInsn(\r\n INVOKEVIRTUAL,\r\n Type.getInternalName(StringBuilder.class),\r\n method.getName(),\r\n Type.getMethodDescriptor(method),\r\n false);\r\n }\r\n };\r\n\r\n public static final BinaryOperation STRING_EQUALS_STRING = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n\r\n Method equalsMethod;\r\n try {\r\n equalsMethod = Objects.class.getDeclaredMethod(\"equals\", Object.class, Object.class);\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"ASTEqualityExpression cannot find Objects.equals method.\");\r\n }\r\n\r\n left.visitMethodInsn(\r\n INVOKESTATIC,\r\n Type.getInternalName(Objects.class),\r\n equalsMethod.getName(),\r\n Type.getMethodDescriptor(equalsMethod),\r\n false);\r\n }\r\n };\r\n\r\n public static final BinaryOperation STRING_NOT_EQUALS_STRING = new BinaryOperation() {\r\n @Override\r\n public SType getType() {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n STRING_EQUALS_STRING.apply(left, right);\r\n UnaryOperation.NOT.apply(left);\r\n }\r\n };\r\n\r\n private static class IntCompare extends BinaryOperation {\r\n\r\n private final int opcode;\r\n\r\n public IntCompare(int opcode) {\r\n this.opcode = opcode;\r\n }\r\n\r\n @Override\r\n public SType getType() {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n Label elseLabel = new Label();\r\n Label endLabel = new Label();\r\n left.visitJumpInsn(opcode, elseLabel);\r\n left.visitInsn(ICONST_0);\r\n left.visitJumpInsn(GOTO, endLabel);\r\n left.visitLabel(elseLabel);\r\n left.visitInsn(ICONST_1);\r\n left.visitLabel(endLabel);\r\n }\r\n }\r\n\r\n private static class FloatCompare extends BinaryOperation {\r\n\r\n private final int opcode;\r\n\r\n public FloatCompare(int opcode) {\r\n this.opcode = opcode;\r\n }\r\n\r\n @Override\r\n public SType getType() {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor left, BufferVisitor right) throws ScriptCompileException {\r\n right.releaseBuffer(left);\r\n Label elseLabel = new Label();\r\n Label endLabel = new Label();\r\n left.visitInsn(DCMPG);\r\n left.visitInsn(ICONST_0);\r\n left.visitJumpInsn(opcode, elseLabel);\r\n left.visitInsn(ICONST_0);\r\n left.visitJumpInsn(GOTO, endLabel);\r\n left.visitLabel(elseLabel);\r\n left.visitInsn(ICONST_1);\r\n left.visitLabel(endLabel);\r\n }\r\n }\r\n}" }, { "identifier": "ImplicitCast", "path": "src/main/java/com/zergatul/scripting/compiler/operations/ImplicitCast.java", "snippet": "public class ImplicitCast {\r\n public static UnaryOperation get(SType source, SType destination) {\r\n if (source == SIntType.instance && destination == SFloatType.instance) {\r\n return UnaryOperation.INT_TO_FLOAT;\r\n }\r\n if (source == SIntType.instance && destination == SStringType.instance) {\r\n return UnaryOperation.INT_TO_STRING;\r\n }\r\n return null;\r\n }\r\n}" }, { "identifier": "UnaryOperation", "path": "src/main/java/com/zergatul/scripting/compiler/operations/UnaryOperation.java", "snippet": "public abstract class UnaryOperation {\r\n\r\n public abstract SType getType() throws ScriptCompileException;\r\n public abstract void apply(CompilerMethodVisitor visitor) throws ScriptCompileException;\r\n\r\n public static final UnaryOperation NONE = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n throw new ScriptCompileException(\"Should not be called.\");\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n\r\n }\r\n };\r\n\r\n public static final UnaryOperation PLUS_INT = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n\r\n }\r\n };\r\n\r\n public static final UnaryOperation PLUS_FLOAT = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n\r\n }\r\n };\r\n\r\n public static final UnaryOperation MINUS_INT = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n visitor.visitInsn(INEG);\r\n }\r\n };\r\n\r\n public static final UnaryOperation MINUS_FLOAT = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n visitor.visitInsn(DNEG);\r\n }\r\n };\r\n\r\n public static final UnaryOperation INT_TO_FLOAT = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SFloatType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) {\r\n visitor.visitInsn(I2D);\r\n }\r\n };\r\n\r\n public static final UnaryOperation INT_TO_STRING = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SIntType.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n Method method;\r\n try {\r\n method = Integer.class.getDeclaredMethod(\"toString\", int.class);\r\n } catch (NoSuchMethodException e) {\r\n throw new ScriptCompileException(\"Cannot find Integer.toString() method.\");\r\n }\r\n\r\n visitor.visitMethodInsn(\r\n INVOKESTATIC,\r\n Type.getInternalName(method.getDeclaringClass()),\r\n method.getName(),\r\n Type.getMethodDescriptor(method),\r\n false);\r\n }\r\n };\r\n\r\n public static final UnaryOperation NOT = new UnaryOperation() {\r\n @Override\r\n public SType getType() throws ScriptCompileException {\r\n return SBoolean.instance;\r\n }\r\n\r\n @Override\r\n public void apply(CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n Label elseLabel = new Label();\r\n Label endLabel = new Label();\r\n visitor.visitJumpInsn(IFNE, elseLabel);\r\n visitor.visitInsn(ICONST_1);\r\n visitor.visitJumpInsn(GOTO, endLabel);\r\n visitor.visitLabel(elseLabel);\r\n visitor.visitInsn(ICONST_0);\r\n visitor.visitLabel(endLabel);\r\n }\r\n };\r\n}" }, { "identifier": "FunctionEntry", "path": "src/main/java/com/zergatul/scripting/compiler/variables/FunctionEntry.java", "snippet": "public class FunctionEntry {\r\n\r\n private final String className;\r\n private final String identifier;\r\n private final SType[] parameters;\r\n private final SType returnType;\r\n\r\n public FunctionEntry(String className, String identifier, SType[] parameters, SType returnType) {\r\n this.className = className;\r\n this.identifier = identifier;\r\n this.parameters = parameters;\r\n this.returnType = returnType;\r\n }\r\n\r\n public String getClassName() {\r\n return className;\r\n }\r\n\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n public SType[] getParameters() {\r\n return parameters;\r\n }\r\n\r\n public SType getReturnType() {\r\n return returnType;\r\n }\r\n\r\n public String getDescriptor() {\r\n StringBuilder builder = new StringBuilder();\r\n builder.append('(');\r\n for (SType type : parameters) {\r\n builder.append(type.getDescriptor());\r\n }\r\n builder.append(')');\r\n builder.append(returnType.getDescriptor());\r\n return builder.toString();\r\n }\r\n}\r" }, { "identifier": "StaticVariableEntry", "path": "src/main/java/com/zergatul/scripting/compiler/variables/StaticVariableEntry.java", "snippet": "public class StaticVariableEntry extends VariableEntry {\r\n\r\n private final String className;\r\n private final String identifier;\r\n\r\n public StaticVariableEntry(SType type, String className, String identifier) {\r\n super(type);\r\n this.className = className;\r\n this.identifier = identifier;\r\n }\r\n\r\n public String getClassName() {\r\n return className;\r\n }\r\n\r\n public String getIdentifier() {\r\n return this.identifier;\r\n }\r\n\r\n @Override\r\n public void compileLoad(CompilerMethodVisitor visitor) {\r\n visitor.visitFieldInsn(\r\n GETSTATIC,\r\n className,\r\n identifier,\r\n Type.getDescriptor(type.getJavaClass()));\r\n }\r\n\r\n @Override\r\n public void compileStore(CompilerMethodVisitor visitor) {\r\n visitor.visitFieldInsn(\r\n PUTSTATIC,\r\n className,\r\n identifier,\r\n Type.getDescriptor(type.getJavaClass()));\r\n }\r\n\r\n @Override\r\n public void compileIncrement(CompilerMethodVisitor visitor, int value) {\r\n compileLoad(visitor);\r\n visitor.visitLdcInsn(value);\r\n visitor.visitInsn(IADD);\r\n compileStore(visitor);\r\n }\r\n}\r" }, { "identifier": "VariableContextStack", "path": "src/main/java/com/zergatul/scripting/compiler/variables/VariableContextStack.java", "snippet": "public class VariableContextStack {\r\n\r\n private final Map<String, StaticVariableEntry> staticVariables = new HashMap<>();\r\n private final Map<String, FunctionEntry> functions = new HashMap<>();\r\n private final Stack<VariableContext> stack = new Stack<>();\r\n private int index;\r\n\r\n public VariableContextStack(int initialLocalVarIndex) {\r\n index = initialLocalVarIndex;\r\n stack.add(new VariableContext(index));\r\n }\r\n\r\n public LocalVariableEntry addLocal(String identifier, SType type) throws ScriptCompileException {\r\n if (identifier != null) {\r\n checkIdentifier(identifier);\r\n }\r\n\r\n LocalVariableEntry entry = new LocalVariableEntry(type, index);\r\n stack.peek().add(identifier, entry);\r\n\r\n if (type == SFloatType.instance) {\r\n index += 2;\r\n } else {\r\n index += 1;\r\n }\r\n\r\n return entry;\r\n }\r\n\r\n public StaticVariableEntry addStatic(String identifier, SType type, String className) throws ScriptCompileException {\r\n if (identifier == null) {\r\n throw new ScriptCompileException(\"Identifier is required.\");\r\n }\r\n\r\n if (staticVariables.containsKey(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Static variable %s is already declared.\", identifier));\r\n }\r\n\r\n StaticVariableEntry entry = new StaticVariableEntry(type, className, identifier);\r\n staticVariables.put(identifier, entry);\r\n return entry;\r\n }\r\n\r\n public void addFunction(String identifier, SType returnType, SType[] arguments, String className) throws ScriptCompileException {\r\n if (identifier == null) {\r\n throw new ScriptCompileException(\"Identifier is required.\");\r\n }\r\n\r\n if (staticVariables.containsKey(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Cannot declare function with the same name as static variable %s.\", identifier));\r\n }\r\n\r\n if (functions.containsKey(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Function %s is already declared.\", identifier));\r\n }\r\n\r\n FunctionEntry entry = new FunctionEntry(className, identifier, arguments, returnType);\r\n functions.put(identifier, entry);\r\n }\r\n\r\n public void begin() {\r\n stack.add(new VariableContext(index));\r\n }\r\n\r\n public void end() {\r\n index = stack.pop().getStartIndex();\r\n }\r\n\r\n public VariableEntry get(String identifier) {\r\n for (int i = stack.size() - 1; i >= 0; i--) {\r\n VariableEntry entry = stack.get(i).get(identifier);\r\n if (entry != null) {\r\n return entry;\r\n }\r\n }\r\n\r\n if (staticVariables.containsKey(identifier)) {\r\n return staticVariables.get(identifier);\r\n }\r\n\r\n return null;\r\n }\r\n\r\n public FunctionEntry getFunction(String identifier) {\r\n return functions.get(identifier);\r\n }\r\n\r\n public Collection<StaticVariableEntry> getStaticVariables() {\r\n return staticVariables.values();\r\n }\r\n\r\n public VariableContextStack newWithStaticVariables(int initialLocalVarIndex) {\r\n VariableContextStack context = new VariableContextStack(initialLocalVarIndex);\r\n for (StaticVariableEntry entry : staticVariables.values()) {\r\n context.staticVariables.put(entry.getIdentifier(), entry);\r\n }\r\n for (FunctionEntry entry : functions.values()) {\r\n context.functions.put(entry.getIdentifier(), entry);\r\n }\r\n return context;\r\n }\r\n\r\n private void checkIdentifier(String identifier) throws ScriptCompileException {\r\n for (int i = stack.size() - 1; i >= 0; i--) {\r\n if (stack.get(i).contains(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Identifier %s is already declared.\", identifier));\r\n }\r\n }\r\n }\r\n}" }, { "identifier": "VariableEntry", "path": "src/main/java/com/zergatul/scripting/compiler/variables/VariableEntry.java", "snippet": "public abstract class VariableEntry {\r\n\r\n protected final SType type;\r\n\r\n protected VariableEntry(SType type) {\r\n this.type = type;\r\n }\r\n\r\n public SType getType() {\r\n return type;\r\n }\r\n\r\n public abstract void compileLoad(CompilerMethodVisitor visitor);\r\n public abstract void compileStore(CompilerMethodVisitor visitor);\r\n public abstract void compileIncrement(CompilerMethodVisitor visitor, int value);\r\n}" } ]
import com.zergatul.scripting.compiler.operations.BinaryOperation; import com.zergatul.scripting.compiler.operations.ImplicitCast; import com.zergatul.scripting.compiler.operations.UnaryOperation; import com.zergatul.scripting.compiler.types.*; import com.zergatul.scripting.compiler.variables.FunctionEntry; import com.zergatul.scripting.compiler.variables.StaticVariableEntry; import com.zergatul.scripting.compiler.variables.VariableContextStack; import com.zergatul.scripting.compiler.variables.VariableEntry; import com.zergatul.scripting.generated.*; import org.objectweb.asm.*; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Parameter; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static org.objectweb.asm.Opcodes.*;
8,137
consumer.apply(writer, constructorVisitorWrapper, runVisitorWrapper); constructorVisitor.visitInsn(RETURN); constructorVisitor.visitMaxs(0, 0); constructorVisitor.visitEnd(); runVisitor.visitInsn(RETURN); runVisitor.visitMaxs(0, 0); runVisitor.visitEnd(); for (StaticVariableEntry entry : runVisitorWrapper.getContextStack().getStaticVariables()) { if (entry.getClassName().equals(name)) { FieldVisitor fieldVisitor = writer.visitField( ACC_PUBLIC | ACC_STATIC, entry.getIdentifier(), Type.getDescriptor(entry.getType().getJavaClass()), null, null); fieldVisitor.visitEnd(); } } writer.visitEnd(); byte[] code = writer.toByteArray(); return (Class<Runnable>) classLoader.defineClass(name.replace('/', '.'), code); } private void compile( ASTInput input, ClassWriter classWriter, CompilerMethodVisitor constructorVisitor, CompilerMethodVisitor runVisitor ) throws ScriptCompileException { if (input.jjtGetNumChildren() < 2) { throw new ScriptCompileException("ASTInput: num children < 2."); } if (!(input.jjtGetChild(0) instanceof ASTStaticVariablesList variablesList)) { throw new ScriptCompileException("ASTInput: static vars list expected."); } if (!(input.jjtGetChild(1) instanceof ASTFunctionsList functionsList)) { throw new ScriptCompileException("ASTInput: functions list expected."); } compile(variablesList, constructorVisitor); compile(functionsList, classWriter, constructorVisitor); for (int i = 2; i < input.jjtGetNumChildren(); i++) { if (!(input.jjtGetChild(i) instanceof ASTStatement statement)) { throw new ScriptCompileException("ASTInput statement expected."); } compile(statement, runVisitor); } } private void compile(ASTStaticVariablesList list, CompilerMethodVisitor visitor) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTStaticVariableDeclaration variableDeclaration)) { throw new ScriptCompileException("ASTStaticVariablesList declaration expected."); } compile(variableDeclaration, visitor); } } private void compile( ASTFunctionsList list, ClassWriter classWriter, CompilerMethodVisitor visitor ) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTFunctionDeclaration functionDeclaration)) { throw new ScriptCompileException("ASTFunctionsList: declaration expected."); } SType type = getFunctionReturnType(functionDeclaration); ASTIdentifier identifier = getFunctionIdentifier(functionDeclaration); List<FunctionParameter> parameters = getFunctionParameters(functionDeclaration); String name = (String) identifier.jjtGetValue(); visitor.getContextStack().addFunction( name, type, parameters.stream().map(p -> p.type).toArray(SType[]::new), visitor.getClassName()); } for (int i = 0; i < list.jjtGetNumChildren(); i++) { compile( (ASTFunctionDeclaration) list.jjtGetChild(i), classWriter, visitor.getContextStack().newWithStaticVariables(0)); } } private void compile(ASTStaticVariableDeclaration declaration, CompilerMethodVisitor visitor) throws ScriptCompileException { if (declaration.jjtGetNumChildren() != 1) { throw new ScriptCompileException("Invalid static var decl structure."); } Node node = declaration.jjtGetChild(0); if (!(node instanceof ASTLocalVariableDeclaration localVariableDeclaration)) { throw new ScriptCompileException("ASTLocalVariableDeclaration expected."); } ASTType astType = (ASTType) localVariableDeclaration.jjtGetChild(0); ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) localVariableDeclaration.jjtGetChild(1); ASTVariableDeclaratorId variableDeclaratorId = (ASTVariableDeclaratorId) variableDeclarator.jjtGetChild(0); ASTIdentifier identifier = (ASTIdentifier) variableDeclaratorId.jjtGetChild(0); ASTVariableInitializer initializer = null; if (variableDeclarator.jjtGetNumChildren() > 1) { initializer = (ASTVariableInitializer) variableDeclarator.jjtGetChild(1); } SType type = parseType(astType); if (initializer != null) { SType returnType = compile((ASTExpression) initializer.jjtGetChild(0), visitor); if (!returnType.equals(type)) {
package com.zergatul.scripting.compiler; public class ScriptingLanguageCompiler { private static AtomicInteger counter = new AtomicInteger(0); private static ScriptingClassLoader classLoader = new ScriptingClassLoader(); private final Class<?> root; private final MethodVisibilityChecker visibilityChecker; public ScriptingLanguageCompiler(Class<?> root) { this(root, new MethodVisibilityChecker()); } public ScriptingLanguageCompiler(Class<?> root, MethodVisibilityChecker visibilityChecker) { this.root = root; this.visibilityChecker = visibilityChecker; } public Runnable compile(String program) throws ParseException, ScriptCompileException { program += "\r\n"; // temp fix for error if last token is comment InputStream stream = new ByteArrayInputStream(program.getBytes(StandardCharsets.UTF_8)); ScriptingLanguage parser = new ScriptingLanguage(stream); ASTInput input = parser.Input(); Class<Runnable> dynamic = compileRunnable((cw, v1, v2) -> { compile(input, cw, v1, v2); }); Constructor<Runnable> constructor; try { constructor = dynamic.getConstructor(); } catch (NoSuchMethodException e) { throw new ScriptCompileException("Cannot find constructor for dynamic class."); } Runnable instance; try { instance = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new ScriptCompileException("Cannot instantiate dynamic class."); } return instance; } private Class<Runnable> compileRunnable(CompileConsumer consumer) throws ScriptCompileException { // since this is instance method, local vars start from 1 // 0 = this return compileRunnable(consumer, new VariableContextStack(1)); } @SuppressWarnings("unchecked") private Class<Runnable> compileRunnable(CompileConsumer consumer, VariableContextStack context) throws ScriptCompileException { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); String name = "com/zergatul/scripting/dynamic/DynamicClass_" + counter.incrementAndGet(); writer.visit(V1_5, ACC_PUBLIC, name, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(Runnable.class) }); MethodVisitor constructorVisitor = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); constructorVisitor.visitCode(); constructorVisitor.visitVarInsn(ALOAD, 0); constructorVisitor.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); MethodVisitor runVisitor = writer.visitMethod(ACC_PUBLIC, "run", "()V", null, null); runVisitor.visitCode(); MethodVisitorWrapper constructorVisitorWrapper = new MethodVisitorWrapper(constructorVisitor, name, context); MethodVisitorWrapper runVisitorWrapper = new MethodVisitorWrapper(runVisitor, name, context); runVisitorWrapper.getLoops().push( v -> { throw new ScriptCompileException("Continue statement without loop."); }, v -> { throw new ScriptCompileException("Break statement without loop."); }); consumer.apply(writer, constructorVisitorWrapper, runVisitorWrapper); constructorVisitor.visitInsn(RETURN); constructorVisitor.visitMaxs(0, 0); constructorVisitor.visitEnd(); runVisitor.visitInsn(RETURN); runVisitor.visitMaxs(0, 0); runVisitor.visitEnd(); for (StaticVariableEntry entry : runVisitorWrapper.getContextStack().getStaticVariables()) { if (entry.getClassName().equals(name)) { FieldVisitor fieldVisitor = writer.visitField( ACC_PUBLIC | ACC_STATIC, entry.getIdentifier(), Type.getDescriptor(entry.getType().getJavaClass()), null, null); fieldVisitor.visitEnd(); } } writer.visitEnd(); byte[] code = writer.toByteArray(); return (Class<Runnable>) classLoader.defineClass(name.replace('/', '.'), code); } private void compile( ASTInput input, ClassWriter classWriter, CompilerMethodVisitor constructorVisitor, CompilerMethodVisitor runVisitor ) throws ScriptCompileException { if (input.jjtGetNumChildren() < 2) { throw new ScriptCompileException("ASTInput: num children < 2."); } if (!(input.jjtGetChild(0) instanceof ASTStaticVariablesList variablesList)) { throw new ScriptCompileException("ASTInput: static vars list expected."); } if (!(input.jjtGetChild(1) instanceof ASTFunctionsList functionsList)) { throw new ScriptCompileException("ASTInput: functions list expected."); } compile(variablesList, constructorVisitor); compile(functionsList, classWriter, constructorVisitor); for (int i = 2; i < input.jjtGetNumChildren(); i++) { if (!(input.jjtGetChild(i) instanceof ASTStatement statement)) { throw new ScriptCompileException("ASTInput statement expected."); } compile(statement, runVisitor); } } private void compile(ASTStaticVariablesList list, CompilerMethodVisitor visitor) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTStaticVariableDeclaration variableDeclaration)) { throw new ScriptCompileException("ASTStaticVariablesList declaration expected."); } compile(variableDeclaration, visitor); } } private void compile( ASTFunctionsList list, ClassWriter classWriter, CompilerMethodVisitor visitor ) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTFunctionDeclaration functionDeclaration)) { throw new ScriptCompileException("ASTFunctionsList: declaration expected."); } SType type = getFunctionReturnType(functionDeclaration); ASTIdentifier identifier = getFunctionIdentifier(functionDeclaration); List<FunctionParameter> parameters = getFunctionParameters(functionDeclaration); String name = (String) identifier.jjtGetValue(); visitor.getContextStack().addFunction( name, type, parameters.stream().map(p -> p.type).toArray(SType[]::new), visitor.getClassName()); } for (int i = 0; i < list.jjtGetNumChildren(); i++) { compile( (ASTFunctionDeclaration) list.jjtGetChild(i), classWriter, visitor.getContextStack().newWithStaticVariables(0)); } } private void compile(ASTStaticVariableDeclaration declaration, CompilerMethodVisitor visitor) throws ScriptCompileException { if (declaration.jjtGetNumChildren() != 1) { throw new ScriptCompileException("Invalid static var decl structure."); } Node node = declaration.jjtGetChild(0); if (!(node instanceof ASTLocalVariableDeclaration localVariableDeclaration)) { throw new ScriptCompileException("ASTLocalVariableDeclaration expected."); } ASTType astType = (ASTType) localVariableDeclaration.jjtGetChild(0); ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) localVariableDeclaration.jjtGetChild(1); ASTVariableDeclaratorId variableDeclaratorId = (ASTVariableDeclaratorId) variableDeclarator.jjtGetChild(0); ASTIdentifier identifier = (ASTIdentifier) variableDeclaratorId.jjtGetChild(0); ASTVariableInitializer initializer = null; if (variableDeclarator.jjtGetNumChildren() > 1) { initializer = (ASTVariableInitializer) variableDeclarator.jjtGetChild(1); } SType type = parseType(astType); if (initializer != null) { SType returnType = compile((ASTExpression) initializer.jjtGetChild(0), visitor); if (!returnType.equals(type)) {
UnaryOperation operation = ImplicitCast.get(returnType, type);
1
2023-12-10 00:37:27+00:00
12k
Lampadina17/MorpheusLauncher
src/team/morpheus/launcher/instance/Morpheus.java
[ { "identifier": "Launcher", "path": "src/team/morpheus/launcher/Launcher.java", "snippet": "public class Launcher {\r\n\r\n private static final MyLogger log = new MyLogger(Launcher.class);\r\n public JSONParser jsonParser = new JSONParser();\r\n private File gameFolder, assetsFolder;\r\n\r\n private MojangProduct vanilla;\r\n private MojangProduct.Version target;\r\n\r\n private MojangProduct.Game game; // Vanilla / Optifine / Fabric / Forge\r\n private MojangProduct.Game inherited; // just Vanilla (is parent of modloader)\r\n\r\n public Launcher(String mcVersion, MorpheusProduct product, boolean isModded) throws Exception {\r\n boolean isLatestVersion = false;\r\n try {\r\n /* Get all versions from mojang */\r\n vanilla = retrieveVersions();\r\n\r\n /* Find version by name gave by user */\r\n String targetName = mcVersion;\r\n\r\n if (mcVersion.equalsIgnoreCase(\"latest\")) {\r\n targetName = vanilla.latest.release;\r\n isLatestVersion = true;\r\n }\r\n if (mcVersion.equalsIgnoreCase(\"snapshot\")) {\r\n targetName = vanilla.latest.snapshot;\r\n isLatestVersion = true;\r\n }\r\n\r\n target = findVersion(vanilla, targetName);\r\n } catch (Exception e) {\r\n log.error(\"Cannot download/parse mojang versions json\");\r\n }\r\n\r\n // Make .minecraft/\r\n gameFolder = makeDirectory(OSUtils.getWorkingDirectory(\"minecraft\").getPath());\r\n\r\n // Make .minecraft/assets/\r\n assetsFolder = makeDirectory(String.format(\"%s/assets\", gameFolder.getPath()));\r\n\r\n // Make .minecraft/versions/<gameVersion>\r\n File versionPath = makeDirectory(String.format(\"%s/versions/%s\", gameFolder.getPath(), mcVersion));\r\n\r\n // Download json to .minecraft/versions/<gameVersion>/<gameVersion.json\r\n File jsonFile = new File(String.format(\"%s/%s.json\", versionPath.getPath(), mcVersion));\r\n if (target != null && target.url != null) {\r\n /* Extract json file hash from download url */\r\n String jsonHash = target.url.substring(target.url.lastIndexOf(\"/\") - 40, target.url.lastIndexOf(\"/\"));\r\n\r\n /* if the json doesn't exist or its hash is invalidated, download from mojang repo */\r\n /* isLatestVersion is put to skip sha check when \"latest\" or \"snapshot\" is used */\r\n if (!jsonFile.exists() || jsonFile.exists() && !jsonHash.equals(CryptoEngine.fileHash(jsonFile, \"SHA-1\")) || isLatestVersion) {\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(target.url), jsonFile.getPath()));\r\n tasks.go();\r\n }\r\n\r\n /* overwrites id field in json to get better recognition by gui */\r\n if (isLatestVersion) {\r\n FileReader reader = new FileReader(jsonFile);\r\n JSONParser jsonParser = new JSONParser();\r\n JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);\r\n jsonObject.replace(\"id\", jsonObject.get(\"id\"), mcVersion);\r\n FileWriter writer = new FileWriter(jsonFile);\r\n writer.write(jsonObject.toJSONString());\r\n writer.flush();\r\n writer.close();\r\n }\r\n }\r\n /* Download fabric json for fabric automated installation */\r\n if (mcVersion.contains(\"fabric\") && !jsonFile.exists()) {\r\n String[] split = mcVersion.split(\"-\");\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(String.format(\"%s/loader/%s/%s/profile/json\", Main.getFabricVersionsURL(), split[3], split[2])), jsonFile.getPath()));\r\n tasks.go();\r\n }\r\n\r\n /* Serialize the json file to read its properties */\r\n game = retrieveGame(jsonFile);\r\n\r\n /* Download vanilla jar to .minecraft/versions/<gameVersion>/<gameVersion.jar */\r\n File jarFile = new File(String.format(\"%s/%s.jar\", versionPath.getPath(), mcVersion));\r\n if (game.downloads != null && game.downloads.client != null) {\r\n String jarHash = game.downloads.client.sha1;\r\n\r\n /* if the vanilla jar doesn't exist or its hash is invalidated, download from mojang repo */\r\n if (!jarFile.exists() || jarFile.exists() && !jarHash.equals(CryptoEngine.fileHash(jarFile, \"SHA-1\"))) {\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(game.downloads.client.url), jarFile.getPath()));\r\n tasks.go();\r\n }\r\n }\r\n\r\n // Make natives dir .minecraft/versions/<gameVersion>/natives/\r\n File nativesPath = makeDirectory(String.format(\"%s/natives\", versionPath.getPath()));\r\n\r\n /* If internet is available download the parent (vanilla) version when you launch a modloader\r\n * Example: downloads the \"1.19.2\" while you launch \"fabric-loader-0.14.21-1.19.2\"\r\n * Because inside optifine, fabric or forge json there is a field called \"inheritsFrom\"\r\n * \"inheritsFrom\" basically describes on which vanilla version the modloader bases of */\r\n if (game.inheritsFrom != null) {\r\n if (vanilla != null) target = findVersion(vanilla, game.inheritsFrom);\r\n\r\n File inheritedVersionPath = makeDirectory(String.format(\"%s/versions/%s\", gameFolder.getPath(), game.inheritsFrom));\r\n\r\n /* Download the vanilla json which modloader put its basis on */\r\n File inheritedjsonFile = new File(String.format(\"%s/%s.json\", inheritedVersionPath.getPath(), game.inheritsFrom));\r\n if (target != null && target.url != null) {\r\n String jsonHash = target.url.substring(target.url.lastIndexOf(\"/\") - 40, target.url.lastIndexOf(\"/\"));\r\n\r\n /* if the vanilla json doesn't exist or its hash is invalidated, download from mojang repo */\r\n if (!inheritedjsonFile.exists() || inheritedjsonFile.exists() && !jsonHash.equals(CryptoEngine.fileHash(inheritedjsonFile, \"SHA-1\"))) {\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(target.url), inheritedjsonFile.getPath()));\r\n tasks.go();\r\n }\r\n }\r\n\r\n inherited = retrieveGame(inheritedjsonFile);\r\n\r\n /* Download the vanilla client jar when you launch a modloader that put its basis on it */\r\n File inheritedjarFile = new File(String.format(\"%s/%s.jar\", inheritedVersionPath.getPath(), game.inheritsFrom));\r\n if (inherited.downloads != null && inherited.downloads.client != null) {\r\n String jarHash = inherited.downloads.client.sha1;\r\n\r\n if (!inheritedjarFile.exists() || inheritedjarFile.exists() && !jarHash.equals(CryptoEngine.fileHash(inheritedjarFile, \"SHA-1\"))) {\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(inherited.downloads.client.url), inheritedjarFile.getPath()));\r\n tasks.go();\r\n }\r\n }\r\n }\r\n\r\n /* This variable returns ALWAYS the vanilla version, even when you launch modloader */\r\n MojangProduct.Game vanilla = (inherited != null ? inherited : game);\r\n\r\n /* Download natives */\r\n setupNatives(vanilla, nativesPath);\r\n\r\n /* Download client assets */\r\n setupAssets(vanilla);\r\n\r\n /* Setup the libraries needed to load vanilla minecraft */\r\n List<URL> paths = new ArrayList<>();\r\n /* Prepare required client arguments */\r\n List<String> gameargs = new ArrayList<>();\r\n\r\n /* Prepare launching arguments for launching minecraft\r\n * replaces placeholders with real values */\r\n for (String s : argbuilder(vanilla)) {\r\n s = s.replace(\"${auth_player_name}\", Main.getMojangSession().getUsername()) // player username\r\n .replace(\"${auth_session}\", \"1234\") // what is this?\r\n .replace(\"${version_name}\", game.id) // Version launched\r\n .replace(\"${game_directory}\", gameFolder.getPath()) // Game root dir\r\n .replace(\"${game_assets}\", assetsFolder.getPath()) // Game assets root dir\r\n .replace(\"${assets_root}\", assetsFolder.getPath()) // Same as the previous one\r\n .replace(\"${assets_index_name}\", vanilla.assetIndex.id) // assets index json filename\r\n .replace(\"${auth_uuid}\", Main.getMojangSession().getUUID()) // player uuid\r\n .replace(\"${auth_access_token}\", Main.getMojangSession().getSessionToken()) // player token for premium\r\n .replace(\"${user_type}\", \"msa\").replace(\"${version_type}\", game.type) // type of premium auth\r\n .replace(\"${user_properties}\", \"{}\"); // unknown\r\n gameargs.add(s);\r\n }\r\n /* Append modloader launching arguments to vanilla */\r\n if (inherited != null) {\r\n for (String s : argbuilder(game)) {\r\n if (!gameargs.contains(s)) {\r\n gameargs.add(s);\r\n }\r\n }\r\n }\r\n\r\n /* Put the client jar to url list */\r\n if (Main.getVanilla() != null) {\r\n if (isModded) {\r\n paths.addAll(setupLibraries(game)); /* Append modloader libraries if the game is modded */\r\n paths.addAll(setupLibraries(vanilla)); /* Append vanilla libraries */\r\n\r\n /* Due to unknown modloader reasons, we need to load even the inherited (vanilla) version */\r\n jarFile = new File(String.format(\"%s/%s.jar\", (new File(String.format(\"%s/versions/%s\", gameFolder.getPath(), vanilla.id))).getPath(), vanilla.id));\r\n\r\n /* Set the java.class.path to make modloaders like forge/fabric to work */\r\n makeModloaderCompatibility(paths, jarFile);\r\n } else {\r\n paths.addAll(setupLibraries(vanilla)); /* Append vanilla libraries */\r\n }\r\n\r\n if (paths.add(jarFile.toURI().toURL())) log.info(String.format(\"loading: %s\", jarFile.toURI().toURL()));\r\n } else if (Main.getMorpheus() != null) {\r\n /* You can ignore this */\r\n paths.addAll(setupLibraries(vanilla)); /* Append vanilla libraries */\r\n paths = replacePaths(paths); /* Update Log4j */\r\n paths.addAll(setupMorpheusPaths(product)); /* Append custom jars */\r\n\r\n gameargs.add(\"-morpheusID\");\r\n gameargs.add(Main.getMorpheus().user.data.id);\r\n }\r\n\r\n /* Launch through classloader\r\n * paths: libraries url path\r\n * gameargs: game launch arguments\r\n * mainclass: the entry point of the game */\r\n doClassloading(paths, gameargs, game.mainClass);\r\n }\r\n\r\n /* Workaround for some modloaders */\r\n private void makeModloaderCompatibility(List<URL> paths, File jarFile) throws URISyntaxException {\r\n StringBuilder classPath = new StringBuilder();\r\n for (URL path : paths) {\r\n classPath.append(new File(path.toURI()).getPath()).append(\";\");\r\n }\r\n classPath.append(new File(jarFile.toURI()).getPath());\r\n System.setProperty(\"java.class.path\", classPath.toString());\r\n\r\n log.info(\"Enabled classpath compatibility mode, this is needed by modloaders to work\");\r\n }\r\n\r\n /* Retrieve versions list from mojang server */\r\n private MojangProduct retrieveVersions() throws IOException {\r\n return new Gson().fromJson(Utils.makeGetRequest(new URL(Main.getVersionsURL())), MojangProduct.class);\r\n }\r\n\r\n /* Retrieve the version json */\r\n private MojangProduct.Game retrieveGame(File file) throws IOException {\r\n return new Gson().fromJson(new String(Files.readAllBytes(file.toPath())), MojangProduct.Game.class);\r\n }\r\n\r\n /* Search a version by \"name\" from the version list */\r\n private MojangProduct.Version findVersion(MojangProduct data, String name) {\r\n for (Object version : data.versions.stream().filter(f -> f.id.equalsIgnoreCase(name)).toArray()) {\r\n return (MojangProduct.Version) version;\r\n }\r\n return null;\r\n }\r\n\r\n private void doClassloading(List<URL> jars, List<String> gameargs, String mainClass) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {\r\n /* Add all url paths to classloader */\r\n URLClassLoader ucl = new URLClassLoader(jars.toArray(new URL[jars.size()]));\r\n Thread.currentThread().setContextClassLoader(ucl); // idk but maybe can helpful\r\n Class<?> c = ucl.loadClass(mainClass);\r\n\r\n /* Mangle game arguments */\r\n String[] args = new String[]{};\r\n String[] concat = Utils.concat(gameargs.toArray(new String[gameargs.size()]), args);\r\n String[] startArgs = Arrays.copyOfRange(concat, 0, concat.length);\r\n\r\n /* Method Handle instead of reflection, to make compatible with jre higher than 8 */\r\n MethodHandles.Lookup lookup = MethodHandles.lookup();\r\n MethodType mainMethodType = MethodType.methodType(void.class, String[].class);\r\n MethodHandle mainMethodHandle = lookup.findStatic(c, \"main\", mainMethodType);\r\n\r\n /* Invoke the main with the given arguments */\r\n try {\r\n log.debug(String.format(\"Invoking: %s\", c.getName()));\r\n mainMethodHandle.invokeExact(startArgs);\r\n } catch (Throwable e) {\r\n if (e.getMessage() != null) log.error(e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n /* in newer minecraft versions mojang changed how launch arguments are specified in JSON\r\n * This automatically choose how arguments should be managed */\r\n private String[] argbuilder(MojangProduct.Game game) {\r\n if (game.minecraftArguments != null) {\r\n // New\r\n return game.minecraftArguments.split(\" \");\r\n } else {\r\n // Old\r\n Object[] objectArray = game.arguments.game.toArray();\r\n String[] stringArray = new String[objectArray.length];\r\n for (int i = 0; i < objectArray.length; i++) {\r\n stringArray[i] = String.valueOf(objectArray[i]);\r\n }\r\n return stringArray;\r\n }\r\n }\r\n\r\n /* This method picks libraries and put into a URL list */\r\n private List<URL> setupLibraries(MojangProduct.Game game) throws IOException, NoSuchAlgorithmException, InterruptedException {\r\n List<URL> paths = new ArrayList<>();\r\n for (MojangProduct.Game.Library lib : game.libraries) {\r\n File libFolder = new File(String.format(\"%s/libraries\", gameFolder.getPath()));\r\n /* Resolve libraries from json links */\r\n if (lib.downloads != null && lib.downloads.artifact != null) {\r\n MojangProduct.Game.Artifact artifact = lib.downloads.artifact;\r\n\r\n /* Rule system, WARNING: potentially incomplete and broken */\r\n boolean allow = true;\r\n if (lib.rules != null) allow = checkRule(lib.rules);\r\n if (!allow) continue;\r\n\r\n /* Jar library local file path */\r\n File file = new File(String.format(\"%s/%s\", libFolder.getPath(), artifact.path));\r\n\r\n /* if the library jar doesn't exist or its hash is invalidated, download from mojang repo */\r\n if (artifact.url != null && !artifact.url.isEmpty() && (!file.exists() || file.exists() && !artifact.sha1.equals(CryptoEngine.fileHash(file, \"SHA-1\")))) {\r\n file.mkdirs();\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(artifact.url), file.getPath()));\r\n tasks.go();\r\n }\r\n\r\n /* Append the library path to local list if not present */\r\n if (!paths.contains(file.toURI().toURL()) && paths.add(file.toURI().toURL())) {\r\n log.info(String.format(\"Loading: %s\", file.toURI().toURL()));\r\n }\r\n }\r\n\r\n /* Reconstructs library path from name and eventually download it, this is used by old json formats and is even used by modloaders */\r\n String[] namesplit = lib.name.split(\":\");\r\n String libpath = String.format(\"%s/%s/%s/%s-%s.jar\", namesplit[0].replace(\".\", \"/\"), namesplit[1], namesplit[2], namesplit[1], namesplit[2]);\r\n File libfile = new File(String.format(\"%s/%s\", libFolder.getPath(), libpath));\r\n\r\n /* when url is provided in json, the specified source will used to download library, instead if not, will used mojang url */\r\n String liburl = (lib.url != null ? lib.url : Main.getLibrariesURL());\r\n URL downloadsource = new URL(String.format(\"%s/%s\", liburl, libpath));\r\n\r\n /* check if library isn't present on disk and check if needed library actually is available from download source */\r\n int response = ((HttpURLConnection) downloadsource.openConnection()).getResponseCode();\r\n if (!libfile.exists() && response == 200) {\r\n libfile.mkdirs();\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(downloadsource, libfile.getPath()));\r\n tasks.go();\r\n }\r\n\r\n /* Append the library path to local list if not present */\r\n if (!paths.contains(libfile.toURI().toURL()) && paths.add(libfile.toURI().toURL())) {\r\n log.info(String.format(\"Loading: %s\", libfile.toURI().toURL()));\r\n }\r\n }\r\n return paths;\r\n }\r\n\r\n /* Used only for morpheus products, you can ignore this */\r\n private List<URL> setupMorpheusPaths(MorpheusProduct product) throws MalformedURLException {\r\n List<URL> paths = new ArrayList<>();\r\n String query = \"%s/api/download?accessToken=%s&productID=%s&resourcePath=%s\";\r\n\r\n /* dependencies to be classloaded */\r\n for (MorpheusProduct.Library customLib : product.data.libraries) {\r\n URL customLibUrl = new URL(String.format(query, Main.getMorpheusAPI(), Main.getMorpheus().session.getSessionToken(), Main.getMorpheus().session.getProductID(), customLib.name));\r\n if (paths.add(customLibUrl)) log.info(String.format(\"Dynamic Loading: %s\", customLib.name));\r\n }\r\n\r\n /* client to be classloaded */\r\n URL customJarUrl = new URL(String.format(query, Main.getMorpheusAPI(), Main.getMorpheus().session.getSessionToken(), Main.getMorpheus().session.getProductID(), product.data.name));\r\n if (paths.add(customJarUrl)) log.info(String.format(\"Dynamic Loading: %s\", product.data.name));\r\n return paths;\r\n }\r\n\r\n /* Replaces certain entries from classpaths */\r\n private List<URL> replacePaths(List<URL> paths) throws MalformedURLException, URISyntaxException {\r\n List<URL> updatedPaths = new ArrayList<>();\r\n for (URL path : paths) {\r\n if (path.getPath().contains(\"log4j-core\")) {\r\n URL log4jcore = new URL(\"https://repo1.maven.org/maven2/org/apache/logging/log4j/log4j-core/2.21.0/log4j-core-2.21.0.jar\");\r\n updatedPaths.add(log4jcore);\r\n log.info(String.format(\"Swapped: %s with %s\", path.getPath(), log4jcore.toURI().toURL()));\r\n } else if (path.getPath().contains(\"log4j-api\")) {\r\n URL log4japi = new URL(\"https://repo1.maven.org/maven2/org/apache/logging/log4j/log4j-api/2.21.0/log4j-api-2.21.0.jar\");\r\n updatedPaths.add(log4japi);\r\n log.info(String.format(\"Swapped: %s with %s\", path.getPath(), log4japi.toURI().toURL()));\r\n } else {\r\n updatedPaths.add(path);\r\n }\r\n }\r\n return updatedPaths;\r\n }\r\n\r\n /* this determine which library should be used, some minecraft versions need to use\r\n * a different library version to work on certain systems, pratically are \"Exceptions\"\r\n * WARNING: Potentially bugged and may not follow what mojang json want do */\r\n private boolean checkRule(ArrayList<MojangProduct.Game.Rule> rules) {\r\n boolean defaultValue = false;\r\n for (MojangProduct.Game.Rule rule : rules) {\r\n if (rule.os == null) {\r\n defaultValue = rule.action.equals(\"allow\");\r\n } else if (rule.os != null && OSUtils.getPlatform().name().contains(rule.os.name.replace(\"osx\", \"mac\"))) {\r\n defaultValue = rule.action.equals(\"allow\");\r\n }\r\n }\r\n return defaultValue;\r\n }\r\n\r\n private void setupNatives(MojangProduct.Game game, File nativesFolder) throws MalformedURLException {\r\n /* Find out what cpu architecture is the user machine, assuming they use baremetal os installation */\r\n String os_arch = OSUtils.getOSArch();\r\n boolean isArmProcessor = (os_arch.contains(\"arm\") || os_arch.contains(\"aarch\"));\r\n boolean isIntelProcessor = (os_arch.contains(\"x86_64\") || os_arch.contains(\"amd64\"));\r\n\r\n for (MojangProduct.Game.Library lib : game.libraries) {\r\n MojangProduct.Game.Classifiers classifiers = lib.downloads.classifiers;\r\n if (classifiers != null) {\r\n /* Natives pojo model for windows */\r\n MojangProduct.Game.NativesWindows windows32 = classifiers.natives_windows_32, windows64 = classifiers.natives_windows_64, windows = classifiers.natives_windows;\r\n /* for gnu/linux */\r\n MojangProduct.Game.NativesLinux linux = classifiers.natives_linux;\r\n /* for osx/macos or whatever you want call it */\r\n MojangProduct.Game.NativesOsx osx = classifiers.natives_osx, macos = classifiers.natives_macos;\r\n\r\n switch (OSUtils.getPlatform()) {\r\n /* These seems \"duplicated\" but is needed for maintaing compatibility with old versions like 1.8.x */\r\n case windows:\r\n if (windows32 != null) {\r\n Utils.downloadAndUnzipNatives(new URL(windows32.url), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", windows32.url, OSUtils.getPlatform()));\r\n }\r\n if (windows64 != null) {\r\n Utils.downloadAndUnzipNatives(new URL(windows64.url), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", windows64.url, OSUtils.getPlatform()));\r\n }\r\n if (windows != null) {\r\n Utils.downloadAndUnzipNatives(new URL(windows.url), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", windows.url, OSUtils.getPlatform()));\r\n }\r\n break;\r\n case linux:\r\n if (linux != null) {\r\n Utils.downloadAndUnzipNatives(new URL(linux.url), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", linux.url, OSUtils.getPlatform()));\r\n }\r\n break;\r\n /* Dear mojang why you use different natives names in your json?? */\r\n case macos:\r\n if (osx != null) {\r\n Utils.downloadAndUnzipNatives(new URL(osx.url), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", osx.url, OSUtils.getPlatform()));\r\n }\r\n if (macos != null) {\r\n Utils.downloadAndUnzipNatives(new URL(macos.url), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", macos.url, OSUtils.getPlatform()));\r\n }\r\n break;\r\n /* Fallback error in case user have weird os like solaris or bsd */\r\n default:\r\n log.error(\"Oops.. seem that your os isn't supported, ask help on https://discord.gg/aerXnBe\");\r\n }\r\n }\r\n /* Mojang with newer versions like 1.16+ introduces new format for natives in json model,\r\n * Plus this method provides recognition for eventual arm natives */\r\n if (lib.name.contains(\"native\") && lib.rules != null) {\r\n String nativeName = lib.name;\r\n String nativeURL = lib.downloads.artifact.url;\r\n\r\n /* Find out which natives allow on user os */\r\n if (checkRule(lib.rules)) {\r\n boolean isArmNative = (lib.name.contains(\"arm\") || lib.name.contains(\"aarch\"));\r\n boolean compatible = true;\r\n\r\n if (isArmNative && !isArmProcessor) compatible = false; // natives ARM on x86 (cpu)\r\n if (!isArmNative && isArmProcessor) compatible = false; // natives x86 on ARM (cpu)\r\n\r\n if (!compatible) continue;\r\n Utils.downloadAndUnzipNatives(new URL(nativeURL), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s (%s)\", nativeURL, OSUtils.getPlatform(), os_arch));\r\n }\r\n }\r\n }\r\n /* Additional code to download missing arm natives */\r\n if (isArmProcessor) for (MojangProduct.Game.Library lib : game.libraries) {\r\n switch (OSUtils.getPlatform()) {\r\n case macos:\r\n // LWJGL 2.X (up to 1.12.2)\r\n // I hope this work and i don't have an apple silicon machine to test if works\r\n if (lib.downloads.classifiers != null && lib.downloads.classifiers.natives_osx != null && lib.downloads.classifiers.natives_osx.url.contains(\"lwjgl-platform-2\")) {\r\n String zipUrl = String.format(\"%s/downloads/extra-natives/lwjgl-2-macos-aarch64.zip\", Main.getMorpheusAPI());\r\n Utils.downloadAndUnzipNatives(new URL(zipUrl), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", zipUrl, OSUtils.getPlatform()));\r\n }\r\n break;\r\n case linux:\r\n // LWJGL 2.X (up to 1.12.2)\r\n if (lib.downloads.classifiers != null && lib.downloads.classifiers.natives_linux != null && lib.downloads.classifiers.natives_linux.url.contains(\"lwjgl-platform-2\")) {\r\n String zipUrl = String.format(\"%s/downloads/extra-natives/lwjgl-2-linux-aarch64.zip\", Main.getMorpheusAPI());\r\n Utils.downloadAndUnzipNatives(new URL(zipUrl), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", zipUrl, OSUtils.getPlatform()));\r\n }\r\n // LWJGL 3.3 (1.19+)\r\n if (lib.name.contains(\"native\") && lib.rules != null && checkRule(lib.rules) && lib.name.contains(\"lwjgl\")) {\r\n String zipUrl = String.format(\"%s/downloads/extra-natives/lwjgl-3.3-linux-aarch64.zip\", Main.getMorpheusAPI());\r\n Utils.downloadAndUnzipNatives(new URL(zipUrl), nativesFolder, log);\r\n log.info(String.format(\"Downloaded and extracted %s for %s\", zipUrl, OSUtils.getPlatform()));\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n\r\n private void setupAssets(MojangProduct.Game game) throws IOException, ParseException, InterruptedException {\r\n /* Download assets indexes from mojang repo */\r\n File indexesPath = new File(String.format(\"%s/indexes/%s.json\", assetsFolder.getPath(), game.assetIndex.id));\r\n if (!indexesPath.exists()) {\r\n indexesPath.mkdirs();\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(new URL(game.assetIndex.url), indexesPath.getPath()));\r\n tasks.go();\r\n log.info(indexesPath.getPath() + \" was created\");\r\n }\r\n\r\n /* Fetch all the entries and read properties */\r\n JSONObject json_objects = (JSONObject) ((JSONObject) jsonParser.parse(new FileReader(indexesPath))).get(\"objects\");\r\n json_objects.keySet().forEach(keyStr -> {\r\n JSONObject json_entry = (JSONObject) json_objects.get(keyStr);\r\n String size = json_entry.get(\"size\").toString();\r\n String hash = json_entry.get(\"hash\").toString();\r\n\r\n /* the asset parent folders is the first two chars of the asset hash\r\n * \"asset\" is intended as the single resource file of the game */\r\n String directory = hash.substring(0, 2);\r\n\r\n try {\r\n boolean isLegacy = game.assetIndex.id.contains(\"pre-1.6\");\r\n\r\n /* legacy versions use .minecraft/resources instead of .minecraft/assets */\r\n File objectsPath;\r\n if (isLegacy) objectsPath = new File(String.format(\"%s/resources/%s\", gameFolder.getPath(), keyStr));\r\n else objectsPath = new File(String.format(\"%s/objects/%s/%s\", assetsFolder.getPath(), directory, hash));\r\n\r\n /* if asset doesn't exist or its hash is invalid, re-download from mojang */\r\n if (!objectsPath.exists() || objectsPath.exists() && !hash.equals(CryptoEngine.fileHash(objectsPath, \"SHA-1\"))) {\r\n objectsPath.mkdirs();\r\n URL object_url = new URL(String.format(\"%s/%s/%s\", Main.getAssetsURL(), directory, hash));\r\n\r\n ParallelTasks tasks = new ParallelTasks();\r\n tasks.add(new DownloadFileTask(object_url, objectsPath.getPath()));\r\n tasks.go();\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n });\r\n }\r\n\r\n private File makeDirectory(String path) {\r\n File temp = new File(path);\r\n if (!temp.exists() && temp.mkdirs()) {\r\n log.info(String.format(\"Directory created: %s\", temp.getPath()));\r\n }\r\n return temp;\r\n }\r\n}\r" }, { "identifier": "Main", "path": "src/team/morpheus/launcher/Main.java", "snippet": "public class Main {\r\n\r\n public static final String build = \"(v1.0.2 | 26_12_2023)\";\r\n private static final MyLogger log = new MyLogger(Main.class);\r\n @Getter\r\n private static Morpheus morpheus;\r\n @Getter\r\n private static Vanilla vanilla;\r\n @Getter\r\n private static MojangSession mojangSession;\r\n\r\n // NOTE: it's important to set -Djava.library.path by giving natives path, else game won't start!\r\n public static void main(String[] args) throws Exception {\r\n log.info(String.format(\"Morpheus Launcher %s | Lampadina_17 (by-nc-sa)\", build));\r\n\r\n /* Morpheus product's related arguments, most people can ignore this */\r\n Option var0 = Option.builder(\"a\").longOpt(\"accessToken\").argName(\"token\").hasArg().desc(\"\").build();\r\n Option var1 = Option.builder(\"p\").longOpt(\"productID\").argName(\"productid\").hasArg().desc(\"\").build();\r\n Option var6 = Option.builder(\"h\").longOpt(\"hwid\").argName(\"showpopup\").hasArg().optionalArg(true).desc(\"Prints hardware-id into a message dialog\").build();\r\n\r\n /* Vanilla related arguments */\r\n Option var2 = Option.builder(\"v\").longOpt(\"version\").argName(\"version\").hasArg().desc(\"Minecraft version to be launched\").build();\r\n Option var3 = Option.builder(\"n\").longOpt(\"minecraftUsername\").argName(\"username\").hasArg().desc(\"Minecraft player username (required)\").build();\r\n Option var4 = Option.builder(\"t\").longOpt(\"minecraftToken\").argName(\"token\").hasArg().desc(\"Minecraft player token (required)\").build();\r\n Option var5 = Option.builder(\"u\").longOpt(\"minecraftUUID\").argName(\"uuid\").hasArg().desc(\"Minecraft player uuid (required)\").build();\r\n\r\n Options options = new Options();\r\n options.addOption(var0).addOption(var1).addOption(var2).addOption(var3).addOption(var4).addOption(var5).addOption(var6);\r\n CommandLine cmd = (new DefaultParser()).parse(options, args);\r\n\r\n if (cmd.getOptionValue(var3) != null && cmd.getOptionValue(var4) != null && cmd.getOptionValue(var5) != null) {\r\n /* Setup minecraft session */\r\n mojangSession = new MojangSession(cmd.getOptionValue(var4), cmd.getOptionValue(var3), cmd.getOptionValue(var5));\r\n\r\n /* Select operative mode */\r\n if (cmd.getOptionValue(var2) != null) {\r\n (vanilla = new Vanilla(cmd.getOptionValue(var2))).prepareLaunch();\r\n } else if (cmd.getOptionValue(var0) != null && cmd.getOptionValue(var1) != null) {\r\n loadNativeLib();\r\n (morpheus = new Morpheus(new MorpheusSession(cmd.getOptionValue(var0), cmd.getOptionValue(var1), OSUtils.getHWID()))).prepareLaunch();\r\n }\r\n } else {\r\n if (cmd.hasOption(var6)) {\r\n loadNativeLib();\r\n /* Print HWID */\r\n String hwid = OSUtils.getHWID();\r\n log.info(String.format(\"HWID: %s\", hwid));\r\n String showPopupValue = cmd.getOptionValue(var6);\r\n if (showPopupValue != null && showPopupValue.equalsIgnoreCase(\"true\")) {\r\n copyToClipboard(hwid);\r\n JOptionPane.showMessageDialog(null, \"Hwid has successfully copied to your clipboard!\");\r\n }\r\n System.exit(0);\r\n } else {\r\n /* Print Help */\r\n printHelp(options);\r\n }\r\n }\r\n }\r\n\r\n private static void printHelp(Options options) {\r\n System.out.println(\"Usage: java -Djava.library.path=<nativespath> -jar Launcher.jar [options]\");\r\n System.out.println(\"\\nAvailable options:\");\r\n for (Option option : options.getOptions()) { /* Shitty workaround due to shitty bug */\r\n System.out.println(String.format(\"-%s, -%-45s %s\", option.getOpt(), (option.getLongOpt() + (option.hasArg() ? \" <\" + option.getArgName() + \">\" : \"\")), option.getDescription()));\r\n }\r\n System.out.println(\"\\nCheck wiki for more details: https://morpheus-launcher.gitbook.io/home/\\n\");\r\n }\r\n\r\n private static void copyToClipboard(String text) {\r\n java.awt.datatransfer.Clipboard clipboard = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard();\r\n java.awt.datatransfer.StringSelection selection = new java.awt.datatransfer.StringSelection(text);\r\n clipboard.setContents(selection, null);\r\n }\r\n\r\n /* Loads morpheusguard dynamic library only when needed, for most users this is useless */\r\n public static void loadNativeLib() {\r\n String nativelibpath = OSUtils.getWorkingDirectory(\"morpheus\").getPath() + File.separator;\r\n switch (OSUtils.getPlatform()) {\r\n case windows:\r\n nativelibpath += \"morpheus_guard.dll\";\r\n break;\r\n case macos:\r\n nativelibpath += \"libmorpheus_guard.dylib\";\r\n break;\r\n case linux:\r\n nativelibpath += \"libmorpheus_guard.so\";\r\n break;\r\n }\r\n System.load(nativelibpath);\r\n }\r\n\r\n /* Vanilla version list */\r\n public static final String getVersionsURL() {\r\n return \"https://launchermeta.mojang.com/mc/game/version_manifest.json\";\r\n }\r\n\r\n /* Vanilla assets */\r\n public static final String getAssetsURL() {\r\n return \"https://resources.download.minecraft.net\";\r\n }\r\n\r\n public static final String getLibrariesURL() {\r\n return \"https://libraries.minecraft.net\";\r\n }\r\n\r\n /* Fabric */\r\n public static final String getFabricVersionsURL() {\r\n return \"https://meta.fabricmc.net/v2/versions\";\r\n }\r\n\r\n /* Morpheus */\r\n public static final String getMorpheusAPI() {\r\n return \"https://morpheuslauncher.it\";\r\n }\r\n}\r" }, { "identifier": "MyLogger", "path": "src/team/morpheus/launcher/logging/MyLogger.java", "snippet": "public class MyLogger {\r\n\r\n public Class clazz;\r\n\r\n public MyLogger(Class clazz) {\r\n this.clazz = clazz;\r\n }\r\n\r\n public void info(String message) {\r\n printLog(LogLevel.INFO, message);\r\n }\r\n\r\n public void warn(String message) {\r\n printLog(LogLevel.WARN, message);\r\n }\r\n\r\n public void error(String message) {\r\n printLog(LogLevel.ERROR, message);\r\n }\r\n\r\n public void debug(String message) {\r\n printLog(LogLevel.DEBUG, message);\r\n }\r\n\r\n public void printLog(LogLevel type, String message) {\r\n System.out.println(String.format(\"[%s]: %s\", type.name(), message));\r\n }\r\n}\r" }, { "identifier": "MorpheusSession", "path": "src/team/morpheus/launcher/model/MorpheusSession.java", "snippet": "@Data\r\n@AllArgsConstructor\r\npublic class MorpheusSession {\r\n\r\n final String sessionToken;\r\n final String productID;\r\n final String hwid;\r\n}\r" }, { "identifier": "MorpheusUser", "path": "src/team/morpheus/launcher/model/MorpheusUser.java", "snippet": "public class MorpheusUser {\r\n\r\n @SerializedName(\"data\")\r\n public Data data;\r\n\r\n public class Data {\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"username\")\r\n public String username;\r\n\r\n @SerializedName(\"hwid\")\r\n public String hwid;\r\n\r\n @SerializedName(\"products\")\r\n public ArrayList<String> products;\r\n }\r\n}" }, { "identifier": "MorpheusProduct", "path": "src/team/morpheus/launcher/model/products/MorpheusProduct.java", "snippet": "public class MorpheusProduct {\r\n\r\n @SerializedName(\"data\")\r\n public Data data;\r\n\r\n public class Data {\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"name\")\r\n public String name;\r\n\r\n @SerializedName(\"version\")\r\n public String version;\r\n\r\n @SerializedName(\"gameversion\")\r\n public String gameversion;\r\n\r\n @SerializedName(\"sha256\")\r\n public String sha256;\r\n\r\n @SerializedName(\"mainclass\")\r\n public String mainclass;\r\n\r\n @SerializedName(\"libraries\")\r\n public ArrayList<Library> libraries;\r\n }\r\n\r\n public class Library {\r\n\r\n @SerializedName(\"name\")\r\n public String name;\r\n\r\n @SerializedName(\"sha256\")\r\n public String sha256;\r\n }\r\n}\r" }, { "identifier": "Utils", "path": "src/team/morpheus/launcher/utils/Utils.java", "snippet": "public class Utils {\r\n\r\n public static <T> T[] concat(T[] first, T[] second) {\r\n T[] result = Arrays.copyOf(first, first.length + second.length);\r\n System.arraycopy(second, 0, result, first.length, second.length);\r\n return result;\r\n }\r\n\r\n public static String readJsonFromConnection(HttpURLConnection conn) throws IOException {\r\n BufferedReader br = new BufferedReader(new InputStreamReader(conn.getResponseCode() < 400 ? conn.getInputStream() : conn.getErrorStream()));\r\n String line, output = \"\";\r\n while ((line = br.readLine()) != null) {\r\n output += (line + \"\\n\");\r\n }\r\n br.close();\r\n return output;\r\n }\r\n\r\n public static HttpURLConnection makePostRequest(URL url, HashMap<String, String> params) throws IOException {\r\n String urlParameters = getDataString(params);\r\n byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);\r\n int postDataLength = postData.length;\r\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\r\n conn.setDoOutput(true);\r\n conn.setInstanceFollowRedirects(false);\r\n conn.setRequestMethod(\"POST\");\r\n conn.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\r\n conn.setRequestProperty(\"charset\", \"utf-8\");\r\n conn.setRequestProperty(\"Content-Length\", Integer.toString(postDataLength));\r\n conn.setUseCaches(false);\r\n try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r\n wr.write(postData);\r\n }\r\n return conn;\r\n }\r\n\r\n public static String makeGetRequest(URL url) throws IOException {\r\n HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();\r\n httpurlconnection.setRequestMethod(\"GET\");\r\n BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));\r\n StringBuilder stringbuilder = new StringBuilder();\r\n String s;\r\n\r\n while ((s = bufferedreader.readLine()) != null) {\r\n stringbuilder.append(s);\r\n stringbuilder.append('\\r');\r\n }\r\n\r\n bufferedreader.close();\r\n return stringbuilder.toString();\r\n }\r\n\r\n private static String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException {\r\n StringBuilder result = new StringBuilder();\r\n boolean first = true;\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n if (first) first = false;\r\n else result.append(\"&\");\r\n result.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.displayName()));\r\n result.append(\"=\");\r\n result.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.displayName()));\r\n }\r\n return result.toString();\r\n }\r\n\r\n public static void downloadAndUnzipNatives(URL source, File targetPath, MyLogger log) {\r\n try {\r\n ZipInputStream zipInputStream = new ZipInputStream(source.openStream());\r\n ZipEntry zipEntry = zipInputStream.getNextEntry();\r\n while (zipEntry != null) {\r\n if (!zipEntry.isDirectory()) {\r\n String fileName = zipEntry.getName().replace(\"\\\\\", \"/\");\r\n String[] fileSplit = fileName.split(\"/\");\r\n File newFile = new File(targetPath.getPath(), fileSplit[Math.max(0, fileSplit.length - 1)]);\r\n\r\n boolean isNativeFile = newFile.getPath().endsWith(\".dll\") || newFile.getPath().endsWith(\".dylib\") || newFile.getPath().endsWith(\".jnilib\") || newFile.getPath().endsWith(\".so\");\r\n if (isNativeFile) {\r\n FileOutputStream fileOutputStream = new FileOutputStream(newFile);\r\n byte[] buffer = new byte[1024];\r\n int length;\r\n while ((length = zipInputStream.read(buffer)) > 0) {\r\n fileOutputStream.write(buffer, 0, length);\r\n }\r\n fileOutputStream.close();\r\n }\r\n }\r\n zipEntry = zipInputStream.getNextEntry();\r\n }\r\n zipInputStream.closeEntry();\r\n zipInputStream.close();\r\n } catch (Exception e) {\r\n log.error(e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n}\r" } ]
import com.google.gson.Gson; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import team.morpheus.launcher.Launcher; import team.morpheus.launcher.Main; import team.morpheus.launcher.logging.MyLogger; import team.morpheus.launcher.model.MorpheusSession; import team.morpheus.launcher.model.MorpheusUser; import team.morpheus.launcher.model.products.MorpheusProduct; import team.morpheus.launcher.utils.Utils; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap;
9,824
package team.morpheus.launcher.instance; public class Morpheus { private static final MyLogger log = new MyLogger(Morpheus.class);
package team.morpheus.launcher.instance; public class Morpheus { private static final MyLogger log = new MyLogger(Morpheus.class);
public MorpheusSession session;
3
2023-12-07 14:34:54+00:00
12k
Serilum/Collective
Common/src/main/java/com/natamus/collective/events/CollectiveEvents.java
[ { "identifier": "RegisterMod", "path": "Common/src/main/java/com/natamus/collective/check/RegisterMod.java", "snippet": "public class RegisterMod {\n\tprivate static final CopyOnWriteArrayList<String> jarlist = new CopyOnWriteArrayList<String>();\n\tprivate static final HashMap<String, String> jartoname = new HashMap<String, String>();\n\tpublic static boolean shouldDoCheck = true;\n\t\n\tpublic static void register(String modname, String modid, String modVersion, String rawGameVersion) {\n\t\tString gameVersion = rawGameVersion.replaceAll(\"\\\\[\", \"\").replaceAll(\"]\",\"\");\n\n\t\tint dotCount = gameVersion.length() - gameVersion.replace(\".\", \"\").length();\n\t\tif (dotCount == 1) {\n\t\t\tgameVersion += \".0\";\n\t\t}\n\n\t\tString jarname = modid + \"-\" + gameVersion + \"-\" + modVersion + \".jar\";\n\t\t\n\t\tjarlist.add(jarname);\n\t\tjartoname.put(jarname, modname);\n\t}\n\t\n\tpublic static void initialProcess() {\n\t\tif (!CollectiveConfigHandler.enableAntiRepostingCheck) {\n\t\t\tshouldDoCheck = false;\n\t\t}\n\t\telse if (!checkAlternative()) {\n\t\t\tshouldDoCheck = false;\n\t\t}\n\t}\n\t\n\tpublic static void joinWorldProcess(Level world, Player player) {\n\t\tif (!(world instanceof ServerLevel)) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tList<String> wrongmodnames = checkIfAllJarsExist();\n\t\tif (wrongmodnames.size() > 0) {\n\t\t\tif (processPreJoinWorldCheck(world)) {\n\t\t\t\tString s = \"\";\n\t\t\t\tif (wrongmodnames.size() > 1) {\n\t\t\t\t\ts = \"s\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tString projecturl = \"https://curseforge.com/members/serilum/projects\";\n\t\t\t\tStringFunctions.sendMessage(player, \"Mod\" + s + \" from incorrect sources:\", ChatFormatting.RED, projecturl);\n\t\t\t\tfor (String wrongmodname : wrongmodnames) {\n\t\t\t\t\tStringFunctions.sendMessage(player, \" \" + wrongmodname, ChatFormatting.YELLOW, projecturl);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tStringFunctions.sendMessage(player, \"You are receiving this message because you are using some of Serilum's mods, but probably haven't downloaded them from the original source. Unofficial sources can contain malicious software, supply no income for developers and host outdated versions.\", ChatFormatting.RED, projecturl);\n\t\t\t\tStringFunctions.sendMessage(player, \"Serilum's mod downloads are only officially available at CurseForge and Modrinth.\", ChatFormatting.DARK_GREEN, projecturl);\n\t\t\t\tStringFunctions.sendMessage(player, \" CF: https://curseforge.com/members/serilum/projects\", ChatFormatting.YELLOW, projecturl);\n\t\t\t\tStringFunctions.sendMessage(player, \" MR: https://modrinth.com/user/Serilum\", ChatFormatting.YELLOW, \"https://modrinth.com/user/Serilum\");\n\t\t\t\tStringFunctions.sendMessage(player, \"You won't see this message again in this instance. Thank you for reading.\", ChatFormatting.DARK_GREEN, projecturl);\n\t\t\t\tStringFunctions.sendMessage(player, \"-Rick (Serilum)\", ChatFormatting.YELLOW, projecturl);\n\t\t\t\t\n\t\t\t\tprocessPostJoinWorldCheck(world);\n\t\t\t}\n\t\t}\n\t\t\n\t\tshouldDoCheck = false;\n\t}\n\t\n\tprivate static boolean processPreJoinWorldCheck(Level world) {\n\t\tString checkfilepath = WorldFunctions.getWorldPath((ServerLevel)world) + File.separator + \"config\" + File.separator + \"collective\" + File.separator + \"checked.txt\";\n\t\tFile checkfile = new File(checkfilepath);\n\t\tif (checkfile.exists()) {\n\t\t\tshouldDoCheck = false;\n\t\t}\n\t\telse if (!checkAlternative()) {\n\t\t\tshouldDoCheck = false;\n\t\t}\n\t\t\n\t\treturn shouldDoCheck;\n\t}\n\t\n\tprivate static void processPostJoinWorldCheck(Level world) {\n\t\tshouldDoCheck = false;\n\n\t\tString worlddatapath = WorldFunctions.getWorldPath((ServerLevel)world) + File.separator + \"config\" + File.separator + \"collective\";\n\t\tFile dir = new File(worlddatapath);\n\t\tif (!dir.mkdirs()) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tPrintWriter writer = new PrintWriter(worlddatapath + File.separator + \"checked.txt\", StandardCharsets.UTF_8);\n\t\t\twriter.println(\"# Please check out https://stopmodreposts.org/ for more information on why this feature exists.\");\n\t\t\twriter.println(\"checked=true\");\n\t\t\twriter.close();\n\t\t} catch (Exception ignored) { }\n\t\t\n\t\tcreateRepostingCheckFile();\n\t}\n\n\tpublic static void createRepostingCheckFile() {\n\t\tString alternativecheckpath = DataFunctions.getConfigDirectory() + File.separator + \"collective\";\n\t\tif (new File(alternativecheckpath + File.separator + \"checked.txt\").isFile()) {\n\t\t\treturn;\n\t\t}\n\n\t\tFile alternativedir = new File(alternativecheckpath);\n\t\tif (!alternativedir.mkdirs()) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tPrintWriter writer = new PrintWriter(alternativecheckpath + File.separator + \"checked.txt\", StandardCharsets.UTF_8);\n\t\t\twriter.println(\"# Please check out https://stopmodreposts.org/ for more information on why this feature exists.\");\n\t\t\twriter.println(\"checked=true\");\n\t\t\twriter.close();\n\t\t} catch (Exception ignored) { }\n\t}\n\t\n\tprivate static List<String> checkIfAllJarsExist() {\n\t\tList<String> installedmods = DataFunctions.getInstalledModJars();\n\t\t\n\t\tList<String> wrongmodnames = new ArrayList<String>();\n\t\tfor (String jarname : jarlist) {\n\t\t\tif (!installedmods.contains(jarname) && jartoname.containsKey(jarname)) {\n\t\t\t\twrongmodnames.add(jartoname.get(jarname));\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (wrongmodnames.size() > 0) {\n\t\t\tCollections.sort(wrongmodnames);\n\t\t}\n\t\treturn wrongmodnames;\n\t}\n\t\n\tprivate static boolean checkAlternative() {\n\t\tString alternativecheckfilepath = DataFunctions.getConfigDirectory() + File.separator + \"collective\" + File.separator + \"checked.txt\";\n\t\tFile alternativecheckfile = new File(alternativecheckfilepath);\n\t\treturn !alternativecheckfile.exists();\n\t}\n}" }, { "identifier": "CollectiveConfigHandler", "path": "Common/src/main/java/com/natamus/collective/config/CollectiveConfigHandler.java", "snippet": "public class CollectiveConfigHandler extends DuskConfig {\n public static HashMap<String, List<String>> configMetaData = new HashMap<String, List<String>>();\n\n @Entry public static boolean transferItemsBetweenReplacedEntities = true;\n @Entry(min = 1, max = 500) public static int loopsAmountUsedToGetAllEntityDrops = 100;\n @Entry(min = 0, max = 3600000) public static int findABlockCheckAroundEntitiesDelayMs = 30000;\n @Entry public static boolean enableAntiRepostingCheck = true;\n @Entry public static boolean enablePatronPets = true;\n\n public static void initConfig() {\n configMetaData.put(\"transferItemsBetweenReplacedEntities\", Arrays.asList(\n \"When enabled, transfer the held items and armour from replaced entities by any of the Entity Spawn mods which depend on Collective.\"\n ));\n configMetaData.put(\"loopsAmountUsedToGetAllEntityDrops\", Arrays.asList(\n \"The amount of times Collective loops through possible mob drops to get them all procedurally. Drops are only generated when a dependent mod uses them. Lowering this can increase world load time but decrease accuracy.\"\n ));\n configMetaData.put(\"findABlockCheckAroundEntitiesDelayMs\", Arrays.asList(\n \"The delay of the is-there-a-block-around-check around entities in ms. Used in mods which depends on a specific blockstate in the world. Increasing this number can increase TPS if needed.\"\n ));\n configMetaData.put(\"enableAntiRepostingCheck\", Arrays.asList(\n \"Please check out https://stopmodreposts.org/ for more information on why this feature exists.\"\n ));\n configMetaData.put(\"enablePatronPets\", Arrays.asList(\n \"Enables pets for Patrons. Will be added in a future release.\"\n ));\n\n DuskConfig.init(CollectiveReference.NAME, CollectiveReference.MOD_ID, CollectiveConfigHandler.class);\n }\n}" }, { "identifier": "GlobalVariables", "path": "Common/src/main/java/com/natamus/collective/data/GlobalVariables.java", "snippet": "public class GlobalVariables {\n\tpublic static Random random = new Random();\n\tpublic static RandomSource randomSource = RandomSource.create();\n\n\t// Spawn A Mob variables\n\tpublic static CopyOnWriteArrayList<EntityType<?>> activeSAMEntityTypes = new CopyOnWriteArrayList<EntityType<?>>();\n\tpublic static CopyOnWriteArrayList<SAMObject> globalSAMs = new CopyOnWriteArrayList<SAMObject>();\n\n\t// Villager names; 1: guard-villagers, 2-4: farlanders\n\tpublic static List<String> moddedvillagers = new ArrayList<String>(Arrays.asList(\"Villager\", \"WanderingTrader\", \"Guard\", \"Farlander\", \"ElderFarlander\", \"Wanderer\", \"ThiefWanderingTrader\", \"PlagueDoctor\", \"GoblinTrader\", \"VeinGoblinTrader\", \"RedMerchant\", \"WanderingWizard\", \"WanderingWinemaker\", \"WanderingBaker\", \"Bowman\", \"Crossbowman\", \"Horseman\", \"Nomad\", \"Recruit\", \"RecruitShieldman\", \"Gatekeeper\", \"VillagerEntityMCA\"));\n\n\t// Names\n\tpublic static List<String> areaNames = new ArrayList<String>();\n\tpublic static List<String> femaleNames = new ArrayList<String>();\n\tpublic static List<String> maleNames = new ArrayList<String>();\n\n\t// Linger Messages\n\tpublic static List<String> lingerMessages = new ArrayList<String>();\n\n\t// Mob drops\n\tpublic static HashMap<EntityType<?>, List<Item>> entitydrops = null;\n\n\t// URLS\n\tpublic static String playerdataurl = \"https://api.mojang.com/users/profiles/minecraft/\";\n\tpublic static String skindataurl = \"https://sessionserver.mojang.com/session/minecraft/profile/\";\n\n\t// HashMaps to generate\n\tpublic static Map<Block, BlockEntityType<?>> blocksWithTileEntity = new HashMap<Block, BlockEntityType<?>>();\n\n\tpublic static void generateHashMaps() {\n\t\t// FAB tile entities.\n\t\tblocksWithTileEntity.put(Blocks.CAMPFIRE, BlockEntityType.CAMPFIRE);\n\t\tblocksWithTileEntity.put(Blocks.OAK_SIGN, BlockEntityType.SIGN);\n\t}\n\n\t// Block and item collections\n\tpublic static List<Block> growblocks = Arrays.asList(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT, Blocks.GRAVEL, Blocks.MYCELIUM, Blocks.PODZOL, Blocks.SAND, Blocks.RED_SAND);\n\tpublic static List<Block> stoneblocks = Arrays.asList(Blocks.COBBLESTONE, Blocks.MOSSY_COBBLESTONE, Blocks.STONE, Blocks.STONE_BRICKS, Blocks.CHISELED_STONE_BRICKS, Blocks.CRACKED_STONE_BRICKS, Blocks.SMOOTH_STONE, Blocks.GRAVEL, Blocks.ANDESITE, Blocks.POLISHED_ANDESITE, Blocks.DIORITE, Blocks.POLISHED_DIORITE, Blocks.GRANITE, Blocks.POLISHED_GRANITE, Blocks.SANDSTONE, Blocks.CHISELED_SANDSTONE, Blocks.CUT_SANDSTONE, Blocks.SMOOTH_SANDSTONE, Blocks.RED_SANDSTONE, Blocks.CHISELED_RED_SANDSTONE, Blocks.CUT_RED_SANDSTONE, Blocks.SMOOTH_RED_SANDSTONE, Blocks.END_STONE, Blocks.END_STONE_BRICKS, Blocks.NETHERRACK, Blocks.NETHER_BRICKS, Blocks.RED_NETHER_BRICKS);\n\tpublic static List<Item> stoneblockitems = Arrays.asList(Items.COBBLESTONE, Items.MOSSY_COBBLESTONE, Items.STONE, Items.STONE_BRICKS, Items.CHISELED_STONE_BRICKS, Items.CRACKED_STONE_BRICKS, Items.SMOOTH_STONE, Items.GRAVEL, Items.ANDESITE, Items.POLISHED_ANDESITE, Items.DIORITE, Items.POLISHED_DIORITE, Items.GRANITE, Items.POLISHED_GRANITE, Items.SANDSTONE, Items.CHISELED_SANDSTONE, Items.CUT_SANDSTONE, Items.SMOOTH_SANDSTONE, Items.RED_SANDSTONE, Items.CHISELED_RED_SANDSTONE, Items.CUT_RED_SANDSTONE, Items.SMOOTH_RED_SANDSTONE, Items.END_STONE, Items.END_STONE_BRICKS, Items.NETHERRACK, Items.NETHER_BRICKS, Items.RED_NETHER_BRICKS);\n\tpublic static List<MapColor> surfacematerials = Arrays.asList(MapColor.WATER, MapColor.ICE);\n}" }, { "identifier": "BlockPosFunctions", "path": "Common/src/main/java/com/natamus/collective/functions/BlockPosFunctions.java", "snippet": "public class BlockPosFunctions {\n\t// START: GET functions\n\tpublic static List<BlockPos> getBlocksAround(BlockPos pos, boolean down) {\n\t\tList<BlockPos> around = new ArrayList<BlockPos>();\n\t\taround.add(pos.north());\n\t\taround.add(pos.east());\n\t\taround.add(pos.south());\n\t\taround.add(pos.west());\n\t\taround.add(pos.above());\n\t\tif (down) {\n\t\t\taround.add(pos.below());\n\t\t}\n\t\treturn around;\n\t}\n\n\t// START: RECURSIVE GET BLOCKS\n\tprivate static final HashMap<BlockPos, Integer> rgnbcount = new HashMap<BlockPos, Integer>();\n\n\tpublic static List<BlockPos> getBlocksNextToEachOther(Level world, BlockPos startpos, List<Block> possibleblocks) {\n\t\treturn getBlocksNextToEachOther(world, startpos, possibleblocks, 50);\n\t}\n\tpublic static List<BlockPos> getBlocksNextToEachOther(Level world, BlockPos startpos, List<Block> possibleblocks, int maxDistance) {\n\t\tList<BlockPos> checkedblocks = new ArrayList<BlockPos>();\n\t\tList<BlockPos> theblocksaround = new ArrayList<BlockPos>();\n\t\tif (possibleblocks.contains(world.getBlockState(startpos).getBlock())) {\n\t\t\ttheblocksaround.add(startpos);\n\t\t\tcheckedblocks.add(startpos);\n\t\t}\n\n\t\trgnbcount.put(startpos.immutable(), 0);\n\t\trecursiveGetNextBlocks(world, startpos, startpos, possibleblocks, theblocksaround, checkedblocks, maxDistance);\n\t\treturn theblocksaround;\n\t}\n\tprivate static void recursiveGetNextBlocks(Level world, BlockPos startpos, BlockPos pos, List<Block> possibleblocks, List<BlockPos> theblocksaround, List<BlockPos> checkedblocks, int maxDistance) {\n\t\tint rgnbc = rgnbcount.get(startpos);\n\t\tif (rgnbc > 100) {\n\t\t\treturn;\n\t\t}\n\t\trgnbcount.put(startpos, rgnbc + 1);\n\n\t\tList<BlockPos> possibleblocksaround = getBlocksAround(pos, true);\n\t\tfor (BlockPos pba : possibleblocksaround) {\n\t\t\tif (checkedblocks.contains(pba)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcheckedblocks.add(pba);\n\n\t\t\tif (possibleblocks.contains(world.getBlockState(pba).getBlock())) {\n\t\t\t\tif (!theblocksaround.contains(pba)) {\n\t\t\t\t\ttheblocksaround.add(pba);\n\t\t\t\t\tif (BlockPosFunctions.withinDistance(startpos, pba, maxDistance)) {\n\t\t\t\t\t\trecursiveGetNextBlocks(world, startpos, pba, possibleblocks, theblocksaround, checkedblocks, maxDistance);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprivate static final HashMap<BlockPos, Integer> rgnbmcount = new HashMap<BlockPos, Integer>();\n\n\tpublic static List<BlockPos> getBlocksNextToEachOtherMaterial(Level world, BlockPos startpos, List<MapColor> possiblematerials) {\n\t\treturn getBlocksNextToEachOtherMaterial(world, startpos, possiblematerials, 50);\n\t}\n\tpublic static List<BlockPos> getBlocksNextToEachOtherMaterial(Level world, BlockPos startpos, List<MapColor> possiblematerials, int maxDistance) {\n\t\tList<BlockPos> checkedblocks = new ArrayList<BlockPos>();\n\t\tList<BlockPos> theblocksaround = new ArrayList<BlockPos>();\n\t\tif (possiblematerials.contains(world.getBlockState(startpos).getMapColor(world, startpos))) {\n\t\t\ttheblocksaround.add(startpos);\n\t\t\tcheckedblocks.add(startpos);\n\t\t}\n\n\t\trgnbmcount.put(startpos.immutable(), 0);\n\t\trecursiveGetNextBlocksMaterial(world, startpos, startpos, possiblematerials, theblocksaround, checkedblocks, maxDistance);\n\t\treturn theblocksaround;\n\t}\n\tprivate static void recursiveGetNextBlocksMaterial(Level world, BlockPos startpos, BlockPos pos, List<MapColor> possiblematerials, List<BlockPos> theblocksaround, List<BlockPos> checkedblocks, int maxDistance) {\n\t\tint rgnbmc = rgnbmcount.get(startpos);\n\t\tif (rgnbmc > 100) {\n\t\t\treturn;\n\t\t}\n\t\trgnbmcount.put(startpos, rgnbmc + 1);\n\n\t\tList<BlockPos> possibleblocksaround = getBlocksAround(pos, true);\n\t\tfor (BlockPos pba : possibleblocksaround) {\n\t\t\tif (checkedblocks.contains(pba)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcheckedblocks.add(pba);\n\n\t\t\tif (possiblematerials.contains(world.getBlockState(pba).getMapColor(world, pba))) {\n\t\t\t\tif (!theblocksaround.contains(pba)) {\n\t\t\t\t\ttheblocksaround.add(pba);\n\t\t\t\t\tif (BlockPosFunctions.withinDistance(startpos, pba, maxDistance)) {\n\t\t\t\t\t\trecursiveGetNextBlocksMaterial(world, startpos, pba, possiblematerials, theblocksaround, checkedblocks, maxDistance);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// END RECURSIVE GET BLOCKS\n\n\tpublic static BlockPos getSurfaceBlockPos(ServerLevel serverLevel, int x, int z) {\n\t\treturn getSurfaceBlockPos(serverLevel, x, z, false);\n\t}\n\tpublic static BlockPos getSurfaceBlockPos(ServerLevel serverLevel, int x, int z, boolean ignoreTrees) {\n\t\tint height = serverLevel.getHeight();\n\t\tint lowestY = serverLevel.getMinBuildHeight();\n\n\t\tBlockPos returnpos = new BlockPos(x, height-1, z);\n\t\tif (!WorldFunctions.isNether(serverLevel)) {\n\t\t\tBlockPos pos = new BlockPos(x, height, z);\n\t\t\tfor (int y = height; y > lowestY; y--) {\n\t\t\t\tboolean continueCycle = false;\n\n\t\t\t\tBlockState blockState = serverLevel.getBlockState(pos);\n\t\t\t\tif (ignoreTrees) {\n\t\t\t\t\tBlock block = blockState.getBlock();\n\t\t\t\t\tif (CompareBlockFunctions.isTreeLeaf(block) || CompareBlockFunctions.isTreeLog(block)) {\n\t\t\t\t\t\tcontinueCycle = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!continueCycle) {\n\t\t\t\t\tMapColor material = blockState.getMapColor(serverLevel, pos);\n\t\t\t\t\tif (blockState.getLightBlock(serverLevel, pos) >= 15 || GlobalVariables.surfacematerials.contains(material)) {\n\t\t\t\t\t\treturnpos = pos.above().immutable();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpos = pos.below();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint maxheight = 128;\n\t\t\tBlockPos pos = new BlockPos(x, lowestY, z);\n\t\t\tfor (int y = lowestY; y < maxheight; y++) {\n\t\t\t\tBlockState blockstate = serverLevel.getBlockState(pos);\n\t\t\t\tif (blockstate.getBlock().equals(Blocks.AIR)) {\n\t\t\t\t\tBlockState upstate = serverLevel.getBlockState(pos.above());\n\t\t\t\t\tif (upstate.getBlock().equals(Blocks.AIR)) {\n\t\t\t\t\t\treturnpos = pos.immutable();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpos = pos.above();\n\t\t\t}\n\t\t}\n\n\t\treturn returnpos;\n\t}\n\n\tpublic static BlockPos getCenterNearbyVillage(ServerLevel serverLevel) {\n\t\treturn getNearbyVillage(serverLevel, new BlockPos(0, 0, 0));\n\t}\n\tpublic static BlockPos getNearbyVillage(ServerLevel serverLevel, BlockPos nearPos) {\n\t\tBlockPos closestvillage = null;\n\t\tif (!serverLevel.getServer().getWorldData().worldGenOptions().generateStructures()) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString rawOutput = CommandFunctions.getRawCommandOutput(serverLevel, Vec3.atBottomCenterOf(nearPos), \"/locate structure #minecraft:village\");\n\n\t\tif (rawOutput.contains(\"[\") && rawOutput.contains(\"]\") && rawOutput.contains(\", \")) {\n\t\t\tString[] coords;\n\t\t\ttry {\n\t\t\t\tif (rawOutput.contains(\":\")) {\n\t\t\t\t\trawOutput = rawOutput.split(\":\", 2)[1];\n\t\t\t\t}\n\n\t\t\t\tString rawcoords = rawOutput.split(\"\\\\[\")[1].split(\"]\")[0];\n\t\t\t\tcoords = rawcoords.split(\", \");\n\t\t\t}\n\t\t\tcatch (IndexOutOfBoundsException ex) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tif (coords.length == 3) {\n\t\t\t\tString sx = coords[0];\n\t\t\t\tString sz = coords[2];\n\t\t\t\tif (NumberFunctions.isNumeric(sx) && NumberFunctions.isNumeric(sz)) {\n\t\t\t\t\treturn getSurfaceBlockPos(serverLevel, Integer.parseInt(sx), Integer.parseInt(sz));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn closestvillage;\n\t}\n\n\tpublic static BlockPos getCenterNearbyBiome(ServerLevel serverLevel, String biome) {\n\t\treturn getNearbyBiome(serverLevel, new BlockPos(0, 0, 0), biome);\n\t}\n\tpublic static BlockPos getNearbyBiome(ServerLevel serverLevel, BlockPos nearPos, String biome) {\n\t\tString rawOutput = CommandFunctions.getRawCommandOutput(serverLevel, Vec3.atBottomCenterOf(nearPos), \"/locate biome \" + biome);\n\n\t\tif (rawOutput.contains(\"nearest\") && rawOutput.contains(\"[\")) {\n\t\t\tString rawcoords = rawOutput.split(\"nearest\")[1].split(\"\\\\[\")[1].split(\"]\")[0];\n\t\t\tString[] coords = rawcoords.split(\", \");\n\t\t\tif (coords.length == 3) {\n\t\t\t\tString sx = coords[0];\n\t\t\t\tString sz = coords[2];\n\t\t\t\tif (NumberFunctions.isNumeric(sx) && NumberFunctions.isNumeric(sz)) {\n\t\t\t\t\treturn getSurfaceBlockPos(serverLevel, Integer.parseInt(sx), Integer.parseInt(sz));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic static BlockPos getCenterNearbyStructure(ServerLevel serverworld, HolderSet<Structure> structure) {\n\t\treturn getNearbyStructure(serverworld, structure, new BlockPos(0, 0, 0));\n\t}\n\tpublic static BlockPos getNearbyStructure(ServerLevel serverworld, HolderSet<Structure> structure, BlockPos nearpos) {\n\t\treturn getNearbyStructure(serverworld, structure, nearpos, 9999);\n\t}\n\tpublic static BlockPos getNearbyStructure(ServerLevel serverworld, HolderSet<Structure> structure, BlockPos nearpos, int radius) {\n\t\tPair<BlockPos, Holder<Structure>> pair = serverworld.getChunkSource().getGenerator().findNearestMapStructure(serverworld, structure, nearpos, radius, false);\n\t\tif (pair == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tBlockPos villagepos = pair.getFirst();\n\t\tif (villagepos == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tBlockPos spawnpos = null;\n\t\tfor (int y = serverworld.getHeight()-1; y > 0; y--) {\n\t\t\tBlockPos checkpos = new BlockPos(villagepos.getX(), y, villagepos.getZ());\n\t\t\tif (serverworld.getBlockState(checkpos).getBlock().equals(Blocks.AIR)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tspawnpos = checkpos.above().immutable();\n\t\t\tbreak;\n\t\t}\n\n\t\treturn spawnpos;\n\t}\n\n\tpublic static BlockPos getBlockPlayerIsLookingAt(Level world, Player player, boolean stopOnLiquid) {\n\t\tHitResult raytraceresult = RayTraceFunctions.rayTrace(world, player, stopOnLiquid);\n double posX = raytraceresult.getLocation().x;\n double posY = Math.floor(raytraceresult.getLocation().y);\n double posZ = raytraceresult.getLocation().z;\n\n return BlockPos.containing(posX, posY, posZ);\n\t}\n\n\tpublic static BlockPos getRandomCoordinatesInNearestUngeneratedChunk(ServerLevel serverLevel, BlockPos aroundPosition) {\n\t\tList<String> regionList = new ArrayList<String>();\n\n\t\ttry {\n\t\t\tFile regionFolder = new File(WorldFunctions.getWorldPath(serverLevel) + File.separator + \"region\");\n\t\t\tFile[] listOfRegionFiles = regionFolder.listFiles();\n\n\t\t\tfor (File regionFile : listOfRegionFiles) {\n\t\t\t\tif (regionFile.isFile()) {\n\t\t\t\t\tregionList.add(regionFile.getName().replaceAll(\"r.\", \"\").replaceAll(\".mca\", \"\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch(NullPointerException ignored) {\n\t\t\treturn null;\n\t\t}\n\n\t\tChunkPos chunkPos = serverLevel.getChunkAt(aroundPosition).getPos();\n\t\tint curRegionX = chunkPos.getRegionX();\n\t\tint curRegionZ = chunkPos.getRegionZ();\n\n\t\tint currentRange = 1;\n\t\tint loops = 0;\n\n\t\tString closestUngeneratedRegionString = \"\";\n\t\twhile (closestUngeneratedRegionString.equals(\"\")) {\n\t\t\tfor (int x = -1; x <= 1; x++) {\n\t\t\t\tfor (int z = -1; z <= 1; z++) {\n\t\t\t\t\tint regionX = curRegionX + (x*currentRange);\n\t\t\t\t\tint regionZ = curRegionZ + (z*currentRange);\n\n\t\t\t\t\tString regionString = regionX + \".\" + regionZ;\n\t\t\t\t\tif (!regionList.contains(regionString)) {\n\t\t\t\t\t\tclosestUngeneratedRegionString = regionString;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!closestUngeneratedRegionString.equals(\"\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentRange += 1;\n\t\t\tloops += 1;\n\n\t\t\tif (loops > 50) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tint outputRegionX, outputRegionZ;\n\n\t\tString[] cursspl = closestUngeneratedRegionString.split(\"\\\\.\");\n\t\ttry {\n\t\t\toutputRegionX = Integer.parseInt(cursspl[0]);\n\t\t\toutputRegionZ = Integer.parseInt(cursspl[1]);\n\t\t}\n\t\tcatch (NumberFormatException ex) {\n\t\t\treturn null;\n\t\t}\n\n\t\tint minXRange = (outputRegionX * 512) - 256;\n\t\tint maxXRange = (outputRegionX * 512) + 256;\n\t\tint minZRange = (outputRegionZ * 512) - 256;\n\t\tint maxZRange = (outputRegionZ * 512) + 256;\n\n\t\tint randomXCoord = ThreadLocalRandom.current().nextInt(minXRange, maxXRange + 1);\n\t\tint randomZCoord = ThreadLocalRandom.current().nextInt(minZRange, maxZRange + 1);\n\t\tint randomYCoord = BlockPosFunctions.getSurfaceBlockPos(serverLevel, randomXCoord, randomZCoord).getY();\n\n\t\treturn new BlockPos(randomXCoord, randomYCoord, randomZCoord);\n\t}\n\t// END: GET functions\n\n\n\t// START: CHECK functions\n\tpublic static Boolean isOnSurface(Level world, BlockPos pos) {\n\t\treturn world.canSeeSky(pos);\n\t}\n\tpublic static Boolean isOnSurface(Level world, Vec3 vecpos) {\n\t\treturn isOnSurface(world, BlockPos.containing(vecpos.x, vecpos.y, vecpos.z));\n\t}\n\n\n\tpublic static Boolean withinDistance(BlockPos start, BlockPos end, int distance) {\n\t\treturn withinDistance(start, end, (double) distance);\n\t}\n\tpublic static Boolean withinDistance(BlockPos start, BlockPos end, double distance) {\n\t\treturn start.closerThan(end, distance);\n\t}\n\t// END: CHECK functions\n\n\tpublic static BlockPos getBlockPosFromHitResult(HitResult hitresult) {\n\t\tVec3 vec = hitresult.getLocation();\n\t\treturn BlockPos.containing(vec.x, vec.y, vec.z);\n\t}\n}" }, { "identifier": "EntityFunctions", "path": "Common/src/main/java/com/natamus/collective/functions/EntityFunctions.java", "snippet": "public class EntityFunctions {\n\t// START: CHECK functions\n\tpublic static Boolean isHorse(Entity entity) {\n\t\treturn entity instanceof AbstractHorse;\n\t}\n\n\tpublic static boolean isModdedVillager(String entitystring) {\n\t\tString type = entitystring.split(\"\\\\[\")[0];\n\t\tfor (String moddedvillager : GlobalVariables.moddedvillagers) {\n\t\t\tif (type.equalsIgnoreCase(moddedvillager)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\tpublic static boolean isModdedVillager(Entity entity) {\n\t\tString entitystring = getEntityString(entity);\n\t\treturn isModdedVillager(entitystring);\n\t}\n\n\tpublic static boolean isMilkable(Entity entity) {\n\t\tif (entity instanceof Sheep || entity instanceof Llama || entity instanceof Pig || entity instanceof Donkey || entity instanceof Horse || entity instanceof Mule) {\n\t\t\tif (!(entity instanceof Animal)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAnimal animal = (Animal)entity;\n\t\t\treturn !animal.isBaby();\n\t\t}\n\t\treturn false;\n\t}\n\t// END: CHECK functions\n\n\n\t// START: GET functions\n\tpublic static String getEntityString(Entity entity) {\n\t\tString entitystring = \"\";\n\n\t\tResourceLocation rl = EntityType.getKey(entity.getType());\n\t\tif (rl != null) {\n\t\t\tentitystring = rl.toString(); // minecraft:villager, minecraft:wandering_trader\n\t\t\tif (entitystring.contains(\":\")) {\n\t\t\t\tentitystring = entitystring.split(\":\")[1];\n\t\t\t}\n\n\t\t\tentitystring = StringFunctions.capitalizeEveryWord(entitystring.replace(\"_\", \" \")).replace(\" \", \"\").replace(\"Entity\", \"\"); // Villager, WanderingTrader\n\t\t}\n\n\t\treturn entitystring;\n\t}\n\t// END: GET functions\n\n\n\t// Do functions\n\tpublic static void nameEntity(Entity entity, String name) {\n\t\tif (!name.equals(\"\")) {\n\t\t\tentity.setCustomName(Component.literal(name));\n\t\t}\n\t}\n\n\tpublic static void addPotionEffect(Entity entity, MobEffect effect, Integer ms) {\n\t\tMobEffectInstance freeze = new MobEffectInstance(effect, ms/50);\n\t\tLivingEntity le = (LivingEntity)entity;\n\t\tle.addEffect(freeze);\n\t}\n\tpublic static void removePotionEffect(Entity entity, MobEffect effect) {\n\t\tLivingEntity le = (LivingEntity)entity;\n\t\tle.removeEffect(effect);\n\t}\n\n\tpublic static void chargeEntity(Entity entity) {\n\t\tLevel world = entity.level();\n\t\tif (entity instanceof Creeper) {\n\t\t\tentity.getEntityData().set(Creeper.DATA_IS_POWERED, true);\n\t\t}\n\t\telse if (entity instanceof MushroomCow) {\n\t\t\t((MushroomCow)entity).setVariant(MushroomCow.MushroomType.BROWN);\n\t\t}\n\t}\n\n\tpublic static void setEntityFlag(Entity entity, int flag, boolean set) {\n\t\tentity.setSharedFlag(flag, set);\n\t}\n\n\tpublic static boolean getAbstractHorseEntityFlagResult(AbstractHorse abstractHorse, int flag) {\n\t\treturn abstractHorse.getFlag(flag);\n\t}\n\n\tpublic static void resetMerchantOffers(Villager villager) {\n\t\tfor (MerchantOffer offer : villager.getOffers()) {\n\t\t\tresetMerchantOffer(offer);\n\t\t}\n\t}\n\tpublic static void resetMerchantOffers(WanderingTrader wanderingTrader) {\n\t\tfor (MerchantOffer offer : wanderingTrader.getOffers()) {\n\t\t\tresetMerchantOffer(offer);\n\t\t}\n\t}\n\tpublic static void resetMerchantOffer(MerchantOffer offer) {\n\t\toffer.uses = 0;\n\t\toffer.maxUses = Integer.MAX_VALUE;\n\t\toffer.demand = 0;\n\t}\n\n\tpublic static void forceSetHealth(LivingEntity livingEntity, float health) {\n\t\tlivingEntity.getEntityData().set(LivingEntity.DATA_HEALTH_ID, health);\n\t}\n\n\tpublic static boolean fishingHookHasCatch(FishingHook fishingHook) {\n\t\treturn fishingHook.biting;\n\t}\n\n\tpublic static void transferItemsBetweenEntities(Entity from, Entity to, boolean ignoremainhand) {\n\t\tif (!(from instanceof Mob)) {\n\t\t\treturn;\n\t\t}\n\t\tMob mobfrom = (Mob)from;\n\n\t\tfor(EquipmentSlot equipmentslottype : EquipmentSlot.values()) {\n\t\t\tif (ignoremainhand) {\n\t\t\t\tif (equipmentslottype.equals(EquipmentSlot.MAINHAND)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tItemStack itemstack = mobfrom.getItemBySlot(equipmentslottype);\n\t\t\tif (!itemstack.isEmpty()) {\n\t\t\t\tto.setItemSlot(equipmentslottype, itemstack.copy());\n\t\t\t}\n\t\t}\n\t}\n\tpublic static void transferItemsBetweenEntities(Entity from, Entity to) {\n\t\ttransferItemsBetweenEntities(from, to, false);\n\t}\n\n\tpublic static Boolean doesEntitySurviveThisDamage(Player player, int halfheartdamage) {\n\t\treturn doesEntitySurviveThisDamage((LivingEntity)player, halfheartdamage);\n\t}\n\tpublic static Boolean doesEntitySurviveThisDamage(LivingEntity entity, int halfheartdamage) {\n\t\tLevel level = entity.level();\n\t\tfloat newhealth = entity.getHealth() - (float)halfheartdamage;\n\t\tif (newhealth > 0f) {\n\t\t\tentity.hurt(level.damageSources().magic(), 0.1F);\n\t\t\tentity.setHealth(newhealth);\n\t\t}\n\t\telse {\n\t\t\tentity.hurt(level.damageSources().magic(), Float.MAX_VALUE);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic static Boolean isEntityFromSpawner(Entity entity) {\n\t\tif (entity == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn entity.getTags().contains(CollectiveReference.MOD_ID + \".fromspawner\");\n\t}\n\n\tpublic static void setEntitySize(Entity entity, EntityDimensions entityDimensions, float eyeHight) {\n\t\tentity.dimensions = entityDimensions;\n\t\tentity.eyeHeight = eyeHight;\n\t}\n\n\tpublic static GoalSelector getGoalSelector(Mob mob) {\n\t\treturn mob.goalSelector;\n\t}\n\tpublic static GoalSelector getTargetSelector(Mob mob) {\n\t\treturn mob.targetSelector;\n\t}\n}" }, { "identifier": "SpawnEntityFunctions", "path": "Common/src/main/java/com/natamus/collective/functions/SpawnEntityFunctions.java", "snippet": "public class SpawnEntityFunctions {\n\tpublic static void spawnEntityOnNextTick(ServerLevel serverlevel, Entity entity) {\n\t\tCollectiveEvents.entitiesToSpawn.computeIfAbsent(serverlevel, k -> new ArrayList<Entity>()).add(entity);\n\t}\n\n\tpublic static void startRidingEntityOnNextTick(ServerLevel serverlevel, Entity ridden, Entity rider) {\n\t\tCollectiveEvents.entitiesToRide.computeIfAbsent(serverlevel, k -> new WeakHashMap<Entity, Entity>()).put(ridden, rider);\n\t}\n}" }, { "identifier": "SAMObject", "path": "Common/src/main/java/com/natamus/collective/objects/SAMObject.java", "snippet": "public class SAMObject {\n\tpublic EntityType<?> fromEntityType;\n\tpublic EntityType<?> toEntityType;\n\tpublic Item itemToHold;\n\n\tpublic double changeChance;\n\tpublic boolean onlyFromSpawner;\n\tpublic boolean rideNotReplace;\n\tpublic boolean onlyOnSurface;\n\tpublic boolean onlyBelowSurface;\n\tpublic boolean onlyBelowSpecificY;\n\tpublic int specificY;\n\n\tpublic SAMObject(EntityType<?> fromEntityTypeIn, EntityType<?> toEntityTypeIn, Item itemToHoldIn, double changeChanceIn, boolean onlyFromSpawnerIn, boolean rideNotReplaceIn, boolean onlyOnSurfaceIn) {\n\t\tnew SAMObject(fromEntityTypeIn, toEntityTypeIn, itemToHoldIn, changeChanceIn, onlyFromSpawnerIn, rideNotReplaceIn, onlyOnSurfaceIn, false);\n\t}\n\tpublic SAMObject(EntityType<?> fromEntityTypeIn, EntityType<?> toEntityTypeIn, Item itemToHoldIn, double changeChanceIn, boolean onlyFromSpawnerIn, boolean rideNotReplaceIn, boolean onlyOnSurfaceIn, boolean onlyBelowSurfaceIn) {\n\t\tnew SAMObject(fromEntityTypeIn, toEntityTypeIn, itemToHoldIn, changeChanceIn, onlyFromSpawnerIn, rideNotReplaceIn, onlyOnSurfaceIn, onlyBelowSurfaceIn, false, Integer.MAX_VALUE);\n\t}\n\tpublic SAMObject(EntityType<?> fromEntityTypeIn, EntityType<?> toEntityTypeIn, Item itemToHoldIn, double changeChanceIn, boolean onlyFromSpawnerIn, boolean rideNotReplaceIn, boolean onlyOnSurfaceIn, boolean onlyBelowSurfaceIn, boolean onlyBelowSpecificYIn, int specificYIn) {\n\t\tfromEntityType = fromEntityTypeIn;\n\t\ttoEntityType = toEntityTypeIn;\n\t\titemToHold = itemToHoldIn;\n\n\t\tchangeChance = changeChanceIn;\n\t\tonlyFromSpawner = onlyFromSpawnerIn;\n\t\trideNotReplace = rideNotReplaceIn;\n\t\tonlyOnSurface = onlyOnSurfaceIn;\n\t\tonlyBelowSurface = onlyBelowSurfaceIn;\n\t\tonlyBelowSpecificY = onlyBelowSpecificYIn;\n\t\tspecificY = specificYIn;\n\n\t\tGlobalVariables.globalSAMs.add(this);\n\t\tif (!GlobalVariables.activeSAMEntityTypes.contains(fromEntityType)) {\n\t\t\tGlobalVariables.activeSAMEntityTypes.add(fromEntityType);\n\t\t}\n\t}\n}" }, { "identifier": "CollectiveReference", "path": "Common/src/main/java/com/natamus/collective/util/CollectiveReference.java", "snippet": "public class CollectiveReference {\n\tpublic static final String MOD_ID = \"collective\";\n\tpublic static final String NAME = \"Collective\";\n\tpublic static final String VERSION = \"7.30\";\n\tpublic static final String ACCEPTED_VERSIONS = \"[1.20.4]\";\n}" } ]
import com.mojang.datafixers.util.Pair; import com.natamus.collective.check.RegisterMod; import com.natamus.collective.config.CollectiveConfigHandler; import com.natamus.collective.data.GlobalVariables; import com.natamus.collective.functions.BlockPosFunctions; import com.natamus.collective.functions.EntityFunctions; import com.natamus.collective.functions.SpawnEntityFunctions; import com.natamus.collective.objects.SAMObject; import com.natamus.collective.util.CollectiveReference; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.AgeableMob; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity.RemovalReason; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.animal.horse.AbstractHorse; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CopyOnWriteArrayList;
9,669
package com.natamus.collective.events; public class CollectiveEvents { public static WeakHashMap<ServerLevel, List<Entity>> entitiesToSpawn = new WeakHashMap<ServerLevel, List<Entity>>(); public static WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>> entitiesToRide = new WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>>(); public static CopyOnWriteArrayList<Pair<Integer, Runnable>> scheduledRunnables = new CopyOnWriteArrayList<Pair<Integer, Runnable>>(); public static void onWorldTick(ServerLevel serverLevel) { if (entitiesToSpawn.computeIfAbsent(serverLevel, k -> new ArrayList<Entity>()).size() > 0) { Entity tospawn = entitiesToSpawn.get(serverLevel).get(0); serverLevel.addFreshEntityWithPassengers(tospawn); if (entitiesToRide.computeIfAbsent(serverLevel, k -> new WeakHashMap<Entity, Entity>()).containsKey(tospawn)) { Entity rider = entitiesToRide.get(serverLevel).get(tospawn); rider.startRiding(tospawn); entitiesToRide.get(serverLevel).remove(tospawn); } entitiesToSpawn.get(serverLevel).remove(0); } } public static void onServerTick(MinecraftServer minecraftServer) { int serverTickCount = minecraftServer.getTickCount(); for (Pair<Integer, Runnable> pair : scheduledRunnables) { if (pair.getFirst() <= serverTickCount) { minecraftServer.tell(new TickTask(minecraftServer.getTickCount(), pair.getSecond())); scheduledRunnables.remove(pair); } } } public static boolean onEntityJoinLevel(Level level, Entity entity) { if (!(entity instanceof LivingEntity)) { return true; } if (RegisterMod.shouldDoCheck) { if (entity instanceof Player) { RegisterMod.joinWorldProcess(level, (Player)entity); } } if (entity.isRemoved()) { return true; } if (GlobalVariables.globalSAMs.isEmpty()) { return true; } Set<String> tags = entity.getTags(); if (tags.contains(CollectiveReference.MOD_ID + ".checked")) { return true; } entity.addTag(CollectiveReference.MOD_ID + ".checked"); EntityType<?> entityType = entity.getType(); if (!GlobalVariables.activeSAMEntityTypes.contains(entityType)) { return true; } boolean isFromSpawner = tags.contains(CollectiveReference.MOD_ID + ".fromspawner");
package com.natamus.collective.events; public class CollectiveEvents { public static WeakHashMap<ServerLevel, List<Entity>> entitiesToSpawn = new WeakHashMap<ServerLevel, List<Entity>>(); public static WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>> entitiesToRide = new WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>>(); public static CopyOnWriteArrayList<Pair<Integer, Runnable>> scheduledRunnables = new CopyOnWriteArrayList<Pair<Integer, Runnable>>(); public static void onWorldTick(ServerLevel serverLevel) { if (entitiesToSpawn.computeIfAbsent(serverLevel, k -> new ArrayList<Entity>()).size() > 0) { Entity tospawn = entitiesToSpawn.get(serverLevel).get(0); serverLevel.addFreshEntityWithPassengers(tospawn); if (entitiesToRide.computeIfAbsent(serverLevel, k -> new WeakHashMap<Entity, Entity>()).containsKey(tospawn)) { Entity rider = entitiesToRide.get(serverLevel).get(tospawn); rider.startRiding(tospawn); entitiesToRide.get(serverLevel).remove(tospawn); } entitiesToSpawn.get(serverLevel).remove(0); } } public static void onServerTick(MinecraftServer minecraftServer) { int serverTickCount = minecraftServer.getTickCount(); for (Pair<Integer, Runnable> pair : scheduledRunnables) { if (pair.getFirst() <= serverTickCount) { minecraftServer.tell(new TickTask(minecraftServer.getTickCount(), pair.getSecond())); scheduledRunnables.remove(pair); } } } public static boolean onEntityJoinLevel(Level level, Entity entity) { if (!(entity instanceof LivingEntity)) { return true; } if (RegisterMod.shouldDoCheck) { if (entity instanceof Player) { RegisterMod.joinWorldProcess(level, (Player)entity); } } if (entity.isRemoved()) { return true; } if (GlobalVariables.globalSAMs.isEmpty()) { return true; } Set<String> tags = entity.getTags(); if (tags.contains(CollectiveReference.MOD_ID + ".checked")) { return true; } entity.addTag(CollectiveReference.MOD_ID + ".checked"); EntityType<?> entityType = entity.getType(); if (!GlobalVariables.activeSAMEntityTypes.contains(entityType)) { return true; } boolean isFromSpawner = tags.contains(CollectiveReference.MOD_ID + ".fromspawner");
List<SAMObject> possibles = new ArrayList<SAMObject>();
6
2023-12-11 22:37:15+00:00
12k
muchfish/ruoyi-vue-pro-sample
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/service/comment/ProductCommentServiceImpl.java
[ { "identifier": "PageResult", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/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": "ProductCommentCreateReqVO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/comment/vo/ProductCommentCreateReqVO.java", "snippet": "@Schema(description = \"管理后台 - 商品评价创建 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\npublic class ProductCommentCreateReqVO extends ProductCommentBaseVO {\n\n}" }, { "identifier": "ProductCommentPageReqVO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/comment/vo/ProductCommentPageReqVO.java", "snippet": "@Schema(description = \"管理后台 - 商品评价分页 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\npublic class ProductCommentPageReqVO extends PageParam {\n\n @Schema(description = \"评价人名称\", example = \"王二狗\")\n private String userNickname;\n\n @Schema(description = \"交易订单编号\", example = \"24428\")\n private Long orderId;\n\n @Schema(description = \"商品SPU编号\", example = \"29502\")\n private Long spuId;\n\n @Schema(description = \"商品SPU名称\", example = \"感冒药\")\n private String spuName;\n\n @Schema(description = \"评分星级 1-5 分\", example = \"5\")\n @InEnum(ProductCommentScoresEnum.class)\n private Integer scores;\n\n @Schema(description = \"商家是否回复\", example = \"true\")\n private Boolean replyStatus;\n\n @Schema(description = \"创建时间\")\n @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)\n private LocalDateTime[] createTime;\n\n}" }, { "identifier": "ProductCommentReplyReqVO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/comment/vo/ProductCommentReplyReqVO.java", "snippet": "@Schema(description = \"管理后台 - 商品评价的商家回复 Request VO\")\n@Data\n@ToString(callSuper = true)\npublic class ProductCommentReplyReqVO {\n\n @Schema(description = \"评价编号\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"15721\")\n @NotNull(message = \"评价编号不能为空\")\n private Long id;\n\n @Schema(description = \"商家回复内容\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"谢谢亲\")\n @NotEmpty(message = \"商家回复内容不能为空\")\n private String replyContent;\n\n}" }, { "identifier": "ProductCommentUpdateVisibleReqVO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/comment/vo/ProductCommentUpdateVisibleReqVO.java", "snippet": "@Schema(description = \"管理后台 - 商品评价可见修改 Request VO\")\n@Data\n@ToString(callSuper = true)\npublic class ProductCommentUpdateVisibleReqVO {\n\n @Schema(description = \"评价编号\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"15721\")\n @NotNull(message = \"评价编号不能为空\")\n private Long id;\n\n @Schema(description = \"是否可见\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"false\")\n @NotNull(message = \"是否可见不能为空\")\n private Boolean visible;\n\n}" }, { "identifier": "ProductCommentConvert", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/convert/comment/ProductCommentConvert.java", "snippet": "@Mapper\npublic interface ProductCommentConvert {\n\n ProductCommentConvert INSTANCE = Mappers.getMapper(ProductCommentConvert.class);\n\n ProductCommentRespVO convert(ProductCommentDO bean);\n\n PageResult<ProductCommentRespVO> convertPage(PageResult<ProductCommentDO> page);\n\n /**\n * 计算综合评分\n *\n * @param descriptionScores 描述星级\n * @param benefitScores 服务星级\n * @return 综合评分\n */\n @Named(\"convertScores\")\n default Integer convertScores(Integer descriptionScores, Integer benefitScores) {\n // 计算评价最终综合评分 最终星数 = (商品评星 + 服务评星) / 2\n BigDecimal sumScore = new BigDecimal(descriptionScores + benefitScores);\n BigDecimal divide = sumScore.divide(BigDecimal.valueOf(2L), 0, RoundingMode.DOWN);\n return divide.intValue();\n }\n\n @Mapping(target = \"visible\", constant = \"true\")\n @Mapping(target = \"replyStatus\", constant = \"false\")\n @Mapping(target = \"userId\", constant = \"0L\")\n @Mapping(target = \"orderId\", constant = \"0L\")\n @Mapping(target = \"orderItemId\", constant = \"0L\")\n @Mapping(target = \"anonymous\", expression = \"java(Boolean.FALSE)\")\n @Mapping(target = \"scores\",\n expression = \"java(convertScores(createReq.getDescriptionScores(), createReq.getBenefitScores()))\")\n ProductCommentDO convert(ProductCommentCreateReqVO createReq);\n\n default ProductCommentDO convert(ProductCommentCreateReqVO createReq, ProductSpuDO spu, ProductSkuDO sku) {\n ProductCommentDO commentDO = convert(createReq);\n if (spu != null) {\n commentDO.setSpuId(spu.getId()).setSpuName(spu.getName());\n }\n if (sku != null) {\n commentDO.setSkuPicUrl(sku.getPicUrl()).setSkuProperties(sku.getProperties());\n }\n return commentDO;\n }\n\n}" }, { "identifier": "ProductCommentDO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/dal/dataobject/comment/ProductCommentDO.java", "snippet": "@TableName(value = \"product_comment\", autoResultMap = true)\n@KeySequence(\"product_comment_seq\") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ProductCommentDO extends BaseDO {\n\n /**\n * 默认匿名昵称\n */\n public static final String NICKNAME_ANONYMOUS = \"匿名用户\";\n\n /**\n * 评论编号,主键自增\n */\n @TableId\n private Long id;\n\n /**\n * 评价人的用户编号\n *\n * 关联 MemberUserDO 的 id 编号\n */\n private Long userId;\n /**\n * 评价人名称\n */\n private String userNickname;\n /**\n * 评价人头像\n */\n private String userAvatar;\n /**\n * 是否匿名\n */\n private Boolean anonymous;\n\n /**\n * 交易订单编号\n *\n * 关联 TradeOrderDO 的 id 编号\n */\n private Long orderId;\n /**\n * 交易订单项编号\n *\n * 关联 TradeOrderItemDO 的 id 编号\n */\n private Long orderItemId;\n\n /**\n * 商品 SPU 编号\n *\n * 关联 {@link ProductSpuDO#getId()}\n */\n private Long spuId;\n /**\n * 商品 SPU 名称\n *\n * 关联 {@link ProductSpuDO#getName()}\n */\n private String spuName;\n /**\n * 商品 SKU 编号\n *\n * 关联 {@link ProductSkuDO#getId()}\n */\n private Long skuId;\n /**\n * 商品 SKU 图片地址\n *\n * 关联 {@link ProductSkuDO#getPicUrl()}\n */\n private String skuPicUrl;\n /**\n * 属性数组,JSON 格式\n *\n * 关联 {@link ProductSkuDO#getProperties()}\n */\n @TableField(typeHandler = ProductSkuDO.PropertyTypeHandler.class)\n private List<ProductSkuDO.Property> skuProperties;\n\n /**\n * 是否可见\n *\n * true:显示\n * false:隐藏\n */\n private Boolean visible;\n /**\n * 评分星级\n *\n * 1-5 分\n */\n private Integer scores;\n /**\n * 描述星级\n *\n * 1-5 星\n */\n private Integer descriptionScores;\n /**\n * 服务星级\n *\n * 1-5 星\n */\n private Integer benefitScores;\n /**\n * 评论内容\n */\n private String content;\n /**\n * 评论图片地址数组\n */\n @TableField(typeHandler = JacksonTypeHandler.class)\n private List<String> picUrls;\n\n /**\n * 商家是否回复\n */\n private Boolean replyStatus;\n /**\n * 回复管理员编号\n * 关联 AdminUserDO 的 id 编号\n */\n private Long replyUserId;\n /**\n * 商家回复内容\n */\n private String replyContent;\n /**\n * 商家回复时间\n */\n private LocalDateTime replyTime;\n\n}" }, { "identifier": "ProductSkuDO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/dal/dataobject/sku/ProductSkuDO.java", "snippet": "@TableName(value = \"product_sku\", autoResultMap = true)\n@KeySequence(\"product_sku_seq\") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ProductSkuDO extends BaseDO {\n\n /**\n * 商品 SKU 编号,自增\n */\n @TableId\n private Long id;\n /**\n * SPU 编号\n *\n * 关联 {@link ProductSpuDO#getId()}\n */\n private Long spuId;\n /**\n * 属性数组,JSON 格式\n */\n @TableField(typeHandler = PropertyTypeHandler.class)\n private List<Property> properties;\n /**\n * 商品价格,单位:分\n */\n private Integer price;\n /**\n * 市场价,单位:分\n */\n private Integer marketPrice;\n /**\n * 成本价,单位:分\n */\n private Integer costPrice;\n /**\n * 商品条码\n */\n private String barCode;\n /**\n * 图片地址\n */\n private String picUrl;\n /**\n * 库存\n */\n private Integer stock;\n /**\n * 商品重量,单位:kg 千克\n */\n private Double weight;\n /**\n * 商品体积,单位:m^3 平米\n */\n private Double volume;\n\n /**\n * 一级分销的佣金,单位:分\n */\n private Integer firstBrokeragePrice;\n /**\n * 二级分销的佣金,单位:分\n */\n private Integer secondBrokeragePrice;\n\n // ========== 营销相关字段 =========\n\n // ========== 统计相关字段 =========\n /**\n * 商品销量\n */\n private Integer salesCount;\n\n /**\n * 商品属性\n */\n @Data\n @NoArgsConstructor\n @AllArgsConstructor\n public static class Property {\n\n /**\n * 属性编号\n * 关联 {@link ProductPropertyDO#getId()}\n */\n private Long propertyId;\n /**\n * 属性名字\n * 冗余 {@link ProductPropertyDO#getName()}\n *\n * 注意:每次属性名字发生变化时,需要更新该冗余\n */\n private String propertyName;\n\n /**\n * 属性值编号\n * 关联 {@link ProductPropertyValueDO#getId()}\n */\n private Long valueId;\n /**\n * 属性值名字\n * 冗余 {@link ProductPropertyValueDO#getName()}\n *\n * 注意:每次属性值名字发生变化时,需要更新该冗余\n */\n private String valueName;\n\n }\n\n // TODO @芋艿:可以找一些新的思路\n public static class PropertyTypeHandler extends AbstractJsonTypeHandler<Object> {\n\n @Override\n protected Object parse(String json) {\n return JsonUtils.parseArray(json, Property.class);\n }\n\n @Override\n protected String toJson(Object obj) {\n return JsonUtils.toJsonString(obj);\n }\n\n }\n\n // TODO 芋艿:integral from y\n // TODO 芋艿:pinkPrice from y\n // TODO 芋艿:seckillPrice from y\n // TODO 芋艿:pinkStock from y\n // TODO 芋艿:seckillStock from y\n\n}" }, { "identifier": "ProductSpuDO", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/dal/dataobject/spu/ProductSpuDO.java", "snippet": "@TableName(value = \"product_spu\", autoResultMap = true)\n@KeySequence(\"product_spu_seq\") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ProductSpuDO extends BaseDO {\n\n /**\n * 商品 SPU 编号,自增\n */\n @TableId\n private Long id;\n\n // ========== 基本信息 =========\n\n /**\n * 商品名称\n */\n private String name;\n /**\n * 关键字\n */\n private String keyword;\n /**\n * 商品简介\n */\n private String introduction;\n /**\n * 商品详情\n */\n private String description;\n // TODO @芋艿:是不是要删除\n /**\n * 商品条码(一维码)\n */\n private String barCode;\n\n /**\n * 商品分类编号\n *\n * 关联 {@link ProductCategoryDO#getId()}\n */\n private Long categoryId;\n /**\n * 商品品牌编号\n *\n * 关联 {@link ProductBrandDO#getId()}\n */\n private Long brandId;\n /**\n * 商品封面图\n */\n private String picUrl;\n /**\n * 商品轮播图\n */\n @TableField(typeHandler = JacksonTypeHandler.class)\n private List<String> sliderPicUrls;\n /**\n * 商品视频\n */\n private String videoUrl;\n\n /**\n * 单位\n *\n * 对应 product_unit 数据字典\n */\n private Integer unit;\n /**\n * 排序字段\n */\n private Integer sort;\n /**\n * 商品状态\n *\n * 枚举 {@link ProductSpuStatusEnum}\n */\n private Integer status;\n\n // ========== SKU 相关字段 =========\n\n /**\n * 规格类型\n *\n * false - 单规格\n * true - 多规格\n */\n private Boolean specType;\n /**\n * 商品价格,单位使用:分\n *\n * 基于其对应的 {@link ProductSkuDO#getPrice()} sku单价最低的商品的\n */\n private Integer price;\n /**\n * 市场价,单位使用:分\n *\n * 基于其对应的 {@link ProductSkuDO#getMarketPrice()} sku单价最低的商品的\n */\n private Integer marketPrice;\n /**\n * 成本价,单位使用:分\n *\n * 基于其对应的 {@link ProductSkuDO#getCostPrice()} sku单价最低的商品的\n */\n private Integer costPrice;\n /**\n * 库存\n *\n * 基于其对应的 {@link ProductSkuDO#getStock()} 求和\n */\n private Integer stock;\n\n // ========== 物流相关字段 =========\n\n /**\n * 物流配置模板编号\n *\n * 对应 TradeDeliveryExpressTemplateDO 的 id 编号\n */\n private Long deliveryTemplateId;\n\n // ========== 营销相关字段 =========\n /**\n * 是否热卖推荐\n */\n private Boolean recommendHot;\n /**\n * 是否优惠推荐\n */\n private Boolean recommendBenefit;\n /**\n * 是否精品推荐\n */\n private Boolean recommendBest;\n /**\n * 是否新品推荐\n */\n private Boolean recommendNew;\n /**\n * 是否优品推荐\n */\n private Boolean recommendGood;\n\n /**\n * 赠送积分\n */\n private Integer giveIntegral;\n /**\n * 赠送的优惠劵编号的数组\n *\n * 对应 CouponTemplateDO 的 id 属性\n */\n @TableField(typeHandler = JacksonTypeHandler.class)\n private List<Long> giveCouponTemplateIds;\n\n // TODO @puhui999:字段估计要改成 brokerageType\n /**\n * 分销类型\n *\n * false - 默认\n * true - 自行设置\n */\n private Boolean subCommissionType;\n\n /**\n * 活动展示顺序\n *\n * 对应 PromotionTypeEnum 枚举\n */\n @TableField(typeHandler = JacksonTypeHandler.class)\n private List<Integer> activityOrders; // TODO @芋艿: 活动顺序字段长度需要增加\n\n // ========== 统计相关字段 =========\n\n /**\n * 商品销量\n */\n private Integer salesCount;\n /**\n * 虚拟销量\n */\n private Integer virtualSalesCount;\n /**\n * 浏览量\n */\n private Integer browseCount;\n}" }, { "identifier": "ProductCommentMapper", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/dal/mysql/comment/ProductCommentMapper.java", "snippet": "@Mapper\npublic interface ProductCommentMapper extends BaseMapperX<ProductCommentDO> {\n\n default PageResult<ProductCommentDO> selectPage(ProductCommentPageReqVO reqVO) {\n return selectPage(reqVO, new LambdaQueryWrapperX<ProductCommentDO>()\n .likeIfPresent(ProductCommentDO::getUserNickname, reqVO.getUserNickname())\n .eqIfPresent(ProductCommentDO::getOrderId, reqVO.getOrderId())\n .eqIfPresent(ProductCommentDO::getSpuId, reqVO.getSpuId())\n .eqIfPresent(ProductCommentDO::getScores, reqVO.getScores())\n .eqIfPresent(ProductCommentDO::getReplyStatus, reqVO.getReplyStatus())\n .betweenIfPresent(ProductCommentDO::getCreateTime, reqVO.getCreateTime())\n .likeIfPresent(ProductCommentDO::getSpuName, reqVO.getSpuName())\n .orderByDesc(ProductCommentDO::getId));\n }\n\n}" }, { "identifier": "ProductSkuService", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/service/sku/ProductSkuService.java", "snippet": "public interface ProductSkuService {\n\n /**\n * 获得商品 SKU 信息\n *\n * @param id 编号\n * @return 商品 SKU 信息\n */\n ProductSkuDO getSku(Long id);\n\n /**\n * 对 sku 的组合的属性等进行合法性校验\n *\n * @param list sku组合的集合\n */\n void validateSkuList(List<ProductSkuCreateOrUpdateReqVO> list, Boolean specType);\n\n /**\n * 批量创建 SKU\n *\n * @param spuId 商品 SPU 编号\n * @param list SKU 对象集合\n */\n void createSkuList(Long spuId, List<ProductSkuCreateOrUpdateReqVO> list);\n\n /**\n * 根据 SPU 编号,批量更新它的 SKU 信息\n *\n * @param spuId SPU 编码\n * @param skus SKU 的集合\n */\n void updateSkuList(Long spuId, List<ProductSkuCreateOrUpdateReqVO> skus);\n\n\n /**\n * 获得商品 SKU 集合\n *\n * @param spuId spu 编号\n * @return 商品sku 集合\n */\n List<ProductSkuDO> getSkuListBySpuId(Long spuId);\n\n /**\n * 获得 spu 对应的 SKU 集合\n *\n * @param spuIds spu 编码集合\n * @return 商品 sku 集合\n */\n List<ProductSkuDO> getSkuListBySpuId(Collection<Long> spuIds);\n\n /**\n * 通过 spuId 删除 sku 信息\n *\n * @param spuId spu 编码\n */\n void deleteSkuBySpuId(Long spuId);\n\n\n /**\n * 更新 sku 属性\n *\n * @param propertyId 属性 id\n * @param propertyName 属性名\n * @return int 影响的行数\n */\n int updateSkuProperty(Long propertyId, String propertyName);\n\n /**\n * 更新 sku 属性值\n *\n * @param propertyValueId 属性值 id\n * @param propertyValueName 属性值名字\n * @return int 影响的行数\n */\n int updateSkuPropertyValue(Long propertyValueId, String propertyValueName);\n\n}" }, { "identifier": "ProductSpuService", "path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/service/spu/ProductSpuService.java", "snippet": "public interface ProductSpuService {\n\n /**\n * 创建商品 SPU\n *\n * @param createReqVO 创建信息\n * @return 编号\n */\n Long createSpu(@Valid ProductSpuCreateReqVO createReqVO);\n\n /**\n * 更新商品 SPU\n *\n * @param updateReqVO 更新信息\n */\n void updateSpu(@Valid ProductSpuUpdateReqVO updateReqVO);\n\n /**\n * 删除商品 SPU\n *\n * @param id 编号\n */\n void deleteSpu(Long id);\n\n /**\n * 获得商品 SPU\n *\n * @param id 编号\n * @return 商品 SPU\n */\n ProductSpuDO getSpu(Long id);\n\n /**\n * 获得商品 SPU 列表\n *\n * @param ids 编号数组\n * @return 商品 SPU 列表\n */\n List<ProductSpuDO> getSpuList(Collection<Long> ids);\n\n /**\n * 获得指定状态的商品 SPU 列表\n *\n * @param status 状态\n * @return 商品 SPU 列表\n */\n List<ProductSpuDO> getSpuListByStatus(Integer status);\n\n /**\n * 获得所有商品 SPU 列表\n *\n * @param reqVO 导出条件\n * @return 商品 SPU 列表\n */\n List<ProductSpuDO> getSpuList(ProductSpuExportReqVO reqVO);\n\n /**\n * 获得商品 SPU 分页,提供给挂你兰后台使用\n *\n * @param pageReqVO 分页查询\n * @return 商品spu分页\n */\n PageResult<ProductSpuDO> getSpuPage(ProductSpuPageReqVO pageReqVO);\n\n /**\n * 更新 SPU 状态\n *\n * @param updateReqVO 更新请求\n */\n void updateSpuStatus(ProductSpuUpdateStatusReqVO updateReqVO);\n\n /**\n * 获取 SPU 列表标签对应的 Count 数量\n *\n * @return Count 数量\n */\n Map<Integer, Long> getTabsCount();\n\n /**\n * 通过分类 categoryId 查询 SPU 个数\n *\n * @param categoryId 分类 categoryId\n * @return SPU 数量\n */\n Long getSpuCountByCategoryId(Long categoryId);\n\n\n}" }, { "identifier": "exception", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/exception/util/ServiceExceptionUtil.java", "snippet": "public static ServiceException exception(ErrorCode errorCode) {\n String messagePattern = MESSAGES.getOrDefault(errorCode.getCode(), errorCode.getMsg());\n return exception0(errorCode.getCode(), messagePattern);\n}" }, { "identifier": "ErrorCodeConstants", "path": "yudao-module-mall/yudao-module-product-api/src/main/java/cn/iocoder/yudao/module/product/enums/ErrorCodeConstants.java", "snippet": "public interface ErrorCodeConstants {\n\n // ========== 商品分类相关 1-008-001-000 ============\n ErrorCode CATEGORY_NOT_EXISTS = new ErrorCode(1_008_001_000, \"商品分类不存在\");\n ErrorCode CATEGORY_PARENT_NOT_EXISTS = new ErrorCode(1_008_001_001, \"父分类不存在\");\n ErrorCode CATEGORY_PARENT_NOT_FIRST_LEVEL = new ErrorCode(1_008_001_002, \"父分类不能是二级分类\");\n ErrorCode CATEGORY_EXISTS_CHILDREN = new ErrorCode(1_008_001_003, \"存在子分类,无法删除\");\n ErrorCode CATEGORY_DISABLED = new ErrorCode(1_008_001_004, \"商品分类({})已禁用,无法使用\");\n ErrorCode CATEGORY_HAVE_BIND_SPU = new ErrorCode(1_008_001_005, \"类别下存在商品,无法删除\");\n\n // ========== 商品品牌相关编号 1-008-002-000 ==========\n ErrorCode BRAND_NOT_EXISTS = new ErrorCode(1_008_002_000, \"品牌不存在\");\n ErrorCode BRAND_DISABLED = new ErrorCode(1_008_002_001, \"品牌已禁用\");\n ErrorCode BRAND_NAME_EXISTS = new ErrorCode(1_008_002_002, \"品牌名称已存在\");\n\n // ========== 商品属性项 1-008-003-000 ==========\n ErrorCode PROPERTY_NOT_EXISTS = new ErrorCode(1_008_003_000, \"属性项不存在\");\n ErrorCode PROPERTY_EXISTS = new ErrorCode(1_008_003_001, \"属性项的名称已存在\");\n ErrorCode PROPERTY_DELETE_FAIL_VALUE_EXISTS = new ErrorCode(1_008_003_002, \"属性项下存在属性值,无法删除\");\n\n // ========== 商品属性值 1-008-004-000 ==========\n ErrorCode PROPERTY_VALUE_NOT_EXISTS = new ErrorCode(1_008_004_000, \"属性值不存在\");\n ErrorCode PROPERTY_VALUE_EXISTS = new ErrorCode(1_008_004_001, \"属性值的名称已存在\");\n\n // ========== 商品 SPU 1-008-005-000 ==========\n ErrorCode SPU_NOT_EXISTS = new ErrorCode(1_008_005_000, \"商品 SPU 不存在\");\n ErrorCode SPU_SAVE_FAIL_CATEGORY_LEVEL_ERROR = new ErrorCode(1_008_005_001, \"商品分类不正确,原因:必须使用第二级的商品分类及以下\");\n ErrorCode SPU_SAVE_FAIL_COUPON_TEMPLATE_NOT_EXISTS = new ErrorCode(1_008_005_002, \"商品 SPU 保存失败,原因:优惠卷不存在\");\n ErrorCode SPU_NOT_ENABLE = new ErrorCode(1_008_005_003, \"商品 SPU【{}】不处于上架状态\");\n ErrorCode SPU_NOT_RECYCLE = new ErrorCode(1_008_005_004, \"商品 SPU 不处于回收站状态\");\n\n // ========== 商品 SKU 1-008-006-000 ==========\n ErrorCode SKU_NOT_EXISTS = new ErrorCode(1_008_006_000, \"商品 SKU 不存在\");\n ErrorCode SKU_PROPERTIES_DUPLICATED = new ErrorCode(1_008_006_001, \"商品 SKU 的属性组合存在重复\");\n ErrorCode SPU_ATTR_NUMBERS_MUST_BE_EQUALS = new ErrorCode(1_008_006_002, \"一个 SPU 下的每个 SKU,其属性项必须一致\");\n ErrorCode SPU_SKU_NOT_DUPLICATE = new ErrorCode(1_008_006_003, \"一个 SPU 下的每个 SKU,必须不重复\");\n ErrorCode SKU_STOCK_NOT_ENOUGH = new ErrorCode(1_008_006_004, \"商品 SKU 库存不足\");\n\n // ========== 商品 评价 1-008-007-000 ==========\n ErrorCode COMMENT_NOT_EXISTS = new ErrorCode(1_008_007_000, \"商品评价不存在\");\n ErrorCode COMMENT_ORDER_EXISTS = new ErrorCode(1_008_007_001, \"订单的商品评价已存在\");\n\n // ========== 商品 收藏 1-008-008-000 ==========\n ErrorCode FAVORITE_EXISTS = new ErrorCode(1_008_008_000, \"该商品已经被收藏\");\n ErrorCode FAVORITE_NOT_EXISTS = new ErrorCode(1_008_008_001, \"商品收藏不存在\");\n\n}" } ]
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentCreateReqVO; import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentPageReqVO; import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentReplyReqVO; import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentUpdateVisibleReqVO; import cn.iocoder.yudao.module.product.convert.comment.ProductCommentConvert; import cn.iocoder.yudao.module.product.dal.dataobject.comment.ProductCommentDO; import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO; import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO; import cn.iocoder.yudao.module.product.dal.mysql.comment.ProductCommentMapper; import cn.iocoder.yudao.module.product.service.sku.ProductSkuService; import cn.iocoder.yudao.module.product.service.spu.ProductSpuService; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.annotation.Resource; import java.time.LocalDateTime; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.*;
8,343
package cn.iocoder.yudao.module.product.service.comment; /** * 商品评论 Service 实现类 * * @author wangzhs */ @Service @Validated public class ProductCommentServiceImpl implements ProductCommentService { @Resource private ProductCommentMapper productCommentMapper; @Resource private ProductSpuService productSpuService; @Resource @Lazy private ProductSkuService productSkuService; @Override public void createComment(ProductCommentCreateReqVO createReqVO) { // 校验 SKU ProductSkuDO skuDO = validateSku(createReqVO.getSkuId()); // 校验 SPU ProductSpuDO spuDO = validateSpu(skuDO.getSpuId()); // 创建评论 ProductCommentDO comment = ProductCommentConvert.INSTANCE.convert(createReqVO, spuDO, skuDO); productCommentMapper.insert(comment); } private ProductSkuDO validateSku(Long skuId) { ProductSkuDO sku = productSkuService.getSku(skuId); if (sku == null) { throw exception(SKU_NOT_EXISTS); } return sku; } private ProductSpuDO validateSpu(Long spuId) { ProductSpuDO spu = productSpuService.getSpu(spuId); if (null == spu) { throw exception(SPU_NOT_EXISTS); } return spu; } @Override public void updateCommentVisible(ProductCommentUpdateVisibleReqVO updateReqVO) { // 校验评论是否存在 validateCommentExists(updateReqVO.getId()); // 更新可见状态 productCommentMapper.updateById(new ProductCommentDO().setId(updateReqVO.getId()) .setVisible(true)); } @Override public void replyComment(ProductCommentReplyReqVO replyVO, Long userId) { // 校验评论是否存在 validateCommentExists(replyVO.getId()); // 回复评论 productCommentMapper.updateById(new ProductCommentDO().setId(replyVO.getId()) .setReplyTime(LocalDateTime.now()).setReplyUserId(userId) .setReplyStatus(Boolean.TRUE).setReplyContent(replyVO.getReplyContent())); } private ProductCommentDO validateCommentExists(Long id) { ProductCommentDO productComment = productCommentMapper.selectById(id); if (productComment == null) { throw exception(COMMENT_NOT_EXISTS); } return productComment; } @Override
package cn.iocoder.yudao.module.product.service.comment; /** * 商品评论 Service 实现类 * * @author wangzhs */ @Service @Validated public class ProductCommentServiceImpl implements ProductCommentService { @Resource private ProductCommentMapper productCommentMapper; @Resource private ProductSpuService productSpuService; @Resource @Lazy private ProductSkuService productSkuService; @Override public void createComment(ProductCommentCreateReqVO createReqVO) { // 校验 SKU ProductSkuDO skuDO = validateSku(createReqVO.getSkuId()); // 校验 SPU ProductSpuDO spuDO = validateSpu(skuDO.getSpuId()); // 创建评论 ProductCommentDO comment = ProductCommentConvert.INSTANCE.convert(createReqVO, spuDO, skuDO); productCommentMapper.insert(comment); } private ProductSkuDO validateSku(Long skuId) { ProductSkuDO sku = productSkuService.getSku(skuId); if (sku == null) { throw exception(SKU_NOT_EXISTS); } return sku; } private ProductSpuDO validateSpu(Long spuId) { ProductSpuDO spu = productSpuService.getSpu(spuId); if (null == spu) { throw exception(SPU_NOT_EXISTS); } return spu; } @Override public void updateCommentVisible(ProductCommentUpdateVisibleReqVO updateReqVO) { // 校验评论是否存在 validateCommentExists(updateReqVO.getId()); // 更新可见状态 productCommentMapper.updateById(new ProductCommentDO().setId(updateReqVO.getId()) .setVisible(true)); } @Override public void replyComment(ProductCommentReplyReqVO replyVO, Long userId) { // 校验评论是否存在 validateCommentExists(replyVO.getId()); // 回复评论 productCommentMapper.updateById(new ProductCommentDO().setId(replyVO.getId()) .setReplyTime(LocalDateTime.now()).setReplyUserId(userId) .setReplyStatus(Boolean.TRUE).setReplyContent(replyVO.getReplyContent())); } private ProductCommentDO validateCommentExists(Long id) { ProductCommentDO productComment = productCommentMapper.selectById(id); if (productComment == null) { throw exception(COMMENT_NOT_EXISTS); } return productComment; } @Override
public PageResult<ProductCommentDO> getCommentPage(ProductCommentPageReqVO pageReqVO) {
0
2023-12-08 02:48:42+00:00
12k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/text/Typewriter.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTexture;\n\n\t// for the empty variables (the tiles that are currently moved by a bot)\n\tpublic static int emptyVariable;\n\n\t// for the possible moves that the bot uses for decision-making\n\t// Array of int values\n\tpublic static ArrayList<Integer> possibleMoves;\n\tpublic static int possibleMove;\n\n\t// for the batch\n\tSpriteBatch batch;\n\n\t// for the background\n\tTexture background;\n\n\t// for the currentStage\n\tstatic Stage currentStage;\n\n\t// stage options\n\tpublic static boolean showOptions;\n\tStage OptionsStage;\n\n\t// stage credit\n\tboolean showCredits;\n\tStage CreditsStage;\n\n\t// stick stage\n\tpublic static Stage stickStage;\n\n\t// typeWriterStage\n\tpublic static Stage typeWriterStage;\n\n\t// hitStage\n\tStage hitStage;\n\tAnimation<TextureRegion> hitAnimation;\n\n\t// helpOverlayStage\n\tstatic Stage helpOverlayStage;\n\tTexture help;\n\tpublic static boolean displayHelp;\n\tTexture hand;\n\t// for the pieces textures unselected\n\tpublic static Texture blackpiece;\n\tpublic static Texture whitepiece;\n\n\t// for the turn constant\n\tstatic Turn gameState;\n\n\t// for the game boolean value of it having just started\n\tpublic static boolean gameStarted;\n\n\t// for the tileSize relative to screenSize from RelativeResizer\n\tpublic static float tileSize;\n\n\t// textures for special state\n\tpublic static Texture happy;\n\tpublic static Texture water;\n\tpublic static Texture safe;\n\tpublic static Texture rebirth;\n\n\t// boolean determining if the game is in progress\n\tpublic static boolean inGame;\n\n\t// typewriter\n\tpublic static Typewriter typeWriter;\n\n\t// for knowing when to skip the Turn\n\tpublic static boolean skipTurn;\n\n\tpublic static Texture logo;\n\n\t// for the textbutton skin\n\tpublic static Skin skin;\n\n\t// if the Sticks are Tumbling\n\tpublic static boolean sticksTumbling;\n\n\t// current Stick value\n\tpublic static int currentStickValue;\n\t// Sticks\n\tpublic static Stick gameSticks;\n\n\t//Game End Stage\n\tpublic static Stage gameEndStage;\n\n\t// legitMove boolean\n\tpublic static boolean legitMove;\n\n\t// rebirth protection\n\tpublic static Texture rebirthProtection;\n\n\t// for the music volume\n\tpublic static float volume;\n\n\t// texture for the tile\n\tpublic static Texture tileTexture;\n\n\t// map stage\n\tpublic static Stage mapStage;\n\n\t// boolean for an extra turn\n\tpublic static boolean extraTurn;\n\t// texture\n\tpublic static Texture extraTurnTexture;\n\n\t//stage for extra turn\n\tpublic static Stage extraTurnStage;\n\n\t// stick value Stage\n\tprivate static Stage stickValueStage;\n\n\t// textures for the sticks\n\tpublic static Texture blackStick;\n\tpublic static Texture whiteStick;\n\n\t// number textures\n\tpublic static Texture number0;\n\tpublic static Texture number1;\n\tpublic static Texture number2;\n\tpublic static Texture number3;\n\tpublic static Texture number4;\n\tpublic static Texture number6;\n\n\t// for the game start\n\tpublic static boolean startUndecided;\n\tpublic static Stage deciderStage;\n\n\t// textures of starter\n\tpublic static Texture whiteStarts;\n\tpublic static Texture blackStarts;\n\n\t// boolean for the decider\n\tpublic static boolean deciderStarted;\n\n\t// for when a turn has not been checked yet\n\tpublic static boolean gameUnchecked;\n\n\t// hint stage\n\tpublic static Stage hintStage;\n\n\t// for displaying the current Turn\n\tpublic static Stage currentTurnStage;\n\n\t// turn play textures\n\tpublic static Texture whitePlays;\n\tpublic static Texture blackPlays;\n\n\t// texture for the help\n\tpublic static Texture helpTexture;\n\n\t// no moves texture\n\tpublic static Texture noMovesTexture;\n\n\tpublic static boolean displayHint = false;\n\n\tpublic static Texture possibleMoveTexture;\n\n\tpublic static boolean needRender;\n\n\t// for the arms\n\tpublic static Image armFromBelow;\n\tpublic static Image armFromAbove;\n\n\t// for the advanced arm stages and their respective boolean\n\n\tpublic static Stage armFromBelowStage;\n\tpublic static Stage armFromAboveStage;\n\tpublic static boolean showArmFromBelowStage;\n\tpublic static boolean showArmFromAboveStage;\n\n\tpublic static MusicPlaylist musicPlaylist;\n\n\t// enum of turn\n\tprivate enum Turn {\n\t\tPLAYERWHITE,\n\t\tPLAYERBLACK,\n\t}\n\n\t@Override\n\tpublic void create () {\n\t\tbatch = new SpriteBatch();\n\t\tbackground = new Texture(\"textures/background.png\");\n\n\t\t// from scene2dUi\n\t\tcurrentStage = new Stage();\n\t\tshowOptions = false;\n\t\tOptionsStage = new Stage();\n\t\tshowCredits = false;\n\t\tCreditsStage = new Stage();\n\t\tinGame = false;\n\t\tgameStarted = false;\n\t\tgameEndStage = new Stage();\n\t\tstickStage = new Stage();\n\t\ttypeWriterStage = new Stage();\n\t\thitStage = new Stage();\n\t\thelpOverlayStage = new Stage();\n\t\tmapStage = new Stage();\n\t\textraTurnStage = new Stage();\n\t\tstickValueStage = new Stage();\n\t\tdeciderStage = new Stage();\n\t\thintStage = new Stage();\n\t\tcurrentTurnStage = new Stage();\n\n\t\t// for the arms\n\n\t\tarmFromBelowStage = new Stage();\n\t\tarmFromAboveStage = new Stage();\n\t\tshowArmFromBelowStage = false;\n\t\tshowArmFromAboveStage = false;\n\n\t\t// possible Moves is a ArrayList of int values\n\t\tpossibleMoves = new ArrayList<Integer>();\n\n\t\tdisplayHelp = false;\n\t\tskipTurn = false;\n\t\tsticksTumbling = false;\n\t\tlegitMove = false;\n\n\t\t// loading the skin\n\t\tskin = new Skin(Gdx.files.internal(\"menu.commodore64/uiskin.json\"));\n\n\t\t// loading all textures\n\t\tblackpiece = new Texture(\"textures/blackpiece.png\");\n\t\twhitepiece = new Texture(\"textures/whitepiece.png\");\n\t\thappy = new Texture(\"textures/happy.png\");\n\t\twater = new Texture(\"textures/water.png\");\n\t\tsafe = new Texture(\"textures/safe.png\");\n\t\trebirth = new Texture(\"textures/rebirth.png\");\n\t\trebirthProtection = new Texture(\"textures/rebirthprotection.png\");\n\t\tlogo = new Texture(\"logoSenet.png\");\n\t\ttileTexture = new Texture(\"textures/tile.png\");\n\t\temptyTexture = new Texture(\"textures/empty.png\");\n\t\textraTurnTexture = new Texture(\"textures/extraTurn.png\");\n\t\twhiteStarts = new Texture(\"textures/whiteStart.png\");\n\t\tblackStarts = new Texture(\"textures/blackStarts.png\");\n\n\t\t// arms\n\n\t\tarmFromAboveStage = new Stage();\n\t\tarmFromBelowStage = new Stage();\n\n\t\tarmFromAbove = new Image(new Texture(\"textures/armabovein.png\"));\n\t\tarmFromBelow = new Image(new Texture(\"textures/armbelowin.png\"));\n\n\t\tarmFromAboveStage.addActor(armFromAbove);\n\t\tarmFromBelowStage.addActor(armFromBelow);\n\n\t\t// for the sticks\n\t\tblackStick = new Texture(\"textures/blackStick.png\");\n\t\twhiteStick = new Texture(\"textures/whiteStick.png\");\n\n\t\t// for the numbers\n\t\tnumber0 = new Texture(\"textures/0.png\");\n\t\tnumber1 = new Texture(\"textures/1.png\");\n\t\tnumber2 = new Texture(\"textures/2.png\");\n\t\tnumber3 = new Texture(\"textures/3.png\");\n\t\tnumber4 = new Texture(\"textures/4.png\");\n\t\tnumber6 = new Texture(\"textures/6.png\");\n\n\t\t// possible Move Texture\n\t\tpossibleMoveTexture = new Texture(\"textures/possibleMove.png\");\n\n\t\t// no moves texture\n\t\tnoMovesTexture = new Texture(\"textures/noMovesTexture.png\");\n\n\t\t// help texture\n\t\thelpTexture = new Texture(\"textures/rules.png\");\n\n\t\t// for the turn plays textures\n\t\twhitePlays = new Texture(\"textures/whitePlays.png\");\n\t\tblackPlays = new Texture(\"textures/blackPlays.png\");\n\n\t\t// for the empty tile texture\n\t\temptyTexture = new Texture(\"textures/empty.png\");\n\n\t\t// music Playlist\n\n\t\tvolume = 0.5f;\n\n\t\tmusicPlaylist = new MusicPlaylist();\n\n\t\t// from youtube: https://www.youtube.com/watch?v=nBmWXmn11YE\n\t\tmusicPlaylist.addSong(\"music/egyptreconstruct.mp3\");\n\t\t// from youtube: https://www.youtube.com/watch?v=mECTRQ0VEyU\n\t\tmusicPlaylist.addSong(\"music/egyptianmusic.mp3\");\n\t\t// from youtube: https://www.youtube.com/watch?v=d7jKP_JngC8\n\t\tmusicPlaylist.addSong(\"music/egyptianmusic2.mp3\");\n\n\t\tmusicPlaylist.play();\n\n\t\t// for the empty variable (the tile that is currently moved by a bot)\n\t\temptyVariable = -1;\n\n\t\t// for the tileSize relative to screenSize from RelativeResizer\n\t\ttileSize = 80;\n\n\t\tgameState = Turn.PLAYERWHITE;\n\n\t\tresize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n\n\t\tGdx.input.setInputProcessor(currentStage);\n\n\t\tcreateHelpStage(); // for the help overlay that can be activated\n\n\t\tcreateMenu();\n\t}\n\n\t@Override\n\tpublic void render () {\n\t\tScreenUtils.clear(1, 0, 0, 1);\n\n\t\tbatch.begin();\n\t\tbatch.draw(background, 0, 0);\n\t\tbatch.end();\n\n\t\tif(needRender){\n\t\t\trenderBoard();\n\t\t\tneedRender = false;\n\t\t}\n\n\t\tif(inGame){\n\t\t\tmapStage.act();\n\t\t\tmapStage.draw();\n\t\t}\n\n\t\t// from scene2dUi\n\t\tcurrentStage.act();\n\t\tcurrentStage.draw();\n\n\t\tif(displayHelp){\n\t\t\thelpOverlayStage.act();\n\t\t\thelpOverlayStage.draw();\n\t\t}\n\n\t\tif (showOptions) {\n\t\t\tOptionsStage.act();\n\t\t\tOptionsStage.draw();\n\t\t}\n\n\t\tif (showCredits) {\n\t\t\tCreditsStage.act();\n\t\t\tCreditsStage.draw();\n\t\t}\n\n\t\tif(inGame){\n\t\t\t// all stages affiliated with the game ongoing\n\n\t\t\tif(gameStarted){\n\t\t\t\t// decide who starts!\n\t\t\t\tif(startUndecided){\n\t\t\t\t\tif(!(deciderStarted)) {\n\t\t\t\t\t\t// randomly decides the first turn state + displays this deciding on the screen\n\t\t\t\t\t\tdecideStarter();\n\t\t\t\t\t}\n\n\t\t\t\t\t// gets called till the timer in deciderStarter is up, then it sets startUndecided to false\n\t\t\t\t\tdeciderStage.act();\n\t\t\t\t\tdeciderStage.draw();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tupdateLogoStage();\n\t\t\t\t// first act of a new game:\n\t\t\t\t// throw the sticks!\n\t\t\t\tgameSticks = new Stick();\n\t\t\t\tcurrentStickValue = gameSticks.getValue();\n\t\t\t\tsticksTumbling = true;\n\t\t\t\t// add the stickValueStage\n\t\t\t\tstickValueStage = SenetBoom.drawStickValue(currentStickValue);\n\t\t\t\tgameStarted = false;\n\t\t\t}\n\n\t\t\t// stick animation\n\t\t\tstickStage.act();\n\t\t\tstickStage.draw();\n\n\t\t\t// for the explicit typewriter\n\t\t\ttypeWriterStage.act();\n\t\t\ttypeWriterStage.draw();\n\n\t\t\t// for the switch animation (kinda like hit)\n\t\t\thitStage.act();\n\t\t\thitStage.draw();\n\n\t\t\t// for the hints if displayHint turned on\n\t\t\tif(displayHint) {\n\t\t\t\thintStage.act();\n\t\t\t\thintStage.draw();\n\t\t\t}\n\n\t\t\t// for the extra turn symbol\n\t\t\textraTurnStage.act();\n\t\t\textraTurnStage.draw();\n\n\t\t\t// current turn stage\n\t\t\tcurrentTurnStage.act();\n\t\t\tcurrentTurnStage.draw();\n\n\t\t\tif(!(sticksTumbling)) {\n\t\t\t\t// display the current stick value if the sticks are not tumbling\n\t\t\t\tstickValueStage.act();\n\t\t\t\tstickValueStage.draw();\n\t\t\t} else{\n\t\t\t\t// waiting for the sticks to end tumbling ( its animation )\n\t\t\t\tStick.update(Gdx.graphics.getDeltaTime());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for the arms\n\t\t\tif(showArmFromBelowStage) {\n\t\t\t\tarmFromBelowStage.act();\n\t\t\t\tarmFromBelowStage.draw();\n\t\t\t}\n\n\t\t\tif(showArmFromAboveStage) {\n\t\t\t\tarmFromAboveStage.act();\n\t\t\t\tarmFromAboveStage.draw();\n\t\t\t}\n\n\t\t\t// for the display of the game having ended\n\t\t\tgameEndStage.act();\n\t\t\tgameEndStage.draw();\n\n\t\t\t// only if the sticks have stopped tumbling, and if the turn hasn't skipped,\n\t\t\t// we can let a turn be processed\n\t\t\tif (skipTurn) { // skip turn gets set to true if player pushed the skipTurn button\n\n\t\t\t\t// add a typewriter of ANGER or CONFUSED or SAD\n\t\t\t\t/* TODO\n\t\t\t\tif (gameState == Turn.PLAYERWHITE)\n\t\t\t\t\ttypeWriter.makeSpeech(Typewriter.Emotion.ANGRY, Typewriter.Character.WHITE);\n\t\t\t\telse\n\t\t\t\t\ttypeWriter.makeSpeech(Typewriter.Emotion.ANGRY, Typewriter.Character.BLACK);\n\t\t\t \t*/\n\n\t\t\t\t// other players turn\n\t\t\t\tswitchTurn();\n\n\t\t\t\tskipTurn = false;\n\t\t\t}\n\n\t\t\tprocessTurn();\n\t\t}\n\t}\n\n\tpublic void processTurn() {\n\n\t\t// ----------------- legit Move part\n\n\t\t// wait for a legitMove from a player of gameState\n\t\tif(legitMove) {\n\t\t\t// resets the legitMove check\n\t\t\tlegitMove = false;\n\n\t\t\t// if not legitMove, waits for a legitMove switch around\n\t\t\t// if legitMove, moves the piece in its respective dragStop Listener\n\t\t\t// check if the game is over\n\t\t\tcheckForGameEnd();\n\t\t\t// switch turn after completing the move\n\t\t\tswitchTurn();\n\t\t}\n\t}\n\n\tprivate void switchTurn() {\n\t\t// switch the turn\n\n\n\t\tif(extraTurn){ // if extraTurn is true, do not switch turn\n\t\t\t// player has an extra turn\n\t\t\textraTurn = false;\n\t\t}\n\t\telse { // switch turn\n\t\t\tif (gameState == Turn.PLAYERWHITE) {\n\t\t\t\tgameState = Turn.PLAYERBLACK;\n\t\t\t} else {\n\t\t\t\tgameState = Turn.PLAYERWHITE;\n\t\t\t}\n\t\t}\n\n\t\tpossibleMoves = new ArrayList<Integer>();\n\n\t\tgameSticks = new Stick();\n\n\t\tcurrentStickValue = gameSticks.getValue();\n\n\t\t// ----------------- help part\n\t\t// after thrown, check if any moves are even possible with the stick(dice) number\n\t\t// if the next player has no moves possible, a slight hint gets added to the screen\n\t\t// we run calculateMove on any piece of the player and if it returns null,\n\t\t// the next player has no moves possible\n\n\t\tif (gameState == Turn.PLAYERWHITE) {\n\t\t\t// check if any moves are possible for the white player\n\t\t\t// if not, add a hint to the screen\n\t\t\tcheckForNoMoves(Turn.PLAYERWHITE);\n\t\t\t// if yes, remove the hint from the screen\n\t\t} else {\n\t\t\t// check if any moves are possible for the black player\n\t\t\t// if not, add a hint to the screen\n\t\t\t// if yes, remove the hint from the screen\n\t\t\tcheckForNoMoves(Turn.PLAYERBLACK);\n\t\t}\n\n\t\t// ----------------- end of help part\n\n\t\trenderBoard();\n\n\t\t// update move logo\n\t\tupdateLogoStage();\n\n\t\trenderBoard();\n\t\tGdx.input.setInputProcessor(currentStage);\n\t}\n\n\tprivate static void checkForNoMoves(Turn turn) {\n\n\t\thintStage.clear();\n\t\t// this method checks if the player has any moves possible\n\t\t// if not, it adds a \"No moves possible\" Actor to the hint screen\n\t\tboolean noMoves = true;\n\t\tTile[] gameBoard = Board.getBoard();\n\t\tPiece.Color currentTurn = turn == Turn.PLAYERWHITE ? Piece.Color.WHITE : Piece.Color.BLACK;\n\t\tfor(Tile tiles: gameBoard){\n\t\t\tif(tiles.hasPiece()){\n\t\t\t\tif(tiles.getPiece().getColour() == currentTurn){\n\t\t\t\t\t// if the piece is of the current turn\n\t\t\t\t\t// check if it has any moves possible\n\t\t\t\t\tif(tiles.isMoveValid(tiles.getPosition(), currentStickValue)){\n\t\t\t\t\t\t// if yes, set noMoves to false\n\t\t\t\t\t\tnoMoves = false;\n\t\t\t\t\t\tpossibleMoves.add(tiles.getPosition()+currentStickValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(noMoves){\n\t\t\t// if noMoves is true, add a hint to the screen\n\t\t\tImage noMove = new Image(noMovesTexture);\n\t\t\t// add at Position middle low\n\t\t\tnoMove.setPosition((float) Gdx.graphics.getWidth() /2, tileSize*2);\n\t\t\thintStage.addActor(noMove);\n\n\t\t\t// add a typewriter of ANGER or CONFUSED or SAD\n\t\t\t// TODO\n\n\t\t\t// render the board so that the possible Moves can be displayed on the screen\n\t\t\trenderBoard();\n\t\t}\n\t}\n\n\t// resize override\n\t@Override\n\tpublic void resize(int width, int height) {\n\t\t// from scene2dUi\n\t\tcurrentStage.getViewport().update(width, height, true);\n\t\tif (showOptions) {\n\t\t\tOptionsStage.getViewport().update(width, height, true);\n\t\t}\n\t\tif (showCredits) {\n\t\t\tCreditsStage.getViewport().update(width, height, true);\n\t\t}\n\t\tif(inGame){\n\t\t\tmapStage.getViewport().update(width, height, true);\n\t\t\tstickStage.getViewport().update(width, height, true);\n\t\t\ttypeWriterStage.getViewport().update(width, height, true);\n\t\t\thitStage.getViewport().update(width, height, true);\n\t\t\thelpOverlayStage.getViewport().update(width, height, true);\n\t\t\tgameEndStage.getViewport().update(width, height, true);\n\t\t\textraTurnStage.getViewport().update(width, height, true);\n\t\t\tstickValueStage.getViewport().update(width, height, true);\n\t\t\tdeciderStage.getViewport().update(width, height, true);\n\t\t\thintStage.getViewport().update(width, height, true);\n\t\t\tcurrentTurnStage.getViewport().update(width, height, true);\n\t\t\tarmFromAboveStage.getViewport().update(width, height, true);\n\t\t\tarmFromBelowStage.getViewport().update(width, height, true);\n\t\t}\n\t}\n\n\tprivate void updateLogoStage() {\n\t\t// updates the logo according to the turn constant\n\n\t\t// remove the old logo\n\t\tcurrentTurnStage.clear();\n\n\t\tImage currentTurner;\n\t\t// add the new logo\n\t\tif(gameState == Turn.PLAYERWHITE){\n\t\t\tcurrentTurner = new Image(whitePlays);\n\t\t} else {\n\t\t\tcurrentTurner = new Image(blackPlays);\n\t\t}\n\t\t// upper left corner\n\t\tcurrentTurner.setSize(tileSize*3, tileSize*2);\n\t\tcurrentTurner.setPosition(tileSize*2, tileSize * 8);\n\t\tcurrentTurnStage.addActor(currentTurner);\n\n\t}\n\n\tprivate void decideStarter() {\n\n\t\tdeciderStarted = true;\n\n\t\t// random decide if turn White or black\n\t\tint random = (int) (Math.random() * 2);\n\t\tif(random == 0){\n\t\t\tgameState = Turn.PLAYERWHITE;\n\t\t} else {\n\t\t\tgameState = Turn.PLAYERBLACK;\n\t\t}\n\t\t// adds the Decider to the stage\n\t\tDecider decider = new Decider(gameState);\n\t\tdeciderStage.addActor(decider);\n\t}\n\n\tprivate class Decider extends Actor{\n\t\t// after 2 seconds, it will set startDecided to true\n\t\tfloat X;\n\t\tfloat Y;\n\t\t// elapsed time since addition to stage\n\t\tfloat elapsed = 0;\n\t\t// this is the maximum duration that the bubble will be on the screen\n\t\tfinal float MAX_DURATION = 2f;\n\t\t// this is the stack of the bubble\n\t\tStack stack;\n\n\t\tpublic Decider(Turn turn){\n\t\t\tthis.stack = new Stack();\n\t\t\tstack.setSize(tileSize*4, tileSize*2);\n\n\t\t\tif(turn == Turn.PLAYERWHITE){\n\t\t\t\tstack.addActor(new Image(whiteStarts));\n\t\t\t} else {\n\t\t\t\tstack.addActor(new Image(blackStarts));\n\t\t\t}\n\n\t\t\tthis.X = tileSize*8;\n\t\t\tthis.Y = tileSize*8;\n\t\t}\n\n\t\t@Override\n\t\tpublic void act(float delta) {\n\t\t\t/*\n\t\t\t * this method is called every frame to update the Actor\n\t\t\t */\n\t\t\tsuper.act(delta);\n\t\t\telapsed += delta;\n\t\t\tif (elapsed > MAX_DURATION) {\n\t\t\t\tstartUndecided = false;\n\t\t\t\tremove(); // This will remove the actor from the stage\n\t\t\t}\n\t\t}\n\n\t\t// Override the draw method to add the stack at the correct position\n\t\t@Override\n\t\tpublic void draw(Batch batch, float parentAlpha) {\n\t\t\t/*\n\t\t\tThis method is called every frame to draw the starter indicator\n\t\t\t */\n\t\t\tsuper.draw(batch, parentAlpha);\n\t\t\tstack.setPosition(X, Y);\n\t\t\tstack.draw(batch, parentAlpha);\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void dispose () {\n\t\tbatch.dispose();\n\t\tbackground.dispose();\n\t\t// dispose of all textures\n\t\tblackpiece.dispose();\n\t\twhitepiece.dispose();\n\t\thappy.dispose();\n\t\twater.dispose();\n\t\tsafe.dispose();\n\t\trebirth.dispose();\n\t\trebirthProtection.dispose();\n\t\tlogo.dispose();\n\t\ttileTexture.dispose();\n\t\temptyTexture.dispose();\n\t\textraTurnTexture.dispose();\n\t\tblackStick.dispose();\n\t\twhiteStick.dispose();\n\t\tnumber0.dispose();\n\t\tnumber1.dispose();\n\t\tnumber2.dispose();\n\t\tnumber3.dispose();\n\t\tnumber4.dispose();\n\t\tnumber6.dispose();\n\t\twhiteStarts.dispose();\n\t\tblackStarts.dispose();\n\t}\n\n\tpublic static Coordinate calculatePXbyTile(int x) {\n\t\t// the screen is 1536 to 896. The board is 3x10 tiles and each tile is 80x80px.\n\t\t// the board is centered on the screen\n\t\tint screenWidth = 1536;\n\t\tint screenHeight = 896;\n\t\tint boardWidth = (int) (tileSize * 10);\n\t\tint boardHeight = (int) (tileSize * 3);\n\n\t\t// Calculate starting position (upper left corner) of the board\n\t\tint boardStartX = (screenWidth - boardWidth) / 2;\n\t\tint boardStartY = (screenHeight - boardHeight) / 2;\n\n\t\tint yCoord;\n\t\tint xCoord;\n\n\t\t// Calculate the tile's position\n\t\tif(x <= 9){\n\t\t\tyCoord = boardStartY + 80;\n\t\t\txCoord = boardStartX + (x * 80);\n\t\t} else if (x <= 19){\n\t\t\tyCoord = boardStartY;\n\t\t\txCoord = boardStartX + (10*80) - ((x-9)*80);\n\t\t} else {\n\t\t\tyCoord = boardStartY - (80);\n\t\t\txCoord = boardStartY * ((x-19) * 80);\n\t\t}\n\n\t\treturn new Coordinate(xCoord, yCoord);\n\t}\n\n\tpublic static int calculateTilebyPx(int x, int y) {\n\t\tint screenWidth = 1536;\n\t\tint screenHeight = 896;\n\t\tint inFuncTileSize = (int) tileSize;\n\t\tint boardWidth = (inFuncTileSize * 10);\n\t\tint boardHeight = (inFuncTileSize * 3);\n\n\t\t// Calculate starting position (upper left corner) of the board\n\t\tint boardStartX = (screenWidth - boardWidth) / 2;\n\t\tint boardStartY = (screenHeight - boardHeight) / 2;\n\n\t\t// Adjust the y-coordinate to reflect libGDX's bottom-left origin\n\t\tint adjustedY = screenHeight - y;\n\n\t\t// Calculate which tile\n\t\tint tileX = (int) ((x - boardStartX) / inFuncTileSize);\n\t\tint tileY = (int) ((adjustedY - boardStartY) / inFuncTileSize);\n\n\t\tint tile;\n\t\tif (tileY == 0) { // Top row\n\t\t\ttile = tileX; // Tiles 0 to 9\n\t\t} else if (tileY == 1) { // Middle row (reversed)\n\t\t\ttile = 19 - tileX; // Tiles 19 to 10, in reverse\n\t\t} else if (tileY == 2) { // Bottom row\n\t\t\ttile = 20 + tileX; // Tiles 20 to 29\n\t\t} else {\n\t\t\t// Handle the case where the coordinates are outside the board\n\t\t\ttile = -1;\n\t\t}\n\n\t\treturn tile;\n\t}\n\n\n\tpublic static void createHelpStage() {\n\t\t// load texture help\n\t\tImage help = new Image(helpTexture);\n\t\thelp.setPosition(tileSize*13.1f, tileSize*2.7f);\n\t\thelp.setSize(tileSize*7, tileSize*9);\n\t\t// add it to help stage\n\t\thelpOverlayStage.addActor(help);\n\t}\n\n\tpublic static void createOptionsStage() {\n\t}\n\n\tpublic static Skin getSkin() {\n\t\treturn skin;\n\t}\n\n\tpublic static void renderBoard() {\n\n\t\tstickValueStage.clear();\n\t\tstickValueStage = SenetBoom.drawStickValue(currentStickValue);\n\n\t\tmapStage.clear();\n\t\tmapStage = GameStage.drawMap();\n\n\t\tcurrentStage.clear();\n\t\tcurrentStage = GameStage.drawBoard();\n\n\t\tGdx.input.setInputProcessor(currentStage);\n\t}\n\n\tprivate static Stage drawStickValue(int currentStickValue) {\n\n\t\tStage stage = new Stage();\n\n\t\t// scene 2D UI stuff\n\t\tStack rawValue = new Stack();\n\t\tTable sticks = new Table();\n\n\t\tImage number;\n\t\t// switch statement for currentStickValue 1,2,3,4,6\n\t\tswitch(currentStickValue){\n\t\t\tcase 1:\n\t\t\t\t// draw 3 black sticks\n\t\t\t\t// draw 1 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number1);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t// draw 2 black sticks\n\t\t\t\t// draw 2 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number2);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t// draw 1 black sticks\n\t\t\t\t// draw 3 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number3);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\t// draw 0 black sticks\n\t\t\t\t// draw 4 white sticks\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number4);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\t// draw 4 black sticks\n\t\t\t\t// draw 0 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tnumber = new Image(number6);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tsticks.setPosition(tileSize, tileSize*2);\n\t\tsticks.setSize(tileSize*2, tileSize*2);\n\t\tstage.addActor(sticks);\n\n\t\trawValue.setPosition(tileSize, tileSize*2.25f);\n\t\tstage.addActor(rawValue);\n\t\treturn stage;\n\t}\n\n\tpublic static void createMenu() {\n\t\tcurrentStage = MainMenu.createMenu();\n\t\tGdx.input.setInputProcessor(currentStage);\n\t\tinGame = false;\n\t}\n\n\tprivate void checkForGameEnd() {\n\t\t// goes over the gameBoard and counts, if someone has no pieces at all left\n\t\t// if so, the game ends and the winner is displayed\n\t\t// if not, the game continues\n\n\t\tTile[] gameBoard = Board.getBoard();\n\t\tint whitePieces = 0;\n\t\tint blackPieces = 0;\n\t\tfor(Tile tile : gameBoard){\n\t\t\tif(tile.hasPiece()){\n\t\t\t\tif(tile.getPiece().getColour() == Piece.Color.WHITE){\n\t\t\t\t\twhitePieces++;\n\t\t\t\t} else {\n\t\t\t\t\tblackPieces++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(whitePieces == 0){\n\t\t\tcreateGameEnd(Piece.Color.WHITE);\n\t\t}\n\t\tif(blackPieces == 0){\n\t\t\tcreateGameEnd(Piece.Color.BLACK);\n\t\t}\n\t}\n\n\tprivate void createGameEnd(Piece.Color color) {\n\t\t/*\n\t\tcreats a stage that displays the winner\n\t\t */\n\n\t\t// TODO\n\t}\n\n\tpublic static Piece.Color getTurn(){\n\t\treturn gameState == Turn.PLAYERWHITE ? Piece.Color.WHITE : Piece.Color.BLACK;\n\t}\n\n\tpublic static void addExtraTurnActor(){\n\t\tExtraTurnActor newTurn = new ExtraTurnActor();\n\t\textraTurnStage.addActor(newTurn);\n\t\tSystem.out.println(\"Added ExtraTurn Actor to Screen\\n\");\n\t}\n}" }, { "identifier": "RandomText", "path": "core/src/com/senetboom/game/frontend/text/RandomText.java", "snippet": "public class RandomText {\n private List<String> texts;\n\n public RandomText() {\n }\n\n public void addText(String text) {\n texts.add(text);\n }\n\n public String getText() {\n return texts.get((int) (Math.random() * texts.size()));\n }\n}" } ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Actor; import com.senetboom.game.SenetBoom; import com.senetboom.game.frontend.text.RandomText;
7,769
package com.senetboom.game.frontend.text; public class Typewriter { /* Typewrite is used to print text on the screen. It prints one character every 0.1 seconds. It is used to display speech. It has enums for emotion and character (colour white or black) */ public enum Emotion { NORMAL, HAPPY, SAD, ANGRY, CONFUSED } public enum Character { WHITE, BLACK }
package com.senetboom.game.frontend.text; public class Typewriter { /* Typewrite is used to print text on the screen. It prints one character every 0.1 seconds. It is used to display speech. It has enums for emotion and character (colour white or black) */ public enum Emotion { NORMAL, HAPPY, SAD, ANGRY, CONFUSED } public enum Character { WHITE, BLACK }
private final RandomText normalText;
1
2023-12-05 22:19:00+00:00
12k
ItzOverS/CoReScreen
src/main/java/me/overlight/corescreen/Commands.java
[ { "identifier": "AnalyzeModule", "path": "src/main/java/me/overlight/corescreen/Analyzer/AnalyzeModule.java", "snippet": "public class AnalyzeModule {\n public String getName() {\n return name;\n }\n\n private final String name;\n\n public AnalyzeModule(String name) {\n this.name = name;\n }\n\n public void activate(Player target){\n\n }\n\n public void result(Player player, Player target){\n\n }\n\n public void send(Player player, String key, String value){\n player.sendMessage(\"§9§l\" + key + \"§7: §e\" + value);\n }\n\n public void packetEvent(PacketPlayReceiveEvent e) { }\n public void packetEvent(PacketPlaySendEvent e) { }\n\n public void clearVariables(Player target){\n Field[] fields = getClass().getFields();\n Arrays.stream(fields).forEach(r -> {\n if(r.getType() == HashMap.class){\n try {\n r.setAccessible(true);\n HashMap<String, ?> map = (HashMap<String, ?>) r.get(getClass());\n map.remove(target.getName());\n r.setAccessible(false);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n });\n }\n}" }, { "identifier": "AnalyzerManager", "path": "src/main/java/me/overlight/corescreen/Analyzer/AnalyzerManager.java", "snippet": "public class AnalyzerManager {\n public final static List<AnalyzeModule> analyzers = new ArrayList<>();\n\n static {\n analyzers.addAll(Arrays.asList(new Ping(), new Reach()));\n\n Bukkit.getScheduler().runTaskLater(CoReScreen.getInstance(), () -> {\n PacketEvents.get().getEventManager().registerListener(new PacketListenerAbstract() {\n @Override\n public void onPacketPlayReceive(PacketPlayReceiveEvent event) {\n analyzers.forEach(r -> r.packetEvent(event));\n }\n @Override\n public void onPacketPlaySend(PacketPlaySendEvent event) {\n analyzers.forEach(r -> r.packetEvent(event));\n }\n });\n }, 5);\n }\n}" }, { "identifier": "CSManager", "path": "src/main/java/me/overlight/corescreen/ClientSettings/CSManager.java", "snippet": "public class CSManager {\n public final static List<CSModule> modules = new ArrayList<>();\n\n static {\n modules.addAll(Arrays.asList(new ClientVersion(), new Locale(), new RenderDistance(), new ChatVisibility()));\n }\n}" }, { "identifier": "CSModule", "path": "src/main/java/me/overlight/corescreen/ClientSettings/CSModule.java", "snippet": "public class CSModule {\n private final String name, permission;\n\n public String getName() {\n return name;\n }\n\n public String getPermission() {\n return permission;\n }\n\n public CSModule(String name, String permission) {\n this.permission = permission;\n this.name = name;\n }\n\n public String getValue(Player player) {\n return null;\n }\n}" }, { "identifier": "CacheManager", "path": "src/main/java/me/overlight/corescreen/Freeze/Cache/CacheManager.java", "snippet": "public class CacheManager {\n public final static boolean isEnabled = CoReScreen.getInstance().getConfig().getBoolean(\"settings.freeze.cache.enabled\");\n public final static int maxSize = CoReScreen.getInstance().getConfig().getInt(\"settings.freeze.cache.max-size\");\n private final static HashMap<String, List<String>> cache = new HashMap<>();\n\n public static void cache(Player who, String data){\n if(!isEnabled || cache.getOrDefault(who.getName(), new ArrayList<>()).size() > maxSize) return;\n if(!cache.containsKey(who.getName())) cache.put(who.getName(), new ArrayList<>());\n cache.get(who.getName()).add(ChatColor.stripColor(data));\n if(cache.get(who.getName()).size() > maxSize) cache.get(who.getName()).add(\"Cache size length has limit to \" + maxSize);\n }\n\n public static void saveCache(Player who){\n if(!isEnabled || !cache.containsKey(who.getName())) return;\n if(!new File(\"plugins\\\\CoReScreen\\\\freeze-cache\").exists()) new File(\"plugins\\\\CoReScreen\\\\freeze-cache\").mkdirs();\n File path = new File(CoReScreen.getInstance().getDataFolder(), \"freeze-cache\\\\\" + who.getName() + \".\" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH.mm.ss.SSSS\")) + \".txt\");\n try {\n Files.createFile(Paths.get(path.getPath()));\n try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {\n cache.get(who.getName()).forEach(r -> {\n try {\n writer.write(r + \"\\n\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n } catch (IOException e) {\n e.printStackTrace();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n cache.remove(who.getName());\n }\n}" }, { "identifier": "FreezeManager", "path": "src/main/java/me/overlight/corescreen/Freeze/FreezeManager.java", "snippet": "public class FreezeManager {\n public final static List<String> frozen = new ArrayList<String>();\n public final static List<String> freezeWhenLogin = new ArrayList<String>();\n public final static HashMap<String, HashMap<Integer, ItemStack>> inventory = new HashMap<>();\n public final static HashMap<String, Location> lastGround = new HashMap<>();\n public final static boolean blindEye = CoReScreen.getInstance().getConfig().getBoolean(\"settings.freeze.blind-eye.enabled\");\n public final static boolean clearInv = CoReScreen.getInstance().getConfig().getBoolean(\"settings.freeze.inventory-clearing.enabled\");\n public static boolean isFrozen(Player player) {\n return frozen.contains(player.getName());\n }\n\n public static void freezePlayer(Player player) {\n frozen.add(player.getName());\n player.setWalkSpeed(0);\n if(blindEye) player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Integer.MAX_VALUE, 1, false, false));\n if(clearInv){\n inventory.put(player.getName(), new HashMap<>());\n for(int i = 0; i < 36; i++){\n if(player.getInventory().getItem(i) == null) continue;\n inventory.get(player.getName()).put(i, player.getInventory().getItem(i));\n }\n inventory.get(player.getName()).put(-10, player.getInventory().getHelmet());\n inventory.get(player.getName()).put(-9, player.getInventory().getChestplate());\n inventory.get(player.getName()).put(-8, player.getInventory().getLeggings());\n inventory.get(player.getName()).put(-7, player.getInventory().getBoots());\n player.getInventory().setArmorContents(new ItemStack[]{ null, null, null, null });\n player.getInventory().clear();\n }\n }\n\n public static void unfreezePlayer(Player player) {\n frozen.remove(player.getName());\n player.setWalkSpeed(.2f);\n if(blindEye) player.removePotionEffect(PotionEffectType.BLINDNESS);\n WarpManager.warpPlayerToLast(player);\n CacheManager.saveCache(player);\n if(clearInv){\n for(int i: inventory.getOrDefault(player.getName(), new HashMap<>()).keySet()){\n if(i < 0) continue;\n player.getInventory().setItem(i, inventory.get(player.getName()).get(i));\n }\n player.getInventory().setHelmet(inventory.get(player.getName()).get(-10));\n player.getInventory().setChestplate(inventory.get(player.getName()).get(-9));\n player.getInventory().setLeggings(inventory.get(player.getName()).get(-8));\n player.getInventory().setBoots(inventory.get(player.getName()).get(-7));\n inventory.remove(player.getName());\n }\n }\n\n public static void toggleFreeze(Player player) {\n if (isFrozen(player)) unfreezePlayer(player);\n else freezePlayer(player);\n }\n\n public static class Handler extends PacketListenerAbstract {\n @Override\n public void onPacketPlayReceive(PacketPlayReceiveEvent e) {\n if (!FreezeManager.isFrozen(e.getPlayer())) return;\n if (e.getPacketId() == PacketType.Play.Client.ARM_ANIMATION) e.setCancelled(true);\n if (e.getPacketId() == PacketType.Play.Client.USE_ENTITY) e.setCancelled(true);\n }\n }\n}" }, { "identifier": "WarpManager", "path": "src/main/java/me/overlight/corescreen/Freeze/Warps/WarpManager.java", "snippet": "public class WarpManager {\n private static FileConfiguration config = CoReScreen.getInstance().getConfig();\n public final static boolean isEnabled = config.getBoolean(\"settings.freeze.warp.enabled\") &&\n config.getConfigurationSection(\"settings.freeze.warp.warps\").getKeys(false).size() > 0,\n teleportBack = config.getBoolean(\"settings.freeze.warp.teleport-back\"),\n protectWarp = config.getBoolean(\"settings.freeze.warp.protect-warp\");\n public final static List<Warp> warps = new ArrayList<>(config.getConfigurationSection(\"settings.freeze.warp.warps\").getKeys(false)).stream().map(r -> {\n String l = config.getConfigurationSection(\"settings.freeze.warp.warps\").getString(r);\n Float[] v = Arrays.stream(l.split(\";\")).collect(Collectors.toList()).subList(1, l.split(\";\").length).stream().map(Float::valueOf).toArray(Float[]::new);\n return new Warp(new Location(Bukkit.getWorld(l.split(\";\")[0]), v[0], v[1], v[2], v[3], v[4]), r);\n }).collect(Collectors.toList());\n\n private final static HashMap<String, Location> teleports = new HashMap<>();\n\n public static boolean warpPlayerToEmpty(Player player){\n if(!isEnabled) return false;\n boolean canWarp = warps.stream().anyMatch(r -> !r.inUse);\n if(!canWarp) return false;\n Warp warp = warps.stream().filter(r -> !r.inUse).findAny().get();\n warp.inUse = true;\n warp.playerName = player.getName();\n if(teleportBack) teleports.put(player.getName(), player.getLocation());\n player.teleport(warp.location.clone());\n return true;\n }\n\n public static void warpPlayerToLast(Player player){\n if(!isEnabled) return;\n if(teleportBack && !teleports.containsKey(player.getName())) {\n player.kickPlayer(\"No Last Known Position Detected For You!\");\n return;\n }\n if(teleportBack) {\n player.teleport(teleports.get(player.getName()));\n teleports.remove(player.getName());\n }\n Warp warp = warps.stream().filter(r -> !r.inUse).findAny().get();\n warp.playerName = null;\n warp.inUse = false;\n }\n\n public static class Warp {\n public Location location;\n public String name, playerName;\n public boolean inUse = false;\n\n public Warp(Location location, String name) {\n this.location = location;\n this.name = name;\n }\n }\n}" }, { "identifier": "ProfilerManager", "path": "src/main/java/me/overlight/corescreen/Profiler/ProfilerManager.java", "snippet": "public class ProfilerManager {\n public final static List<Profiler> profilers = new ArrayList<>();\n public final static List<NmsHandler.NmsProfiler> profilersNms = new ArrayList<>();\n public final static List<ProfilingSystem> profilingSystems = new ArrayList<>();\n\n static {\n profilingSystems.addAll(Arrays.asList(new CPS(), new MovementSpeed(), new Ping(), new Sneaking(), new Sprinting(), new SwordBlocking(), new HorizontalRotationSpeed(),\n new VerticalRotationSpeed(), new Reach(), new FallSpeed()));\n profilingSystems.stream().filter(r -> r instanceof Listener).forEach(r -> CoReScreen.getInstance().getServer().getPluginManager().registerEvents((Listener) r, CoReScreen.getInstance()));\n }\n\n public static void addProfiler(Player staff, Player who, Profiler.ProfileOption... options) {\n profilers.removeIf(p -> p.getStaff().equals(staff.getName()) && !p.getWho().equals(who.getName()));\n if (profilers.stream().anyMatch(r -> r.getStaff().equals(staff.getName()) && r.getWho().equals(who.getName())))\n profilers.stream().filter(r -> r.getStaff().equals(staff.getName()) && r.getWho().equals(who.getName())).collect(Collectors.toList()).get(0).options.addAll(new ArrayList<>(Arrays.asList(options)));\n else profilers.add(new Profiler(staff.getName(), who.getName(), new ArrayList<>(Arrays.asList(options))));\n }\n\n public static void addProfiler(Player staff, Player who, NmsHandler.NmsWrapper... options) {\n profilersNms.removeIf(p -> p.getStaff().equals(staff.getName()) && !p.getWho().equals(who.getName()));\n if (profilersNms.stream().anyMatch(r -> r.getStaff().equals(staff.getName()) && r.getWho().equals(who.getName())))\n profilersNms.stream().filter(r -> r.getStaff().equals(staff.getName()) && r.getWho().equals(who.getName())).collect(Collectors.toList()).get(0).nmsWrapper.addAll(new ArrayList<>(Arrays.asList(options)));\n else profilersNms.add(new NmsHandler.NmsProfiler(staff.getName(), who.getName(), new ArrayList<>(Arrays.asList(options))));\n }\n\n public static void removeProfiler(Player staff) {\n profilers.removeIf(p -> p.getStaff().equals(staff.getName()));\n profilersNms.removeIf(p -> p.getStaff().equals(staff.getName()));\n }\n\n public static void removeProfiler(String staff) {\n profilers.removeIf(p -> p.getStaff().equals(staff));\n profilersNms.removeIf(p -> p.getStaff().equals(staff));\n }\n\n public static boolean isProfiling(String staff) {\n return profilers.stream().anyMatch(r -> r.getStaff().equals(staff)) || profilersNms.stream().anyMatch(r -> r.getStaff().equals(staff));\n }\n}" }, { "identifier": "NmsHandler", "path": "src/main/java/me/overlight/corescreen/Profiler/Profiles/NmsHandler.java", "snippet": "public class NmsHandler {\n public final static List<NmsWrapper> handlers = new ArrayList<>();\n\n public static String handleNMS(Player who, NmsWrapper packet) {\n try {\n Object CraftPlayer = who.getClass().getMethod(\"getHandle\").invoke(who);\n return CraftPlayer.getClass().getField(packet.getPath()).get(CraftPlayer).toString();\n } catch (Exception e) {\n e.printStackTrace();\n return \"INVALIDATE_ARGUMENT\";\n }\n }\n\n public static void loadCustomSettings(){\n ConfigurationSection section = CoReScreen.getInstance().getConfig().getConfigurationSection(\"settings.profiler.formats.player-handler\");\n handlers.addAll(new ArrayList<>(section.getKeys(false).stream().map(r -> new NmsWrapper(section.getString(r + \".path\"), section.getString(r + \".label\"), r)).collect(Collectors.toList())));\n }\n\n public static class NmsWrapper {\n private final String path, label, name;\n\n public NmsWrapper(String path, String label, String name) {\n this.path = path;\n this.label = label;\n this.name = name;\n }\n\n public String getPath() {\n return path;\n }\n\n public String getLabel() {\n return label;\n }\n\n public String getName() {\n return name;\n }\n }\n\n public static class NmsProfiler {\n public List<NmsWrapper> nmsWrapper;\n private final String staff, who;\n\n public NmsProfiler(String staff, String who, List<NmsWrapper> nmsWrapper) {\n this.nmsWrapper = nmsWrapper;\n this.staff = staff;\n this.who = who;\n }\n\n public String getStaff() {\n return staff;\n }\n\n public String getWho() {\n return who;\n }\n }\n}" }, { "identifier": "ProfilingSystem", "path": "src/main/java/me/overlight/corescreen/Profiler/ProfilingSystem.java", "snippet": "public class ProfilingSystem {\n private final String name, placeholder;\n private final Profiler.ProfileOption mode;\n\n public boolean isProfiling(Player player) {\n return (ProfilerManager.profilers.stream().anyMatch(r -> r.getWho().equalsIgnoreCase(player.getName()) && r.options.contains(mode)));\n }\n\n public Profiler.ProfileOption getMode() {\n return mode;\n }\n\n public String getName() {\n return name;\n }\n\n public String getPlaceholder() {\n return placeholder;\n }\n\n public ProfilingSystem(String name, String placeholder, Profiler.ProfileOption mode) {\n this.name = name;\n this.placeholder = placeholder;\n this.mode = mode;\n }\n\n public String valueRequest(Player player, String text) {\n return null;\n }\n\n public void startHandling(Player player) {\n\n }\n\n public void stopHandling(String player) {\n\n }\n}" }, { "identifier": "TestCheck", "path": "src/main/java/me/overlight/corescreen/Test/TestCheck.java", "snippet": "public class TestCheck {\n private final String name;\n private final String[] alias;\n\n public String getName() {\n return name;\n }\n\n public String[] getAlias() {\n return alias;\n }\n\n public TestCheck(String name, String[] alias) {\n this.name = name;\n this.alias = alias;\n }\n\n public void handle(Player player, Player executor) {\n\n }\n}" }, { "identifier": "TestManager", "path": "src/main/java/me/overlight/corescreen/Test/TestManager.java", "snippet": "public class TestManager {\n public final static List<TestCheck> tests = new ArrayList<>();\n\n static {\n tests.addAll(Arrays.asList(new Knockback(), new Rotation(), new Shuffle()));\n }\n}" }, { "identifier": "VanishManager", "path": "src/main/java/me/overlight/corescreen/Vanish/VanishManager.java", "snippet": "public class VanishManager {\n public static final List<String> vanishes = new ArrayList<>();\n\n static {\n Bukkit.getScheduler().runTaskTimer(CoReScreen.getInstance(), () -> {\n new PlayerActionBar(CoReScreen.translate(\"messages.vanish.game.action-bar\")).send(\n vanishes.stream().filter(r -> Bukkit.getOnlinePlayers().stream().anyMatch(f -> f.getName().equals(r))\n && !ProfilerManager.isProfiling(r)).map(r -> Bukkit.getOnlinePlayers().stream().filter(f -> f.getName().equals(r)).collect(Collectors.toList()).get(0)).toArray(Player[]::new));\n vanishes.stream().filter(r -> Bukkit.getOnlinePlayers().stream().anyMatch(f -> f.getName().equals(r))).map(r -> Bukkit.getOnlinePlayers().stream().filter(f -> f.getName().equals(r))\n .collect(Collectors.toList()).get(0)).forEach(r -> {\n r.setAllowFlight(true);\n });\n }, 10, 20);\n }\n\n public static boolean isVanish(Player player) {\n if(player == null) return false;\n return vanishes.contains(player.getName());\n }\n\n public static void vanishPlayer(Player player) {\n if (isVanish(player)) return;\n if (CoReScreen.getInstance().getConfig().getString(\"messages.vanish.game.quit-message\", null) != null && !CoReScreen.translate(\"messages.vanish.game.quit-message\").trim().isEmpty())\n Bukkit.getOnlinePlayers().forEach(p -> p.sendMessage(CoReScreen.translate(\"messages.vanish.game.quit-message\").replace(\"%player%\", player.getName())));\n Bukkit.getOnlinePlayers().stream().filter(p -> !p.hasPermission(PacketHandler.see_other_permission) && !p.getName().equals(player.getName())).forEach(p -> {\n Bukkit.getScheduler().runTask(CoReScreen.getInstance(), () -> PacketEvents.get().getPlayerUtils().sendPacket(p, new WrappedPacketOutEntityDestroy(player.getEntityId())));\n PacketEvents.get().getPlayerUtils().sendPacket(p, new WrappedPacketOutPlayerInfo(WrappedPacketOutPlayerInfo.PlayerInfoAction.REMOVE_PLAYER, getPlayerInfo(player)));\n });\n vanishes.add(player.getName());\n player.setAllowFlight(true);\n BackwardServerMessenger.sendData(\"enable\", player.getName());\n }\n\n public static void vanishOffline(String name) {\n if (vanishes.contains(name.trim())) return;\n vanishes.add(name.trim());\n }\n\n public static void unVanishOffline(String name) {\n vanishes.remove(name.trim());\n }\n\n public static void unVanishPlayer(Player player) {\n if (!isVanish(player)) return;\n vanishes.remove(player.getName());\n if (CoReScreen.getInstance().getConfig().getString(\"messages.vanish.game.join-message\", null) != null && !CoReScreen.getInstance().getConfig().getString(\"messages.vanish.game.join-message\", null).trim().isEmpty())\n Bukkit.getOnlinePlayers().forEach(p -> p.sendMessage(CoReScreen.translate(\"messages.vanish.game.join-message\").replace(\"%player%\", player.getName())));\n Bukkit.getOnlinePlayers().stream().filter(p -> !p.hasPermission(PacketHandler.see_other_permission) && !p.getName().equals(player.getName())).forEach(p -> {\n Bukkit.getScheduler().runTask(CoReScreen.getInstance(), () -> {\n PacketEvents.get().getPlayerUtils().sendPacket(p, new WrappedPacketOutPlayerInfo(WrappedPacketOutPlayerInfo.PlayerInfoAction.ADD_PLAYER, getPlayerInfo(player)));\n PacketEvents.get().getPlayerUtils().sendPacket(p, new WrappedPacketOutNamedEntitySpawn(player));\n });\n });\n player.setAllowFlight(false);\n player.setFlying(false);\n BackwardServerMessenger.sendData(\"disable\", player.getName());\n }\n\n public static void toggleVanish(Player player) {\n if (isVanish(player)) unVanishPlayer(player);\n else vanishPlayer(player);\n }\n private static WrappedPacketOutPlayerInfo.PlayerInfo getPlayerInfo(Player player){\n return new WrappedPacketOutPlayerInfo.PlayerInfo(player.getName(), PacketEvents.get().getPlayerUtils().getGameProfile(player), player.getGameMode(), PacketEvents.get().getPlayerUtils().getPing(player));\n }\n}" }, { "identifier": "PlayerFreezeEvent", "path": "src/main/java/me/overlight/corescreen/api/Freeze/PlayerFreezeEvent.java", "snippet": "public class PlayerFreezeEvent extends Event implements Cancellable {\n public static HandlerList list = new HandlerList();\n\n private boolean cancelled = false;\n\n public Player getTarget() {\n return target;\n }\n\n public Player getStaff() {\n return staff;\n }\n\n private final Player target, staff;\n\n public PlayerFreezeEvent(boolean cancelled, Player target, Player staff) {\n this.cancelled = cancelled;\n this.target = target;\n this.staff = staff;\n }\n\n @Override\n public boolean isCancelled() {\n return cancelled;\n }\n\n @Override\n public void setCancelled(boolean b) {\n cancelled = b;\n }\n\n @Override\n public HandlerList getHandlers() {\n return list;\n }\n}" }, { "identifier": "PlayerUnfreezeEvent", "path": "src/main/java/me/overlight/corescreen/api/Freeze/PlayerUnfreezeEvent.java", "snippet": "public class PlayerUnfreezeEvent extends Event implements Cancellable {\n public static HandlerList list = new HandlerList();\n\n private boolean cancelled = false;\n\n public Player getTarget() {\n return target;\n }\n\n public Player getStaff() {\n return staff;\n }\n\n private final Player target, staff;\n\n public PlayerUnfreezeEvent(boolean cancelled, Player target, Player staff) {\n this.cancelled = cancelled;\n this.target = target;\n this.staff = staff;\n }\n\n @Override\n public boolean isCancelled() {\n return cancelled;\n }\n\n @Override\n public void setCancelled(boolean b) {\n cancelled = b;\n }\n\n @Override\n public HandlerList getHandlers() {\n return list;\n }\n}" } ]
import me.overlight.corescreen.Analyzer.AnalyzeModule; import me.overlight.corescreen.Analyzer.AnalyzerManager; import me.overlight.corescreen.ClientSettings.CSManager; import me.overlight.corescreen.ClientSettings.CSModule; import me.overlight.corescreen.Freeze.Cache.CacheManager; import me.overlight.corescreen.Freeze.FreezeManager; import me.overlight.corescreen.Freeze.Warps.WarpManager; import me.overlight.corescreen.Profiler.ProfilerManager; import me.overlight.corescreen.Profiler.Profiles.NmsHandler; import me.overlight.corescreen.Profiler.ProfilingSystem; import me.overlight.corescreen.Test.TestCheck; import me.overlight.corescreen.Test.TestManager; import me.overlight.corescreen.Vanish.VanishManager; import me.overlight.corescreen.api.Freeze.PlayerFreezeEvent; import me.overlight.corescreen.api.Freeze.PlayerUnfreezeEvent; import me.overlight.powerlib.Chat.Text.impl.PlayerChatMessage; import me.overlight.powerlib.Chat.Text.impl.ext.ClickableCommand; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors;
7,252
package me.overlight.corescreen; public class Commands { public static String prefix; public static class Vanish implements CommandExecutor { private final HashMap<String, Long> cooldown_vanish = new HashMap<>(); private final HashMap<String, Long> cooldown_unvanish = new HashMap<>(); private final int vanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.vanish"), unvanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.unvanish"); @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 0) { if (!commandSender.hasPermission("corescreen.vanish.self")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } if ((!VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_vanish.getOrDefault(commandSender.getName(), 0L) > vanishCooldown) || (VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_unvanish.getOrDefault(commandSender.getName(), 0L) > unvanishCooldown)) { if(VanishManager.isVanish((Player) commandSender)) cooldown_unvanish.put(commandSender.getName(), System.currentTimeMillis()); else cooldown_vanish.put(commandSender.getName(), System.currentTimeMillis()); VanishManager.toggleVanish((Player) commandSender); if (VanishManager.isVanish((Player) commandSender)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-vanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + commandSender.getName() + "** has vanished they self!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-unvanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + commandSender.getName() + "** has un-vanished they self!").execute(); } } else { commandSender.sendMessage(CoReScreen.translate("settings.vanish.command-cooldown.message")); } } else if (args.length == 1) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); VanishManager.toggleVanish(who); if (VanishManager.isVanish(who)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + who.getName() + "** has vanished by **" + commandSender.getName() + "**!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + who.getName() + "** has un-vanished by **" + commandSender.getName() + "**!").execute(); } } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } boolean forceEnabled = args[1].equalsIgnoreCase("on"); List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); if (forceEnabled) VanishManager.vanishPlayer(who); else VanishManager.unVanishPlayer(who); if (VanishManager.isVanish(who)) commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); else commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { if(args.length == 1 && commandSender.hasPermission("corescreen.vanish.other")) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Profiler implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1 && args[0].equalsIgnoreCase("remove")) { if (!commandSender.hasPermission("corescreen.profiler.remove")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } ProfilerManager.removeProfiler((Player) commandSender); } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.profiler.append")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); try {
package me.overlight.corescreen; public class Commands { public static String prefix; public static class Vanish implements CommandExecutor { private final HashMap<String, Long> cooldown_vanish = new HashMap<>(); private final HashMap<String, Long> cooldown_unvanish = new HashMap<>(); private final int vanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.vanish"), unvanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.unvanish"); @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 0) { if (!commandSender.hasPermission("corescreen.vanish.self")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } if ((!VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_vanish.getOrDefault(commandSender.getName(), 0L) > vanishCooldown) || (VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_unvanish.getOrDefault(commandSender.getName(), 0L) > unvanishCooldown)) { if(VanishManager.isVanish((Player) commandSender)) cooldown_unvanish.put(commandSender.getName(), System.currentTimeMillis()); else cooldown_vanish.put(commandSender.getName(), System.currentTimeMillis()); VanishManager.toggleVanish((Player) commandSender); if (VanishManager.isVanish((Player) commandSender)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-vanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + commandSender.getName() + "** has vanished they self!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-unvanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + commandSender.getName() + "** has un-vanished they self!").execute(); } } else { commandSender.sendMessage(CoReScreen.translate("settings.vanish.command-cooldown.message")); } } else if (args.length == 1) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); VanishManager.toggleVanish(who); if (VanishManager.isVanish(who)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + who.getName() + "** has vanished by **" + commandSender.getName() + "**!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + who.getName() + "** has un-vanished by **" + commandSender.getName() + "**!").execute(); } } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } boolean forceEnabled = args[1].equalsIgnoreCase("on"); List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); if (forceEnabled) VanishManager.vanishPlayer(who); else VanishManager.unVanishPlayer(who); if (VanishManager.isVanish(who)) commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); else commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { if(args.length == 1 && commandSender.hasPermission("corescreen.vanish.other")) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Profiler implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1 && args[0].equalsIgnoreCase("remove")) { if (!commandSender.hasPermission("corescreen.profiler.remove")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } ProfilerManager.removeProfiler((Player) commandSender); } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.profiler.append")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); try {
ProfilingSystem profiler = ProfilerManager.profilingSystems.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).collect(Collectors.toList()).get(0);
9
2023-12-07 16:34:39+00:00
12k
fabriciofx/cactoos-pdf
src/test/java/com/github/fabriciofx/cactoos/pdf/resource/FontTest.java
[ { "identifier": "Document", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Document.java", "snippet": "public final class Document implements Bytes {\n /**\n * PDF Version.\n */\n private static final String VERSION = \"1.3\";\n\n /**\n * PDF binary file signature.\n */\n private static final byte[] SIGNATURE = {\n (byte) 0x25, (byte) 0xc4, (byte) 0xe5, (byte) 0xf2, (byte) 0xe5,\n (byte) 0xeb, (byte) 0xa7, (byte) 0xf3, (byte) 0xa0, (byte) 0xd0,\n (byte) 0xc4, (byte) 0xc6, (byte) 0x0a,\n };\n\n /**\n * PDF end of file.\n */\n private static final String EOF = \"%%EOF\";\n\n /**\n * Id.\n */\n private final Id id;\n\n /**\n * PDF metadata.\n */\n private final Information information;\n\n /**\n * Catalog.\n */\n private final Catalog catalog;\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param information Information\n * @param pages Pages\n */\n public Document(\n final Id id,\n final Information information,\n final Pages pages\n ) {\n this(id, information, new Catalog(id, pages));\n }\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param pages Pages\n */\n public Document(final Id id, final Pages pages) {\n this(id, new Information(id), new Catalog(id, pages));\n }\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param catalog Catalog\n */\n public Document(final Id id, final Catalog catalog) {\n this(id, new Information(id), catalog);\n }\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param information Metadata\n * @param catalog Catalog\n */\n public Document(\n final Id id,\n final Information information,\n final Catalog catalog\n ) {\n this.id = id;\n this.information = information;\n this.catalog = catalog;\n }\n\n @Override\n public byte[] asBytes() throws Exception {\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n baos.write(\n new FormattedText(\n \"%%PDF-%s\\n\",\n Locale.ENGLISH,\n Document.VERSION\n ).asString().getBytes(StandardCharsets.UTF_8)\n );\n baos.write(Document.SIGNATURE);\n final Indirect info = this.information.indirect();\n baos.write(info.asBytes());\n final Indirect clog = this.catalog.indirect();\n baos.write(clog.asBytes());\n baos.write(\n new FormattedText(\n \"trailer << /Root %s /Size %d /Info %s >>\\n\",\n Locale.ENGLISH,\n clog.reference().asString(),\n this.id.value(),\n info.reference().asString()\n ).asString().getBytes(StandardCharsets.UTF_8)\n );\n baos.write(Document.EOF.getBytes(StandardCharsets.UTF_8));\n return baos.toByteArray();\n }\n}" }, { "identifier": "Font", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Font.java", "snippet": "public interface Font extends Resource {\n /**\n * Font name.\n *\n * @return The font name\n */\n String name();\n\n /**\n * Font size.\n *\n * @return The font size in points\n */\n int size();\n\n /**\n * Char width in a font.\n *\n * @param chr The character\n * @return The size of the char in a font\n */\n int width(char chr);\n}" }, { "identifier": "Id", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Id.java", "snippet": "public interface Id extends Scalar<Integer> {\n /**\n * Return the last object id and increment it.\n *\n * @return The last object id integer\n */\n int increment();\n}" }, { "identifier": "Contents", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/content/Contents.java", "snippet": "public final class Contents extends ListEnvelope<Content> implements Object {\n /**\n * Ctor.\n *\n * @param objects An array of objects\n */\n public Contents(final Content... objects) {\n this(new ListOf<>(objects));\n }\n\n /**\n * Ctor.\n *\n * @param list A list of objects\n */\n public Contents(\n final List<Content> list\n ) {\n super(list);\n }\n\n @Override\n public Indirect indirect() throws Exception {\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (final Object obj : this) {\n baos.write(obj.indirect().asBytes());\n }\n return new ContentIndirect(baos::toByteArray);\n }\n}" }, { "identifier": "Text", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/content/Text.java", "snippet": "public final class Text implements Content {\n /**\n * Object number.\n */\n private final int number;\n\n /**\n * Generation number.\n */\n private final int generation;\n\n /**\n * Font.\n */\n private final Font typeface;\n\n /**\n * Position X.\n */\n private final double posx;\n\n /**\n * Position Y.\n */\n private final double posy;\n\n /**\n * Max line length.\n */\n private final int max;\n\n /**\n * Space between lines.\n */\n private final double leading;\n\n /**\n * Text content.\n */\n private final org.cactoos.Text content;\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param font Font\n * @param posx Position X\n * @param posy Position Y\n * @param content Text content\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public Text(\n final Id id,\n final Font font,\n final double posx,\n final double posy,\n final org.cactoos.Text content\n ) {\n this(\n id.increment(),\n 0,\n font,\n posx,\n posy,\n 80,\n font.size() * 1.20,\n content\n );\n }\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param font Font\n * @param posx Position X\n * @param posy Position Y\n * @param max Max line length\n * @param content Text content\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public Text(\n final Id id,\n final Font font,\n final double posx,\n final double posy,\n final int max,\n final org.cactoos.Text content\n ) {\n this(\n id.increment(),\n 0,\n font,\n posx,\n posy,\n max,\n font.size() * 1.20,\n content\n );\n }\n\n /**\n * Ctor.\n *\n * @param id Id\n * @param font Font\n * @param posx Position X\n * @param posy Position Y\n * @param max Max line length\n * @param leading Space between lines\n * @param content Text content\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public Text(\n final Id id,\n final Font font,\n final double posx,\n final double posy,\n final int max,\n final double leading,\n final org.cactoos.Text content\n ) {\n this(id.increment(), 0, font, posx, posy, max, leading, content);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param font Font\n * @param posx Position X\n * @param posy Position Y\n * @param max Max line length\n * @param leading Space between lines\n * @param content Text content\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public Text(\n final int number,\n final int generation,\n final Font font,\n final double posx,\n final double posy,\n final int max,\n final double leading,\n final org.cactoos.Text content\n ) {\n this.number = number;\n this.generation = generation;\n this.typeface = font;\n this.posx = posx;\n this.posy = posy;\n this.max = max;\n this.leading = leading;\n this.content = new Escaped(content);\n }\n\n /**\n * Font.\n *\n * @return The font of text\n */\n public Font font() {\n return this.typeface;\n }\n\n @Override\n public byte[] asStream() throws Exception {\n final StringBuilder out = new StringBuilder();\n for (final org.cactoos.Text line : new Multiline(this.content, this.max)) {\n out.append(\n new FormattedText(\n \"(%s) Tj T*\\n\",\n Locale.ENGLISH,\n line\n ).asString()\n );\n }\n return new FormattedText(\n \"BT /%s %d Tf %.2f %.2f Td %.2f TL\\n%sET\",\n Locale.ENGLISH,\n this.typeface.name(),\n this.typeface.size(),\n this.posx,\n this.posy,\n this.leading,\n out.toString()\n ).asString().getBytes(StandardCharsets.UTF_8);\n }\n\n @Override\n public List<Resource> resource() {\n return new ListOf<>(this.typeface);\n }\n\n @Override\n public Indirect indirect() throws Exception {\n final byte[] stream = this.asStream();\n final Dictionary dictionary = new Dictionary()\n .add(\"Length\", new Int(stream.length))\n .with(new Stream(stream));\n return new DefaultIndirect(this.number, this.generation, dictionary);\n }\n}" }, { "identifier": "Serial", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/id/Serial.java", "snippet": "public final class Serial implements Id {\n /**\n * Seed.\n */\n private final AtomicInteger seed;\n\n /**\n * Ctor.\n */\n public Serial() {\n this(1);\n }\n\n /**\n * Ctor.\n *\n * @param seed Seed to start counting\n */\n public Serial(final int seed) {\n this(new AtomicInteger(seed));\n }\n\n /**\n * Ctor.\n *\n * @param seed Seed to start counting\n */\n public Serial(final AtomicInteger seed) {\n this.seed = seed;\n }\n\n @Override\n public Integer value() {\n return this.seed.get();\n }\n\n @Override\n public int increment() {\n return this.seed.getAndIncrement();\n }\n}" }, { "identifier": "DefaultPage", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/page/DefaultPage.java", "snippet": "@SuppressWarnings(\"PMD.AvoidFieldNameMatchingMethodName\")\npublic final class DefaultPage implements Page {\n /**\n * Object number.\n */\n private final int number;\n\n /**\n * Generation number.\n */\n private final int generation;\n\n /**\n * Resources.\n */\n private final Scalar<Resources> resources;\n\n /**\n * Page contents.\n */\n private final Contents contents;\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param contents Page contents\n */\n public DefaultPage(\n final Id id,\n final Contents contents\n ) {\n this(id.increment(), 0, id, contents);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param id Id number\n * @param contents Page contents\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public DefaultPage(\n final int number,\n final int generation,\n final Id id,\n final Contents contents\n ) {\n this.number = number;\n this.generation = generation;\n this.contents = contents;\n this.resources = new Sticky<>(\n () -> {\n final List<Resource> rscrs = new ListOf<>();\n rscrs.add(new ProcSet());\n for (final Content content : contents) {\n if (!content.resource().isEmpty()) {\n rscrs.add(content.resource().get(0));\n }\n }\n return new Resources(id.increment(), 0, rscrs);\n }\n );\n }\n\n @Override\n public Resources resources() {\n return new Unchecked<>(this.resources).value();\n }\n\n @Override\n public Contents contents() {\n return this.contents;\n }\n\n @Override\n public Indirect indirect(final int parent) throws Exception {\n final Indirect resrcs = this.resources().indirect();\n final Indirect conts = this.contents.indirect();\n Array refs = new Array();\n for (final Content content : this.contents) {\n refs = refs.add(new Text(content.indirect().reference().asString()));\n }\n final Dictionary dictionary = new Dictionary()\n .add(\"Type\", new Name(\"Page\"))\n .add(\"Resources\", new Text(resrcs.reference().asString()))\n .add(\"Contents\", refs)\n .add(\"Parent\", new Text(new Reference(parent, 0).asString()));\n return new DefaultIndirect(\n this.number,\n this.generation,\n dictionary,\n resrcs,\n conts\n );\n }\n}" }, { "identifier": "DefaultPages", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/pages/DefaultPages.java", "snippet": "public final class DefaultPages implements Pages {\n /**\n * Object number.\n */\n private final int number;\n\n /**\n * Generation number.\n */\n private final int generation;\n\n /**\n * Pages size.\n */\n private final Format fmt;\n\n /**\n * Pages.\n */\n private final List<Page> kids;\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param kids Some Page\n */\n public DefaultPages(\n final Id id,\n final Page... kids\n ) {\n this(id.increment(), 0, Format.A4, kids);\n }\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param format Page's size\n * @param kids Some Page\n */\n public DefaultPages(\n final Id id,\n final Format format,\n final Page... kids\n ) {\n this(id.increment(), 0, format, kids);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param format Page's size\n * @param kids Some Page\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public DefaultPages(\n final int number,\n final int generation,\n final Format format,\n final Page... kids\n ) {\n this.number = number;\n this.generation = generation;\n this.fmt = format;\n this.kids = new ListOf<>(kids);\n }\n\n @Override\n public Indirect indirect() throws Exception {\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n Array kds = new Array();\n for (final Page page : this.kids) {\n final Indirect indirect = page.indirect(this.number);\n kds = kds.add(new Text(indirect.reference().asString()));\n baos.write(indirect.asBytes());\n }\n final Dictionary dictionary = new Dictionary()\n .add(\"Type\", new Name(\"Pages\"))\n .add(\"Kids\", kds)\n .add(\"Count\", new Int(this.kids.size()))\n .add(\n \"MediaBox\",\n new Array(\n new Int(0),\n new Int(0),\n new Text(this.fmt.asString())\n )\n );\n return new DefaultIndirect(\n this.number,\n this.generation,\n dictionary,\n baos::toByteArray\n );\n }\n\n @Override\n public void add(final Page page) {\n this.kids.add(page);\n }\n\n @Override\n public Format format() {\n return this.fmt;\n }\n}" }, { "identifier": "Courier", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/resource/font/Courier.java", "snippet": "public final class Courier extends FontEnvelope {\n /**\n * Ctor.\n *\n * @param id Id number\n * @param size Font size in points\n */\n public Courier(final Id id, final int size) {\n this(id.increment(), 0, size);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param size Font size in points\n */\n public Courier(final int number, final int generation, final int size) {\n super(\n number,\n new FontFamily(number, generation, \"Courier\", \"Type1\"),\n size\n );\n }\n\n @Override\n public int width(final char chr) {\n return 600;\n }\n}" }, { "identifier": "FontEnvelope", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/resource/font/FontEnvelope.java", "snippet": "public abstract class FontEnvelope implements Font {\n /**\n * Object number.\n */\n private final int number;\n\n /**\n * Family.\n */\n private final FontFamily family;\n\n /**\n * Size.\n */\n private final int points;\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param family Font family\n * @param size Font size\n * @checkstyle ParameterNumberCheck (10 lines)\n */\n public FontEnvelope(\n final int number,\n final FontFamily family,\n final int size\n ) {\n this.number = number;\n this.family = family;\n this.points = size;\n }\n\n @Override\n public String name() {\n return new UncheckedText(\n new FormattedText(\"F%d\", this.number)\n ).asString();\n }\n\n @Override\n public int size() {\n return this.points;\n }\n\n @Override\n public int width(final char chr) {\n return 1;\n }\n\n @Override\n public Indirect indirect() throws Exception {\n final Indirect indirect = this.family.indirect();\n final Dictionary dictionary = new Dictionary()\n .add(\n \"Font\",\n new Dictionary().add(\n this.name(),\n new Text(indirect.reference().asString())\n )\n );\n return new NoReferenceIndirect(dictionary, indirect);\n }\n}" }, { "identifier": "Helvetica", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/resource/font/Helvetica.java", "snippet": "public final class Helvetica extends FontEnvelope {\n /**\n * Widths.\n */\n private static final int[] WIDTHS = {\n 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 355, 556, 556, 889, 667, 191,\n 333, 333, 389, 584, 278, 333, 278, 278, 556, 556,\n 556, 556, 556, 556, 556, 556, 556, 556, 278, 278,\n 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667,\n 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944, 667, 667,\n 611, 278, 278, 278, 469, 556, 333, 556, 556, 500,\n 556, 556, 278, 556, 556, 222, 222, 500, 222, 833,\n 556, 556, 556, 556, 333, 500, 278, 556, 500, 722,\n 500, 500, 500, 334, 260, 334, 584, 350, 556, 350,\n 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333,\n 1000, 350, 611, 350, 350, 222, 222, 333, 333, 350,\n 556, 1000, 333, 1000, 500, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 260, 556, 333, 737,\n 370, 556, 584, 333, 737, 333, 400, 584, 333, 333,\n 333, 556, 537, 278, 333, 333, 365, 556, 834, 834,\n 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278, 722, 722,\n 778, 778, 778, 778, 778, 584, 778, 722, 722, 722,\n 722, 667, 667, 611, 556, 556, 556, 556, 556, 556,\n 889, 500, 556, 556, 556, 556, 278, 278, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 584, 611, 556,\n 556, 556, 556, 500, 556, 500,\n };\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param size Font size in points\n */\n public Helvetica(final Id id, final int size) {\n this(id.increment(), 0, size);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param size Font size in points\n */\n public Helvetica(final int number, final int generation, final int size) {\n super(\n number,\n new FontFamily(number, generation, \"Helvetica\", \"Type1\"),\n size\n );\n }\n\n @Override\n public int width(final char chr) {\n return Helvetica.WIDTHS[chr];\n }\n}" }, { "identifier": "Symbol", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/resource/font/Symbol.java", "snippet": "public final class Symbol extends FontEnvelope {\n /**\n * Widths.\n */\n private static final int[] WIDTHS = {\n 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 333, 713, 500, 549, 833, 778, 439,\n 333, 333, 500, 549, 250, 549, 250, 278, 500, 500,\n 500, 500, 500, 500, 500, 500, 500, 500, 278, 278,\n 549, 549, 549, 444, 549, 722, 667, 722, 612, 611,\n 763, 603, 722, 333, 631, 722, 686, 889, 722, 722,\n 768, 741, 556, 592, 611, 690, 439, 768, 645, 795,\n 611, 333, 863, 333, 658, 500, 500, 631, 549, 549,\n 494, 439, 521, 411, 603, 329, 603, 549, 549, 576,\n 521, 549, 549, 521, 549, 603, 439, 576, 713, 686,\n 493, 686, 494, 480, 200, 480, 549, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 750, 620, 247, 549, 167, 713, 500, 753, 753, 753,\n 753, 1042, 987, 603, 987, 603, 400, 549, 411, 549,\n 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603,\n 1000, 658, 823, 686, 795, 987, 768, 768, 823, 768,\n 768, 713, 713, 713, 713, 713, 713, 713, 768, 713,\n 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042,\n 987, 603, 987, 603, 494, 329, 790, 790, 786, 713,\n 384, 384, 384, 384, 384, 384, 494, 494, 494, 494,\n 0, 329, 274, 686, 686, 686, 384, 384, 384, 384,\n 384, 384, 494, 494, 494, 0,\n };\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param size Font size in points\n */\n public Symbol(final Id id, final int size) {\n this(id.increment(), 0, size);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param size Font size in points\n */\n public Symbol(final int number, final int generation, final int size) {\n super(\n number,\n new FontFamily(number, generation, \"Symbol\", \"Type1\"),\n size\n );\n }\n\n @Override\n public int width(final char chr) {\n return Symbol.WIDTHS[chr];\n }\n}" }, { "identifier": "TimesRoman", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/resource/font/TimesRoman.java", "snippet": "public final class TimesRoman extends FontEnvelope {\n /**\n * Widths.\n */\n private static final int[] WIDTHS = {\n 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 333, 408, 500, 500, 833, 778, 180,\n 333, 333, 500, 564, 250, 333, 250, 278, 500, 500,\n 500, 500, 500, 500, 500, 500, 500, 500, 278, 278,\n 564, 564, 564, 444, 921, 722, 667, 667, 722, 611,\n 556, 722, 722, 333, 389, 722, 611, 889, 722, 722,\n 556, 722, 667, 556, 611, 722, 722, 944, 722, 722,\n 611, 333, 278, 333, 469, 500, 333, 444, 500, 444,\n 500, 444, 333, 500, 500, 278, 278, 500, 278, 778,\n 500, 500, 500, 500, 333, 389, 278, 500, 500, 722,\n 500, 500, 444, 480, 200, 480, 541, 350, 500, 350,\n 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333,\n 889, 350, 611, 350, 350, 333, 333, 444, 444, 350,\n 500, 1000, 333, 980, 389, 333, 722, 350, 444, 722,\n 250, 333, 500, 500, 500, 500, 200, 500, 333, 760,\n 276, 500, 564, 333, 760, 333, 400, 564, 300, 300,\n 333, 500, 453, 250, 333, 300, 310, 500, 750, 750,\n 750, 444, 722, 722, 722, 722, 722, 722, 889, 667,\n 611, 611, 611, 611, 333, 333, 333, 333, 722, 722,\n 722, 722, 722, 722, 722, 564, 722, 722, 722, 722,\n 722, 722, 556, 500, 444, 444, 444, 444, 444, 444,\n 667, 444, 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 500, 500, 500, 500, 500, 500, 564, 500, 500,\n 500, 500, 500, 500, 500, 500,\n };\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param size Font size in points\n */\n public TimesRoman(final Id id, final int size) {\n this(id.increment(), 0, size);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param size Font size in points\n */\n public TimesRoman(final int number, final int generation, final int size) {\n super(\n number,\n new FontFamily(number, generation, \"Times-Roman\", \"Type1\"),\n size\n );\n }\n\n @Override\n public int width(final char chr) {\n return TimesRoman.WIDTHS[chr];\n }\n}" }, { "identifier": "ZapfDingbats", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/resource/font/ZapfDingbats.java", "snippet": "public final class ZapfDingbats extends FontEnvelope {\n /**\n * Widths.\n */\n private static final int[] WIDTHS = {\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 278, 974, 961, 974, 980, 719, 789, 790,\n 791, 690, 960, 939, 549, 855, 911, 933, 911, 945,\n 974, 755, 846, 762, 761, 571, 677, 763, 760, 759,\n 754, 494, 552, 537, 577, 692, 786, 788, 788, 790,\n 793, 794, 816, 823, 789, 841, 823, 833, 816, 831,\n 923, 744, 723, 749, 790, 792, 695, 776, 768, 792,\n 759, 707, 708, 682, 701, 826, 815, 789, 789, 707,\n 687, 696, 689, 786, 787, 713, 791, 785, 791, 873,\n 761, 762, 762, 759, 759, 892, 892, 788, 784, 438,\n 138, 277, 415, 392, 392, 668, 668, 0, 390, 390,\n 317, 317, 276, 276, 509, 509, 410, 410, 234, 234,\n 334, 334, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 732, 544, 544, 910, 667, 760, 760, 776, 595,\n 694, 626, 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918,\n 927, 928, 928, 834, 873, 828, 924, 924, 917, 930,\n 931, 463, 883, 836, 836, 867, 867, 696, 696, 874,\n 0, 874, 760, 946, 771, 865, 771, 888, 967, 888,\n 831, 873, 927, 970, 918, 0,\n };\n\n /**\n * Ctor.\n *\n * @param id Id number\n * @param size Font size in points\n */\n public ZapfDingbats(final Id id, final int size) {\n this(id.increment(), 0, size);\n }\n\n /**\n * Ctor.\n *\n * @param number Object number\n * @param generation Generation number\n * @param size Font size in points\n */\n public ZapfDingbats(\n final int number,\n final int generation,\n final int size\n ) {\n super(\n number,\n new FontFamily(number, generation, \"ZapfDingbats\", \"Type1\"),\n size\n );\n }\n\n @Override\n public int width(final char chr) {\n return ZapfDingbats.WIDTHS[chr];\n }\n}" } ]
import com.github.fabriciofx.cactoos.pdf.Document; import com.github.fabriciofx.cactoos.pdf.Font; import com.github.fabriciofx.cactoos.pdf.Id; import com.github.fabriciofx.cactoos.pdf.content.Contents; import com.github.fabriciofx.cactoos.pdf.content.Text; import com.github.fabriciofx.cactoos.pdf.id.Serial; import com.github.fabriciofx.cactoos.pdf.page.DefaultPage; import com.github.fabriciofx.cactoos.pdf.pages.DefaultPages; import com.github.fabriciofx.cactoos.pdf.resource.font.Courier; import com.github.fabriciofx.cactoos.pdf.resource.font.FontEnvelope; import com.github.fabriciofx.cactoos.pdf.resource.font.Helvetica; import com.github.fabriciofx.cactoos.pdf.resource.font.Symbol; import com.github.fabriciofx.cactoos.pdf.resource.font.TimesRoman; import com.github.fabriciofx.cactoos.pdf.resource.font.ZapfDingbats; import org.cactoos.bytes.BytesOf; import org.cactoos.io.ResourceOf; import org.cactoos.text.Concatenated; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsText;
9,973
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf.resource; /** * Test case for {@link FontEnvelope}. * * @since 0.0.1 */ final class FontTest { @Test void fontDictionary() throws Exception { new Assertion<>( "Must must print a Times-Roman font dictionary", new TextOf( new TimesRoman(new Serial(), 12).indirect().dictionary() ), new IsText("<< /Font << /F1 1 0 R >> >>") ).affirm(); } @Test void fontAsBytes() throws Exception { new Assertion<>( "Must must build Times-Roman font as bytes", new TextOf( new TimesRoman(new Serial(), 12).indirect().asBytes() ), new IsText( new Concatenated( "1 0 obj\n<< /Type /Font /BaseFont /Times-Roman ", "/Subtype /Type1 >>\nendobj\n" ) ) ).affirm(); } @Test void buildDocumentWithFonts() throws Exception {
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf.resource; /** * Test case for {@link FontEnvelope}. * * @since 0.0.1 */ final class FontTest { @Test void fontDictionary() throws Exception { new Assertion<>( "Must must print a Times-Roman font dictionary", new TextOf( new TimesRoman(new Serial(), 12).indirect().dictionary() ), new IsText("<< /Font << /F1 1 0 R >> >>") ).affirm(); } @Test void fontAsBytes() throws Exception { new Assertion<>( "Must must build Times-Roman font as bytes", new TextOf( new TimesRoman(new Serial(), 12).indirect().asBytes() ), new IsText( new Concatenated( "1 0 obj\n<< /Type /Font /BaseFont /Times-Roman ", "/Subtype /Type1 >>\nendobj\n" ) ) ).affirm(); } @Test void buildDocumentWithFonts() throws Exception {
final Id id = new Serial();
2
2023-12-05 00:07:24+00:00
12k
BeansGalaxy/Beans-Backpacks-2
fabric/src/main/java/com/beansgalaxy/backpacks/FabricMain.java
[ { "identifier": "BackpackEntity", "path": "common/src/main/java/com/beansgalaxy/backpacks/entity/BackpackEntity.java", "snippet": "public class BackpackEntity extends Backpack {\n public Direction direction;\n protected BlockPos pos;\n public double actualY;\n private static final int BREAK_TIMER = 20;\n public int wobble = 0;\n\n public BackpackEntity(EntityType<? extends Entity> type, Level level) {\n super(type, level);\n }\n\n public BackpackEntity(Player player, Level world, int x, double y, int z, Direction direction,\n LocalData traits, NonNullList<ItemStack> stacks, float yaw) {\n super(world);\n this.actualY = y;\n this.pos = BlockPos.containing(x, y, z);\n this.setDirection(direction);\n this.initDisplay(traits);\n\n if (!direction.getAxis().isHorizontal())\n this.setYRot(yaw);\n\n if (!world.isClientSide()) {\n world.gameEvent(player, GameEvent.ENTITY_PLACE, this.position());\n world.addFreshEntity(this);\n }\n\n if (stacks != null && !stacks.isEmpty()) {\n this.backpackInventory.getItemStacks().addAll(stacks);\n stacks.clear();\n }\n }\n\n public static ItemStack toStack(BackpackEntity backpack) {\n Kind kind = backpack.getLocalData().kind();\n Item item = kind.getItem();\n ItemStack stack = item.getDefaultInstance();\n String key = backpack.getKey();\n\n CompoundTag display = new CompoundTag();\n display.putString(\"key\", key);\n stack.getOrCreateTag().put(\"display\", display);\n\n CompoundTag trim = backpack.getTrim();\n if (trim != null)\n stack.addTagElement(\"Trim\", trim);\n\n int color = backpack.getColor();\n if (color != DEFAULT_COLOR && stack.getItem() instanceof DyableBackpack)\n stack.getOrCreateTagElement(\"display\").putInt(\"color\", color);\n\n return stack;\n }\n\n protected float getEyeHeight(Pose p_31784_, EntityDimensions p_31785_) {\n return 6F / 16;\n }\n\n public Direction getDirection() {\n return this.direction;\n }\n\n protected void setDirection(Direction direction) {\n if (direction != null) {\n this.direction = direction;\n if (direction.getAxis().isHorizontal()) {\n this.setNoGravity(true);\n this.setYRot((float) direction.get2DDataValue() * 90);\n }\n this.xRotO = this.getXRot();\n this.yRotO = this.getYRot();\n this.recalculateBoundingBox();\n }\n }\n\n public void setPos(double x, double y, double z) {\n this.actualY = y;\n this.pos = BlockPos.containing(x, y, z);\n this.recalculateBoundingBox();\n this.hasImpulse = true;\n }\n\n public static AABB newBox(BlockPos blockPos, double y, double height, Direction direction) {\n double x1 = blockPos.getX() + 0.5D;\n double z1 = blockPos.getZ() + 0.5D;\n double Wx = 8D / 32;\n double Wz = 8D / 32;\n if (direction != null) {\n if (direction.getAxis().isHorizontal()) {\n double D = 4D / 32;\n double off = 6D / 16;\n int stepX = direction.getStepX();\n int stepZ = direction.getStepZ();\n Wx -= D * Math.abs(stepX);\n Wz -= D * Math.abs(stepZ);\n x1 -= off * stepX;\n z1 -= off * stepZ;\n } else {\n Wx -= 1D / 16;\n Wz -= 1D / 16;\n }\n }\n\n return new AABB(x1 - Wx, y, z1 - Wz, x1 + Wx, y + height, z1 + Wz);\n }\n\n // BUILDS NEW BOUNDING BOX\n protected void recalculateBoundingBox() {\n AABB box = newBox(this.pos, this.actualY, 9D / 16, direction);\n this.setPosRaw((box.minX + box.maxX) / 2, box.minY, (box.minZ + box.maxZ) / 2);\n this.setBoundingBox(box);\n }\n\n /** IMPLEMENTS GRAVITY WHEN HUNG BACKPACKS LOSES SUPPORTING BLOCK **/\n public void tick() {\n super.tick();\n this.updateGravity();\n this.wobble();\n this.move(MoverType.SELF, this.getDeltaMovement());\n this.baseTick();\n }\n\n private void wobble() {\n Kind kind = getLocalData().kind();\n if (!Kind.UPGRADED.is(kind) && isInLava() || !Kind.METAL.is(kind) && isOnFire()) {\n wobble += 2;\n } else\n if (wobble > 0)\n wobble -= 1;\n }\n\n\n private void updateGravity() {\n this.setNoGravity(this.isNoGravity() && !this.level().noCollision(this, this.getBoundingBox().inflate(0.1, -0.1, 0.1)));\n boolean inLava = this.isInLava();\n Kind b$kind = getLocalData().kind();\n if (!this.isNoGravity()) {\n if (this.isInWater()) {\n inWaterGravity();\n } else if (inLava) {\n if (b$kind == Kind.UPGRADED && this.isEyeInFluid(FluidTags.LAVA) && getDeltaMovement().y < 0.1) {\n this.setDeltaMovement(this.getDeltaMovement().add(0D, 0.02D, 0D));\n }\n this.setDeltaMovement(this.getDeltaMovement().scale(0.6D));\n } else {\n this.setDeltaMovement(this.getDeltaMovement().add(0.0D, -0.03D, 0.0D));\n this.setDeltaMovement(this.getDeltaMovement().scale(0.98D));\n }\n }\n }\n\n private void inWaterGravity() {\n AABB thisBox = this.getBoundingBox();\n AABB box = new AABB(thisBox.maxX, thisBox.maxY + 6D / 16D, thisBox.maxZ, thisBox.minX, thisBox.maxY, thisBox.minZ);\n List<Entity> entityList = this.getCommandSenderWorld().getEntities(this, box);\n if (!entityList.isEmpty()) {\n Entity entity = entityList.get(0);\n double velocity = this.actualY - entity.getY();\n if (entityList.get(0) instanceof Player player) {\n this.setDeltaMovement(0, velocity / 10, 0);\n if (player instanceof ServerPlayer serverPlayer)\n Services.REGISTRY.triggerSpecial(serverPlayer, SpecialCriterion.Special.HOP);\n }\n else if (velocity < -0.6)\n inWaterBob();\n else this.setDeltaMovement(0, velocity / 20, 0);\n } else inWaterBob();\n }\n\n private void inWaterBob() {\n if (this.isUnderWater()) {\n this.setDeltaMovement(this.getDeltaMovement().scale(0.95D));\n this.setDeltaMovement(this.getDeltaMovement().add(0D, 0.003D, 0D));\n } else if (this.isInWater() && getDeltaMovement().y < 0.01) {\n this.setDeltaMovement(this.getDeltaMovement().scale(0.9D));\n this.setDeltaMovement(this.getDeltaMovement().add(0D, -0.01D, 0D));\n }\n }\n\n public boolean displayFireAnimation() {\n return this.isOnFire() && !this.isSpectator() && getLocalData().kind() != Kind.UPGRADED;\n }\n\n public boolean fireImmune() {\n return getLocalData().kind() == Kind.UPGRADED || this.getType().fireImmune();\n }\n\n /** DATA MANAGEMENT **/\n // CLIENT\n public Packet<ClientGamePacketListener> getAddEntityPacket() {\n return new ClientboundAddEntityPacket(this, this.direction.get3DDataValue());\n }\n\n public void recreateFromPacket(ClientboundAddEntityPacket p_149626_) {\n super.recreateFromPacket(p_149626_);\n this.setDirection(Direction.from3DDataValue(p_149626_.getData()));\n }\n\n // NBT\n protected void addAdditionalSaveData(CompoundTag tag) {\n super.addAdditionalSaveData(tag);\n tag.putByte(\"facing\", (byte)this.direction.get3DDataValue());\n tag.put(\"display\", getDisplay());\n }\n\n protected void readAdditionalSaveData(CompoundTag tag) {\n super.readAdditionalSaveData(tag);\n this.setDirection(Direction.from3DDataValue(tag.getByte(\"facing\")));\n this.setDisplay(tag.getCompound(\"display\"));\n }\n\n // LOCAL\n public CompoundTag getDisplay() {\n CompoundTag tag = new CompoundTag();\n tag.putString(\"key\", this.entityData.get(KEY));\n tag.putInt(\"color\", this.entityData.get(COLOR));\n if (TRIM != null)\n tag.put(\"Trim\", this.entityData.get(TRIM));\n return tag;\n }\n\n /** COLLISIONS AND INTERACTIONS **/\n public boolean canCollideWith(Entity that) {\n if (that instanceof LivingEntity livingEntity && !livingEntity.isAlive())\n return false;\n\n if (this.isPassengerOfSameVehicle(that))\n return false;\n\n return (that.canBeCollidedWith() || that.isPushable());\n }\n\n public boolean canBeCollidedWith() {\n return true;\n }\n\n public boolean skipAttackInteraction(Entity attacker) {\n if (attacker instanceof Player player) {\n return this.hurt(this.damageSources().playerAttack(player), 0.0f);\n }\n return false;\n }\n\n public boolean hurt(DamageSource damageSource, float amount) {\n if ((damageSource.is(DamageTypes.IN_FIRE) || damageSource.is(DamageTypes.ON_FIRE) || damageSource.is(DamageTypes.LAVA)) && this.fireImmune())\n return false;\n double height = 0.1D;\n if (damageSource.is(DamageTypes.EXPLOSION) || damageSource.is(DamageTypes.PLAYER_EXPLOSION)) {\n height += Math.sqrt(amount) / 20;\n return hop(height);\n }\n if (damageSource.is(DamageTypes.ARROW) || damageSource.is(DamageTypes.THROWN) || damageSource.is(DamageTypes.TRIDENT) || damageSource.is(DamageTypes.MOB_PROJECTILE)) {\n hop(height);\n return false;\n }\n if (damageSource.is(DamageTypes.PLAYER_ATTACK) && damageSource.getDirectEntity() instanceof Player player) {\n if (player.isCreative()) {\n this.kill();\n this.markHurt();\n }\n else {\n wobble += BREAK_TIMER * .8;\n if (wobble > BREAK_TIMER) {\n breakAndDropContents();\n return true;\n }\n else {\n PlaySound.HIT.at(this, getKind());\n return hop(height);\n }\n }\n }\n\n hop(height);\n return true;\n }\n\n private void breakAndDropContents() {\n PlaySound.BREAK.at(this, getKind());\n boolean dropItems = level().getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS);\n if (dropItems) {\n while (!this.getItemStacks().isEmpty()) {\n ItemStack stack = this.getItemStacks().remove(0);\n this.spawnAtLocation(stack);\n }\n }\n ItemStack backpack = toStack(this);\n if (!this.isRemoved() && !this.level().isClientSide()) {\n this.kill();\n this.markHurt();\n if (dropItems) this.spawnAtLocation(backpack);\n }\n }\n\n public boolean hop(double height) {\n if (this.isNoGravity())\n this.setNoGravity(false);\n else {\n this.setDeltaMovement(this.getDeltaMovement().add(0.0D, height, 0.0D));\n }\n return true;\n }\n\n // PREFORMS THIS ACTION WHEN IT IS RIGHT-CLICKED\n @Override\n public InteractionResult interact(Player player, InteractionHand hand) {\n boolean actionKeyPressed = BackSlot.get(player).actionKeyPressed;\n ItemStack backStack = BackSlot.get(player).getItem();\n ItemStack handStack = player.getMainHandItem();\n ItemStack backpackStack = actionKeyPressed ? backStack : handStack;\n\n if (Kind.isBackpack(backpackStack))\n return BackpackItem.useOnBackpack(player, this, backpackStack, actionKeyPressed);\n\n if (!actionKeyPressed) {\n if (viewable.viewers < 1)\n PlaySound.OPEN.at(this, getKind());\n Services.NETWORK.openBackpackMenu(player, this);\n return InteractionResult.SUCCESS;\n }\n\n attemptEquip(player, this);\n return InteractionResult.SUCCESS;\n }\n\n public static boolean attemptEquip(Player player, BackpackEntity backpackEntity) {\n Slot backSlot = BackSlot.get(player);\n if (backSlot.hasItem() && !backpackEntity.isRemoved()) {\n if (backpackEntity.getItemStacks().isEmpty()) {\n if (!player.level().isClientSide())\n backpackEntity.spawnAtLocation(toStack(backpackEntity));\n PlaySound.BREAK.at(backpackEntity, backpackEntity.getKind());\n }\n else {\n PlaySound.HIT.at(backpackEntity, backpackEntity.getKind());\n return backpackEntity.hop(.1);\n }\n }\n else {\n/* Equips Backpack only if...\n - damage source is player.\n - player is not creative.\n - backSlot is not occupied */\n NonNullList<ItemStack> playerInventoryStacks = BackSlot.getInventory(player).getItemStacks();\n NonNullList<ItemStack> backpackEntityStacks = backpackEntity.getItemStacks();\n playerInventoryStacks.clear();\n playerInventoryStacks.addAll(backpackEntityStacks);\n backSlot.set(toStack(backpackEntity));\n PlaySound.EQUIP.at(player, backpackEntity.getKind());\n }\n if (!backpackEntity.isRemoved() && !player.level().isClientSide()) {\n backpackEntity.kill();\n backpackEntity.markHurt();\n }\n return true;\n }\n\n @Override\n public ItemStack getPickResult() {\n return toStack(this);\n }\n /** REQUIRED FEILDS **/\n protected boolean repositionEntityAfterLoad() {\n return false;\n }\n\n public boolean isPickable() {\n return true;\n }\n\n public Vec3 position() {\n return new Vec3(this.pos.getX(), this.actualY, this.pos.getZ());\n }\n\n}" }, { "identifier": "EquipAnyCriterion", "path": "common/src/main/java/com/beansgalaxy/backpacks/events/advancements/EquipAnyCriterion.java", "snippet": "public class EquipAnyCriterion extends SimpleCriterionTrigger<EquipAnyCriterion.Conditions> {\n\n @Override\n protected Conditions createInstance(JsonObject object, Optional var2, DeserializationContext var3) {\n Holder<Item> item = GsonHelper.getAsItem(object, \"item\");\n String key = GsonHelper.getAsString(object, \"key\", \"\");\n boolean isDyed = GsonHelper.getAsBoolean(object, \"is_dyed\", false);\n\n return new Conditions(item, key, isDyed);\n }\n\n public static class Conditions extends AbstractCriterionTriggerInstance {\n Holder<Item> item;\n String key;\n Boolean isDyed;\n\n public Conditions(Holder<Item> item, String key, Boolean isDyed) {\n super(Optional.empty());\n this.item = item;\n this.key = key;\n this.isDyed = isDyed;\n }\n\n boolean requirementsMet(ItemStack backStack) {\n if (isDyed) {\n boolean backpackDyed =\n backStack.getItem() instanceof DyableBackpack dyableBackpack &&\n dyableBackpack.getColor(backStack) != Backpack.DEFAULT_COLOR;\n return backpackDyed;\n }\n\n CompoundTag display = backStack.getTagElement(\"display\");\n if (!key.isEmpty() && display != null) {\n String key = display.getString(\"key\");\n return Objects.equals(this.key, key);\n }\n\n if (item != null && !item.value().equals(Items.AIR))\n return backStack.is(item);\n\n return !backStack.isEmpty();\n }\n }\n\n public void trigger(ServerPlayer player) {\n BackSlot backSlot = BackSlot.get(player);\n ItemStack backStack = backSlot.getItem();\n trigger(player, conditions -> conditions.requirementsMet(backStack));\n }\n}" }, { "identifier": "PlaceCriterion", "path": "common/src/main/java/com/beansgalaxy/backpacks/events/advancements/PlaceCriterion.java", "snippet": "public class PlaceCriterion extends SimpleCriterionTrigger<PlaceCriterion.Conditions> {\n\n @Override\n protected Conditions createInstance(JsonObject jsonObject, Optional<ContextAwarePredicate> var2, DeserializationContext var3) {\n String key = GsonHelper.getAsString(jsonObject, \"key\", \"\");\n return new Conditions(key);\n }\n\n public static class Conditions extends AbstractCriterionTriggerInstance {\n private final String key;\n\n public Conditions(String key) {\n super(Optional.empty());\n this.key = key;\n }\n\n boolean requirementsMet(String key) {\n if (this.key == null || this.key.isEmpty())\n return true;\n\n return Objects.equals(this.key, key);\n }\n }\n\n public void trigger(ServerPlayer player, String key) {\n trigger(player, conditions -> conditions.requirementsMet(key));\n }\n}" }, { "identifier": "SpecialCriterion", "path": "common/src/main/java/com/beansgalaxy/backpacks/events/advancements/SpecialCriterion.java", "snippet": "public class SpecialCriterion extends SimpleCriterionTrigger<SpecialCriterion.Conditions> {\n\n @Override\n protected Conditions createInstance(JsonObject object, Optional<ContextAwarePredicate> var2, DeserializationContext var3) {\n String special = GsonHelper.getAsString(object, \"special\", \"\");\n return new Conditions(special);\n }\n\n public static class Conditions extends AbstractCriterionTriggerInstance {\n Special special;\n\n public Conditions(String special) {\n super(Optional.empty());\n this.special = Special.valueOf(special);\n }\n\n boolean requirementsMet(Special special) {\n return this.special == special;\n }\n }\n\n public void trigger(ServerPlayer player, Special special) {\n trigger(player, conditions -> conditions.requirementsMet(special));\n }\n\n public enum Special {\n HOP,\n LAYERED,\n FILLED_LEATHER\n }\n}" }, { "identifier": "BackpackItem", "path": "common/src/main/java/com/beansgalaxy/backpacks/items/BackpackItem.java", "snippet": "public class BackpackItem extends Item {\n public BackpackItem() {\n super(new Item.Properties().stacksTo(1));\n }\n\n @Override\n public InteractionResult useOn(UseOnContext ctx) {\n Player player = ctx.getPlayer();\n Direction direction = ctx.getClickedFace();\n BlockPos clickedPos = ctx.getClickedPos();\n ItemStack backpackStack = ctx.getItemInHand();\n\n if (useOnBlock(player, direction, clickedPos, backpackStack, false)) {\n return InteractionResult.SUCCESS;\n }\n\n return InteractionResult.PASS;\n }\n\n public static InteractionResult hotkeyOnBlock(Player player, Direction direction, BlockPos clickedPos) {\n BackSlot backSlot = BackSlot.get(player);\n ItemStack backpackStack = backSlot.getItem();\n\n if (useOnBlock(player, direction, clickedPos, backpackStack, true)) {\n backSlot.setChanged();\n return InteractionResult.SUCCESS;\n }\n\n return InteractionResult.PASS;\n }\n\n private static Boolean useOnBlock(Player player, Direction direction, BlockPos clickedPos, ItemStack backpackStack, boolean fromBackSlot) {\n Level level = player.level();\n BlockPos blockPos;\n\n boolean isVertical = direction.getAxis().isVertical();\n if (isVertical && level.getBlockState(clickedPos).getCollisionShape(level, clickedPos).isEmpty()) {\n blockPos = clickedPos;\n } else\n blockPos = clickedPos.relative(direction);\n\n int y = blockPos.getY();\n AABB box = BackpackEntity.newBox(blockPos, y, 9 / 16d, direction);\n double yOffset = 2d / 16;\n\n if (isVertical) {\n boolean isRelative = !Objects.equals(blockPos, clickedPos);\n AABB $$4 = new AABB(blockPos);\n if (isRelative)\n $$4 = $$4.expandTowards(0.0, -1.0, 0.0);\n\n Iterable<VoxelShape> $$5 = level.getCollisions(null, $$4);\n yOffset += Shapes.collide(Direction.Axis.Y, box, $$5, isRelative ? -2.0 : -1.0);\n\n if (level.noCollision($$4))\n yOffset += 1;\n }\n\n boolean spaceEmpty = level.noCollision(box.move(0, yOffset, 0));\n return spaceEmpty && doesPlace(player, blockPos.getX(), y + yOffset, blockPos.getZ(), direction, backpackStack, fromBackSlot);\n }\n\n public static InteractionResult useOnBackpack(Player player, BackpackEntity backpackEntity, ItemStack backpackStack, boolean fromBackSlot) {\n Vec3 pos = backpackEntity.position();\n Direction direction = backpackEntity.direction;\n\n int invert = player.isCrouching() ? -1 : 1;\n int x = Mth.floor(pos.x);\n double y = pos.y + 11d / 16 * invert;\n int z = Mth.floor(pos.z);\n\n AABB box = backpackEntity.getBoundingBox().move(0, 10d / 16 * invert, 0);\n boolean spaceEmpty = player.level().noCollision(box);\n if (spaceEmpty && doesPlace(player, x, y, z, direction, backpackStack, fromBackSlot)) {\n BackSlot.get(player).setChanged();\n return InteractionResult.SUCCESS;\n }\n\n return InteractionResult.PASS;\n }\n\n public static boolean doesPlace(Player player, int x, double y, int z, Direction direction, ItemStack backpackStack, boolean fromBackSlot) {\n LocalData traits = BackpackItem.getItemTraits(backpackStack);\n if (traits == null || traits.key.isEmpty())\n return false;\n\n Level world = player.level();\n BlockPos blockPos = BlockPos.containing(x, y, z);\n\n NonNullList<ItemStack> stacks = fromBackSlot ?\n BackSlot.getInventory(player).getItemStacks() : NonNullList.create();\n\n BackpackEntity backpackEntity = new BackpackEntity(player, world, x, y, z, direction,\n traits, stacks, rotFromBlock(blockPos, player) + 90);\n\n PlaySound.PLACE.at(backpackEntity, traits.kind());\n if (player instanceof ServerPlayer serverPlayer)\n Services.REGISTRY.triggerPlace(serverPlayer, traits.key);\n\n backpackStack.shrink(1);\n return true;\n }\n\n private static float rotFromBlock(BlockPos blockPos, Player player) {\n Vec3 CPos = blockPos.getCenter();\n float YRot = (float) Math.toDegrees(Math.atan2\n (CPos.z - player.getZ(), CPos.x - player.getX()));\n if (YRot < -180) YRot += 360;\n else if (YRot > 180) YRot -= 360;\n return YRot;\n }\n\n @Override\n public Component getName(ItemStack stack) {\n return Tooltip.name(stack);\n }\n\n @Override\n public Optional<TooltipComponent> getTooltipImage(ItemStack stack) {\n return Tooltip.get(stack);\n }\n\n @Override\n public void appendHoverText(ItemStack stack, @Nullable Level $$1, List<Component> components, TooltipFlag $$3) {\n Tooltip.lore(stack, components);\n }\n\n @Override\n public boolean isBarVisible(ItemStack stack) {\n return Tooltip.isBarVisible(stack);\n }\n\n @Override\n public int getBarWidth(ItemStack stack) {\n return Tooltip.getBarWidth(stack);\n }\n\n @Override\n public int getBarColor(ItemStack $$0) {\n return Tooltip.barColor;\n }\n\n public static LocalData getItemTraits(ItemStack stack) {\n if (stack.is(Items.DECORATED_POT))\n return LocalData.POT;\n\n if (!Kind.isBackpack(stack))\n return LocalData.EMPTY;\n\n CompoundTag display = stack.getOrCreateTagElement(\"display\");\n\n String key = display.getString(\"key\");\n int itemColor = stack.getItem() instanceof DyableBackpack dyableBackpack ? dyableBackpack.getColor(stack) : 0xFFFFFF;\n CompoundTag trim = stack.getTagElement(\"Trim\");\n\n return new LocalData(key, itemColor, trim);\n }\n\n public static ItemStack stackFromKey(String key) {\n Traits traits = Traits.get(key);\n CompoundTag display = new CompoundTag();\n display.putString(\"key\", key);\n\n ItemStack stack = traits.kind.getItem().getDefaultInstance();\n stack.getOrCreateTag().put(\"display\", display);\n return stack;\n }\n}" }, { "identifier": "DyableBackpack", "path": "common/src/main/java/com/beansgalaxy/backpacks/items/DyableBackpack.java", "snippet": "public class DyableBackpack extends BackpackItem implements DyeableLeatherItem {\n\n @Override\n public int getColor(ItemStack stack) {\n CompoundTag nbtCompound = stack.getTagElement(TAG_DISPLAY);\n if (nbtCompound != null && nbtCompound.contains(TAG_COLOR, Tag.TAG_ANY_NUMERIC)) {\n return nbtCompound.getInt(TAG_COLOR);\n }\n return Backpack.DEFAULT_COLOR;\n }\n}" }, { "identifier": "RecipeCrafting", "path": "common/src/main/java/com/beansgalaxy/backpacks/items/RecipeCrafting.java", "snippet": "public class RecipeCrafting extends ShapedRecipe {\n public static final String ID = \"backpack_crafting\";\n public static final ResourceLocation LOCATION = new ResourceLocation(Constants.MOD_ID, ID);\n public static final RecipeSerializer<RecipeCrafting> INSTANCE = new Serializer();\n private final String key;\n\n public RecipeCrafting(String key) {\n super(\"backpack_\" + key, CraftingBookCategory.EQUIPMENT, 3, 3, getIngredients(key), getResultItem(key));\n this.key = key;\n }\n\n @Override\n public boolean matches(CraftingContainer container, Level level) {\n if (container.getWidth() != 3 || container.getHeight() != 3)\n return false;\n\n Item material = container.getItem(0).getItem();\n Item binder = container.getItem(1).getItem();\n\n if (container.getItem(0).isEmpty() || container.getItem(1).isEmpty())\n return false;\n\n if (binder != container.getItem(7).getItem())\n return false;\n\n int[] materialSlots = {2, 3, 5, 6, 8};\n for (int i: materialSlots)\n {\n Item item = container.getItem(i).getItem();\n if (item != material)\n return false;\n }\n\n// RETURNS TRUE ONLY IF...\n// - CRAFTING GRID IS 3x3\n// - MATERIALS AND BINDERS ARE IN THEIR CORRECT SLOTS\n// - THERE IS A REGISTERED BACKPACK WITH THOSE MATERIALS AND BINDERS\n\n String key = Traits.keyFromIngredients(material, binder);\n return key != null && !key.isEmpty();\n }\n\n @Override\n public @NotNull ItemStack assemble(CraftingContainer container, RegistryAccess leve) {\n String key = Traits.keyFromIngredients(container.getItem(0).getItem(), container.getItem(1).getItem());\n if (key == null || key.isEmpty())\n return ItemStack.EMPTY;\n\n return BackpackItem.stackFromKey(key);\n }\n\n @Override\n public boolean isIncomplete() {\n return false;\n }\n\n @Override\n public boolean canCraftInDimensions(int $$0, int $$1) {\n return true;\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess $$0) {\n return getResultItem(this.key);\n }\n\n public static ItemStack getResultItem(String key) {\n if (key == null || key.isEmpty())\n return ItemStack.EMPTY;\n return BackpackItem.stackFromKey(key);\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return getIngredients(this.key);\n }\n\n public static NonNullList<Ingredient> getIngredients(String key) {\n if (key == null || key.isEmpty())\n return NonNullList.create();\n\n Traits traits = Traits.get(key);\n Ingredient mat = Ingredient.of(traits.material);\n Ingredient bin = Ingredient.of(traits.binder);\n Ingredient emp = Ingredient.EMPTY;\n\n return NonNullList.of(Ingredient.EMPTY,\n mat, bin, mat,\n mat, emp, mat,\n mat, bin, mat);\n }\n\n @Override\n public @NotNull RecipeSerializer<RecipeCrafting> getSerializer() {\n return INSTANCE;\n }\n\n public static class Serializer implements RecipeSerializer<RecipeCrafting> {\n public static final Codec<RecipeCrafting> CODEC = RecordCodecBuilder.create(\n in -> in.group(\n PrimitiveCodec.STRING.fieldOf(\"key\").forGetter(RecipeCrafting::getKey)\n ).apply(in, RecipeCrafting::new)\n );\n\n @Override\n public Codec<RecipeCrafting> codec() {\n return CODEC;\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, RecipeCrafting recipe) {\n buf.writeUtf(recipe.key);\n }\n\n @Override\n public RecipeCrafting fromNetwork(FriendlyByteBuf buf) {\n String key = buf.readUtf();\n return new RecipeCrafting(key);\n }\n }\n\n public String getKey() {\n return key;\n }\n}" }, { "identifier": "RecipeSmithing", "path": "common/src/main/java/com/beansgalaxy/backpacks/items/RecipeSmithing.java", "snippet": "public class RecipeSmithing implements SmithingRecipe {\n public static final String ID = \"backpack_smithing\";\n public static final ResourceLocation LOCATION = new ResourceLocation(Constants.MOD_ID, ID);\n public static final RecipeSerializer<RecipeSmithing> INSTANCE = new Serializer();\n private final String key;\n private final Traits traits;\n\n public RecipeSmithing(String key) {\n this.key = key;\n this.traits = Traits.get(this.key);\n }\n\n @Override\n public boolean isTemplateIngredient(ItemStack var1) {\n return var1.is(traits.template);\n }\n\n @Override\n public boolean isBaseIngredient(ItemStack var1) {\n return var1.is(traits.base);\n }\n\n @Override\n public boolean isAdditionIngredient(ItemStack var1) {\n return var1.is(traits.material);\n }\n\n @Override\n public boolean matches(Container container, Level var2) {\n return container.getItem(0).is(traits.template) &&\n container.getItem(1).is(traits.base) &&\n container.getItem(2).is(traits.material);\n }\n\n @Override\n public boolean isIncomplete() {\n return key == null || key.isEmpty() || traits == null;\n }\n\n @Override\n public ItemStack assemble(Container var1, RegistryAccess var2) {\n return BackpackItem.stackFromKey(key);\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess var1) {\n return BackpackItem.stackFromKey(key);\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return INSTANCE;\n }\n\n public static class Serializer implements RecipeSerializer<RecipeSmithing> {\n public static final Codec<RecipeSmithing> CODEC = RecordCodecBuilder.create(\n in -> in.group(\n PrimitiveCodec.STRING.fieldOf(\"key\").forGetter(RecipeSmithing::getKey)\n ).apply(in, RecipeSmithing::new)\n );\n\n @Override\n public Codec<RecipeSmithing> codec() {\n return CODEC;\n }\n\n @Override\n public RecipeSmithing fromNetwork(FriendlyByteBuf buf) {\n String key = buf.readUtf();\n return new RecipeSmithing(key);\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, RecipeSmithing var2) {\n buf.writeUtf(var2.getKey());\n }\n }\n\n private String getKey() {\n return this.key;\n }\n}" }, { "identifier": "NetworkPackages", "path": "fabric/src/main/java/com/beansgalaxy/backpacks/network/NetworkPackages.java", "snippet": "public class NetworkPackages {\n public static final ResourceLocation SPRINT_KEY_2S = new ResourceLocation(Constants.MOD_ID, \"sprint_key_s\");\n public static final ResourceLocation SYNC_VIEWERS_2All = new ResourceLocation(Constants.MOD_ID, \"sync_viewers_a\");\n public static final ResourceLocation SYNC_BACK_SLOT_2C = new ResourceLocation(Constants.MOD_ID, \"back_slot_a\");\n public static final ResourceLocation CALL_BACK_SLOT_2S = new ResourceLocation(Constants.MOD_ID, \"call_back_slot_s\");\n public static final ResourceLocation SYNC_BACK_INV_2C = new ResourceLocation(Constants.MOD_ID, \"backpack_inventory_c\");\n public static final ResourceLocation CALL_BACK_INV_2S = new ResourceLocation(Constants.MOD_ID, \"call_backpack_inventory_s\");\n public static final ResourceLocation CONFIG_DATA_2C = new ResourceLocation(Constants.MOD_ID, \"backpack_config_c\");\n\n public static void registerC2SPackets() {\n ServerPlayNetworking.registerGlobalReceiver(SPRINT_KEY_2S, SprintKeyPacket2S::receiveAtServer);\n ServerPlayNetworking.registerGlobalReceiver(CALL_BACK_SLOT_2S, SyncBackSlot2All::callSyncBackSlot);\n ServerPlayNetworking.registerGlobalReceiver(CALL_BACK_INV_2S, SyncBackInventory2C::callSyncBackInventory);\n }\n\n public static void registerS2CPackets() {\n ClientPlayNetworking.registerGlobalReceiver(SYNC_VIEWERS_2All, ReceiveAtClient::SyncViewers);\n ClientPlayNetworking.registerGlobalReceiver(SYNC_BACK_SLOT_2C, ReceiveAtClient::SyncBackSlot);\n ClientPlayNetworking.registerGlobalReceiver(SYNC_BACK_INV_2C, ReceiveAtClient::SyncBackInventory);\n ClientPlayNetworking.registerGlobalReceiver(CONFIG_DATA_2C, ReceiveAtClient::ConfigBackpackData);\n }\n}" }, { "identifier": "BackpackMenu", "path": "common/src/main/java/com/beansgalaxy/backpacks/screen/BackpackMenu.java", "snippet": "public class BackpackMenu extends AbstractContainerMenu {\n private static final ResourceLocation BACKPACK_ATLAS = new ResourceLocation(\"textures/atlas/blocks.png\");\n private static final ResourceLocation INPUT = new ResourceLocation(\"sprites/empty_slot_input_large\");\n private static int FIRST_SLOT_INDEX;\n public final BackpackInventory backpackInventory;\n protected final Backpack mirror;\n protected final Player viewer;\n protected final Entity owner;\n protected final BlockPos ownerPos;\n protected final float ownerYaw;\n private final int max_stacks;\n public int invOffset = 108;\n // SERVER CONSTRUCTOR\n public BackpackMenu(int id, Inventory playerInventory, BackpackInventory backpackInventory) {\n super(Services.REGISTRY.getMenu(), id);\n this.backpackInventory = backpackInventory;\n this.owner = backpackInventory.getOwner();\n this.ownerPos = owner.blockPosition();\n this.ownerYaw = owner.getVisualRotationYInDegrees();\n this.viewer = playerInventory.player;\n this.mirror = createMirror(playerInventory.player.level());\n this.max_stacks = backpackInventory.getLocalData().maxStacks();\n createInventorySlots(playerInventory);\n FIRST_SLOT_INDEX = slots.size();\n createBackpackSlots(backpackInventory);\n }\n\n private Backpack createMirror(Level level) {\n Backpack backpack = new Backpack(level) {\n\n @Override\n public BackpackInventory getBackpackInventory() {\n return BackpackMenu.this.backpackInventory;\n }\n\n @Override\n public LocalData getLocalData() {\n return this.backpackInventory.getLocalData();\n }\n };\n return backpack;\n }\n\n // CLIENT CONSTRUCTOR\n public BackpackMenu(int id, Inventory playerInv, FriendlyByteBuf buf) {\n this(id, playerInv, getBackpackInventory(buf.readInt(), playerInv.player.level()));\n }\n\n public static BackpackInventory getBackpackInventory(int entityId, Level level) {\n Entity entity = level.getEntity(entityId);\n return BackpackInventory.get(entity);\n }\n\n\n private void createBackpackSlots(Container inventory) {\n final int columns = Math.min(5 + (max_stacks / 4), 11);\n final int rows = 4;\n final int spacing = 17;\n int bpCenter = (columns / 2) * spacing;\n int x = 80 - bpCenter;\n x += spacing / 2 * -((columns % 2) - 1);\n int y = invOffset - rows * spacing + 35;\n\n\n for(int r = 0; r < rows; ++r)\n for(int c = 0; c < columns; ++c)\n this.addSlot(new Slot(inventory, c + r * columns, x + c * spacing, y + r * spacing) {\n public boolean mayPlace(ItemStack p_40231_) {\n return false;\n }\n });\n }\n\n private void createInventorySlots(Inventory playerInventory) {\n for(int l = 0; l < 3; ++l) {\n for(int k = 0; k < 9; ++k) {\n this.addSlot(new Slot(playerInventory, k + l * 9 + 9, 8 + k * 18, l * 18 + 51 + invOffset));\n }\n }\n for(int i1 = 0; i1 < 9; ++i1) {\n this.addSlot(new Slot(playerInventory, i1, 8 + i1 * 18, 109 + invOffset));\n }\n }\n\n public void clicked(int slotIndex, int button, ClickType actionType, Player player) {\n if (slotIndex >= FIRST_SLOT_INDEX && actionType != ClickType.QUICK_MOVE) {\n ItemStack cursorStack = this.getCarried();\n if (button == 0 && !cursorStack.isEmpty()) {\n this.setRemoteCarried(cursorStack);\n ItemStack stack = backpackInventory.insertItem(cursorStack);\n this.setCarried(stack);\n return;\n }\n if (button == 1 && !cursorStack.isEmpty()) {\n this.setRemoteCarried(cursorStack);\n ItemStack stack = backpackInventory.insertItem(cursorStack, 1);\n this.setCarried(stack);\n return;\n }\n }\n super.clicked(slotIndex, button, actionType, player);\n }\n\n @Override\n public ItemStack quickMoveStack(Player player, int slotId) {\n Slot clickedSlot = slots.get(slotId);\n ItemStack clickedStack = clickedSlot.getItem();\n if (clickedStack == ItemStack.EMPTY)\n return ItemStack.EMPTY;\n if (slotId < FIRST_SLOT_INDEX) { // HANDLES INSERT TO BACKPACK\n if (backpackInventory.spaceLeft() < 1)\n return ItemStack.EMPTY;\n backpackInventory.insertItem(clickedStack);\n clickedSlot.set(clickedStack);\n } else { // HANDLES INSERT TO INVENTORY\n clickedStack = backpackInventory.getItemStacks().get(slotId - FIRST_SLOT_INDEX);\n this.moveItemStackTo(clickedStack, 0, FIRST_SLOT_INDEX, true);\n if (clickedStack.isEmpty()) backpackInventory.getItemStacks().remove(slotId - FIRST_SLOT_INDEX);\n }\n return ItemStack.EMPTY;\n }\n\n @Override\n public boolean stillValid(Player player) {\n return true;\n }\n\n public void removed(Player player) {\n backpackInventory.stopOpen(player);\n mirror.discard();\n super.removed(player);\n }\n}" } ]
import com.beansgalaxy.backpacks.entity.BackpackEntity; import com.beansgalaxy.backpacks.events.*; import com.beansgalaxy.backpacks.events.advancements.EquipAnyCriterion; import com.beansgalaxy.backpacks.events.advancements.PlaceCriterion; import com.beansgalaxy.backpacks.events.advancements.SpecialCriterion; import com.beansgalaxy.backpacks.items.BackpackItem; import com.beansgalaxy.backpacks.items.DyableBackpack; import com.beansgalaxy.backpacks.items.RecipeCrafting; import com.beansgalaxy.backpacks.items.RecipeSmithing; import com.beansgalaxy.backpacks.network.NetworkPackages; import com.beansgalaxy.backpacks.screen.BackpackMenu; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.entity.event.v1.EntityElytraEvents; import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerType; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer;
9,959
package com.beansgalaxy.backpacks; public class FabricMain implements ModInitializer { public static EquipAnyCriterion EQUIP_ANY = CriteriaTriggers.register(Constants.MOD_ID + "/equip_any", new EquipAnyCriterion());
package com.beansgalaxy.backpacks; public class FabricMain implements ModInitializer { public static EquipAnyCriterion EQUIP_ANY = CriteriaTriggers.register(Constants.MOD_ID + "/equip_any", new EquipAnyCriterion());
public static PlaceCriterion PLACE = CriteriaTriggers.register(Constants.MOD_ID + "/place", new PlaceCriterion());
2
2023-12-14 21:55:00+00:00
12k
sinbad-navigator/erp-crm
auth/src/main/java/com/ec/auth/aspectj/DataScopeAspect.java
[ { "identifier": "BaseEntity", "path": "common/src/main/java/com/ec/common/core/domain/BaseEntity.java", "snippet": "public class BaseEntity implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * 搜索值\n */\n private String searchValue;\n\n /**\n * 创建者\n */\n private String createBy;\n\n /**\n * 创建时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date createTime;\n\n /**\n * 更新者\n */\n private String updateBy;\n\n /**\n * 更新时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date updateTime;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 请求参数\n */\n private Map<String, Object> params;\n\n public String getSearchValue() {\n return searchValue;\n }\n\n public void setSearchValue(String searchValue) {\n this.searchValue = searchValue;\n }\n\n public String getCreateBy() {\n return createBy;\n }\n\n public void setCreateBy(String createBy) {\n this.createBy = createBy;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public String getUpdateBy() {\n return updateBy;\n }\n\n public void setUpdateBy(String updateBy) {\n this.updateBy = updateBy;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n\n public String getRemark() {\n return remark;\n }\n\n public void setRemark(String remark) {\n this.remark = remark;\n }\n\n public Map<String, Object> getParams() {\n if (params == null) {\n params = new HashMap<>();\n }\n return params;\n }\n\n public void setParams(Map<String, Object> params) {\n this.params = params;\n }\n}" }, { "identifier": "SysRole", "path": "common/src/main/java/com/ec/common/core/domain/entity/SysRole.java", "snippet": "public class SysRole extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /**\n * 角色ID\n */\n @Excel(name = \"角色序号\", cellType = ColumnType.NUMERIC)\n private Long roleId;\n\n /**\n * 角色名称\n */\n @Excel(name = \"角色名称\")\n private String roleName;\n\n /**\n * 角色权限\n */\n @Excel(name = \"角色权限\")\n private String roleKey;\n\n /**\n * 角色排序\n */\n @Excel(name = \"角色排序\")\n private String roleSort;\n\n /**\n * 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限;5:仅本人数据权限)\n */\n @Excel(name = \"数据范围\", readConverterExp = \"1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限\")\n private String dataScope;\n\n /**\n * 菜单树选择项是否关联显示( 0:父子不互相关联显示 1:父子互相关联显示)\n */\n private boolean menuCheckStrictly;\n\n /**\n * 部门树选择项是否关联显示(0:父子不互相关联显示 1:父子互相关联显示 )\n */\n private boolean deptCheckStrictly;\n\n /**\n * 角色状态(0正常 1停用)\n */\n @Excel(name = \"角色状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /**\n * 删除标志(0代表存在 2代表删除)\n */\n private String delFlag;\n\n /**\n * 用户是否存在此角色标识 默认不存在\n */\n private boolean flag = false;\n\n /**\n * 菜单组\n */\n private Long[] menuIds;\n\n /**\n * 部门组(数据权限)\n */\n private Long[] deptIds;\n\n public SysRole() {\n\n }\n\n public SysRole(Long roleId) {\n this.roleId = roleId;\n }\n\n public static boolean isAdmin(Long roleId) {\n return roleId != null && 1L == roleId;\n }\n\n public Long getRoleId() {\n return roleId;\n }\n\n public void setRoleId(Long roleId) {\n this.roleId = roleId;\n }\n\n public boolean isAdmin() {\n return isAdmin(this.roleId);\n }\n\n @NotBlank(message = \"角色名称不能为空\")\n @Size(min = 0, max = 30, message = \"角色名称长度不能超过30个字符\")\n public String getRoleName() {\n return roleName;\n }\n\n public void setRoleName(String roleName) {\n this.roleName = roleName;\n }\n\n @NotBlank(message = \"权限字符不能为空\")\n @Size(min = 0, max = 100, message = \"权限字符长度不能超过100个字符\")\n public String getRoleKey() {\n return roleKey;\n }\n\n public void setRoleKey(String roleKey) {\n this.roleKey = roleKey;\n }\n\n @NotBlank(message = \"显示顺序不能为空\")\n public String getRoleSort() {\n return roleSort;\n }\n\n public void setRoleSort(String roleSort) {\n this.roleSort = roleSort;\n }\n\n public String getDataScope() {\n return dataScope;\n }\n\n public void setDataScope(String dataScope) {\n this.dataScope = dataScope;\n }\n\n public boolean isMenuCheckStrictly() {\n return menuCheckStrictly;\n }\n\n public void setMenuCheckStrictly(boolean menuCheckStrictly) {\n this.menuCheckStrictly = menuCheckStrictly;\n }\n\n public boolean isDeptCheckStrictly() {\n return deptCheckStrictly;\n }\n\n public void setDeptCheckStrictly(boolean deptCheckStrictly) {\n this.deptCheckStrictly = deptCheckStrictly;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public boolean isFlag() {\n return flag;\n }\n\n public void setFlag(boolean flag) {\n this.flag = flag;\n }\n\n public Long[] getMenuIds() {\n return menuIds;\n }\n\n public void setMenuIds(Long[] menuIds) {\n this.menuIds = menuIds;\n }\n\n public Long[] getDeptIds() {\n return deptIds;\n }\n\n public void setDeptIds(Long[] deptIds) {\n this.deptIds = deptIds;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)\n .append(\"roleId\", getRoleId())\n .append(\"roleName\", getRoleName())\n .append(\"roleKey\", getRoleKey())\n .append(\"roleSort\", getRoleSort())\n .append(\"dataScope\", getDataScope())\n .append(\"menuCheckStrictly\", isMenuCheckStrictly())\n .append(\"deptCheckStrictly\", isDeptCheckStrictly())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .toString();\n }\n}" }, { "identifier": "SysUser", "path": "common/src/main/java/com/ec/common/core/domain/entity/SysUser.java", "snippet": "public class SysUser extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /**\n * 用户ID\n */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, prompt = \"用户编号\")\n private Long userId;\n\n /**\n * 部门ID\n */\n @Excel(name = \"部门编号\", type = Type.IMPORT)\n private Long deptId;\n\n /**\n * 用户账号\n */\n @Excel(name = \"登录名称\")\n private String userName;\n\n /**\n * 用户昵称\n */\n @Excel(name = \"用户名称\")\n private String nickName;\n\n /**\n * 用户邮箱\n */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /**\n * 手机号码\n */\n @Excel(name = \"手机号码\")\n private String phonenumber;\n\n /**\n * 用户性别\n */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /**\n * 用户头像\n */\n private String avatar;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 盐加密\n */\n private String salt;\n\n /**\n * 帐号状态(0正常 1停用)\n */\n @Excel(name = \"帐号状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /**\n * 删除标志(0代表存在 2代表删除)\n */\n private String delFlag;\n\n /**\n * 最后登录IP\n */\n @Excel(name = \"最后登录IP\", type = Type.EXPORT)\n private String loginIp;\n\n /**\n * 最后登录时间\n */\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\", type = Type.EXPORT)\n private Date loginDate;\n\n /**\n * 部门对象\n */\n @Excels({\n @Excel(name = \"部门名称\", targetAttr = \"deptName\", type = Type.EXPORT),\n @Excel(name = \"部门负责人\", targetAttr = \"leader\", type = Type.EXPORT)\n })\n private SysDept dept;\n\n /**\n * 角色对象\n */\n private List<SysRole> roles;\n\n /**\n * 角色组\n */\n private Long[] roleIds;\n\n /**\n * 岗位组\n */\n private Long[] postIds;\n\n /**\n * 角色ID\n */\n private Long roleId;\n\n public SysUser() {\n\n }\n\n public SysUser(Long userId) {\n this.userId = userId;\n }\n\n public static boolean isAdmin(Long userId) {\n return userId != null && 1L == userId;\n }\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public boolean isAdmin() {\n return isAdmin(this.userId);\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @Size(min = 0, max = 30, message = \"用户昵称长度不能超过30个字符\")\n public String getNickName() {\n return nickName;\n }\n\n public void setNickName(String nickName) {\n this.nickName = nickName;\n }\n\n @Xss(message = \"用户账号不能包含脚本字符\")\n @NotBlank(message = \"用户账号不能为空\")\n @Size(min = 0, max = 30, message = \"用户账号长度不能超过30个字符\")\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n @Size(min = 0, max = 11, message = \"手机号码长度不能超过11个字符\")\n public String getPhonenumber() {\n return phonenumber;\n }\n\n public void setPhonenumber(String phonenumber) {\n this.phonenumber = phonenumber;\n }\n\n public String getSex() {\n return sex;\n }\n\n public void setSex(String sex) {\n this.sex = sex;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n @JsonIgnore\n @JsonProperty\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getSalt() {\n return salt;\n }\n\n public void setSalt(String salt) {\n this.salt = salt;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public String getLoginIp() {\n return loginIp;\n }\n\n public void setLoginIp(String loginIp) {\n this.loginIp = loginIp;\n }\n\n public Date getLoginDate() {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate) {\n this.loginDate = loginDate;\n }\n\n public SysDept getDept() {\n return dept;\n }\n\n public void setDept(SysDept dept) {\n this.dept = dept;\n }\n\n public List<SysRole> getRoles() {\n return roles;\n }\n\n public void setRoles(List<SysRole> roles) {\n this.roles = roles;\n }\n\n public Long[] getRoleIds() {\n return roleIds;\n }\n\n public void setRoleIds(Long[] roleIds) {\n this.roleIds = roleIds;\n }\n\n public Long[] getPostIds() {\n return postIds;\n }\n\n public void setPostIds(Long[] postIds) {\n this.postIds = postIds;\n }\n\n public Long getRoleId() {\n return roleId;\n }\n\n public void setRoleId(Long roleId) {\n this.roleId = roleId;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"deptId\", getDeptId())\n .append(\"userName\", getUserName())\n .append(\"nickName\", getNickName())\n .append(\"email\", getEmail())\n .append(\"phonenumber\", getPhonenumber())\n .append(\"sex\", getSex())\n .append(\"avatar\", getAvatar())\n .append(\"password\", getPassword())\n .append(\"salt\", getSalt())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"loginIp\", getLoginIp())\n .append(\"loginDate\", getLoginDate())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .append(\"dept\", getDept())\n .toString();\n }\n}" }, { "identifier": "LoginUser", "path": "common/src/main/java/com/ec/common/core/domain/model/LoginUser.java", "snippet": "public class LoginUser implements UserDetails {\n private static final long serialVersionUID = 1L;\n\n /**\n * 租户ID\n */\n private String tenant;\n\n /**\n * 用户ID\n */\n private Long userId;\n\n /**\n * 部门ID\n */\n private Long deptId;\n\n /**\n * 用户唯一标识\n */\n private String token;\n\n /**\n * 登录时间\n */\n private Long loginTime;\n\n /**\n * 过期时间\n */\n private Long expireTime;\n\n /**\n * 登录IP地址\n */\n private String ipaddr;\n\n /**\n * 登录地点\n */\n private String loginLocation;\n\n /**\n * 浏览器类型\n */\n private String browser;\n\n /**\n * 操作系统\n */\n private String os;\n\n /**\n * 权限列表\n */\n private Set<String> permissions;\n\n /**\n * 用户信息\n */\n private SysUser user;\n\n public LoginUser() {\n }\n\n public LoginUser(SysUser user, Set<String> permissions) {\n this.user = user;\n this.permissions = permissions;\n }\n\n public LoginUser(Long userId, Long deptId, SysUser user, Set<String> permissions) {\n this.userId = userId;\n this.deptId = deptId;\n this.user = user;\n this.permissions = permissions;\n }\n\n public LoginUser(String tenant, Long userId, Long deptId, SysUser user, Set<String> permissions) {\n this.tenant = tenant;\n this.userId = userId;\n this.deptId = deptId;\n this.user = user;\n this.permissions = permissions;\n }\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n @JSONField(serialize = false) // 加在属性上表示,这个属性不会参与序列化\n @Override\n public String getPassword() {\n return user.getPassword();\n }\n\n @Override\n public String getUsername() {\n return user.getUserName();\n }\n\n /**\n * 账户是否未过期,过期无法验证\n */\n @JSONField(serialize = false)\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n /**\n * 指定用户是否解锁,锁定的用户无法进行身份验证\n *\n * @return\n */\n @JSONField(serialize = false)\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n /**\n * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证\n *\n * @return\n */\n @JSONField(serialize = false)\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n /**\n * 是否可用 ,禁用的用户不能身份验证\n *\n * @return\n */\n @JSONField(serialize = false)\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public Long getLoginTime() {\n return loginTime;\n }\n\n public void setLoginTime(Long loginTime) {\n this.loginTime = loginTime;\n }\n\n public String getIpaddr() {\n return ipaddr;\n }\n\n public void setIpaddr(String ipaddr) {\n this.ipaddr = ipaddr;\n }\n\n public String getLoginLocation() {\n return loginLocation;\n }\n\n public void setLoginLocation(String loginLocation) {\n this.loginLocation = loginLocation;\n }\n\n public String getBrowser() {\n return browser;\n }\n\n public void setBrowser(String browser) {\n this.browser = browser;\n }\n\n public String getOs() {\n return os;\n }\n\n public void setOs(String os) {\n this.os = os;\n }\n\n public Long getExpireTime() {\n return expireTime;\n }\n\n public void setExpireTime(Long expireTime) {\n this.expireTime = expireTime;\n }\n\n public Set<String> getPermissions() {\n return permissions;\n }\n\n public void setPermissions(Set<String> permissions) {\n this.permissions = permissions;\n }\n\n public SysUser getUser() {\n return user;\n }\n\n public void setUser(SysUser user) {\n this.user = user;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return null;\n }\n\n public String getTenant() {\n return tenant;\n }\n\n public void setTenant(String tenant) {\n this.tenant = tenant;\n }\n}" }, { "identifier": "StringUtils", "path": "common/src/main/java/com/ec/common/utils/StringUtils.java", "snippet": "public class StringUtils extends org.apache.commons.lang3.StringUtils {\n /**\n * 空字符串\n */\n private static final String NULLSTR = \"\";\n\n /**\n * 下划线\n */\n private static final char SEPARATOR = '_';\n\n /**\n * 获取参数不为空值\n *\n * @param value defaultValue 要判断的value\n * @return value 返回值\n */\n public static <T> T nvl(T value, T defaultValue) {\n return value != null ? value : defaultValue;\n }\n\n /**\n * * 判断一个Collection是否为空, 包含List,Set,Queue\n *\n * @param coll 要判断的Collection\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Collection<?> coll) {\n return isNull(coll) || coll.isEmpty();\n }\n\n /**\n * * 判断一个Collection是否非空,包含List,Set,Queue\n *\n * @param coll 要判断的Collection\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Collection<?> coll) {\n return !isEmpty(coll);\n }\n\n /**\n * * 判断一个对象数组是否为空\n *\n * @param objects 要判断的对象数组\n * * @return true:为空 false:非空\n */\n public static boolean isEmpty(Object[] objects) {\n return isNull(objects) || (objects.length == 0);\n }\n\n /**\n * * 判断一个对象数组是否非空\n *\n * @param objects 要判断的对象数组\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Object[] objects) {\n return !isEmpty(objects);\n }\n\n /**\n * * 判断一个Map是否为空\n *\n * @param map 要判断的Map\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Map<?, ?> map) {\n return isNull(map) || map.isEmpty();\n }\n\n /**\n * * 判断一个Map是否为非空\n *\n * @param map 要判断的Map\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Map<?, ?> map) {\n return !isEmpty(map);\n }\n\n /**\n * * 判断一个字符串是否为空串\n *\n * @param str String\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(String str) {\n return isNull(str) || NULLSTR.equals(str.trim());\n }\n\n /**\n * * 判断一个字符串是否为非空串\n *\n * @param str String\n * @return true:非空串 false:空串\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n\n /**\n * * 判断一个对象是否为空\n *\n * @param object Object\n * @return true:为空 false:非空\n */\n public static boolean isNull(Object object) {\n return object == null;\n }\n\n /**\n * * 判断一个对象是否非空\n *\n * @param object Object\n * @return true:非空 false:空\n */\n public static boolean isNotNull(Object object) {\n return !isNull(object);\n }\n\n /**\n * * 判断一个对象是否是数组类型(Java基本型别的数组)\n *\n * @param object 对象\n * @return true:是数组 false:不是数组\n */\n public static boolean isArray(Object object) {\n return isNotNull(object) && object.getClass().isArray();\n }\n\n /**\n * 去空格\n */\n public static String trim(String str) {\n return (str == null ? \"\" : str.trim());\n }\n\n /**\n * 截取字符串\n *\n * @param str 字符串\n * @param start 开始\n * @return 结果\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return NULLSTR;\n }\n\n if (start < 0) {\n start = str.length() + start;\n }\n\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return NULLSTR;\n }\n\n return str.substring(start);\n }\n\n /**\n * 截取字符串\n *\n * @param str 字符串\n * @param start 开始\n * @param end 结束\n * @return 结果\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return NULLSTR;\n }\n\n if (end < 0) {\n end = str.length() + end;\n }\n if (start < 0) {\n start = str.length() + start;\n }\n\n if (end > str.length()) {\n end = str.length();\n }\n\n if (start > end) {\n return NULLSTR;\n }\n\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n\n return str.substring(start, end);\n }\n\n /**\n * 格式化文本, {} 表示占位符<br>\n * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>\n * 如果想输出 {} 使用 \\\\转义 { 即可,如果想输出 {} 之前的 \\ 使用双转义符 \\\\\\\\ 即可<br>\n * 例:<br>\n * 通常使用:format(\"this is {} for {}\", \"a\", \"b\") -> this is a for b<br>\n * 转义{}: format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is \\{} for a<br>\n * 转义\\: format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b<br>\n *\n * @param template 文本模板,被替换的部分用 {} 表示\n * @param params 参数值\n * @return 格式化后的文本\n */\n public static String format(String template, Object... params) {\n if (isEmpty(params) || isEmpty(template)) {\n return template;\n }\n return StrFormatter.format(template, params);\n }\n\n /**\n * 是否为http(s)://开头\n *\n * @param link 链接\n * @return 结果\n */\n public static boolean ishttp(String link) {\n return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);\n }\n\n /**\n * 字符串转set\n *\n * @param str 字符串\n * @param sep 分隔符\n * @return set集合\n */\n public static final Set<String> str2Set(String str, String sep) {\n return new HashSet<String>(str2List(str, sep, true, false));\n }\n\n /**\n * 字符串转list\n *\n * @param str 字符串\n * @param sep 分隔符\n * @param filterBlank 过滤纯空白\n * @param trim 去掉首尾空白\n * @return list集合\n */\n public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {\n List<String> list = new ArrayList<String>();\n if (StringUtils.isEmpty(str)) {\n return list;\n }\n\n // 过滤空白字符串\n if (filterBlank && StringUtils.isBlank(str)) {\n return list;\n }\n String[] split = str.split(sep);\n for (String string : split) {\n if (filterBlank && StringUtils.isBlank(string)) {\n continue;\n }\n if (trim) {\n string = string.trim();\n }\n list.add(string);\n }\n\n return list;\n }\n\n /**\n * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时忽略大小写\n *\n * @param cs 指定字符串\n * @param searchCharSequences 需要检查的字符串数组\n * @return 是否包含任意一个字符串\n */\n public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {\n if (isEmpty(cs) || isEmpty(searchCharSequences)) {\n return false;\n }\n for (CharSequence testStr : searchCharSequences) {\n if (containsIgnoreCase(cs, testStr)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 驼峰转下划线命名\n */\n public static String toUnderScoreCase(String str) {\n if (str == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n // 前置字符是否大写\n boolean preCharIsUpperCase = true;\n // 当前字符是否大写\n boolean curreCharIsUpperCase = true;\n // 下一字符是否大写\n boolean nexteCharIsUpperCase = true;\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (i > 0) {\n preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));\n } else {\n preCharIsUpperCase = false;\n }\n\n curreCharIsUpperCase = Character.isUpperCase(c);\n\n if (i < (str.length() - 1)) {\n nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));\n }\n\n if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {\n sb.append(SEPARATOR);\n } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {\n sb.append(SEPARATOR);\n }\n sb.append(Character.toLowerCase(c));\n }\n\n return sb.toString();\n }\n\n /**\n * 是否包含字符串\n *\n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n if (str != null && strs != null) {\n for (String s : strs) {\n if (str.equalsIgnoreCase(trim(s))) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld\n *\n * @param name 转换前的下划线大写方式命名的字符串\n * @return 转换后的驼峰式命名的字符串\n */\n public static String convertToCamelCase(String name) {\n StringBuilder result = new StringBuilder();\n // 快速检查\n if (name == null || name.isEmpty()) {\n // 没必要转换\n return \"\";\n } else if (!name.contains(\"_\")) {\n // 不含下划线,仅将首字母大写\n return name.substring(0, 1).toUpperCase() + name.substring(1);\n }\n // 用下划线将原始字符串分割\n String[] camels = name.split(\"_\");\n for (String camel : camels) {\n // 跳过原始字符串中开头、结尾的下换线或双重下划线\n if (camel.isEmpty()) {\n continue;\n }\n // 首字母大写\n result.append(camel.substring(0, 1).toUpperCase());\n result.append(camel.substring(1).toLowerCase());\n }\n return result.toString();\n }\n\n /**\n * 驼峰式命名法 例如:user_name->userName\n */\n public static String toCamelCase(String s) {\n if (s == null) {\n return null;\n }\n s = s.toLowerCase();\n StringBuilder sb = new StringBuilder(s.length());\n boolean upperCase = false;\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n if (c == SEPARATOR) {\n upperCase = true;\n } else if (upperCase) {\n sb.append(Character.toUpperCase(c));\n upperCase = false;\n } else {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n /**\n * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串\n *\n * @param str 指定字符串\n * @param strs 需要检查的字符串数组\n * @return 是否匹配\n */\n public static boolean matches(String str, List<String> strs) {\n if (isEmpty(str) || isEmpty(strs)) {\n return false;\n }\n for (String pattern : strs) {\n if (isMatch(pattern, str)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断url是否与规则配置:\n * ? 表示单个字符;\n * * 表示一层路径内的任意字符串,不可跨层级;\n * ** 表示任意层路径;\n *\n * @param pattern 匹配规则\n * @param url 需要匹配的url\n * @return\n */\n public static boolean isMatch(String pattern, String url) {\n AntPathMatcher matcher = new AntPathMatcher();\n return matcher.match(pattern, url);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T cast(Object obj) {\n return (T) obj;\n }\n}" }, { "identifier": "SecurityUtils", "path": "common/src/main/java/com/ec/common/utils/SecurityUtils.java", "snippet": "public class SecurityUtils {\n /**\n * 用户ID\n **/\n public static Long getUserId() {\n try {\n return getLoginUser().getUserId();\n } catch (Exception e) {\n throw new ServiceException(\"获取用户ID异常\", HttpStatus.UNAUTHORIZED);\n }\n }\n\n /**\n * 获取部门ID\n **/\n public static Long getDeptId() {\n try {\n return getLoginUser().getDeptId();\n } catch (Exception e) {\n throw new ServiceException(\"获取部门ID异常\", HttpStatus.UNAUTHORIZED);\n }\n }\n\n /**\n * 获取用户账户\n **/\n public static String getUsername() {\n try {\n return getLoginUser().getUsername();\n } catch (Exception e) {\n throw new ServiceException(\"获取用户账户异常\", HttpStatus.UNAUTHORIZED);\n }\n }\n\n /**\n * 获取用户\n **/\n public static LoginUser getLoginUser() {\n try {\n return (LoginUser) getAuthentication().getPrincipal();\n } catch (Exception e) {\n throw new ServiceException(\"获取用户信息异常\", HttpStatus.UNAUTHORIZED);\n }\n }\n\n /**\n * 获取Authentication\n */\n public static Authentication getAuthentication() {\n return SecurityContextHolder.getContext().getAuthentication();\n }\n\n /**\n * 生成BCryptPasswordEncoder密码\n *\n * @param password 密码\n * @return 加密字符串\n */\n public static String encryptPassword(String password) {\n BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();\n return passwordEncoder.encode(password);\n }\n\n /**\n * 判断密码是否相同\n *\n * @param rawPassword 真实密码\n * @param encodedPassword 加密后字符\n * @return 结果\n */\n public static boolean matchesPassword(String rawPassword, String encodedPassword) {\n BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();\n return passwordEncoder.matches(rawPassword, encodedPassword);\n }\n\n /**\n * 是否为管理员\n *\n * @param userId 用户ID\n * @return 结果\n */\n public static boolean isAdmin(Long userId) {\n return userId != null && 1L == userId;\n }\n}" } ]
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import com.ec.common.annotation.DataScope; import com.ec.common.core.domain.BaseEntity; import com.ec.common.core.domain.entity.SysRole; import com.ec.common.core.domain.entity.SysUser; import com.ec.common.core.domain.model.LoginUser; import com.ec.common.utils.StringUtils; import com.ec.common.utils.SecurityUtils;
10,160
package com.ec.auth.aspectj; /** * 数据过滤处理 * * @author ec */ @Aspect @Component public class DataScopeAspect { /** * 全部数据权限 */ public static final String DATA_SCOPE_ALL = "1"; /** * 自定数据权限 */ public static final String DATA_SCOPE_CUSTOM = "2"; /** * 部门数据权限 */ public static final String DATA_SCOPE_DEPT = "3"; /** * 部门及以下数据权限 */ public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; /** * 仅本人数据权限 */ public static final String DATA_SCOPE_SELF = "5"; /** * 数据权限过滤关键字 */ public static final String DATA_SCOPE = "dataScope"; /** * 数据范围过滤 * * @param joinPoint 切点 * @param user 用户 * @param userAlias 别名 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { StringBuilder sqlString = new StringBuilder(); for (SysRole role : user.getRoles()) { String dataScope = role.getDataScope(); if (DATA_SCOPE_ALL.equals(dataScope)) { sqlString = new StringBuilder(); break; } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
package com.ec.auth.aspectj; /** * 数据过滤处理 * * @author ec */ @Aspect @Component public class DataScopeAspect { /** * 全部数据权限 */ public static final String DATA_SCOPE_ALL = "1"; /** * 自定数据权限 */ public static final String DATA_SCOPE_CUSTOM = "2"; /** * 部门数据权限 */ public static final String DATA_SCOPE_DEPT = "3"; /** * 部门及以下数据权限 */ public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; /** * 仅本人数据权限 */ public static final String DATA_SCOPE_SELF = "5"; /** * 数据权限过滤关键字 */ public static final String DATA_SCOPE = "dataScope"; /** * 数据范围过滤 * * @param joinPoint 切点 * @param user 用户 * @param userAlias 别名 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { StringBuilder sqlString = new StringBuilder(); for (SysRole role : user.getRoles()) { String dataScope = role.getDataScope(); if (DATA_SCOPE_ALL.equals(dataScope)) { sqlString = new StringBuilder(); break; } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
sqlString.append(StringUtils.format(
4
2023-12-07 14:23:12+00:00
12k
ganeshbabugb/NASC-CMS
src/main/java/com/nasc/application/views/marks/table/MarksView.java
[ { "identifier": "AcademicYearEntity", "path": "src/main/java/com/nasc/application/data/core/AcademicYearEntity.java", "snippet": "@Data\n@Entity\n@Table(name = \"t_academic_year\")\npublic class AcademicYearEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String startYear;\n\n private String endYear;\n\n @Override\n public Long getId() {\n return id;\n }\n}" }, { "identifier": "DepartmentEntity", "path": "src/main/java/com/nasc/application/data/core/DepartmentEntity.java", "snippet": "@Entity\n@Table(name = \"t_departments\")\npublic class DepartmentEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String name;\n\n private String shortName;\n\n @OneToMany(mappedBy = \"department\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n private Set<SubjectEntity> subjects = new HashSet<>();\n\n @Override\n public String toString() {\n return name;\n }\n\n\n @Override\n public Long getId() {\n return id;\n }\n\n public void setId(Long 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 getShortName() {\n return shortName;\n }\n\n public void setShortName(String shortName) {\n this.shortName = shortName;\n }\n\n public Set<SubjectEntity> getSubjects() {\n return subjects;\n }\n\n public void setSubjects(Set<SubjectEntity> subjects) {\n this.subjects = subjects;\n }\n}" }, { "identifier": "SubjectEntity", "path": "src/main/java/com/nasc/application/data/core/SubjectEntity.java", "snippet": "@Entity\n@Table(name = \"t_subjects\")\npublic class SubjectEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String subjectName;\n private String subjectShortForm;\n private String subjectCode;\n @Enumerated(EnumType.STRING)\n private PaperType paperType;\n\n @Enumerated(EnumType.STRING)\n private MajorOfPaper majorOfPaper;\n\n @ManyToOne\n @JoinColumn(name = \"department_id\")\n private DepartmentEntity department;\n\n @Enumerated(EnumType.STRING)\n private Semester semester;\n\n @Override\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public PaperType getPaperType() {\n return paperType;\n }\n\n public void setPaperType(PaperType paperType) {\n this.paperType = paperType;\n }\n\n public String getSubjectCode() {\n return subjectCode;\n }\n\n public void setSubjectCode(String subjectCode) {\n this.subjectCode = subjectCode;\n }\n\n public String getSubjectName() {\n return subjectName;\n }\n\n public void setSubjectName(String subjectName) {\n this.subjectName = subjectName;\n }\n\n public String getSubjectShortForm() {\n return subjectShortForm;\n }\n\n public void setSubjectShortForm(String subjectShortForm) {\n this.subjectShortForm = subjectShortForm;\n }\n\n public MajorOfPaper getMajorOfPaper() {\n return majorOfPaper;\n }\n\n public void setMajorOfPaper(MajorOfPaper majorOfPaper) {\n this.majorOfPaper = majorOfPaper;\n }\n\n public DepartmentEntity getDepartment() {\n return department;\n }\n\n public void setDepartment(DepartmentEntity department) {\n this.department = department;\n }\n\n public Semester getSemester() {\n return semester;\n }\n\n public void setSemester(Semester semester) {\n this.semester = semester;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof SubjectEntity subject)) return false;\n return Objects.equals(id, subject.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n}" }, { "identifier": "User", "path": "src/main/java/com/nasc/application/data/core/User.java", "snippet": "@Entity\n@Table(name = \"application_user\")\npublic class User extends AbstractEntity {\n\n @CsvBindByName\n private String username;\n @CsvBindByName\n @Column(unique = true)\n private String registerNumber;\n @CsvBindByName\n private String email;\n @JsonIgnore\n @CsvBindByName\n private String password;\n @Enumerated(EnumType.STRING)\n @ElementCollection(fetch = FetchType.EAGER)\n private Set<Role> roles;\n @Enumerated(EnumType.STRING)\n private StudentSection studentSection;\n\n /*\n @Lob\n @Column(length = 1000000)\n private byte[] profilePicture;\n */\n\n private Boolean personalDetailsCompleted;\n private Boolean addressDetailsCompleted;\n private Boolean bankDetailsCompleted;\n\n @ManyToOne\n @JoinColumn(name = \"department_id\")\n private DepartmentEntity department;\n\n @ManyToOne\n @JoinColumn(name = \"academic_year_id\")\n private AcademicYearEntity academicYear;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)\n @JoinColumn(name = \"bank_details_id\")\n private BankDetails bankDetails;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n @JoinColumn(name = \"address_details_id\")\n private AddressDetails addressDetails;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)\n @JoinColumn(name = \"personal_details_id\")\n private PersonalDetails personalDetails;\n\n public User() {\n this.personalDetailsCompleted = Boolean.FALSE;\n this.addressDetailsCompleted = Boolean.FALSE;\n this.bankDetailsCompleted = Boolean.FALSE;\n }\n\n public AcademicYearEntity getAcademicYear() {\n return academicYear;\n }\n\n public void setAcademicYear(AcademicYearEntity academicYear) {\n this.academicYear = academicYear;\n }\n\n public DepartmentEntity getDepartment() {\n return department;\n }\n\n public void setDepartment(DepartmentEntity department) {\n this.department = department;\n }\n\n public StudentSection getStudentSection() {\n return studentSection;\n }\n\n public void setStudentSection(StudentSection studentSection) {\n this.studentSection = studentSection;\n }\n\n public PersonalDetails getPersonalDetails() {\n return personalDetails;\n }\n\n public void setPersonalDetails(PersonalDetails personalDetails) {\n this.personalDetails = personalDetails;\n }\n\n\n public Boolean getPersonalDetailsCompleted() {\n return personalDetailsCompleted;\n }\n\n public void setPersonalDetailsCompleted(Boolean personalDetailsCompleted) {\n this.personalDetailsCompleted = personalDetailsCompleted;\n }\n\n public Boolean getAddressDetailsCompleted() {\n return addressDetailsCompleted;\n }\n\n public void setAddressDetailsCompleted(Boolean addressDetailsCompleted) {\n this.addressDetailsCompleted = addressDetailsCompleted;\n }\n\n public Boolean getBankDetailsCompleted() {\n return bankDetailsCompleted;\n }\n\n public void setBankDetailsCompleted(Boolean bankDetailsCompleted) {\n this.bankDetailsCompleted = bankDetailsCompleted;\n }\n\n public AddressDetails getAddressDetails() {\n return addressDetails;\n }\n\n public void setAddressDetails(AddressDetails addressDetails) {\n this.addressDetails = addressDetails;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getRegisterNumber() {\n return registerNumber;\n }\n\n public void setRegisterNumber(String registerNumber) {\n this.registerNumber = registerNumber;\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<Role> getRoles() {\n return roles;\n }\n\n public void setRoles(Set<Role> roles) {\n this.roles = roles;\n }\n\n /*\n public byte[] getProfilePicture() {\n return profilePicture;\n }\n public void setProfilePicture(byte[] profilePicture) {\n this.profilePicture = profilePicture;\n }\n */\n public BankDetails getBankDetails() {\n return bankDetails;\n }\n\n public void setBankDetails(BankDetails bankDetails) {\n this.bankDetails = bankDetails;\n }\n\n //This is ued to indicate user completed all three forms are not.\n public boolean isFormsCompleted() {\n return personalDetailsCompleted && addressDetailsCompleted && bankDetailsCompleted;\n }\n\n}" }, { "identifier": "StudentMarksDTO", "path": "src/main/java/com/nasc/application/data/core/dto/StudentMarksDTO.java", "snippet": "public class StudentMarksDTO {\n\n private String id;\n private User student;\n private Map<SubjectEntity, StudentSubjectInfo> subjectInfoMap = new HashMap<>();\n\n // TESTING\n private int totalPass;\n private int totalFail;\n private int totalAbsent;\n private int totalPresent;\n\n public StudentMarksDTO() {\n this.id = UUID.randomUUID().toString();\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public User getStudent() {\n return student;\n }\n\n public void setStudent(User student) {\n this.student = student;\n }\n\n public Map<SubjectEntity, StudentSubjectInfo> getSubjectInfoMap() {\n return subjectInfoMap;\n }\n\n public void setSubjectInfoMap(Map<SubjectEntity, StudentSubjectInfo> subjectInfoMap) {\n this.subjectInfoMap = subjectInfoMap;\n }\n\n public int getTotalPass() {\n return totalPass;\n }\n\n public void setTotalPass(int totalPass) {\n this.totalPass = totalPass;\n }\n\n public int getTotalFail() {\n return totalFail;\n }\n\n public void setTotalFail(int totalFail) {\n this.totalFail = totalFail;\n }\n\n public int getTotalAbsent() {\n return totalAbsent;\n }\n\n public void setTotalAbsent(int totalAbsent) {\n this.totalAbsent = totalAbsent;\n }\n\n public int getTotalPresent() {\n return totalPresent;\n }\n\n public void setTotalPresent(int totalPresent) {\n this.totalPresent = totalPresent;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof StudentMarksDTO that)) return false;\n return Objects.equals(id, that.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n}" }, { "identifier": "StudentSubjectInfo", "path": "src/main/java/com/nasc/application/data/core/dto/StudentSubjectInfo.java", "snippet": "public class StudentSubjectInfo {\n private Double marks;\n private Boolean absent;\n private Double passMarks;\n private Double maxMarks;\n\n // Default constructor (implicitly provided by Java)\n public StudentSubjectInfo() {\n // No need to explicitly write this constructor unless you want to do some initialization.\n }\n\n // Custom constructor\n public StudentSubjectInfo(Double marks, Boolean absent, Double passMarks, Double maxMarks) {\n this.marks = marks;\n this.absent = absent;\n this.passMarks = passMarks;\n this.maxMarks = maxMarks;\n }\n\n // for grid\n public StudentSubjectInfo(Double mark) {\n this.marks = mark;\n }\n\n public Double getMarks() {\n return marks;\n }\n\n public void setMarks(Double marks) {\n this.marks = marks;\n }\n\n public Boolean getAbsent() {\n return absent;\n }\n\n public void setAbsent(Boolean absent) {\n this.absent = absent;\n }\n\n public Double getPassMarks() {\n return passMarks;\n }\n\n public void setPassMarks(Double passMarks) {\n this.passMarks = passMarks;\n }\n\n public Double getMaxMarks() {\n return maxMarks;\n }\n\n public void setMaxMarks(Double maxMarks) {\n this.maxMarks = maxMarks;\n }\n}" }, { "identifier": "ExamType", "path": "src/main/java/com/nasc/application/data/core/enums/ExamType.java", "snippet": "public enum ExamType {\n INTERNAL_1,\n INTERNAL_2,\n MODEL,\n SEMESTER;\n\n public String getDisplayName() {\n String capitalize = UIUtils.toCapitalize(name());\n return capitalize.contains(\"_\") ? capitalize.replace(\"_\", \" \") : capitalize;\n }\n}" }, { "identifier": "Role", "path": "src/main/java/com/nasc/application/data/core/enums/Role.java", "snippet": "public enum Role {\n ADMIN, STUDENT, PROFESSOR, HOD, EDITOR;\n\n public String getDisplayName() {\n return UIUtils.toCapitalize(name());\n }\n}" }, { "identifier": "Semester", "path": "src/main/java/com/nasc/application/data/core/enums/Semester.java", "snippet": "public enum Semester {\n SEMESTER_1,\n SEMESTER_2,\n SEMESTER_3,\n SEMESTER_4,\n SEMESTER_5,\n SEMESTER_6;\n\n public String getDisplayName() {\n String capitalize = UIUtils.toCapitalize(name());\n return capitalize.replace(\"_\", \" \");\n }\n\n}" }, { "identifier": "StudentSection", "path": "src/main/java/com/nasc/application/data/core/enums/StudentSection.java", "snippet": "public enum StudentSection {\n SECTION_A,\n SECTION_B,\n SECTION_C,\n SECTION_D,\n SECTION_E,\n SECTION_F,\n SECTION_G,\n SECTION_H;\n\n public String getDisplayName() {\n String enumName = name();\n int underscoreIndex = enumName.indexOf('_');\n\n if (underscoreIndex > 0) {\n String substring = enumName.substring(0, underscoreIndex);\n String capitalize = UIUtils.toCapitalize(substring);\n char nextChar = enumName.charAt(underscoreIndex + 1);\n String string = Character.toString(nextChar).toUpperCase();\n\n return capitalize + \" \" + string;\n } else {\n return enumName;\n }\n }\n}" }, { "identifier": "NotificationUtils", "path": "src/main/java/com/nasc/application/utils/NotificationUtils.java", "snippet": "public class NotificationUtils {\n\n // Duration\n private static final int SUCCESS_NOTIFICATION_DURATION = 2000;\n private static final int INFO_NOTIFICATION_DURATION = 3000;\n private static final int ERROR_NOTIFICATION_DURATION = 4000;\n private static final int WARNING_NOTIFICATION_DURATION = 5000;\n\n // Position\n private static final Notification.Position SUCCESS_NOTIFICATION_POSITION = Notification.Position.BOTTOM_END;\n private static final Notification.Position ERROR_NOTIFICATION_POSITION = Notification.Position.TOP_END;\n private static final Notification.Position INFO_NOTIFICATION_POSITION = Notification.Position.TOP_CENTER;\n private static final Notification.Position WARNING_NOTIFICATION_POSITION = Notification.Position.BOTTOM_CENTER;\n\n public static void showSuccessNotification(String message) {\n showNotification(message, SUCCESS_NOTIFICATION_DURATION, SUCCESS_NOTIFICATION_POSITION, VaadinIcon.CHECK_CIRCLE.create());\n }\n\n public static void showInfoNotification(String message) {\n showNotification(message, INFO_NOTIFICATION_DURATION, INFO_NOTIFICATION_POSITION, VaadinIcon.INFO_CIRCLE.create());\n }\n\n public static void showErrorNotification(String message) {\n showNotification(message, ERROR_NOTIFICATION_DURATION, ERROR_NOTIFICATION_POSITION, VaadinIcon.EXCLAMATION_CIRCLE.create());\n }\n\n public static void showWarningNotification(String message) {\n showNotification(message, WARNING_NOTIFICATION_DURATION, WARNING_NOTIFICATION_POSITION, VaadinIcon.WARNING.create());\n }\n\n private static void showNotification(String message, int duration, Notification.Position position, Icon icon) {\n Notification notification = new Notification();\n\n Div messageDiv = new Div(new Text(message));\n messageDiv.getStyle().set(\"font-weight\", \"600\");\n\n Icon closeIcon = VaadinIcon.CLOSE.create();\n closeIcon.addClickListener(event -> notification.close());\n\n HorizontalLayout layout = new HorizontalLayout(icon, messageDiv, closeIcon);\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.setDuration(duration);\n notification.setPosition(position);\n notification.open();\n }\n\n public static void createSubmitSuccess(String message) {\n Notification notification = new Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);\n\n\n Icon icon = VaadinIcon.CHECK_CIRCLE.create();\n\n HorizontalLayout layout = new HorizontalLayout(icon, new Text(message));\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.setDuration(SUCCESS_NOTIFICATION_DURATION);\n notification.setPosition(SUCCESS_NOTIFICATION_POSITION);\n notification.open();\n }\n\n public static void createReportError(String message) {\n Notification notification = new Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_ERROR);\n\n notification.setDuration(ERROR_NOTIFICATION_DURATION);\n notification.setPosition(ERROR_NOTIFICATION_POSITION);\n\n Icon icon = VaadinIcon.WARNING.create();\n\n HorizontalLayout layout = new HorizontalLayout(icon, new Text(message));\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.open();\n }\n\n public static void createUploadSuccess(String message, String fileName) {\n Notification notification = new Notification();\n\n Icon icon = VaadinIcon.CHECK_CIRCLE.create();\n icon.setColor(\"var(--lumo-success-color)\");\n\n Div uploadSuccessful = new Div(new Text(message));\n uploadSuccessful.getStyle()\n .set(\"font-weight\", \"600\")\n .setColor(\"var(--lumo-success-text-color)\");\n\n Span fn = new Span(fileName);\n fn.getStyle()\n .set(\"font-size\", \"var(--lumo-font-size-s)\")\n .set(\"font-weight\", \"600\");\n\n var layout = new HorizontalLayout(icon, uploadSuccessful, new Text(\" \"), fn);\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n\n notification.setDuration(SUCCESS_NOTIFICATION_DURATION);\n notification.setPosition(SUCCESS_NOTIFICATION_POSITION);\n notification.open();\n }\n}" }, { "identifier": "UIUtils", "path": "src/main/java/com/nasc/application/utils/UIUtils.java", "snippet": "public class UIUtils {\n public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(\"dd-MM-yyyy\");\n\n public static String toCapitalize(String string) {\n return SharedUtil.capitalize(string.toLowerCase());\n }\n}" }, { "identifier": "MainLayout", "path": "src/main/java/com/nasc/application/views/MainLayout.java", "snippet": "@PreserveOnRefresh\npublic class MainLayout extends AppLayout {\n\n private H2 viewTitle;\n\n private final AuthenticatedUser authenticatedUser;\n private final AccessAnnotationChecker accessChecker;\n\n public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {\n this.authenticatedUser = authenticatedUser;\n this.accessChecker = accessChecker;\n\n setPrimarySection(Section.DRAWER);\n addDrawerContent();\n addHeaderContent();\n }\n\n private void addHeaderContent() {\n DrawerToggle toggle = new DrawerToggle();\n toggle.setAriaLabel(\"Menu toggle\");\n\n viewTitle = new H2();\n viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);\n\n addToNavbar(true, toggle, viewTitle);\n }\n\n private void addDrawerContent() {\n H1 appName = new H1(\"NASC\");\n appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);\n Header header = new Header(appName);\n Scroller scroller = new Scroller(createNavigation());\n addToDrawer(header, scroller, createFooter());\n }\n\n private SideNav createNavigation() {\n SideNav nav = new SideNav();\n\n if (accessChecker.hasAccess(DashboardView.class)) {\n nav.addItem(new SideNavItem(\"Dashboard\", DashboardView.class, LineAwesomeIcon.CHART_AREA_SOLID.create()));\n }\n if (accessChecker.hasAccess(PersonalFormView.class)) {\n nav.addItem(new SideNavItem(\"Person Form\", PersonalFormView.class, LineAwesomeIcon.USER.create()));\n }\n if (accessChecker.hasAccess(AddressFormView.class)) {\n nav.addItem(\n new SideNavItem(\"Address Form\", AddressFormView.class, LineAwesomeIcon.MAP_MARKER_SOLID.create()));\n }\n if (accessChecker.hasAccess(BankDetailsFormView.class)) {\n nav.addItem(new SideNavItem(\"Bank Details Form\", BankDetailsFormView.class,\n LineAwesomeIcon.CREDIT_CARD.create()));\n }\n if (accessChecker.hasAccess(StudentsStatusView.class)) {\n nav.addItem(\n new SideNavItem(\"Students Status\", StudentsStatusView.class, LineAwesomeIcon.TH_SOLID.create()));\n }\n if (accessChecker.hasAccess(ProfessorStatusView.class)) {\n nav.addItem(\n new SideNavItem(\"Professor Status\", ProfessorStatusView.class, LineAwesomeIcon.TH_SOLID.create()));\n }\n if (accessChecker.hasAccess(StudentMasterDetailsView.class)) {\n nav.addItem(new SideNavItem(\"Student Master Details\", StudentMasterDetailsView.class,\n LineAwesomeIcon.USERS_SOLID.create()));\n }\n if (accessChecker.hasAccess(AddressMasterDetailView.class)) {\n nav.addItem(new SideNavItem(\"Address Master Detail\", AddressMasterDetailView.class,\n LineAwesomeIcon.ADDRESS_CARD.create()));\n }\n if (accessChecker.hasAccess(CreateSubjectCrud.class)) {\n nav.addItem(new SideNavItem(\"Create Subject Crud\", CreateSubjectCrud.class,\n FontAwesome.Solid.BOOK_OPEN.create()));\n }\n if (accessChecker.hasAccess(MarkEntryView.class)) {\n nav.addItem(new SideNavItem(\"Mark-Book Entry\", MarkEntryView.class,\n FontAwesome.Solid.PENCIL.create()));\n }\n if (accessChecker.hasAccess(MarksView.class)) {\n nav.addItem(\n new SideNavItem(\"Mark-Book Overview\", MarksView.class, FontAwesome.Solid.DATABASE.create()));\n }\n if (accessChecker.hasAccess(CreateUsers.class)) {\n nav.addItem(new SideNavItem(\"Create Users\", CreateUsers.class,\n FontAwesome.Solid.USER_PLUS.create()));\n }\n if (accessChecker.hasAccess(PasswordChangeView.class)) {\n nav.addItem(new SideNavItem(\"Change Password\", PasswordChangeView.class,\n FontAwesome.Solid.USER_LOCK.create()));\n }\n if (accessChecker.hasAccess(ValueVaultView.class)) {\n nav.addItem(\n new SideNavItem(\"Value Vault\", ValueVaultView.class, FontAwesome.Solid.DATABASE.create()));\n }\n if (accessChecker.hasAccess(ActiveUsersView.class)) {\n nav.addItem(\n new SideNavItem(\"Active Users\", ActiveUsersView.class, FontAwesome.Solid.DATABASE.create()));\n }\n if (accessChecker.hasAccess(AboutView.class)) {\n nav.addItem(new SideNavItem(\"About\", AboutView.class, LineAwesomeIcon.FILE.create()));\n }\n return nav;\n }\n\n private Footer createFooter() {\n Footer layout = new Footer();\n\n Optional<User> maybeUser = authenticatedUser.get();\n if (maybeUser.isPresent()) {\n User user = maybeUser.get();\n\n Avatar avatar = new Avatar(user.getUsername());\n\n // https://vaadin.com/blog/saving-and-displaying-images-using-jpa\n // Profile icon\n // StreamResource resource = new StreamResource(\"profile-pic\",\n // () -> new ByteArrayInputStream(user.getProfilePicture()));\n // avatar.setImageResource(resource);\n\n avatar.setThemeName(\"xsmall\");\n avatar.getElement().setAttribute(\"tabindex\", \"-1\");\n\n MenuBar userMenu = new MenuBar();\n userMenu.setThemeName(\"tertiary-inline contrast\");\n\n MenuItem userName = userMenu.addItem(\"\");\n Div div = new Div();\n div.add(avatar);\n div.add(user.getUsername() + \" [ \" + user.getRegisterNumber() + \" ]\");\n div.add(new Icon(\"lumo\", \"dropdown\"));\n div.getElement().getStyle().set(\"display\", \"flex\");\n div.getElement().getStyle().set(\"align-items\", \"center\");\n div.getElement().getStyle().set(\"gap\", \"var(--lumo-space-s)\");\n userName.add(div);\n userName.getSubMenu().addItem(\"log out\", e -> authenticatedUser.logout());\n\n layout.add(userMenu);\n } else {\n Anchor loginLink = new Anchor(\"login\", \"Sign in\");\n layout.add(loginLink);\n }\n\n return layout;\n }\n\n @Override\n protected void afterNavigation() {\n super.afterNavigation();\n viewTitle.setText(getCurrentPageTitle());\n }\n\n private String getCurrentPageTitle() {\n PageTitle title = getContent().getClass().getAnnotation(PageTitle.class);\n return title == null ? \"\" : title.value();\n }\n}" } ]
import com.flowingcode.vaadin.addons.fontawesome.FontAwesome; import com.nasc.application.data.core.AcademicYearEntity; import com.nasc.application.data.core.DepartmentEntity; import com.nasc.application.data.core.SubjectEntity; import com.nasc.application.data.core.User; import com.nasc.application.data.core.dto.StudentMarksDTO; import com.nasc.application.data.core.dto.StudentSubjectInfo; import com.nasc.application.data.core.enums.ExamType; import com.nasc.application.data.core.enums.Role; import com.nasc.application.data.core.enums.Semester; import com.nasc.application.data.core.enums.StudentSection; import com.nasc.application.services.*; import com.nasc.application.utils.NotificationUtils; import com.nasc.application.utils.UIUtils; import com.nasc.application.views.MainLayout; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Html; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.charts.Chart; import com.vaadin.flow.component.charts.export.SVGGenerator; import com.vaadin.flow.component.charts.model.*; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.combobox.ComboBoxVariant; import com.vaadin.flow.component.contextmenu.ContextMenu; import com.vaadin.flow.component.contextmenu.MenuItem; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.grid.ColumnTextAlign; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.GridVariant; import com.vaadin.flow.component.grid.HeaderRow; import com.vaadin.flow.component.grid.dataview.GridListDataView; import com.vaadin.flow.component.gridpro.GridPro; import com.vaadin.flow.component.gridpro.GridProVariant; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.NumberField; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.textfield.TextFieldVariant; import com.vaadin.flow.data.provider.Query; import com.vaadin.flow.data.renderer.TextRenderer; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.StreamResource; import jakarta.annotation.security.RolesAllowed; import lombok.extern.slf4j.Slf4j; import org.vaadin.olli.FileDownloadWrapper; import software.xdev.vaadin.grid_exporter.GridExporter; import software.xdev.vaadin.grid_exporter.column.ColumnConfigurationBuilder; import software.xdev.vaadin.grid_exporter.jasper.format.HtmlFormat; import software.xdev.vaadin.grid_exporter.jasper.format.PdfFormat; import software.xdev.vaadin.grid_exporter.jasper.format.XlsxFormat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.*; import java.util.function.Consumer;
8,234
Button exportButton = new Button("Export", FontAwesome.Solid.FILE_EXPORT.create(), e -> { ExamType selectedExamType = examTypeComboBox.getValue(); Semester selectedSemester = semesterComboBox.getValue(); DepartmentEntity selectedDepartment = departmentComboBox.getValue(); AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue(); StudentSection studentSection = studentSectionComboBox.getValue(); // Check Grid and Filter Before Export int size = marksGrid.getDataProvider().size(new Query<>()); if (!isFilterInValid() && size > 0) { String fileName = selectedDepartment.getShortName() + "_" + selectedAcademicYear.getStartYear() + "-" + selectedAcademicYear.getEndYear() + "_" + studentSection.getDisplayName() + "_" + selectedSemester.getDisplayName() + "_" + selectedExamType.getDisplayName() + "_Marks"; XlsxFormat xlsxFormat = new XlsxFormat(); PdfFormat pdfFormat = new PdfFormat(); HtmlFormat htmlFormat = new HtmlFormat(); gridExporter = GridExporter .newWithDefaults(marksGrid) .withFileName(fileName) // Ignoring chart column .withColumnFilter(studentMarksDTOColumn -> studentMarksDTOColumn.isVisible() && !studentMarksDTOColumn.getKey().equals("Chart")) .withAvailableFormats(xlsxFormat, pdfFormat, htmlFormat) .withPreSelectedFormat(xlsxFormat) .withColumnConfigurationBuilder(new ColumnConfigurationBuilder()); gridExporter.open(); } } ); exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL); HorizontalLayout horizontalLayout = new HorizontalLayout(menuButton, exportButton); horizontalLayout.setWidthFull(); horizontalLayout.setJustifyContentMode(JustifyContentMode.END); horizontalLayout.setAlignItems(Alignment.CENTER); add(new H3("Marks View"), filterLayout, horizontalLayout, marksGrid); setSizeFull(); } private boolean isFilterInValid() { return examTypeComboBox.getValue() == null || semesterComboBox.getValue() == null || departmentComboBox.getValue() == null || academicYearComboBox.getValue() == null || studentSectionComboBox.getValue() == null; } private static Component createFilterHeader(Consumer<String> filterChangeConsumer) { TextField textField = new TextField(); textField.setValueChangeMode(ValueChangeMode.EAGER); textField.setClearButtonVisible(true); textField.addThemeVariants(TextFieldVariant.LUMO_SMALL); textField.setWidthFull(); // CASE IN SENSITIVE textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase())); return textField; } private void configureComboBoxes() { List<AcademicYearEntity> academicYears = academicYearService.findAll(); List<DepartmentEntity> departments = departmentService.findAll(); Semester[] semesters = Semester.values(); ExamType[] examTypes = ExamType.values(); StudentSection[] studentSections = StudentSection.values(); semesterComboBox.setItems(semesters); semesterComboBox.setItemLabelGenerator(Semester::getDisplayName); semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); semesterComboBox.setRequiredIndicatorVisible(true); examTypeComboBox.setItems(examTypes); examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName); examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); examTypeComboBox.setRequiredIndicatorVisible(true); academicYearComboBox.setItems(academicYears); academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + " - " + item.getEndYear()); academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); academicYearComboBox.setRequiredIndicatorVisible(true); departmentComboBox.setItems(departments); departmentComboBox.setItemLabelGenerator(item -> item.getName() + " - " + item.getShortName()); departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); departmentComboBox.setRequiredIndicatorVisible(true); studentSectionComboBox.setItems(studentSections); studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName); studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); studentSectionComboBox.setRequiredIndicatorVisible(true); } private void updateTotalPassFailCounts(List<StudentMarksDTO> allStudentMarks, PassFailCounts counts) { counts.totalPass = 0; counts.totalFail = 0; counts.totalPresent = 0; counts.totalAbsent = 0; counts.subjectPassCounts.clear(); counts.subjectFailCounts.clear(); counts.subjectPresentCounts.clear(); counts.subjectAbsentCounts.clear(); for (StudentMarksDTO studentMarksDTO : allStudentMarks) { updateTotalPassFailCounts(studentMarksDTO, counts); } } private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {
package com.nasc.application.views.marks.table; @Route(value = "marks", layout = MainLayout.class) @RolesAllowed({"HOD", "ADMIN", "PROFESSOR"}) @PageTitle("Marks") @CssImport( themeFor = "vaadin-grid", value = "./recipe/gridcell/grid-cell.css" ) @Slf4j public class MarksView extends VerticalLayout { // Service private final MarksService marksService; private final DepartmentService departmentService; private final AcademicYearService academicYearService; private final Button menuButton = new Button("Show/Hide Columns"); private final SubjectService subjectService; private final UserService userService; // Grid private final GridPro<StudentMarksDTO> marksGrid = new GridPro<>(StudentMarksDTO.class); private GridListDataView<StudentMarksDTO> dataProvider; // Combobox private final ComboBox<ExamType> examTypeComboBox = new ComboBox<>("Select Exam Type"); private final ComboBox<Semester> semesterComboBox = new ComboBox<>("Select Semester"); private final ComboBox<DepartmentEntity> departmentComboBox = new ComboBox<>("Select Department"); private final ComboBox<AcademicYearEntity> academicYearComboBox = new ComboBox<>("Select Academic Year"); private final ComboBox<StudentSection> studentSectionComboBox = new ComboBox<>("Select Student Section"); // UTILS private final ColumnToggleContextMenu contextMenu = new ColumnToggleContextMenu(menuButton); private final HeaderRow headerRow; private GridExporter<StudentMarksDTO> gridExporter; public MarksView(MarksService marksService, DepartmentService departmentService, AcademicYearService academicYearService, SubjectService subjectService, UserService userService ) { this.marksService = marksService; this.departmentService = departmentService; this.academicYearService = academicYearService; this.subjectService = subjectService; this.userService = userService; configureComboBoxes(); marksGrid.removeAllColumns(); marksGrid.setSizeFull(); marksGrid.setEditOnClick(true); marksGrid.setSingleCellEdit(true); marksGrid.setMultiSort(true); marksGrid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT, GridVariant.LUMO_COLUMN_BORDERS); marksGrid.addThemeVariants(GridProVariant.LUMO_ROW_STRIPES); // marksGrid.setAllRowsVisible(true); // TO AVOID SCROLLER DISPLAY ALL THE ROWS headerRow = marksGrid.appendHeaderRow(); // Button Button searchButton = new Button("Search/Refresh"); searchButton.addClickListener(e -> updateGridData()); searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL); menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL); HorizontalLayout filterLayout = new HorizontalLayout(); filterLayout.setAlignItems(Alignment.BASELINE); filterLayout.add( departmentComboBox, academicYearComboBox, semesterComboBox, examTypeComboBox, studentSectionComboBox, searchButton ); Button exportButton = new Button("Export", FontAwesome.Solid.FILE_EXPORT.create(), e -> { ExamType selectedExamType = examTypeComboBox.getValue(); Semester selectedSemester = semesterComboBox.getValue(); DepartmentEntity selectedDepartment = departmentComboBox.getValue(); AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue(); StudentSection studentSection = studentSectionComboBox.getValue(); // Check Grid and Filter Before Export int size = marksGrid.getDataProvider().size(new Query<>()); if (!isFilterInValid() && size > 0) { String fileName = selectedDepartment.getShortName() + "_" + selectedAcademicYear.getStartYear() + "-" + selectedAcademicYear.getEndYear() + "_" + studentSection.getDisplayName() + "_" + selectedSemester.getDisplayName() + "_" + selectedExamType.getDisplayName() + "_Marks"; XlsxFormat xlsxFormat = new XlsxFormat(); PdfFormat pdfFormat = new PdfFormat(); HtmlFormat htmlFormat = new HtmlFormat(); gridExporter = GridExporter .newWithDefaults(marksGrid) .withFileName(fileName) // Ignoring chart column .withColumnFilter(studentMarksDTOColumn -> studentMarksDTOColumn.isVisible() && !studentMarksDTOColumn.getKey().equals("Chart")) .withAvailableFormats(xlsxFormat, pdfFormat, htmlFormat) .withPreSelectedFormat(xlsxFormat) .withColumnConfigurationBuilder(new ColumnConfigurationBuilder()); gridExporter.open(); } } ); exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL); HorizontalLayout horizontalLayout = new HorizontalLayout(menuButton, exportButton); horizontalLayout.setWidthFull(); horizontalLayout.setJustifyContentMode(JustifyContentMode.END); horizontalLayout.setAlignItems(Alignment.CENTER); add(new H3("Marks View"), filterLayout, horizontalLayout, marksGrid); setSizeFull(); } private boolean isFilterInValid() { return examTypeComboBox.getValue() == null || semesterComboBox.getValue() == null || departmentComboBox.getValue() == null || academicYearComboBox.getValue() == null || studentSectionComboBox.getValue() == null; } private static Component createFilterHeader(Consumer<String> filterChangeConsumer) { TextField textField = new TextField(); textField.setValueChangeMode(ValueChangeMode.EAGER); textField.setClearButtonVisible(true); textField.addThemeVariants(TextFieldVariant.LUMO_SMALL); textField.setWidthFull(); // CASE IN SENSITIVE textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase())); return textField; } private void configureComboBoxes() { List<AcademicYearEntity> academicYears = academicYearService.findAll(); List<DepartmentEntity> departments = departmentService.findAll(); Semester[] semesters = Semester.values(); ExamType[] examTypes = ExamType.values(); StudentSection[] studentSections = StudentSection.values(); semesterComboBox.setItems(semesters); semesterComboBox.setItemLabelGenerator(Semester::getDisplayName); semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); semesterComboBox.setRequiredIndicatorVisible(true); examTypeComboBox.setItems(examTypes); examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName); examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); examTypeComboBox.setRequiredIndicatorVisible(true); academicYearComboBox.setItems(academicYears); academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + " - " + item.getEndYear()); academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); academicYearComboBox.setRequiredIndicatorVisible(true); departmentComboBox.setItems(departments); departmentComboBox.setItemLabelGenerator(item -> item.getName() + " - " + item.getShortName()); departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); departmentComboBox.setRequiredIndicatorVisible(true); studentSectionComboBox.setItems(studentSections); studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName); studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); studentSectionComboBox.setRequiredIndicatorVisible(true); } private void updateTotalPassFailCounts(List<StudentMarksDTO> allStudentMarks, PassFailCounts counts) { counts.totalPass = 0; counts.totalFail = 0; counts.totalPresent = 0; counts.totalAbsent = 0; counts.subjectPassCounts.clear(); counts.subjectFailCounts.clear(); counts.subjectPresentCounts.clear(); counts.subjectAbsentCounts.clear(); for (StudentMarksDTO studentMarksDTO : allStudentMarks) { updateTotalPassFailCounts(studentMarksDTO, counts); } } private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {
for (Map.Entry<SubjectEntity, StudentSubjectInfo> entry : studentMarksDTO.getSubjectInfoMap().entrySet()) {
2
2023-12-10 18:07:28+00:00
12k
Viola-Siemens/StellarForge
src/main/java/com/hexagram2021/stellarforge/StellarForge.java
[ { "identifier": "ClientProxy", "path": "src/main/java/com/hexagram2021/stellarforge/client/ClientProxy.java", "snippet": "@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD)\npublic class ClientProxy {\n\tpublic static void modConstruction() {\n\t}\n\n\t@SubscribeEvent\n\tpublic static void setup(FMLClientSetupEvent event) {\n\t\tevent.enqueueWork(() -> {\n\t\t\tregisterContainersAndScreens();\n\t\t});\n\t}\n\n\tprivate static void registerContainersAndScreens() {\n\n\t}\n}" }, { "identifier": "SFContent", "path": "src/main/java/com/hexagram2021/stellarforge/common/SFContent.java", "snippet": "public class SFContent {\n\tpublic static void modConstruction(IEventBus bus) {\n\t\tSFBlocks.init(bus);\n\t\tSFItems.init(bus);\n\t\tSFBlockFunctions.init(bus);\n\t\tSFCreativeModeTabs.init(bus);\n\t}\n\n\tpublic static void registerCommands(RegisterCommandsEvent event) {\n\t\tevent.getDispatcher().register(SFCommands.register());\n\t}\n\n\tpublic static void onNewRegistry(NewRegistryEvent event) {\n\t\tevent.create(new RegistryBuilder<>().setName(SFRegistries.BLOCK_FUNCTIONS.location()).disableSync().disableSaving().hasTags());\n\t}\n}" }, { "identifier": "SFCommonConfig", "path": "src/main/java/com/hexagram2021/stellarforge/common/config/SFCommonConfig.java", "snippet": "public class SFCommonConfig {\n\tprivate static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n\tprivate static final ForgeConfigSpec SPEC;\n\n\tpublic static final ForgeConfigSpec.BooleanValue ENABLE_REGISTRY_CHECK;\n\tpublic static final ForgeConfigSpec.IntValue COMMAND_PERMISSION;\n\n\tstatic {\n\t\tBUILDER.push(\"stellarforge-common-config\");\n\n\t\tCOMMAND_PERMISSION = BUILDER.comment(\"Permission level for command `/stellarforge`\").defineInRange(\"COMMAND_PERMISSION\", 2, 0, 4);\n\t\tENABLE_REGISTRY_CHECK = BUILDER.comment(\"Enable registry check. This function is good for debugging, especially for developers, server operators, and players who find the game not working. But it takes time to check everytime the game starts. It is recommended for you to run it in game test server.\").define(\"ENABLE_REGISTRY_CHECK\", false);\n\n\t\tBUILDER.pop();\n\n\t\tSPEC = BUILDER.build();\n\t}\n\n\tpublic static ForgeConfigSpec getConfig() {\n\t\treturn SPEC;\n\t}\n}" }, { "identifier": "RegistryChecker", "path": "src/main/java/com/hexagram2021/stellarforge/common/util/RegistryChecker.java", "snippet": "@SuppressWarnings({\"deprecation\", \"unused\", \"UnusedReturnValue\"})\npublic interface RegistryChecker {\n\tSet<Block> WHITELIST_NO_LOOT_TABLE_BLOCKS = ImmutableSet.of(\n\t\t\tBlocks.AIR, Blocks.VOID_AIR, Blocks.CAVE_AIR, Blocks.WATER, Blocks.LAVA, Blocks.LIGHT,\n\t\t\tBlocks.PISTON_HEAD, Blocks.MOVING_PISTON, Blocks.FIRE, Blocks.SOUL_FIRE, Blocks.END_PORTAL,\n\t\t\tBlocks.FROSTED_ICE, Blocks.END_GATEWAY, Blocks.END_PORTAL_FRAME, Blocks.COMMAND_BLOCK,\n\t\t\tBlocks.REPEATING_COMMAND_BLOCK, Blocks.CHAIN_COMMAND_BLOCK, Blocks.STRUCTURE_BLOCK, Blocks.STRUCTURE_VOID,\n\t\t\tBlocks.BUBBLE_COLUMN, Blocks.JIGSAW, Blocks.BARRIER\n\t);\n\tSet<Block> WHITELIST_NOT_IN_MINEABLE_TAGS = ImmutableSet.of(\n\t\t\tBlocks.COMMAND_BLOCK, Blocks.REPEATING_COMMAND_BLOCK, Blocks.CHAIN_COMMAND_BLOCK,\n\t\t\tBlocks.STRUCTURE_BLOCK, Blocks.JIGSAW\n\t);\n\tSet<Block> WHITELIST_NO_ITEM_BLOCKS = ImmutableSet.of(\n\t\t\tBlocks.AIR, Blocks.VOID_AIR, Blocks.CAVE_AIR, Blocks.WATER, Blocks.LAVA, Blocks.PISTON_HEAD,\n\t\t\tBlocks.MOVING_PISTON, Blocks.FIRE, Blocks.SOUL_FIRE, Blocks.END_PORTAL, Blocks.NETHER_PORTAL,\n\t\t\tBlocks.CANDLE_CAKE, Blocks.END_GATEWAY, Blocks.FROSTED_ICE, Blocks.BUBBLE_COLUMN\n\t);\n\n\tstatic void registryCheck(LootDataManager lootDataManager) {\n\t\tForgeRegistries.BLOCKS.forEach(block -> {\n\t\t\tResourceLocation id = getRegistryName(block);\n\t\t\tItem blockItem = block.asItem();\n\t\t\tif(!WHITELIST_NO_ITEM_BLOCKS.contains(block) && (!id.getPath().startsWith(\"potted_\") && !id.getPath().endsWith(\"_candle_cake\")) && blockItem.equals(Items.AIR)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] No BlockItem registered for block %s.\".formatted(id));\n\t\t\t}\n\t\t\t//vanilla tags\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_slab\", BlockTags.SLABS, ItemTags.SLABS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_stairs\", BlockTags.STAIRS, ItemTags.STAIRS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_wall\", BlockTags.WALLS, ItemTags.WALLS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_planks\", BlockTags.PLANKS, ItemTags.PLANKS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_button\", BlockTags.BUTTONS, ItemTags.BUTTONS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_door\", BlockTags.DOORS, ItemTags.DOORS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_trapdoor\", BlockTags.TRAPDOORS, ItemTags.TRAPDOORS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_fence\", BlockTags.FENCES, ItemTags.FENCES);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_fence_gate\", BlockTags.FENCE_GATES, ItemTags.FENCE_GATES);\n\t\t\ttagCheckSuffix(id, block, \"_pressure_plates\", BlockTags.PRESSURE_PLATES);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_leaves\", BlockTags.LEAVES, ItemTags.LEAVES);\n\t\t\ttagCheckSuffix(id, block, \"_wall_hanging_sign\", BlockTags.WALL_HANGING_SIGNS).ifFailed(\n\t\t\t\t\t() -> tagCheckSuffix(id, block, blockItem, \"_hanging_sign\", BlockTags.CEILING_HANGING_SIGNS, ItemTags.HANGING_SIGNS).or(\n\t\t\t\t\t\t\ttagCheckSuffix(id, block, \"_wall_sign\", BlockTags.WALL_SIGNS)\n\t\t\t\t\t)\n\t\t\t).ifFailed(\n\t\t\t\t\t() -> tagCheckSuffix(id, block, blockItem, \"_sign\", BlockTags.STANDING_SIGNS, ItemTags.SIGNS)\n\t\t\t);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_bed\", BlockTags.BEDS, ItemTags.BEDS);\n\t\t\ttagCheckPrefix(id, block, \"potted_\", BlockTags.FLOWER_POTS).ifFailed(\n\t\t\t\t\t() -> tagCheckSuffix(id, block, blockItem, \"_sapling\", BlockTags.SAPLINGS, ItemTags.SAPLINGS)\n\t\t\t);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_rail\", BlockTags.RAILS, ItemTags.RAILS);\n\t\t\ttagCheckSuffix(id, block, \"_cauldron\", BlockTags.CAULDRONS);\n\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_wool\", BlockTags.WOOL, ItemTags.WOOL);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_log\", BlockTags.LOGS, ItemTags.LOGS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_wood\", BlockTags.LOGS, ItemTags.LOGS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_stem\", BlockTags.LOGS, ItemTags.LOGS);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_hyphae\", BlockTags.LOGS, ItemTags.LOGS);\n\t\t\ttagCheckSuffix(id, block, \"_nylium\", BlockTags.NYLIUM);\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_sand\", BlockTags.SAND, ItemTags.SAND);\n\t\t\ttagCheckSuffix(id, \"_glazed_terracotta\").ifFailed(\n\t\t\t\t\t() -> tagCheckSuffix(id, block, blockItem, \"_terracotta\", BlockTags.TERRACOTTA, ItemTags.TERRACOTTA)\n\t\t\t);\n\n\t\t\ttagCheckSubstr(id, block, blockItem, \"gold\", BlockTags.GUARDED_BY_PIGLINS, ItemTags.PIGLIN_LOVED);\n\n\t\t\t//forge tags\n\t\t\ttagCheckSuffix(id, block, blockItem, \"_ore\", Tags.Blocks.ORES, Tags.Items.ORES).ifFailed(\n\t\t\t\t\t() -> tagCheckPrefix(id, block, blockItem, \"ore_\", Tags.Blocks.ORES, Tags.Items.ORES)\n\t\t\t);\n\t\t\ttagCheckSuffix(id, blockItem, \"_seed\", Tags.Items.SEEDS).ifFailed(\n\t\t\t\t\t() -> tagCheckPrefix(id, blockItem, \"seed_\", Tags.Items.SEEDS)\n\t\t\t);\n\n\t\t\tif(!WHITELIST_NO_LOOT_TABLE_BLOCKS.contains(block)) {\n\t\t\t\tif(block.getLootTable().equals(BuiltInLootTables.EMPTY) || lootDataManager.getLootTable(block.getLootTable()).equals(LootTable.EMPTY)) {\n\t\t\t\t\tSFLogger.warn(\"[Registry Check] Missing loot table for block %s.\".formatted(id));\n\t\t\t\t}\n\t\t\t\tif(block.defaultBlockState().requiresCorrectToolForDrops()) {\n\t\t\t\t\tcheckIn(id, block, \"mineable\", BlockTags.MINEABLE_WITH_AXE, BlockTags.MINEABLE_WITH_HOE, BlockTags.MINEABLE_WITH_PICKAXE, BlockTags.MINEABLE_WITH_SHOVEL);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tSet<Item> ENTRANCES = Util.make(Sets.newIdentityHashSet(), set -> set.addAll(ImmutableSet.of(\n\t\t\tItems.AIR, Items.BARRIER, Items.COMMAND_BLOCK, Items.END_PORTAL_FRAME, Items.JIGSAW, Items.LIGHT,\n\t\t\tItems.CHAIN_COMMAND_BLOCK, Items.STRUCTURE_BLOCK, Items.REPEATING_COMMAND_BLOCK, Items.STRUCTURE_VOID,\n\n\t\t\tItems.SUSPICIOUS_SAND, Items.SUSPICIOUS_GRAVEL, Items.BUNDLE, Items.FILLED_MAP,\n\t\t\tItems.WATER_BUCKET, Items.LAVA_BUCKET, Items.POWDER_SNOW_BUCKET, Items.MILK_BUCKET,\n\t\t\tItems.PUFFERFISH_BUCKET, Items.SALMON_BUCKET, Items.COD_BUCKET, Items.TROPICAL_FISH_BUCKET,\n\t\t\tItems.AXOLOTL_BUCKET, Items.TADPOLE_BUCKET,\n\t\t\tItems.EGG, Items.POTION, Items.SPLASH_POTION, Items.LINGERING_POTION,\n\t\t\tItems.DRAGON_EGG, Items.DRAGON_BREATH, Items.ENCHANTED_BOOK, Items.HONEYCOMB, Items.SCUTE, Items.NETHER_STAR,\n\t\t\tItems.CHIPPED_ANVIL, Items.DAMAGED_ANVIL,\n\n\t\t\tItems.CREEPER_HEAD, Items.PIGLIN_HEAD, Items.PLAYER_HEAD, Items.ZOMBIE_HEAD, Items.SKELETON_SKULL,\n\t\t\tItems.ENDER_DRAGON_SPAWN_EGG, Items.WITHER_SPAWN_EGG\n\t)));\n\n\t/**\n\t * API for recipe check.\n\t * @param item Natural resource item, not crafted by any other items.\n\t */\n\tstatic void addEntranceItem(Item item) {\n\t\tENTRANCES.add(item);\n\t}\n\n\tList<Pair<Item, Item>> EXTRA_RELATIONS = Util.make(Lists.newArrayList(), list -> list.addAll(ImmutableList.of(\n\t\t\tPair.of(Items.COPPER_BLOCK, Items.EXPOSED_COPPER),\n\t\t\tPair.of(Items.EXPOSED_COPPER, Items.WEATHERED_COPPER),\n\t\t\tPair.of(Items.WEATHERED_COPPER, Items.OXIDIZED_COPPER)\n\t)));\n\n\t/**\n\t * API for recipe check.\n\t * @param from For example, copper_block in copper_block -> exposed_copper relation.\n\t * @param to For example, exposed_copper in copper_block -> exposed_copper relation.\n\t */\n\tstatic void addRelation(Item from, Item to) {\n\t\tEXTRA_RELATIONS.add(Pair.of(from, to));\n\t}\n\n\t@SuppressWarnings(\"ConstantValue\")\n\tstatic void recipeCheck(LootDataManager lootDataManager, RecipeManager recipeManager, RegistryAccess registryAccess) {\n\t\tItemGraph graph = new ItemGraph();\n\t\trecipeManager.getRecipes().forEach(recipe -> {\n\t\t\tNonNullList<Ingredient> ingredients = recipe.getIngredients();\n\t\t\tif(recipe instanceof SmithingTransformRecipe smithingTransformRecipe) {\n\t\t\t\tingredients = NonNullList.create();\n\t\t\t\tingredients.add(smithingTransformRecipe.template);\n\t\t\t\tingredients.add(smithingTransformRecipe.base);\n\t\t\t\tingredients.add(smithingTransformRecipe.addition);\n\t\t\t}\n\t\t\tItemStack result = recipe.getResultItem(registryAccess);\n\t\t\tif(result != null) {\n\t\t\t\trecipe.getIngredients().forEach(\n\t\t\t\t\t\tingredient -> Arrays.stream(ingredient.getItems()).forEach(itemStack -> graph.addEdge(itemStack.getItem(), result.getItem()))\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t\tForgeRegistries.ENTITY_TYPES.forEach(entityType -> {\n\t\t\tif (!entityType.getDefaultLootTable().equals(BuiltInLootTables.EMPTY)) {\n\t\t\t\tLootTable table = lootDataManager.getLootTable(entityType.getDefaultLootTable());\n\t\t\t\tif (!table.equals(LootTable.EMPTY)) {\n\t\t\t\t\ttable.pools.forEach(pool -> Arrays.stream(pool.entries).forEach(entry -> {\n\t\t\t\t\t\tif (entry instanceof LootItem lootItem) {\n\t\t\t\t\t\t\taddEntranceItem(lootItem.item);\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tlootDataManager.elements.forEach((id, o) -> {\n\t\t\tif(id.type().equals(LootDataType.TABLE)) {\n\t\t\t\tLootTable table = (LootTable)o;\n\t\t\t\tResourceLocation type = LootContextParamSets.getKey(table.getParamSet());\n\t\t\t\tif(type != null && (\n\t\t\t\t\t\ttype.equals(new ResourceLocation(DEFAULT_NAMESPACE, \"chest\")) ||\n\t\t\t\t\t\t\t\ttype.equals(new ResourceLocation(DEFAULT_NAMESPACE, \"archaeology\")) ||\n\t\t\t\t\t\t\t\ttype.equals(new ResourceLocation(DEFAULT_NAMESPACE, \"fishing\"))\n\t\t\t\t)) {\n\t\t\t\t\tif (!table.equals(LootTable.EMPTY)) {\n\t\t\t\t\t\ttable.pools.forEach(pool -> Arrays.stream(pool.entries).forEach(entry -> {\n\t\t\t\t\t\t\tif (entry instanceof LootItem lootItem) {\n\t\t\t\t\t\t\t\taddEntranceItem(lootItem.item);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tEXTRA_RELATIONS.forEach(pair -> graph.addEdge(pair.getLeft(), pair.getRight()));\n\t\tObjects.requireNonNull(registryAccess.registry(Registries.CREATIVE_MODE_TAB).get().get(CreativeModeTabs.NATURAL_BLOCKS))\n\t\t\t\t.displayItemsGenerator.accept(null, (itemStack, ignored) -> addEntranceItem(itemStack.getItem()));\n\t\tObjects.requireNonNull(registryAccess.registry(Registries.CREATIVE_MODE_TAB).get().get(CreativeModeTabs.SPAWN_EGGS))\n\t\t\t\t.displayItemsGenerator.accept(null, (itemStack, ignored) -> addEntranceItem(itemStack.getItem()));\n\n\t\tForgeRegistries.ITEMS.forEach(item -> {\n\t\t\taddEdgesForLoot(item, graph, lootDataManager);\n\t\t\tif(item instanceof BlockItem blockItem) {\n\t\t\t\tBlock block = blockItem.getBlock();\n\t\t\t\tBlockState blockState;\n\t\t\t\tif((blockState = AxeItem.getAxeStrippingState(block.defaultBlockState())) != null) {\n\t\t\t\t\tgraph.addEdge(item, blockState.getBlock().asItem());\n\t\t\t\t}\n\t\t\t\tif((blockState = ShovelItem.getShovelPathingState(block.defaultBlockState())) != null) {\n\t\t\t\t\tgraph.addEdge(item, blockState.getBlock().asItem());\n\t\t\t\t}\n\t\t\t\tif(InfestedBlock.isCompatibleHostBlock(block.defaultBlockState())) {\n\t\t\t\t\tgraph.addEdge(item, InfestedBlock.infestedStateByHost(block.defaultBlockState()).getBlock().asItem());\n\t\t\t\t}\n\t\t\t\tif(block instanceof ConcretePowderBlock concretePowderBlock) {\n\t\t\t\t\tgraph.addEdge(item, concretePowderBlock.concrete.getBlock().asItem());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tENTRANCES.forEach(graph::visit);\n\n\t\tForgeRegistries.ITEMS.forEach(item -> graph.degreeIfNotVisited(item).ifPresent(\n\t\t\t\tdegree -> SFLogger.warn(\"[Recipe Check] Found a non-natural item %s without any recipes or loot tables (degree = %d).\".formatted(getRegistryName(item), degree))\n\t\t));\n\t}\n\n\tSet<Item> ITEMS_ALREADY_ADDED_EDGES = Sets.newIdentityHashSet();\n\tprivate static void addEdgesForLoot(Item item, ItemGraph graph, LootDataManager lootDataManager) {\n\t\tif(ITEMS_ALREADY_ADDED_EDGES.contains(item)) {\n\t\t\treturn;\n\t\t}\n\t\tITEMS_ALREADY_ADDED_EDGES.add(item);\n\t\tif (item instanceof BlockItem blockItem) {\n\t\t\tBlock block = blockItem.getBlock();\n\t\t\tif (!block.getLootTable().equals(BuiltInLootTables.EMPTY)) {\n\t\t\t\tLootTable table = lootDataManager.getLootTable(block.getLootTable());\n\t\t\t\tif (!table.equals(LootTable.EMPTY)) {\n\t\t\t\t\ttable.pools.forEach(pool -> Arrays.stream(pool.entries).forEach(entry -> addEdgeForLootTableEntry(item, entry, graph, lootDataManager)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void addEdgeForLootTableEntry(Item item, LootPoolEntryContainer entryContainer, ItemGraph graph, LootDataManager lootDataManager) {\n\t\tif (entryContainer instanceof LootItem lootItem) {\n\t\t\tgraph.addEdge(item, lootItem.item);\n\t\t} else if(entryContainer instanceof CompositeEntryBase compositeEntry) {\n\t\t\tArrays.stream(compositeEntry.children).forEach(entry -> addEdgeForLootTableEntry(item, entry, graph, lootDataManager));\n\t\t} else if(entryContainer instanceof LootTableReference lootTableReference) {\n\t\t\tLootTable table = lootDataManager.getLootTable(lootTableReference.name);\n\t\t\ttable.pools.forEach(pool -> Arrays.stream(pool.entries).forEach(entry -> addEdgeForLootTableEntry(item, entry, graph, lootDataManager)));\n\t\t}\n\t}\n\n\t@OnlyIn(Dist.CLIENT)\n\tstatic void i18nCheck() {\n\t\tForgeRegistries.BLOCKS.forEach(block -> {\n\t\t\tResourceLocation id = getRegistryName(block);\n\t\t\tif(!I18n.exists(block.getDescriptionId())) {\n\t\t\t\tSFLogger.warn(\"[I18n Check] Missing I18n for block %s.\".formatted(id));\n\t\t\t}\n\t\t});\n\t\tForgeRegistries.ITEMS.forEach(item -> {\n\t\t\tResourceLocation id = getRegistryName(item);\n\t\t\tif(!I18n.exists(item.getDescriptionId())) {\n\t\t\t\tSFLogger.warn(\"[I18n Check] Missing I18n for item %s.\".formatted(id));\n\t\t\t}\n\t\t});\n\t\tForgeRegistries.ENTITY_TYPES.forEach(entityType -> {\n\t\t\tResourceLocation id = getRegistryName(entityType);\n\t\t\tif(!I18n.exists(entityType.getDescriptionId())) {\n\t\t\t\tSFLogger.warn(\"[I18n Check] Missing I18n for entity type %s.\".formatted(id));\n\t\t\t}\n\t\t});\n\t\tForgeRegistries.SOUND_EVENTS.forEach(soundEvent -> {\n\t\t\tResourceLocation id = soundEvent.getLocation();\n\t\t\tWeighedSoundEvents weighedSoundEvents = Minecraft.getInstance().getSoundManager().getSoundEvent(id);\n\t\t\tif(weighedSoundEvents != null &&\n\t\t\t\t\tweighedSoundEvents.getSubtitle() instanceof MutableComponent translatableComponent &&\n\t\t\t\t\ttranslatableComponent.getContents() instanceof TranslatableContents translatableContents &&\n\t\t\t\t\t!I18n.exists(translatableContents.getKey())) {\n\t\t\t\tSFLogger.warn(\"[I18n Check] Missing I18n for subtitle of sound %s.\".formatted(id));\n\t\t\t}\n\t\t});\n\t}\n\n\tstatic CheckResult tagCheckSubstr(ResourceLocation id, String substr) {\n\t\treturn new CheckResult(id.getPath().contains(substr));\n\t}\n\tstatic CheckResult tagCheckSubstr(ResourceLocation id, Block block, Item blockItem, String substr, TagKey<Block> blockTag, TagKey<Item> itemTag) {\n\t\tif(id.getPath().contains(substr)) {\n\t\t\tboolean error = false;\n\t\t\tsubstr = substr.replace('_', ' ');\n\t\t\tif(!block.builtInRegistryHolder().is(blockTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s block %s is not in tag %s.\".formatted(substr, id, blockTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\tif(!blockItem.builtInRegistryHolder().is(itemTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s item %s is not in tag %s.\".formatted(substr, id, itemTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\tstatic CheckResult tagCheckSubstr(ResourceLocation id, Block block, String substr, TagKey<Block> blockTag) {\n\t\tif(id.getPath().contains(substr)) {\n\t\t\tboolean error = false;\n\t\t\tsubstr = substr.replace('_', ' ');\n\t\t\tif(!block.builtInRegistryHolder().is(blockTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s block %s is not in tag %s.\".formatted(substr, id, blockTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\tstatic CheckResult tagCheckSubstr(ResourceLocation id, Item item, String substr, TagKey<Item> itemTag) {\n\t\tif(id.getPath().contains(substr)) {\n\t\t\tboolean error = false;\n\t\t\tsubstr = substr.replace('_', ' ');\n\t\t\tif(!item.builtInRegistryHolder().is(itemTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s item %s is not in tag %s.\".formatted(substr, id, itemTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\n\tstatic CheckResult tagCheckSuffix(ResourceLocation id, String suffix) {\n\t\treturn new CheckResult(id.getPath().endsWith(suffix));\n\t}\n\tstatic CheckResult tagCheckSuffix(ResourceLocation id, Block block, Item blockItem, String suffix, TagKey<Block> blockTag, TagKey<Item> itemTag) {\n\t\tif(id.getPath().endsWith(suffix)) {\n\t\t\tboolean error = false;\n\t\t\tsuffix = suffix.substring(1).replace('_', ' ');\n\t\t\tif(!block.builtInRegistryHolder().is(blockTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s block %s is not in tag %s.\".formatted(suffix, id, blockTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\tif(!blockItem.builtInRegistryHolder().is(itemTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s item %s is not in tag %s.\".formatted(suffix, id, itemTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\tstatic CheckResult tagCheckSuffix(ResourceLocation id, Block block, String suffix, TagKey<Block> blockTag) {\n\t\tif(id.getPath().endsWith(suffix)) {\n\t\t\tboolean error = false;\n\t\t\tsuffix = suffix.substring(1).replace('_', ' ');\n\t\t\tif(!block.builtInRegistryHolder().is(blockTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s block %s is not in tag %s.\".formatted(suffix, id, blockTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\tstatic CheckResult tagCheckSuffix(ResourceLocation id, Item item, String suffix, TagKey<Item> itemTag) {\n\t\tif(id.getPath().endsWith(suffix)) {\n\t\t\tboolean error = false;\n\t\t\tsuffix = suffix.substring(1).replace('_', ' ');\n\t\t\tif(!item.builtInRegistryHolder().is(itemTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s item %s is not in tag %s.\".formatted(suffix, id, itemTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\n\tstatic CheckResult tagCheckPrefix(ResourceLocation id, String prefix) {\n\t\treturn new CheckResult(id.getPath().startsWith(prefix));\n\t}\n\tstatic CheckResult tagCheckPrefix(ResourceLocation id, Block block, Item blockItem, String prefix, TagKey<Block> blockTag, TagKey<Item> itemTag) {\n\t\tif(id.getPath().startsWith(prefix)) {\n\t\t\tboolean error = false;\n\t\t\tprefix = prefix.substring(0, prefix.length() - 1).replace('_', ' ');\n\t\t\tif(!block.builtInRegistryHolder().is(blockTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s block %s is not in tag %s.\".formatted(prefix, id, blockTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\tif(!blockItem.builtInRegistryHolder().is(itemTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s item %s is not in tag %s.\".formatted(prefix, id, itemTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\tstatic CheckResult tagCheckPrefix(ResourceLocation id, Block block, String prefix, TagKey<Block> blockTag) {\n\t\tif(id.getPath().startsWith(prefix)) {\n\t\t\tboolean error = false;\n\t\t\tprefix = prefix.substring(0, prefix.length() - 1).replace('_', ' ');\n\t\t\tif(!block.builtInRegistryHolder().is(blockTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s block %s is not in tag %s.\".formatted(prefix, id, blockTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\tstatic CheckResult tagCheckPrefix(ResourceLocation id, Item item, String prefix, TagKey<Item> itemTag) {\n\t\tif(id.getPath().startsWith(prefix)) {\n\t\t\tboolean error = false;\n\t\t\tprefix = prefix.substring(0, prefix.length() - 1).replace('_', ' ');\n\t\t\tif(!item.builtInRegistryHolder().is(itemTag)) {\n\t\t\t\tSFLogger.warn(\"[Registry Check] Likely %s item %s is not in tag %s.\".formatted(prefix, id, itemTag));\n\t\t\t\terror = true;\n\t\t\t}\n\t\t\treturn new CheckResult(true, error);\n\t\t}\n\t\treturn new CheckResult(false);\n\t}\n\n\t@SafeVarargs\n\tstatic CheckResult checkIn(ResourceLocation id, Block block, String tagDesc, TagKey<Block>... blockTags) {\n\t\tboolean error = true;\n\t\tHolder.Reference<Block> holder = block.builtInRegistryHolder();\n\t\tfor(TagKey<Block> blockTag: blockTags) {\n\t\t\tif(holder.is(blockTag)) {\n\t\t\t\terror = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(error) {\n\t\t\tSFLogger.warn(\"[Registry Check] Block %s is not in any of the `%s` tags.\".formatted(id, tagDesc));\n\t\t}\n\t\treturn new CheckResult(true, error);\n\t}\n\n\t@SafeVarargs\n\tstatic CheckResult checkNotIn(ResourceLocation id, Block block, TagKey<Block>... blockTags) {\n\t\tboolean error = false;\n\t\tHolder.Reference<Block> holder = block.builtInRegistryHolder();\n\t\tfor(TagKey<Block> blockTag: blockTags) {\n\t\t\tif(holder.is(blockTag)) {\n\t\t\t\terror = true;\n\t\t\t\tSFLogger.warn(\"[Registry Check] Block %s is not supposed to be in tag %s.\".formatted(id, blockTag));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn new CheckResult(true, error);\n\t}\n\n\tclass CheckResult {\n\t\tprivate final boolean matches;\n\t\tprivate final boolean error;\n\n\t\tpublic CheckResult(boolean matches) {\n\t\t\tthis(matches, false);\n\t\t}\n\n\t\tpublic CheckResult(boolean matches, boolean error) {\n\t\t\tthis.matches = matches;\n\t\t\tthis.error = error;\n\t\t}\n\n\t\tpublic CheckResult ifFailed(Supplier<CheckResult> next) {\n\t\t\treturn this.matches ? this : next.get();\n\t\t}\n\n\t\tpublic CheckResult ifError(Supplier<CheckResult> next) {\n\t\t\treturn this.error ? this : next.get();\n\t\t}\n\n\t\tpublic CheckResult or(CheckResult other) {\n\t\t\treturn new CheckResult(this.matches || other.matches, this.error || other.error);\n\t\t}\n\t}\n}" }, { "identifier": "SFLogger", "path": "src/main/java/com/hexagram2021/stellarforge/common/util/SFLogger.java", "snippet": "public class SFLogger {\n\tpublic static boolean debugMode = true;\n\t@SuppressWarnings(\"NotNullFieldNotInitialized\")\n\tpublic static Logger logger;\n\n\tpublic static void log(Level logLevel, Object object) {\n\t\tlogger.log(logLevel, String.valueOf(object));\n\t}\n\n\tpublic static void error(Object object) {\n\t\tlog(Level.ERROR, object);\n\t}\n\n\tpublic static void info(Object object) {\n\t\tlog(Level.INFO, object);\n\t}\n\n\tpublic static void warn(Object object) {\n\t\tlog(Level.WARN, object);\n\t}\n\n\tpublic static void error(String message, Object... params) {\n\t\tlogger.log(Level.ERROR, message, params);\n\t}\n\n\tpublic static void info(String message, Object... params) {\n\t\tlogger.log(Level.INFO, message, params);\n\t}\n\n\tpublic static void warn(String message, Object... params) {\n\t\tlogger.log(Level.WARN, message, params);\n\t}\n\n\tpublic static void debug(Object object) {\n\t\tif(debugMode) {\n\t\t\tlog(Level.INFO, \"[DEBUG:] \" + object);\n\t\t}\n\t}\n\n\tpublic static void debug(String format, Object... params) {\n\t\tif(debugMode) {\n\t\t\tinfo(\"[DEBUG:] \" + format, params);\n\t\t}\n\t}\n}" } ]
import com.hexagram2021.stellarforge.client.ClientProxy; import com.hexagram2021.stellarforge.common.SFContent; import com.hexagram2021.stellarforge.common.config.SFCommonConfig; import com.hexagram2021.stellarforge.common.util.RegistryChecker; import com.hexagram2021.stellarforge.common.util.SFLogger; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.server.ServerAboutToStartEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLLoader; import org.apache.logging.log4j.LogManager; import java.util.function.Supplier;
7,313
package com.hexagram2021.stellarforge; @Mod(StellarForge.MODID) public class StellarForge { public static final String MODID = "stellarforge"; public static final String MODNAME = "StellarForge"; public static final String VERSION = ModList.get().getModFileById(MODID).versionString(); public static <T> Supplier<T> bootstrapErrorToXCPInDev(Supplier<T> in) { if(FMLLoader.isProduction()) { return in; } return () -> { try { return in.get(); } catch(BootstrapMethodError e) { throw new RuntimeException(e); } }; } public StellarForge() { SFLogger.logger = LogManager.getLogger(MODID); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); SFContent.modConstruction(bus); DistExecutor.safeRunWhenOn(Dist.CLIENT, bootstrapErrorToXCPInDev(() -> ClientProxy::modConstruction));
package com.hexagram2021.stellarforge; @Mod(StellarForge.MODID) public class StellarForge { public static final String MODID = "stellarforge"; public static final String MODNAME = "StellarForge"; public static final String VERSION = ModList.get().getModFileById(MODID).versionString(); public static <T> Supplier<T> bootstrapErrorToXCPInDev(Supplier<T> in) { if(FMLLoader.isProduction()) { return in; } return () -> { try { return in.get(); } catch(BootstrapMethodError e) { throw new RuntimeException(e); } }; } public StellarForge() { SFLogger.logger = LogManager.getLogger(MODID); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); SFContent.modConstruction(bus); DistExecutor.safeRunWhenOn(Dist.CLIENT, bootstrapErrorToXCPInDev(() -> ClientProxy::modConstruction));
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, SFCommonConfig.getConfig());
2
2023-12-10 07:20:43+00:00
12k
gaetanBloch/jhlite-gateway
src/main/java/com/mycompany/myapp/shared/pagination/domain/JhipsterSampleApplicationPage.java
[ { "identifier": "JhipsterSampleApplicationCollections", "path": "src/main/java/com/mycompany/myapp/shared/collection/domain/JhipsterSampleApplicationCollections.java", "snippet": "public final class JhipsterSampleApplicationCollections {\n\n private JhipsterSampleApplicationCollections() {}\n\n /**\n * Get an immutable collection from the given collection\n *\n * @param <T>\n * Type of this collection\n * @param collection\n * input collection\n * @return An immutable collection\n */\n public static <T> Collection<T> immutable(Collection<T> collection) {\n if (collection == null) {\n return Set.of();\n }\n\n return Collections.unmodifiableCollection(collection);\n }\n\n /**\n * Get an immutable set from the given set\n *\n * @param <T>\n * Type of this set\n * @param set\n * input set\n * @return An immutable set\n */\n public static <T> Set<T> immutable(Set<T> set) {\n if (set == null) {\n return Set.of();\n }\n\n return Collections.unmodifiableSet(set);\n }\n\n /**\n * Get an immutable set from the given list\n *\n * @param <T>\n * Type of this list\n * @param list\n * input list\n * @return An immutable list\n */\n public static <T> List<T> immutable(List<T> list) {\n if (list == null) {\n return List.of();\n }\n\n return Collections.unmodifiableList(list);\n }\n\n /**\n * Get an immutable map from the given map\n *\n * @param <K> Key type of this map\n * @param <V> value type of this map\n * @return An immutable map\n */\n public static <K, V> Map<K, V> immutable(Map<K, V> map) {\n if (map == null) {\n return Map.of();\n }\n return Collections.unmodifiableMap(map);\n }\n}" }, { "identifier": "Assert", "path": "src/main/java/com/mycompany/myapp/shared/error/domain/Assert.java", "snippet": "public class Assert {\n\n private Assert() {}\n\n /**\n * Ensure that the input is not null\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * input to check\n * @throws MissingMandatoryValueException\n * if the input is null\n */\n public static void notNull(String field, Object input) {\n if (input == null) {\n throw MissingMandatoryValueException.forNullValue(field);\n }\n }\n\n /**\n * Ensure that the value is not blank (null, empty or only whitespace)\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * input to check\n * @throws MissingMandatoryValueException\n * if the input is blank\n */\n public static void notBlank(String field, String input) {\n Assert.field(field, input).notBlank();\n }\n\n /**\n * Ensure that the given collection is not empty\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param collection\n * collection to check\n * @throws MissingMandatoryValueException\n * if the collection is null or empty\n */\n public static void notEmpty(String field, Collection<?> collection) {\n field(field, collection).notEmpty();\n }\n\n /**\n * Ensure that the given map is not empty\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param map\n * map to check\n * @throws MissingMandatoryValueException\n * if the map is null or empty\n */\n public static void notEmpty(String field, Map<?, ?> map) {\n notNull(field, map);\n\n if (map.isEmpty()) {\n throw MissingMandatoryValueException.forEmptyValue(field);\n }\n }\n\n /**\n * Create a fluent asserter for {@link String}\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"name\", name)\n * .notBlank()\n * .maxLength(150);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * string to check\n * @return A {@link StringAsserter} for this field and value\n */\n public static StringAsserter field(String field, String input) {\n return new StringAsserter(field, input);\n }\n\n /**\n * Create a fluent asserter for Integer values (int and {@link Integer})\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"age\", age)\n * .min(0)\n * .max(150);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * value to check\n * @return An {@link IntegerAsserter} for this field and value\n */\n public static IntegerAsserter field(String field, Integer input) {\n return new IntegerAsserter(field, input);\n }\n\n /**\n * Create a fluent asserter for Long values (long and {@link Long})\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"duration\", duration)\n * .min(100)\n * .max(500_000);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * value to check\n * @return An {@link LongAsserter} for this field and value\n */\n public static LongAsserter field(String field, Long input) {\n return new LongAsserter(field, input);\n }\n\n /**\n * Create a fluent asserter for Float values (float and {@link Float})\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"rate\", rate)\n * .min(0)\n * .max(1);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * value to check\n * @return An {@link DoubleAsserter} for this field and value\n */\n public static FloatAsserter field(String field, Float input) {\n return new FloatAsserter(field, input);\n }\n\n /**\n * Create a fluent asserter for Double values (double and {@link Double})\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"rate\", rate)\n * .min(0)\n * .max(1);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * value to check\n * @return An {@link DoubleAsserter} for this field and value\n */\n public static DoubleAsserter field(String field, Double input) {\n return new DoubleAsserter(field, input);\n }\n\n /**\n * Create a fluent asserter for {@link BigDecimal} values\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"rate\", rate)\n * .min(0)\n * .max(1);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * value to check\n * @return An {@link BigDecimalAsserter} for this field and value\n */\n public static BigDecimalAsserter field(String field, BigDecimal input) {\n return new BigDecimalAsserter(field, input);\n }\n\n /**\n * Create a fluent asserter for {@link Collection}\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"name\", name)\n * .notEmpty()\n * .maxSize(150);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * collection to check\n * @return A {@link CollectionAsserter} for this field and value\n */\n public static <T> CollectionAsserter<T> field(String field, Collection<T> input) {\n return new CollectionAsserter<>(field, input);\n }\n\n /**\n * Create a fluent asserter for an array\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"name\", name)\n * .notEmpty()\n * .maxSize(150);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * array to check\n * @return A {@link ArrayAsserter} for this field and value\n */\n public static <T> ArrayAsserter<T> field(String field, T[] input) {\n return new ArrayAsserter<>(field, input);\n }\n\n /**\n * Create a fluent asserter for an Instant\n *\n * <p>\n * Usage:\n * </p>\n *\n * <pre>\n * <code>\n * Assert.field(\"date\", date)\n * .inPast()\n * .after(otherDate);\n * </code>\n * </pre>\n *\n * @param field\n * name of the field to check (will be displayed in exception message)\n * @param input\n * value to check\n * @return An {@link InstantAsserter} for this field and value\n */\n public static InstantAsserter field(String field, Instant input) {\n return new InstantAsserter(field, input);\n }\n\n /**\n * Asserter dedicated to {@link String} assertions\n */\n public static class StringAsserter {\n\n private final String field;\n private final String value;\n\n private StringAsserter(String field, String value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the value is not null\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the value is null\n */\n public StringAsserter notNull() {\n Assert.notNull(field, value);\n\n return this;\n }\n\n /**\n * Ensure that the value is not blank (null, empty or only whitespace)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the value is blank\n */\n public StringAsserter notBlank() {\n notNull();\n\n if (value.isBlank()) {\n throw MissingMandatoryValueException.forBlankValue(field);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is at least of the given length\n *\n * @param length\n * inclusive min length of the {@link String}\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the expected length is strictly positive and the value is null\n * @throws StringTooShortException\n * if the value is shorter than min length\n */\n public StringAsserter minLength(int length) {\n if (length <= 0 && value == null) {\n return this;\n }\n\n notNull();\n\n if (value.length() < length) {\n throw StringTooShortException.builder().field(field).value(value).minLength(length).build();\n }\n\n return this;\n }\n\n /**\n * Ensure that the given input value is not over the given length\n *\n * @param length\n * inclusive max length of the {@link String}\n * @return The current asserter\n * @throws StringTooLongException\n * if the value is longer than the max length\n */\n public StringAsserter maxLength(int length) {\n if (value == null) {\n return this;\n }\n\n if (value.length() > length) {\n throw StringTooLongException.builder().field(field).value(value).maxLength(length).build();\n }\n\n return this;\n }\n }\n\n /**\n * Asserter dedicated to Integer values (int and {@link Integer})\n */\n public static class IntegerAsserter {\n\n private final String field;\n private final Integer value;\n\n private IntegerAsserter(String field, Integer value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the input value is positive (0 is positive)\n *\n * @return The current asserters\n * @throws MissingMandatoryValueException\n * if the value is null\n * @throws NumberValueTooLowException\n * if the value is negative\n */\n public IntegerAsserter positive() {\n return min(0);\n }\n\n /**\n * Ensure that the input value is over the given value\n *\n * @param minValue\n * inclusive min value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooLowException\n * if the value is under min\n */\n public IntegerAsserter min(int minValue) {\n notNull(field, value);\n\n if (value.intValue() < minValue) {\n throw NumberValueTooLowException.builder().field(field).minValue(String.valueOf(minValue)).value(String.valueOf(value)).build();\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is under the given value\n *\n * @param maxValue\n * inclusive max value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is over max\n */\n public IntegerAsserter max(int maxValue) {\n notNull(field, value);\n\n if (value.intValue() > maxValue) {\n throw NumberValueTooHighException.builder().field(field).maxValue(String.valueOf(maxValue)).value(String.valueOf(value)).build();\n }\n\n return this;\n }\n }\n\n /**\n * Asserter dedicated to long values (long and {@link Long})\n */\n public static class LongAsserter {\n\n private final String field;\n private final Long value;\n\n private LongAsserter(String field, Long value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the input value is positive (0 is positive)\n *\n * @return The current asserters\n * @throws MissingMandatoryValueException\n * if the value is null\n * @throws NumberValueTooLowException\n * if the value is negative\n */\n public LongAsserter positive() {\n return min(0);\n }\n\n /**\n * Ensure that the input value is over the given value\n *\n * @param minValue\n * inclusive min value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooLowException\n * if the value is under min\n */\n public LongAsserter min(long minValue) {\n notNull(field, value);\n\n if (value.longValue() < minValue) {\n throw NumberValueTooLowException.builder().field(field).minValue(String.valueOf(minValue)).value(String.valueOf(value)).build();\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is under the given value\n *\n * @param maxValue\n * inclusive max value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is over max\n */\n public LongAsserter max(long maxValue) {\n notNull(field, value);\n\n if (value.longValue() > maxValue) {\n throw NumberValueTooHighException.builder().field(field).maxValue(String.valueOf(maxValue)).value(String.valueOf(value)).build();\n }\n\n return this;\n }\n }\n\n /**\n * Asserter dedicated to float values (float and {@link Float})\n */\n public static class FloatAsserter {\n\n private final String field;\n private final Float value;\n\n private FloatAsserter(String field, Float value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the input value is positive (0 is positive)\n *\n * @return The current asserters\n * @throws MissingMandatoryValueException\n * if the value is null\n * @throws NumberValueTooLowException\n * if the value is negative\n */\n public FloatAsserter positive() {\n return min(0);\n }\n\n /**\n * Ensure that the input value is strictly positive (0 is not strictly positive)\n *\n * @return The current asserters\n * @throws MissingMandatoryValueException\n * if the value is null\n * @throws NumberValueTooLowException\n * if the value is negative\n */\n public FloatAsserter strictlyPositive() {\n return over(0);\n }\n\n /**\n * Ensure that the input value is over the given value\n *\n * @param minValue\n * inclusive min value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooLowException\n * if the value is under min\n */\n public FloatAsserter min(float minValue) {\n notNull(field, value);\n\n if (value.floatValue() < minValue) {\n throw tooLow(minValue);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is over the given floor\n *\n * @param floor\n * exclusive floor value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is under floor\n */\n public FloatAsserter over(float floor) {\n notNull(field, value);\n\n if (value.floatValue() <= floor) {\n throw tooLow(floor);\n }\n\n return this;\n }\n\n private NumberValueTooLowException tooLow(float floor) {\n return NumberValueTooLowException.builder().field(field).minValue(String.valueOf(floor)).value(String.valueOf(value)).build();\n }\n\n /**\n * Ensure that the input value is under the given value\n *\n * @param maxValue\n * inclusive max value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is over max\n */\n public FloatAsserter max(float maxValue) {\n notNull(field, value);\n\n if (value.floatValue() > maxValue) {\n throw tooHigh(maxValue);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is under the given ceil\n *\n * @param ceil\n * exclusive ceil value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is over ceil\n */\n public FloatAsserter under(float ceil) {\n notNull(field, value);\n\n if (value.floatValue() >= ceil) {\n throw tooHigh(ceil);\n }\n\n return this;\n }\n\n private NumberValueTooHighException tooHigh(float ceil) {\n return NumberValueTooHighException.builder().field(field).maxValue(String.valueOf(ceil)).value(String.valueOf(value)).build();\n }\n }\n\n /**\n * Asserter dedicated to double values (double and {@link Double})\n */\n public static class DoubleAsserter {\n\n private final String field;\n private final Double value;\n\n private DoubleAsserter(String field, Double value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the input value is positive (0 is positive)\n *\n * @return The current asserters\n * @throws MissingMandatoryValueException\n * if the value is null\n * @throws NumberValueTooLowException\n * if the value is negative\n */\n public DoubleAsserter positive() {\n return min(0);\n }\n\n /**\n * Ensure that the input value is strictly positive (0 is not strictly positive)\n *\n * @return The current asserters\n * @throws MissingMandatoryValueException\n * if the value is null\n * @throws NumberValueTooLowException\n * if the value is negative\n */\n public DoubleAsserter strictlyPositive() {\n return over(0);\n }\n\n /**\n * Ensure that the input value is over the given value\n *\n * @param minValue\n * inclusive min value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooLowException\n * if the value is under min\n */\n public DoubleAsserter min(double minValue) {\n notNull(field, value);\n\n if (value.doubleValue() < minValue) {\n throw tooLow(minValue);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is over the given floor\n *\n * @param floor\n * exclusive floor value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is under floor\n */\n public DoubleAsserter over(double floor) {\n notNull(field, value);\n\n if (value.doubleValue() <= floor) {\n throw tooLow(floor);\n }\n\n return this;\n }\n\n private NumberValueTooLowException tooLow(double floor) {\n return NumberValueTooLowException.builder().field(field).minValue(String.valueOf(floor)).value(String.valueOf(value)).build();\n }\n\n /**\n * Ensure that the input value is under the given value\n *\n * @param maxValue\n * inclusive max value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is over max\n */\n public DoubleAsserter max(double maxValue) {\n notNull(field, value);\n\n if (value.doubleValue() > maxValue) {\n throw tooHigh(maxValue);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is under the given ceil\n *\n * @param ceil\n * exclusive ceil value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is over ceil\n */\n public DoubleAsserter under(double ceil) {\n notNull(field, value);\n\n if (value.doubleValue() >= ceil) {\n throw tooHigh(ceil);\n }\n\n return this;\n }\n\n private NumberValueTooHighException tooHigh(double ceil) {\n return NumberValueTooHighException.builder().field(field).maxValue(String.valueOf(ceil)).value(String.valueOf(value)).build();\n }\n }\n\n /**\n * Asserter dedicated to {@link BigDecimal} assertions\n */\n public static class BigDecimalAsserter {\n\n private final String field;\n private final BigDecimal value;\n\n private BigDecimalAsserter(String field, BigDecimal value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the input value is positive (0 is positive)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n * @throws NumberValueTooLowException\n * if the input value is negative\n */\n public BigDecimalAsserter positive() {\n return min(0);\n }\n\n /**\n * Ensure that the input value is strictly positive (0 is not strictly positive)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n * @throws NumberValueTooLowException\n * if the input value is negative\n */\n public BigDecimalAsserter strictlyPositive() {\n return over(0);\n }\n\n /**\n * Ensure that the input value is at least at min value\n *\n * @param minValue\n * inclusive min value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n * @throws NumberValueTooLowException\n * if the input value is under the min value\n */\n public BigDecimalAsserter min(long minValue) {\n return min(new BigDecimal(minValue));\n }\n\n /**\n * Ensure that the input value is at least at min value\n *\n * @param minValue\n * inclusive min value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input or min value is null\n * @throws NumberValueTooLowException\n * if the input value is under the min value\n */\n public BigDecimalAsserter min(BigDecimal minValue) {\n notNull();\n Assert.notNull(\"minValue\", minValue);\n\n if (value.compareTo(minValue) < 0) {\n throw tooLow(minValue);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is over the given floor\n *\n * @param floor\n * exclusive floor value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooLowException\n * if the value is under floor\n */\n public BigDecimalAsserter over(long floor) {\n return over(new BigDecimal(floor));\n }\n\n /**\n * Ensure that the input value is over the given floor\n *\n * @param floor\n * exclusive floor value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value or floor is null\n * @throws NumberValueTooLowException\n * if the value is under floor\n */\n public BigDecimalAsserter over(BigDecimal floor) {\n notNull();\n Assert.notNull(\"floor\", floor);\n\n if (value.compareTo(floor) <= 0) {\n throw tooLow(floor);\n }\n\n return this;\n }\n\n private NumberValueTooLowException tooLow(BigDecimal floor) {\n return NumberValueTooLowException.builder().field(field).minValue(String.valueOf(floor)).value(value.toPlainString()).build();\n }\n\n /**\n * Ensure that the input value is at most at max value\n *\n * @param maxValue\n * inclusive max value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n * @throws NumberValueTooHighException\n * if the input value is over max\n */\n public BigDecimalAsserter max(long maxValue) {\n return max(new BigDecimal(maxValue));\n }\n\n /**\n * Ensure that the input value is at most at max value\n *\n * @param maxValue\n * inclusive max value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input or max value is null\n * @throws NumberValueTooHighException\n * if the input value is over max\n */\n public BigDecimalAsserter max(BigDecimal maxValue) {\n notNull();\n Assert.notNull(\"maxValue\", maxValue);\n\n if (value.compareTo(maxValue) > 0) {\n throw tooHigh(maxValue);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input value is under the given ceil\n *\n * @param ceil\n * exclusive ceil value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value is null\n * @throws NumberValueTooHighException\n * if the value is under floor\n */\n public BigDecimalAsserter under(long ceil) {\n return under(new BigDecimal(ceil));\n }\n\n /**\n * Ensure that the input value is under the given ceil\n *\n * @param ceil\n * exclusive ceil value\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if value or ceil is null\n * @throws NumberValueTooHighException\n * if the value is under floor\n */\n public BigDecimalAsserter under(BigDecimal ceil) {\n notNull();\n Assert.notNull(\"ceil\", ceil);\n\n if (value.compareTo(ceil) >= 0) {\n throw tooHigh(ceil);\n }\n\n return this;\n }\n\n private NumberValueTooHighException tooHigh(BigDecimal ceil) {\n return NumberValueTooHighException.builder().field(field).maxValue(String.valueOf(ceil)).value(value.toPlainString()).build();\n }\n\n /**\n * Ensure that the input value is not null\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n */\n public BigDecimalAsserter notNull() {\n Assert.notNull(field, value);\n\n return this;\n }\n }\n\n /**\n * Asserter dedicated to {@link Collection} assertions\n */\n public static class CollectionAsserter<T> {\n\n private final String field;\n private final Collection<T> value;\n\n private CollectionAsserter(String field, Collection<T> value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the value is not null\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the value is null\n */\n public CollectionAsserter<T> notNull() {\n Assert.notNull(field, value);\n\n return this;\n }\n\n /**\n * Ensure that the value is not empty (null or empty)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the value is null or empty\n */\n public CollectionAsserter<T> notEmpty() {\n notNull();\n\n if (value.isEmpty()) {\n throw MissingMandatoryValueException.forEmptyValue(field);\n }\n\n return this;\n }\n\n /**\n * Ensure that the size of the given input value is not over the given size\n *\n * @param maxSize\n * inclusive max size of the {@link Collection}\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the expected size is strictly positive and the value is null\n * @throws TooManyElementsException\n * if the size of value is over the max size\n */\n public CollectionAsserter<T> maxSize(int maxSize) {\n if (maxSize <= 0 && value == null) {\n return this;\n }\n\n notNull();\n\n if (value.size() > maxSize) {\n throw TooManyElementsException.builder().field(field).maxSize(maxSize).size(value.size()).build();\n }\n\n return this;\n }\n\n /**\n * Ensure that no element in this {@link Collection} is null\n *\n * @return The current asserter\n * @throws NullElementInCollectionException\n * if an element is null\n */\n public CollectionAsserter<T> noNullElement() {\n if (value == null) {\n return this;\n }\n\n if (value.stream().anyMatch(Objects::isNull)) {\n throw new NullElementInCollectionException(field);\n }\n\n return this;\n }\n }\n\n /**\n * Asserter dedicated to arrays assertions\n */\n public static class ArrayAsserter<T> {\n\n private final String field;\n private final T[] value;\n\n private ArrayAsserter(String field, T[] value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the value is not null\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the value is null\n */\n public ArrayAsserter<T> notNull() {\n Assert.notNull(field, value);\n\n return this;\n }\n\n /**\n * Ensure that the value is not empty (null or empty)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the value is null or empty\n */\n public ArrayAsserter<T> notEmpty() {\n notNull();\n\n if (value.length == 0) {\n throw MissingMandatoryValueException.forEmptyValue(field);\n }\n\n return this;\n }\n\n /**\n * Ensure that the size of the given input value is not over the given size\n *\n * @param maxSize\n * inclusive max size of the array\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the expected size is strictly positive and the value is null\n * @throws TooManyElementsException\n * if the size of value is over the max size\n */\n public ArrayAsserter<T> maxSize(int maxSize) {\n if (maxSize <= 0 && value == null) {\n return this;\n }\n\n notNull();\n\n if (value.length > maxSize) {\n throw TooManyElementsException.builder().field(field).maxSize(maxSize).size(value.length).build();\n }\n\n return this;\n }\n\n /**\n * Ensure that no element in this array is null\n *\n * @return The current asserter\n * @throws NullElementInCollectionException\n * if an element is null\n */\n public ArrayAsserter<T> noNullElement() {\n if (value == null) {\n return this;\n }\n\n if (Stream.of(value).anyMatch(Objects::isNull)) {\n throw new NullElementInCollectionException(field);\n }\n\n return this;\n }\n }\n\n /**\n * Asserter dedicated to instant value\n */\n public static class InstantAsserter {\n\n private static final String OTHER_FIELD_NAME = \"other\";\n\n private final String field;\n private final Instant value;\n\n private InstantAsserter(String field, Instant value) {\n this.field = field;\n this.value = value;\n }\n\n /**\n * Ensure that the given instant is in the future or at current Instant (considering this method invocation time)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n * @throws NotAfterTimeException\n * if the input instant is in past\n */\n public InstantAsserter inFuture() {\n return afterOrAt(Instant.now());\n }\n\n /**\n * Ensure that the input instant is after the given instant\n *\n * @param other\n * exclusive after instant\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if input or other are null\n * @throws NotAfterTimeException\n * if the input instant is not after the other instant\n */\n public InstantAsserter after(Instant other) {\n notNull();\n Assert.notNull(OTHER_FIELD_NAME, other);\n\n if (value.compareTo(other) <= 0) {\n throw NotAfterTimeException.field(field, value).strictlyNotAfter(other);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input instant is after the given instant\n *\n * @param other\n * inclusive after instant\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if input or other are null\n * @throws NotAfterTimeException\n * if the input instant is not after the other instant\n */\n public InstantAsserter afterOrAt(Instant other) {\n notNull();\n Assert.notNull(OTHER_FIELD_NAME, other);\n\n if (value.compareTo(other) < 0) {\n throw NotAfterTimeException.field(field, value).notAfter(other);\n }\n\n return this;\n }\n\n /**\n * Ensure that the given instant is in the past or at current Instant (considering this method invocation time)\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the input value is null\n * @throws NotBeforeTimeException\n * if the input instant is in future\n */\n public InstantAsserter inPast() {\n return beforeOrAt(Instant.now());\n }\n\n /**\n * Ensure that the input instant is before the given instant\n *\n * @param other\n * exclusive before instant\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if input or other are null\n * @throws NotBeforeTimeException\n * if the input instant is not before the other instant\n */\n public InstantAsserter before(Instant other) {\n notNull();\n Assert.notNull(OTHER_FIELD_NAME, other);\n\n if (value.compareTo(other) >= 0) {\n throw NotBeforeTimeException.field(field, value).strictlyNotBefore(other);\n }\n\n return this;\n }\n\n /**\n * Ensure that the input instant is before the given instant\n *\n * @param other\n * inclusive before instant\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if input or other are null\n * @throws NotBeforeTimeException\n * if the input instant is not before the other instant\n */\n public InstantAsserter beforeOrAt(Instant other) {\n notNull();\n Assert.notNull(OTHER_FIELD_NAME, other);\n\n if (value.compareTo(other) > 0) {\n throw NotBeforeTimeException.field(field, value).notBefore(other);\n }\n\n return this;\n }\n\n /**\n * Ensure that the instant is not null\n *\n * @return The current asserter\n * @throws MissingMandatoryValueException\n * if the instant is null\n */\n public InstantAsserter notNull() {\n Assert.notNull(field, value);\n\n return this;\n }\n }\n}" } ]
import java.util.List; import java.util.function.Function; import com.mycompany.myapp.shared.collection.domain.JhipsterSampleApplicationCollections; import com.mycompany.myapp.shared.error.domain.Assert;
10,604
package com.mycompany.myapp.shared.pagination.domain; public class JhipsterSampleApplicationPage<T> { private static final int MINIMAL_PAGE_COUNT = 1; private final List<T> content; private final int currentPage; private final int pageSize; private final long totalElementsCount; private JhipsterSampleApplicationPage(JhipsterSampleApplicationPageBuilder<T> builder) { content = JhipsterSampleApplicationCollections.immutable(builder.content); currentPage = builder.currentPage; pageSize = buildPageSize(builder.pageSize); totalElementsCount = buildTotalElementsCount(builder.totalElementsCount); } private int buildPageSize(int pageSize) { if (pageSize == -1) { return content.size(); } return pageSize; } private long buildTotalElementsCount(long totalElementsCount) { if (totalElementsCount == -1) { return content.size(); } return totalElementsCount; } public static <T> JhipsterSampleApplicationPage<T> singlePage(List<T> content) { return builder(content).build(); } public static <T> JhipsterSampleApplicationPageBuilder<T> builder(List<T> content) { return new JhipsterSampleApplicationPageBuilder<>(content); } public static <T> JhipsterSampleApplicationPage<T> of(List<T> elements, JhipsterSampleApplicationPageable pagination) {
package com.mycompany.myapp.shared.pagination.domain; public class JhipsterSampleApplicationPage<T> { private static final int MINIMAL_PAGE_COUNT = 1; private final List<T> content; private final int currentPage; private final int pageSize; private final long totalElementsCount; private JhipsterSampleApplicationPage(JhipsterSampleApplicationPageBuilder<T> builder) { content = JhipsterSampleApplicationCollections.immutable(builder.content); currentPage = builder.currentPage; pageSize = buildPageSize(builder.pageSize); totalElementsCount = buildTotalElementsCount(builder.totalElementsCount); } private int buildPageSize(int pageSize) { if (pageSize == -1) { return content.size(); } return pageSize; } private long buildTotalElementsCount(long totalElementsCount) { if (totalElementsCount == -1) { return content.size(); } return totalElementsCount; } public static <T> JhipsterSampleApplicationPage<T> singlePage(List<T> content) { return builder(content).build(); } public static <T> JhipsterSampleApplicationPageBuilder<T> builder(List<T> content) { return new JhipsterSampleApplicationPageBuilder<>(content); } public static <T> JhipsterSampleApplicationPage<T> of(List<T> elements, JhipsterSampleApplicationPageable pagination) {
Assert.notNull("elements", elements);
1
2023-12-10 06:39:18+00:00
12k
zerodevstuff/ExploitFixerv2
src/main/java/dev/_2lstudios/exploitfixer/managers/ModuleManager.java
[ { "identifier": "NotificationsModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/NotificationsModule.java", "snippet": "public class NotificationsModule extends Module {\n private Server server;\n private Logger logger;\n private Map<String, Integer> packetDebug = new HashMap<>();\n private Collection<String> notifications = new HashSet<>();\n private boolean debug;\n private String message;\n\n // Violations done per category\n private Map<String, Double> categorizedVls = new HashMap<>();\n\n public void clearCategorizedVls() {\n this.categorizedVls.clear();\n }\n\n public Map<String, Double> getCategorizedVls() {\n return categorizedVls;\n }\n\n public void addCategorizedVl(String name, double amount) {\n if (amount <= 0) {\n return;\n }\n\n this.categorizedVls.put(name, this.categorizedVls.getOrDefault(name, 0D) + amount);\n }\n\n public NotificationsModule(Server server, Logger logger) {\n this.server = server;\n this.logger = logger;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void reload(IConfiguration configYml) {\n setName(\"Notifications\");\n setEnabled(configYml.getBoolean(\"notifications.enabled\"));\n this.debug = configYml.getBoolean(\"notifications.debug\");\n this.message = configYml.getString(\"notifications.message\").replace('&', '\\u00A7');\n }\n\n public void addPacketDebug(String packetType) {\n if (this.debug) {\n packetDebug.put(packetType, packetDebug.getOrDefault(packetType, 0) + 1);\n }\n }\n\n public void debugPackets() {\n if (!this.debug) {\n return;\n }\n\n if (!categorizedVls.isEmpty()) {\n StringBuilder stringBuilder = new StringBuilder();\n Set<Entry<String, Double>> entries = new HashSet<>(categorizedVls.entrySet());\n int total = 0;\n\n stringBuilder.append(\"Categorized Violations (x%total%):\");\n\n categorizedVls.clear();\n\n for (Entry<String, Double> vlsCategory : entries) {\n double value = (double) ((int) (vlsCategory.getValue() * 1000)) / 1000;\n\n if (value <= 0) {\n continue;\n }\n\n if (total++ != 0) {\n stringBuilder.append(\",\");\n }\n\n stringBuilder.append(\" \" + vlsCategory.getKey() + \" \" + value);\n }\n\n debug(stringBuilder.toString().replace(\"%total%\", String.valueOf(total)));\n }\n\n int total = 0;\n\n if (!packetDebug.isEmpty()) {\n StringBuilder stringBuilder = new StringBuilder();\n Set<Entry<String, Integer>> entries = new HashSet<>(packetDebug.entrySet());\n stringBuilder.append(\"Received Packets (x%total%):\");\n\n packetDebug.clear();\n\n for (Entry<String, Integer> packetEntry : entries) {\n String packetType = packetEntry.getKey();\n int amount = packetEntry.getValue();\n\n if (total != 0) {\n stringBuilder.append(\",\");\n }\n\n stringBuilder.append(\" x\").append(amount).append(\" \").append(packetType);\n total += amount;\n }\n\n debug(stringBuilder.toString().replace(\"%total%\", String.valueOf(total)));\n }\n }\n\n public void debug(String message) {\n if (this.debug) {\n this.logger.info(message);\n }\n }\n\n public void setNotifications(String playerName, boolean input) {\n if (input) {\n notifications.add(playerName);\n } else {\n notifications.remove(playerName);\n }\n }\n\n public boolean isNotifications(String playerName) {\n return notifications.contains(playerName);\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public Collection<String> getNotifications() {\n return notifications;\n }\n\n public void sendNotification(String check, ExploitPlayer player, int violations) {\n if (isEnabled() && player != null) {\n int ping = player.getPing();\n String notification = getMessage().replace(\"%player%\", player.getName()).replace(\"%check%\", check)\n .replace(\"%ping%\", String.valueOf(ping)).replace(\"%vls%\", String.valueOf(violations));\n String packets = player.getPacketsText();\n TextComponent textNotification = new TextComponent(notification);\n textNotification.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(packets).create()));\n\n server.getConsoleSender().sendMessage(notification);\n\n for (String notificationPlayerName : getNotifications()) {\n Player notificationPlayer = server.getPlayer(notificationPlayerName);\n\n if (notificationPlayer != null) {\n notificationPlayer.spigot().sendMessage(textNotification);\n }\n }\n }\n }\n}" }, { "identifier": "ItemAnalysisModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/ItemAnalysisModule.java", "snippet": "public class ItemAnalysisModule extends ViolationModule {\n private double vls;\n\n\tpublic void reload(IConfiguration config) {\n\t\tString prefix = \"item-analysis.\";\n\t\tsetName(\"ItemAnalysis\");\n\n\t\tsetEnabled(config.getBoolean(prefix + \"enabled\", true));\n\t\tsetCancelVls(config.getDouble(prefix + \"cancel_vls\", 1));\n\t\tsetReduceVls(config.getDouble(prefix + \"reduce_vls\", 1));\n vls = config.getDouble(prefix + \"vls\", 1);\n\t\tsetViolations(new Violations(config.getSection(prefix + \"violations\")));\n\t}\n\n public double getVls() {\n return vls;\n }\n}" }, { "identifier": "PatcherModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/PatcherModule.java", "snippet": "public class PatcherModule extends Module {\n\tprivate boolean nullChunk;\n\tprivate boolean selfDamage;\n\tprivate boolean disableTracking;\n\tprivate boolean enderPortalBreak;\n\tprivate boolean dispenserCrash;\n\tprivate boolean portalCrash;\n\tprivate boolean inventoryExploit;\n\tprivate boolean closeUnloadedEntitiesInventories;\n\tprivate boolean bowBomb;\n\tprivate boolean offlinePackets;\n\tprivate boolean endGateway;\n\tprivate boolean godMode;\n\tprivate boolean bedDuplication;\n\tprivate boolean redstoneTrapdoorCrash;\n\n\tpublic void reload(IConfiguration configYml) {\n\t\tsetName(\"Patcher\");\n\t\tString name = getName().toLowerCase();\n\n\t\tnullChunk = configYml.getBoolean(name + \".null_chunk\", true);\n\t\tselfDamage = configYml.getBoolean(name + \".self_damage\", true);\n\t\tdisableTracking = configYml.getBoolean(name + \".disable_tracking\", true);\n\t\tenderPortalBreak = configYml.getBoolean(name + \".ender_portal_break\", true);\n\t\tdispenserCrash = configYml.getBoolean(name + \".dispenser_crash\", true);\n\t\tportalCrash = configYml.getBoolean(name + \".portal_crash\", true);\n\t\tinventoryExploit = configYml.getBoolean(name + \".inventory_exploit\", true);\n\t\tcloseUnloadedEntitiesInventories = configYml.getBoolean(name + \".close_unloaded_entities_inventories\", true);\n\t\tbowBomb = configYml.getBoolean(name + \".bow_bomb\", true);\n\t\tofflinePackets = configYml.getBoolean(name + \".offline_packets\", true);\n\t\tendGateway = configYml.getBoolean(name + \".end_gateway\", true);\n\t\tgodMode = configYml.getBoolean(name + \".god_mode\", true);\n\t\tbedDuplication = configYml.getBoolean(name + \".bed_duplication\", true);\n\t\tredstoneTrapdoorCrash = configYml.getBoolean(name + \".redstone_trapdoor_crash\", true);\n\t}\n\n\tpublic boolean isSelfDamage() {\n\t\treturn selfDamage;\n\t}\n\n\tpublic boolean isNullChunk() {\n\t\treturn nullChunk;\n\t}\n\n public boolean isDisableTracking() {\n return disableTracking;\n }\n\n public boolean isEnderPortalBreak() {\n return enderPortalBreak;\n }\n\n public boolean isDispenserCrash() {\n return dispenserCrash;\n }\n\n public boolean isPortalCrash() {\n return portalCrash;\n }\n\n public boolean isInventoryExploit() {\n return inventoryExploit;\n }\n\n\tpublic boolean isBowBomb() {\n\t\treturn bowBomb;\n\t}\n\n\tpublic boolean isOfflinePackets() {\n\t\treturn offlinePackets;\n\t}\n\n public boolean isEndGateway() {\n return endGateway;\n }\n\n\tpublic boolean isGodMode() {\n\t\treturn godMode;\n\t}\n\n public boolean isCloseUnloadedEntitiesInventories() {\n return closeUnloadedEntitiesInventories;\n }\n\n public boolean isBedDuplication() {\n return bedDuplication;\n }\n\n public boolean isRedstoneTrapdoorCrash() {\n return redstoneTrapdoorCrash;\n }\n}" }, { "identifier": "ConfigUtil", "path": "src/main/java/dev/_2lstudios/exploitfixer/utils/ConfigUtil.java", "snippet": "public class ConfigUtil {\n\tprivate static String DATA_FOLDER_PLACEHOLDER = \"%datafolder%\";\n\tprivate String dataFolderPath;\n\tprivate Logger logger;\n\tprivate Plugin plugin;\n\tprivate BukkitScheduler scheduler;\n\tprivate ClassLoader classLoader;\n\n\tpublic ConfigUtil(Plugin plugin) {\n\t\tthis.plugin = plugin;\n\t\tthis.scheduler = plugin.getServer().getScheduler();\n\t\tthis.logger = plugin.getLogger();\n\t\tthis.classLoader = plugin.getClass().getClassLoader();\n\t\tthis.dataFolderPath = plugin.getDataFolder().toString();\n\t}\n\n\tprivate void createParentFolder(File file) {\n\t\tFile parentFile = file.getParentFile();\n\n\t\tif (parentFile != null) {\n\t\t\tparentFile.mkdirs();\n\t\t}\n\t}\n\n\tpublic IConfiguration get(String path) {\n\t\tFile file = new File(path.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath));\n\n\t\tif (file.exists()) {\n\t\t\treturn new BukkitConfiguration(YamlConfiguration.loadConfiguration(file));\n\t\t} else {\n\t\t\treturn new BukkitConfiguration(new YamlConfiguration());\n\t\t}\n\t}\n\n\tpublic void create(String rawPath, String resourcePath) {\n\t\tString path = rawPath.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath);\n\n\t\ttry {\n\t\t\tFile configFile = new File(path);\n\n\t\t\tif (!configFile.exists()) {\n\t\t\t\tInputStream inputStream = classLoader.getResourceAsStream(resourcePath);\n\n\t\t\t\tcreateParentFolder(configFile);\n\n\t\t\t\tif (inputStream != null) {\n\t\t\t\t\tFiles.copy(inputStream, configFile.toPath());\n\t\t\t\t} else {\n\t\t\t\t\tconfigFile.createNewFile();\n\t\t\t\t}\n\n\t\t\t\tlogger.info(\"File '\" + path + \"' has been created!\");\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tlogger.info(\"Unable to create '\" + path + \"'!\");\n\t\t}\n\t}\n\n\tpublic void save(IConfiguration configuration, String rawPath) {\n\t\tString path = rawPath.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath);\n\n\t\tscheduler.runTaskAsynchronously(plugin, () -> {\n\t\t\ttry {\n\t\t\t\t((YamlConfiguration) configuration.getObject()).save(path);\n\n\t\t\t\tlogger.info(\"File '\" + path + \"' has been saved!\");\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.info(\"Unable to save '\" + path + \"'!\");\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void delete(String rawPath) {\n\t\tString path = rawPath.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath);\n\n\t\tscheduler.runTaskAsynchronously(plugin, () -> {\n\t\t\ttry {\n\t\t\t\tFiles.delete(new File(path).toPath());\n\n\t\t\t\tlogger.info(\"File '\" + path + \"' has been removed!\");\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.info(\"Unable to remove '\" + path + \"'!\");\n\t\t\t}\n\t\t});\n\t}\n}" }, { "identifier": "CreativeItemsFixModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/CreativeItemsFixModule.java", "snippet": "public class CreativeItemsFixModule extends Module {\n\tprivate Plugin plugin;\n\tprivate int enchantLimit;\n\tprivate int maxStackSize;\n\tprivate Collection<String> blacklist;\n\tprivate String bypassPermission;\n\tprivate boolean useGameProfile;\n\n\t// Whitelist already created items\n\tprivate boolean whitelistItems;\n\tprivate Collection<ItemStack> fixed = new HashSet<>();\n\n\tpublic CreativeItemsFixModule(Plugin plugin) {\n\t\tthis.plugin = plugin;\n\t\tString version = Bukkit.getServer().getClass().getPackage().getName().split(\"\\\\.\")[3];\n\t\tthis.useGameProfile = \n\t\t\t\t!version.startsWith(\"v1_17\") && !version.startsWith(\"v1_16\")\n && !version.startsWith(\"v1_15\") && !version.startsWith(\"v1_14\")\n && !version.startsWith(\"v1_13\") && !version.startsWith(\"v1_12\")\n && !version.startsWith(\"v1_11\") && !version.startsWith(\"v1_10\")\n && !version.startsWith(\"v1_9\") && !version.startsWith(\"v1_8\");\n\t}\n\n\tpublic void reload(IConfiguration configYml) {\n\t\tString prefix = \"creative-items-fix.\";\n\n\t\tsetEnabled(configYml.getBoolean(prefix + \"enabled\"));\n\t\tsetName(\"Creative Items Fix\");\n\t\tthis.enchantLimit = configYml.getInt(prefix + \"enchant-limit\");\n\t\tthis.maxStackSize = configYml.getInt(prefix + \"max-stack-size\");\n\t\tthis.blacklist = configYml.getStringList(prefix + \"blacklist\");\n\t\tthis.whitelistItems = configYml.getBoolean(prefix + \"whitelist-items\");\n\t\tthis.bypassPermission = configYml.getString(prefix + \"bypass-permission\");\n\t}\n\n\tpublic int getEnchantLimit() {\n\t\treturn enchantLimit;\n\t}\n\n\tpublic int getMaxStackSize() {\n\t\treturn maxStackSize;\n\t}\n\n\tpublic Collection<String> getBlacklist() {\n\t\treturn blacklist;\n\t}\n\n\tpublic String getBypassPermission() {\n return bypassPermission;\n }\n\n\tpublic void setWhitelisted(ItemStack inventoryItem) {\n\t\tfixed.add(inventoryItem);\n\t}\n\n public boolean isWhitelisted(ItemStack item) {\n return fixed.contains(item);\n }\n\n\tpublic boolean isWhitelistItems() {\n\t\treturn whitelistItems;\n\t}\n\n\tpublic ItemStack fixItem(ItemStack item) {\n\t\tMaterial material = Material.getMaterial(item.getType().name());\n\t\tItemMeta newItemMeta = plugin.getServer().getItemFactory().getItemMeta(material);\n\t\tshort durability = item.getDurability();\n\n\t\tif (item.hasItemMeta()) {\n\t\t\tItemMeta oldItemMeta = item.getItemMeta();\n\t\t\tString displayName = oldItemMeta.getDisplayName();\n\t\t\tList<String> lore = oldItemMeta.getLore();\n\t\t\t// This applies vanilla levels to enchants\n\t\t\tboolean ignoreLevelRestriction = enchantLimit > 0;\n\n\t\t\ttry {\n\t\t\t\tif (oldItemMeta.hasCustomModelData()) {\n\t\t\t\t\tnewItemMeta.setCustomModelData(oldItemMeta.getCustomModelData());\n\t\t\t\t}\n\t\t\t} catch (NoSuchMethodError ex) {\n\t\t\t\t// Does not support customModelData\n\t\t\t}\n\n\t\t\tif (oldItemMeta instanceof EnchantmentStorageMeta) {\n\t\t\t\tEnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) oldItemMeta;\n\t\t\t\tEnchantmentStorageMeta newEnchantmentStorageMeta = (EnchantmentStorageMeta) newItemMeta;\n\n\t\t\t\tfor (Entry<Enchantment, Integer> entry : enchantmentStorageMeta.getStoredEnchants().entrySet()) {\n\t\t\t\t\tEnchantment enchantment = entry.getKey();\n\t\t\t\t\tint level = Math.min(entry.getValue(), enchantLimit > 0 ? enchantLimit : 5);\n\n\t\t\t\t\tif (enchantLimit > -1 && level > -1) {\n\t\t\t\t\t\tnewEnchantmentStorageMeta.addStoredEnchant(enchantment, level, ignoreLevelRestriction);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {\n\t\t\t\t\tEnchantment enchantment = entry.getKey();\n\t\t\t\t\tint level = Math.min(entry.getValue(), enchantLimit > 0 ? enchantLimit : 5);\n\n\t\t\t\t\tif (enchantLimit > -1 && level > -1) {\n\t\t\t\t\t\tnewItemMeta.addEnchant(enchantment, level, ignoreLevelRestriction);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newItemMeta instanceof BookMeta) {\n\t\t\t\tBookMeta oldBookMeta = (BookMeta) oldItemMeta;\n\t\t\t\tBookMeta newBookMeta = (BookMeta) newItemMeta;\n\n\t\t\t\tnewBookMeta.setTitle(oldBookMeta.getTitle());\n\t\t\t\tnewBookMeta.setAuthor(oldBookMeta.getAuthor());\n\t\t\t\tnewBookMeta.setPages(oldBookMeta.getPages());\n\t\t\t} else if (newItemMeta instanceof SkullMeta) {\n\t\t\t\tSkullMeta oldSkullMeta = (SkullMeta) oldItemMeta;\n\t\t\t\tSkullMeta newSkullMeta = (SkullMeta) newItemMeta;\n\n\t\t\t\tif (useGameProfile) {\n\t\t\t\t\tnewSkullMeta.setOwnerProfile(oldSkullMeta.getOwnerProfile());\n\t\t\t\t} else {\n\t\t\t\t\tnewSkullMeta.setOwner(oldSkullMeta.getOwner());\n\t\t\t\t}\n\t\t\t} else if (newItemMeta instanceof BannerMeta) {\n\t\t\t\tBannerMeta oldBannerMeta = (BannerMeta) oldItemMeta;\n\t\t\t\tBannerMeta newBannerMeta = (BannerMeta) newItemMeta;\n\n\t\t\t\tnewBannerMeta.setBaseColor(oldBannerMeta.getBaseColor());\n\t\t\t} else if (newItemMeta instanceof LeatherArmorMeta) {\n\t\t\t\tLeatherArmorMeta oldLeatherArmorMeta = (LeatherArmorMeta) oldItemMeta;\n\t\t\t\tLeatherArmorMeta newLeatherArmorMeta = (LeatherArmorMeta) newItemMeta;\n\n\t\t\t\tnewLeatherArmorMeta.setColor(oldLeatherArmorMeta.getColor());\n\t\t\t}\n\n\t\t\tif (displayName != null && displayName.getBytes().length < 128) {\n\t\t\t\tnewItemMeta.setDisplayName(displayName);\n\t\t\t}\n\n\t\t\tif (lore != null && lore.toString().getBytes().length < 1024) {\n\t\t\t\tnewItemMeta.setLore(lore);\n\t\t\t}\n\t\t}\n\n\t\tif (maxStackSize > 0 && item.getAmount() > maxStackSize) {\n\t\t\titem.setAmount(maxStackSize);\n\t\t}\n\n\t\titem.setType(material);\n\t\titem.setItemMeta(newItemMeta);\n\t\titem.setDurability(durability);\n\n\t\treturn item;\n\t}\n}" }, { "identifier": "IConfiguration", "path": "src/main/java/dev/_2lstudios/exploitfixer/configuration/IConfiguration.java", "snippet": "public interface IConfiguration {\n public IConfiguration getSection(String string);\n\n public Collection<String> getKeys();\n\n public Collection<String> getStringList(String string);\n\n public String getString(String path);\n\n public String getString(String path, String def);\n\n public double getDouble(String path);\n\n public double getDouble(String path, double def);\n\n public long getLong(String path);\n\n public int getInt(String path);\n\n public boolean getBoolean(String path);\n\n public boolean getBoolean(String path, boolean def);\n\n public Object getObject();\n\n public boolean contains(String string);\n}" }, { "identifier": "CommandsModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/CommandsModule.java", "snippet": "public class CommandsModule extends ViolationModule {\n\tprivate static Pattern SYNTAX_PATTERN = Pattern.compile(\"[a-z0-9-]{1,}:\");\n\n\tprivate Collection<String> commands;\n\tprivate String bypassPermission;\n\tprivate double vls;\n\n\tpublic void reload(IConfiguration configYml) {\n\t\tsetName(\"Commands\");\n\t\tsetEnabled(configYml.getBoolean(\"commands.enabled\", true));\n\t\tsetCancelVls(configYml.getDouble(\"commands.cancel_vls\", 1D));\n\t\tsetReduceVls(configYml.getDouble(\"commands.reduce_vls\", 1D));\n\t\tsetViolations(new Violations(configYml.getSection(\"commands.violations\")));\n\t\tthis.vls = configYml.getDouble(\"commands.vls\", 1D);\n\t\tthis.commands = configYml.getStringList(\"commands.commands\");\n\t\tthis.bypassPermission = configYml.getString(\"commands.bypass-permission\");\n\t}\n\n\tpublic boolean isCommand(String rawMessage) {\n\t\tif (rawMessage != null) {\n\t\t\tString message = SYNTAX_PATTERN.matcher(rawMessage).replaceAll(\"\").toLowerCase();\n\n\t\t\tfor (String command : commands) {\n\t\t\t\tif (message.startsWith(command)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic String getBypassPermission() {\n\t\treturn bypassPermission;\n\t}\n\n\tpublic double getVls() {\n\t\treturn vls;\n\t}\n}" }, { "identifier": "ConnectionModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/ConnectionModule.java", "snippet": "public class ConnectionModule extends PunishmentModule {\n\tprivate boolean nullAddressEnabled;\n\n\tpublic void reload(IConfiguration configYml) {\n\t\tthis.nullAddressEnabled = configYml.getBoolean(\"connection.null_address\");\n\t\tsetName(\"Connection\");\n\t\tsetPunishments(configYml.getStringList(\"connection.punishments\"));\n\t}\n\n\tpublic boolean isNullAddressEnabled() {\n\t\treturn nullAddressEnabled;\n\t}\n}" }, { "identifier": "MessagesModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/MessagesModule.java", "snippet": "public class MessagesModule extends Module {\n private static String NOTFOUND_STRING = \"<STRING_%PATH%_NOT_FOUND>\";\n private ConfigUtil configurationUtil;\n private Logger logger;\n private String version;\n private Map<String, Map<String, String>> locales = new HashMap<>();\n private Collection<String> defaultLocales = new HashSet<>();\n private String web;\n private String defaultLocale;\n\n public MessagesModule(ConfigUtil configurationUtil, Logger logger, String version) {\n this.configurationUtil = configurationUtil;\n this.logger = logger;\n this.version = version;\n\n setName(\"Messages\");\n\n defaultLocales.add(\"de\");\n defaultLocales.add(\"en\");\n defaultLocales.add(\"es\");\n defaultLocales.add(\"fr\");\n defaultLocales.add(\"he\");\n defaultLocales.add(\"hu\");\n defaultLocales.add(\"it\");\n defaultLocales.add(\"ja\");\n defaultLocales.add(\"ko\");\n defaultLocales.add(\"nl\");\n defaultLocales.add(\"pl\");\n defaultLocales.add(\"pt\");\n defaultLocales.add(\"ro\");\n defaultLocales.add(\"ru\");\n defaultLocales.add(\"th\");\n defaultLocales.add(\"tr\");\n defaultLocales.add(\"zh\");\n defaultLocales.add(\"zhtw\");\n }\n\n public void putSection(IConfiguration langFile, Map<String, String> locale, String currentPath) {\n for (String key : langFile.getKeys()) {\n IConfiguration section = langFile.getSection(key);\n\n if (section != null) {\n if (currentPath.isEmpty()) {\n putSection(section, locale, key);\n } else {\n putSection(section, locale, currentPath + \".\" + key);\n }\n } else {\n if (currentPath.isEmpty()) {\n locale.put(key, langFile.getString(key));\n } else {\n locale.put(currentPath + \".\" + key, langFile.getString(key));\n }\n }\n }\n }\n\n public void reload(IConfiguration configYml, File localeFolder) {\n web = configYml.getString(\"web\", \"<WEB_NOT_FOUND> (Reset ExploitFixer config file)\");\n defaultLocale = configYml.getString(\"locale\", \"en\").toLowerCase();\n\n for (String locale : defaultLocales) {\n configurationUtil.create(\"%datafolder%/locales/\" + locale + \".yml\", \"locales/\" + locale + \".yml\");\n }\n\n for (File file : localeFolder.listFiles()) {\n String fileName = file.getName();\n\n try {\n IConfiguration langFile = configurationUtil.get(file.toPath().toString());\n Map<String, String> locale = new HashMap<>();\n\n putSection(langFile, locale, \"\");\n\n locales.put(fileName.substring(0, 2).toLowerCase(), locale);\n } catch (Exception ex) {\n logger.info(\n \"Wasn't able to load locale \" + fileName + \" because of a \" + ex.getClass().getName() + \"!\");\n }\n }\n }\n\n public String getString(String locale, String path) {\n String string;\n\n if (locale != null && locales.containsKey(locale)) {\n string = locales.get(locale).getOrDefault(path, NOTFOUND_STRING.replace(\"%PATH%\", path.toUpperCase()));\n } else if (locales.containsKey(defaultLocale)) {\n string = locales.get(defaultLocale).getOrDefault(path,\n NOTFOUND_STRING.replace(\"%PATH%\", path.toUpperCase()));\n } else if (locale != null) {\n string = NOTFOUND_STRING.replace(\"%PATH%\", locale.toUpperCase());\n } else {\n string = NOTFOUND_STRING.replace(\"%PATH%\", \"<NULL>\");\n }\n\n return string.replace(\"%version%\", version).replace(\"%web%\", web).replace('&', '\\u00a7');\n }\n\n public String getReload(String locale) {\n return getString(locale, \"commands.reload\");\n }\n\n public String getHelp(String locale) {\n return getString(locale, \"commands.help\");\n }\n\n public String getUnknown(String locale) {\n return getString(locale, \"commands.error.unknown\");\n }\n\n public String getPermission(String locale) {\n return getString(locale, \"commands.error.permission\");\n }\n\n public String getConsole(String locale) {\n return getString(locale, \"commands.error.console\");\n }\n\n public String getEnable(String locale) {\n return getString(locale, \"commands.notifications.enable\");\n }\n\n public String getDisable(String locale) {\n return getString(locale, \"commands.notifications.disable\");\n }\n\n public String getKickMessage(Module module, String locale) {\n return getString(locale, \"modules.\" + module.getName().toLowerCase() + \".kick_message\");\n }\n\n public String getKickMessage(String module, String locale) {\n return getString(locale, \"modules.\" + module.toLowerCase() + \".kick_message\");\n }\n\n public String getStats(String locale) {\n return getString(locale, \"commands.stats\");\n }\n\n public String getMojangDown(String locale) {\n return getString(locale, \"mojang_down\");\n }\n}" }, { "identifier": "PacketsModule", "path": "src/main/java/dev/_2lstudios/exploitfixer/modules/PacketsModule.java", "snippet": "public class PacketsModule extends ViolationModule {\n\tprivate Map<String, Double> rateMultipliers = new HashMap<>();\n\tprivate Collection<String> blacklist = new HashSet<>();\n\tprivate double dataVls, bookVls, tagVls, blockDigVls, blockPlaceVls, setCreativeSlot, windowClick, byteMultiplier;\n\tprivate int dataMaxSizeBook, dataMaxSizeSign, dataMaxSize, dataMaxFlags, dataMaxFireworkFlags;\n\tprivate String bypassPermission;\n\n\tpublic void reload(IConfiguration configYml) {\n\t\tsetName(\"Packets\");\n\t\tString name = getName().toLowerCase();\n\t\tIConfiguration rateMultipliersSection = configYml.getSection(name + \".rate_multipliers\");\n\n\t\tsetEnabled(configYml.getBoolean(name + \".enabled\"));\n\t\tsetCancelVls(configYml.getDouble(name + \".cancel_vls\"));\n\t\tsetReduceVls(configYml.getDouble(name + \".reduce_vls\"));\n\t\tsetViolations(new Violations(configYml.getSection(name + \".violations\")));\n\t\tthis.dataVls = configYml.getDouble(name + \".data.vls\");\n\t\tthis.bookVls = configYml.getDouble(name + \".book\");\n\t\tthis.tagVls = configYml.getDouble(name + \".tag\");\n\t\tthis.dataMaxSize = configYml.getInt(name + \".data.max_size\");\n\t\tthis.dataMaxSizeBook = configYml.getInt(name + \".data.max_size_book\");\n\t\tthis.dataMaxSizeSign = configYml.getInt(name + \".data.max_size_sign\");\n\t\tthis.dataMaxFlags = configYml.getInt(name + \".data.max_flags\");\n\t\tthis.dataMaxFireworkFlags = configYml.getInt(name + \".data.max_firework_flags\");\n\t\tthis.byteMultiplier = configYml.getDouble(name + \".byte_multiplier\");\n\t\tthis.windowClick = configYml.getDouble(name + \".window_click\");\n\t\tthis.blockPlaceVls = configYml.getDouble(name + \".block_place\");\n\t\tthis.blockDigVls = configYml.getDouble(name + \".block_dig\");\n\t\tthis.setCreativeSlot = configYml.getDouble(name + \".set_creative_slot\");\n\t\tthis.bypassPermission = configYml.getString(name + \".bypass-permission\");\n\t\tthis.blacklist = new HashSet<>(configYml.getStringList(name + \".blacklist\"));\n\n\t\tfor (String key : rateMultipliersSection.getKeys()) {\n\t\t\trateMultipliers.put(key, rateMultipliersSection.getDouble(key));\n\t\t}\n\t}\n\n\tpublic double getMultiplier(String packetName) {\n\t\treturn rateMultipliers.getOrDefault(packetName, rateMultipliers.getOrDefault(\"PacketPlayInOther\", 1D));\n\t}\n\n\tpublic double getWindowClick() {\n\t\treturn windowClick;\n\t}\n\n\tpublic double getSetCreativeSlot() {\n\t\treturn setCreativeSlot;\n\t}\n\n\tpublic double getBlockDigVls() {\n\t\treturn blockDigVls;\n\t}\n\n\tpublic double getBlockPlaceVls() {\n\t\treturn blockPlaceVls;\n\t}\n\n\tpublic double getDataVls() {\n\t\treturn dataVls;\n\t}\n\n\tpublic double getBookVls() {\n\t\treturn bookVls;\n\t}\n\n\tpublic double getTagVls() {\n\t\treturn tagVls;\n\t}\n\n\tpublic int getDataMaxSize() {\n\t\treturn dataMaxSize;\n\t}\n\n\tpublic int getDataMaxSizeBook() {\n\t\treturn dataMaxSizeBook;\n\t}\n\n\tpublic int getDataMaxSizeSign() {\n\t\treturn dataMaxSizeSign;\n\t}\n\n\tpublic double getDataVlMultiplier() {\n\t\treturn byteMultiplier;\n\t}\n\n public boolean isBlacklisted(String packetName) {\n return blacklist.contains(packetName);\n }\n\n public int getDataMaxFireworkFlags() {\n return dataMaxFireworkFlags;\n }\n\n\tpublic int getDataMaxFlags() {\n\t\treturn dataMaxFlags;\n\t}\n\n public String getBypassPermission() {\n return bypassPermission;\n }\n}" } ]
import java.io.File; import java.util.logging.Logger; import org.bukkit.Server; import org.bukkit.plugin.Plugin; import dev._2lstudios.exploitfixer.modules.NotificationsModule; import dev._2lstudios.exploitfixer.modules.ItemAnalysisModule; import dev._2lstudios.exploitfixer.modules.PatcherModule; import dev._2lstudios.exploitfixer.utils.ConfigUtil; import dev._2lstudios.exploitfixer.modules.CreativeItemsFixModule; import dev._2lstudios.exploitfixer.configuration.IConfiguration; import dev._2lstudios.exploitfixer.modules.CommandsModule; import dev._2lstudios.exploitfixer.modules.ConnectionModule; import dev._2lstudios.exploitfixer.modules.MessagesModule; import dev._2lstudios.exploitfixer.modules.PacketsModule;
7,373
package dev._2lstudios.exploitfixer.managers; public class ModuleManager { private Plugin plugin; private CommandsModule commandsModule; private ConnectionModule connectionModule; private PatcherModule eventsModule; private CreativeItemsFixModule itemsFixModule; private MessagesModule messagesModule; private NotificationsModule notificationsModule;
package dev._2lstudios.exploitfixer.managers; public class ModuleManager { private Plugin plugin; private CommandsModule commandsModule; private ConnectionModule connectionModule; private PatcherModule eventsModule; private CreativeItemsFixModule itemsFixModule; private MessagesModule messagesModule; private NotificationsModule notificationsModule;
private PacketsModule packetsModule;
9
2023-12-13 21:49:27+00:00
12k
xuexu2/Crasher
src/main/java/cn/sn0wo/crasher/utils/Utils.java
[ { "identifier": "Crasher", "path": "src/main/java/cn/sn0wo/crasher/Crasher.java", "snippet": "public final class Crasher extends JavaPlugin {\n\n public Crasher() {\n Utils.utils = new Utils(this);\n }\n\n @Override\n public void onLoad() {\n getLogger().info(\"Loaded \" + getDescription().getFullName());\n }\n\n @Override\n public void onEnable() {\n Utils.utils.setupPlugin();\n getLogger().info(\"Enabled \" + getDescription().getFullName());\n }\n\n @Override\n public void onDisable() {\n Utils.utils.unregisterInstance();\n getLogger().info(\"Disabled \" + getDescription().getFullName());\n }\n}" }, { "identifier": "Metrics", "path": "src/main/java/cn/sn0wo/crasher/bstats/Metrics.java", "snippet": "public final class Metrics {\r\n\r\n private final Plugin plugin;\r\n\r\n private final MetricsBase metricsBase;\r\n\r\n public Metrics(final JavaPlugin plugin, final int serviceId) {\r\n this.plugin = plugin;\r\n final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), \"bStats\");\r\n final File configFile = new File(bStatsFolder, \"config.yml\");\r\n final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);\r\n if (!config.isSet(\"serverUuid\")) {\r\n config.addDefault(\"enabled\", true);\r\n config.addDefault(\"serverUuid\", UUID.randomUUID().toString());\r\n config.addDefault(\"logFailedRequests\", false);\r\n config.addDefault(\"logSentData\", false);\r\n config.addDefault(\"logResponseStatusText\", false);\r\n config\r\n .options()\r\n .header(\r\n \"bStats (https://bStats.org) collects some basic information for plugin authors, like how\\n\"\r\n + \"many people use their plugin and their total player count. It's recommended to keep bStats\\n\"\r\n + \"enabled, but if you're not comfortable with this, you can turn this setting off. There is no\\n\"\r\n + \"performance penalty associated with having metrics enabled, and data sent to bStats is fully\\n\"\r\n + \"anonymous.\")\r\n .copyDefaults(true);\r\n try {\r\n config.save(configFile);\r\n } catch (IOException ignored) {\r\n }\r\n }\r\n final boolean enabled = config.getBoolean(\"enabled\", true);\r\n final String serverUUID = config.getString(\"serverUuid\");\r\n final boolean logErrors = config.getBoolean(\"logFailedRequests\", false);\r\n final boolean logSentData = config.getBoolean(\"logSentData\", false);\r\n final boolean logResponseStatusText = config.getBoolean(\"logResponseStatusText\", false);\r\n metricsBase =\r\n new MetricsBase(\r\n \"bukkit\",\r\n serverUUID,\r\n serviceId,\r\n enabled,\r\n this::appendPlatformData,\r\n this::appendServiceData,\r\n submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),\r\n plugin::isEnabled,\r\n (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),\r\n (message) -> this.plugin.getLogger().log(Level.INFO, message),\r\n logErrors,\r\n logSentData,\r\n logResponseStatusText);\r\n }\r\n\r\n public void shutdown() {\r\n metricsBase.shutdown();\r\n }\r\n\r\n public void addCustomChart(final CustomChart chart) {\r\n metricsBase.addCustomChart(chart);\r\n }\r\n\r\n private void appendPlatformData(final JsonObjectBuilder builder) {\r\n builder.appendField(\"playerAmount\", getPlayerAmount());\r\n builder.appendField(\"onlineMode\", Bukkit.getOnlineMode() ? 1 : 0);\r\n builder.appendField(\"bukkitVersion\", Bukkit.getVersion());\r\n builder.appendField(\"bukkitName\", Bukkit.getName());\r\n builder.appendField(\"javaVersion\", System.getProperty(\"java.version\"));\r\n builder.appendField(\"osName\", System.getProperty(\"os.name\"));\r\n builder.appendField(\"osArch\", System.getProperty(\"os.arch\"));\r\n builder.appendField(\"osVersion\", System.getProperty(\"os.version\"));\r\n builder.appendField(\"coreCount\", Runtime.getRuntime().availableProcessors());\r\n }\r\n\r\n private void appendServiceData(final JsonObjectBuilder builder) {\r\n builder.appendField(\"pluginVersion\", plugin.getDescription().getVersion());\r\n }\r\n\r\n private int getPlayerAmount() {\r\n try {\r\n final Method onlinePlayersMethod = Class.forName(\"org.bukkit.Server\").getMethod(\"getOnlinePlayers\");\r\n return onlinePlayersMethod.getReturnType().equals(Collection.class)\r\n ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()\r\n : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;\r\n } catch (Exception e) {\r\n return Bukkit.getOnlinePlayers().size();\r\n }\r\n }\r\n\r\n public final static class MetricsBase {\r\n public static final String METRICS_VERSION = \"3.0.2\";\r\n\r\n private static final String REPORT_URL = \"https://bStats.org/api/v2/data/%s\";\r\n\r\n private final ScheduledExecutorService scheduler;\r\n\r\n private final String platform;\r\n\r\n private final String serverUuid;\r\n\r\n private final int serviceId;\r\n\r\n private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;\r\n\r\n private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;\r\n\r\n private final Consumer<Runnable> submitTaskConsumer;\r\n\r\n private final Supplier<Boolean> checkServiceEnabledSupplier;\r\n\r\n private final BiConsumer<String, Throwable> errorLogger;\r\n\r\n private final Consumer<String> infoLogger;\r\n\r\n private final boolean logErrors;\r\n\r\n private final boolean logSentData;\r\n\r\n private final boolean logResponseStatusText;\r\n\r\n private final Set<CustomChart> customCharts = new HashSet<>();\r\n\r\n private final boolean enabled;\r\n\r\n public MetricsBase(\r\n final String platform,\r\n final String serverUuid,\r\n final int serviceId,\r\n final boolean enabled,\r\n final Consumer<JsonObjectBuilder> appendPlatformDataConsumer,\r\n final Consumer<JsonObjectBuilder> appendServiceDataConsumer,\r\n final Consumer<Runnable> submitTaskConsumer,\r\n final Supplier<Boolean> checkServiceEnabledSupplier,\r\n final BiConsumer<String, Throwable> errorLogger,\r\n final Consumer<String> infoLogger,\r\n final boolean logErrors,\r\n final boolean logSentData,\r\n final boolean logResponseStatusText) {\r\n final ScheduledThreadPoolExecutor scheduler =\r\n new ScheduledThreadPoolExecutor(1, task -> new Thread(task, \"bStats-Metrics\"));\r\n scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);\r\n this.scheduler = scheduler;\r\n this.platform = platform;\r\n this.serverUuid = serverUuid;\r\n this.serviceId = serviceId;\r\n this.enabled = enabled;\r\n this.appendPlatformDataConsumer = appendPlatformDataConsumer;\r\n this.appendServiceDataConsumer = appendServiceDataConsumer;\r\n this.submitTaskConsumer = submitTaskConsumer;\r\n this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;\r\n this.errorLogger = errorLogger;\r\n this.infoLogger = infoLogger;\r\n this.logErrors = logErrors;\r\n this.logSentData = logSentData;\r\n this.logResponseStatusText = logResponseStatusText;\r\n checkRelocation();\r\n if (enabled) {\r\n startSubmitting();\r\n }\r\n }\r\n\r\n private static byte[] compress(final String str) throws IOException {\r\n if (str == null) {\r\n return null;\r\n }\r\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\r\n try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {\r\n gzip.write(str.getBytes(StandardCharsets.UTF_8));\r\n }\r\n return outputStream.toByteArray();\r\n }\r\n\r\n public void addCustomChart(final CustomChart chart) {\r\n this.customCharts.add(chart);\r\n }\r\n\r\n public void shutdown() {\r\n scheduler.shutdown();\r\n }\r\n\r\n private void startSubmitting() {\r\n final Runnable submitTask =\r\n () -> {\r\n if (!enabled || !checkServiceEnabledSupplier.get()) {\r\n scheduler.shutdown();\r\n return;\r\n }\r\n if (submitTaskConsumer != null) {\r\n submitTaskConsumer.accept(this::submitData);\r\n } else {\r\n this.submitData();\r\n }\r\n };\r\n final long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));\r\n final long secondDelay = (long) (1000 * 60 * (Math.random() * 30));\r\n scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);\r\n scheduler.scheduleAtFixedRate(\r\n submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);\r\n }\r\n\r\n private void submitData() {\r\n final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();\r\n appendPlatformDataConsumer.accept(baseJsonBuilder);\r\n final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();\r\n appendServiceDataConsumer.accept(serviceJsonBuilder);\r\n final JsonObjectBuilder.JsonObject[] chartData =\r\n customCharts.stream()\r\n .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))\r\n .filter(Objects::nonNull)\r\n .toArray(JsonObjectBuilder.JsonObject[]::new);\r\n serviceJsonBuilder.appendField(\"id\", serviceId);\r\n serviceJsonBuilder.appendField(\"customCharts\", chartData);\r\n baseJsonBuilder.appendField(\"service\", serviceJsonBuilder.build());\r\n baseJsonBuilder.appendField(\"serverUUID\", serverUuid);\r\n baseJsonBuilder.appendField(\"metricsVersion\", METRICS_VERSION);\r\n final JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();\r\n scheduler.execute(\r\n () -> {\r\n try {\r\n sendData(data);\r\n } catch (Exception e) {\r\n if (logErrors) {\r\n errorLogger.accept(\"Could not submit bStats metrics data\", e);\r\n }\r\n }\r\n });\r\n }\r\n\r\n private void sendData(final JsonObjectBuilder.JsonObject data) throws Exception {\r\n if (logSentData) {\r\n infoLogger.accept(\"Sent bStats metrics data: \" + data.toString());\r\n }\r\n final String url = String.format(REPORT_URL, platform);\r\n final HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\r\n final byte[] compressedData = compress(data.toString());\r\n connection.setRequestMethod(\"POST\");\r\n connection.addRequestProperty(\"Accept\", \"application/json\");\r\n connection.addRequestProperty(\"Connection\", \"close\");\r\n connection.addRequestProperty(\"Content-Encoding\", \"gzip\");\r\n connection.addRequestProperty(\"Content-Length\", String.valueOf(compressedData.length));\r\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\r\n connection.setRequestProperty(\"User-Agent\", \"Metrics-Service/1\");\r\n connection.setDoOutput(true);\r\n try (final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {\r\n outputStream.write(compressedData);\r\n }\r\n final StringBuilder builder = new StringBuilder();\r\n try (BufferedReader bufferedReader =\r\n new BufferedReader(new InputStreamReader(connection.getInputStream()))) {\r\n String line;\r\n while ((line = bufferedReader.readLine()) != null) {\r\n builder.append(line);\r\n }\r\n }\r\n if (logResponseStatusText) {\r\n infoLogger.accept(\"Sent data to bStats and received response: \" + builder);\r\n }\r\n }\r\n\r\n private void checkRelocation() {\r\n if (System.getProperty(\"bstats.relocatecheck\") == null\r\n || !System.getProperty(\"bstats.relocatecheck\").equals(\"false\")) {\r\n final String defaultPackage =\r\n new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});\r\n final String examplePackage =\r\n new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});\r\n if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)\r\n || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {\r\n throw new IllegalStateException(\"bStats Metrics class has not been relocated correctly!\");\r\n }\r\n }\r\n }\r\n }\r\n\r\n public abstract static class CustomChart {\r\n\r\n private final String chartId;\r\n\r\n protected CustomChart(String chartId) {\r\n if (chartId == null) {\r\n throw new IllegalArgumentException(\"chartId must not be null\");\r\n }\r\n this.chartId = chartId;\r\n }\r\n\r\n public final JsonObjectBuilder.JsonObject getRequestJsonObject(\r\n final BiConsumer<String, Throwable> errorLogger, final boolean logErrors) {\r\n final JsonObjectBuilder builder = new JsonObjectBuilder();\r\n builder.appendField(\"chartId\", chartId);\r\n try {\r\n final JsonObjectBuilder.JsonObject data = getChartData();\r\n if (data == null) {\r\n return null;\r\n }\r\n builder.appendField(\"data\", data);\r\n } catch (Throwable t) {\r\n if (logErrors) {\r\n errorLogger.accept(\"Failed to get data for custom chart with id \" + chartId, t);\r\n }\r\n return null;\r\n }\r\n return builder.build();\r\n }\r\n\r\n protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;\r\n }\r\n\r\n public final static class JsonObjectBuilder {\r\n\r\n private StringBuilder builder = new StringBuilder();\r\n\r\n private boolean hasAtLeastOneField = false;\r\n\r\n public JsonObjectBuilder() {\r\n builder.append(\"{\");\r\n }\r\n\r\n private static String escape(final String value) {\r\n final StringBuilder builder = new StringBuilder();\r\n for (int i = 0; i < value.length(); i++) {\r\n final char c = value.charAt(i);\r\n if (c == '\"') {\r\n builder.append(\"\\\\\\\"\");\r\n } else if (c == '\\\\') {\r\n builder.append(\"\\\\\\\\\");\r\n } else if (c <= '\\u000F') {\r\n builder.append(\"\\\\u000\").append(Integer.toHexString(c));\r\n } else if (c <= '\\u001F') {\r\n builder.append(\"\\\\u00\").append(Integer.toHexString(c));\r\n } else {\r\n builder.append(c);\r\n }\r\n }\r\n return builder.toString();\r\n }\r\n\r\n public JsonObjectBuilder appendField(final String key, final String value) {\r\n if (value == null) {\r\n throw new IllegalArgumentException(\"JSON value must not be null\");\r\n }\r\n appendFieldUnescaped(key, \"\\\"\" + escape(value) + \"\\\"\");\r\n return this;\r\n }\r\n\r\n public JsonObjectBuilder appendField(final String key, final int value) {\r\n appendFieldUnescaped(key, String.valueOf(value));\r\n return this;\r\n }\r\n\r\n public JsonObjectBuilder appendField(final String key, final JsonObject object) {\r\n if (object == null) {\r\n throw new IllegalArgumentException(\"JSON object must not be null\");\r\n }\r\n appendFieldUnescaped(key, object.toString());\r\n return this;\r\n }\r\n\r\n public JsonObjectBuilder appendField(final String key, final int[] values) {\r\n if (values == null) {\r\n throw new IllegalArgumentException(\"JSON values must not be null\");\r\n }\r\n final String escapedValues =\r\n Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(\",\"));\r\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\r\n return this;\r\n }\r\n\r\n public JsonObjectBuilder appendField(final String key, final JsonObject[] values) {\r\n if (values == null) {\r\n throw new IllegalArgumentException(\"JSON values must not be null\");\r\n }\r\n final String escapedValues =\r\n Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(\",\"));\r\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\r\n return this;\r\n }\r\n\r\n private void appendFieldUnescaped(final String key, final String escapedValue) {\r\n if (builder == null) {\r\n throw new IllegalStateException(\"JSON has already been built\");\r\n }\r\n if (key == null) {\r\n throw new IllegalArgumentException(\"JSON key must not be null\");\r\n }\r\n if (hasAtLeastOneField) {\r\n builder.append(\",\");\r\n }\r\n builder.append(\"\\\"\").append(escape(key)).append(\"\\\":\").append(escapedValue);\r\n hasAtLeastOneField = true;\r\n }\r\n\r\n public JsonObject build() {\r\n if (builder == null) {\r\n throw new IllegalStateException(\"JSON has already been built\");\r\n }\r\n final JsonObject object = new JsonObject(builder.append(\"}\").toString());\r\n builder = null;\r\n return object;\r\n }\r\n\r\n public final static class JsonObject {\r\n\r\n private final String value;\r\n\r\n private JsonObject(final String value) {\r\n this.value = value;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return value;\r\n }\r\n }\r\n }\r\n}" }, { "identifier": "Crash", "path": "src/main/java/cn/sn0wo/crasher/commands/Crash.java", "snippet": "public final class Crash implements TabExecutor {\r\n @Override\r\n public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {\r\n if (!sender.hasPermission(\"crasher.admin\")) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandNoPermission\")));\r\n return false;\r\n }\r\n if (args.length == 0 || args.length == 1 && !\"reload\".equalsIgnoreCase(args[0])) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.HelpMessage\")));\r\n return false;\r\n } else if (\"reload\".equalsIgnoreCase(args[0])) {\r\n Utils.utils.instance.saveDefaultConfig();\r\n Utils.utils.instance.reloadConfig();\r\n Utils.utils.dataManager.reloadConfig();\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n }\r\n if (args.length != 2 && args.length != 4) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.HelpMessage\")));\r\n return false;\r\n }\r\n final Player player = Bukkit.getPlayer(args[0]);\r\n final String action = args[1].toLowerCase();\r\n if (args.length != 4) {\r\n if (\"banlist\".equalsIgnoreCase(args[0])) {\r\n final StringBuilder players = new StringBuilder();\r\n final List<String> playerList = new ArrayList<>(Utils.utils.dataManager.dataConfig.getKeys(false));\r\n if (!playerList.isEmpty()) {\r\n final int itemsPerPage = Utils.utils.instance.getConfig().getInt(\"Settings.BanList.ItemsPerPage\");\r\n int page;\r\n try {\r\n page = Integer.parseInt(args[1]);\r\n } catch (NumberFormatException e) {\r\n page = 1;\r\n }\r\n final int totalPages = (int) Math.ceil((double) playerList.size() / itemsPerPage);\r\n if (page < 1 || page > totalPages) {\r\n page = totalPages;\r\n }\r\n players.append(ChatColor.translateAlternateColorCodes('&', \"&4&lBanLists - Page \" + page + \"/\" + totalPages + \": \\n\"));\r\n final int startIndex = (page - 1) * itemsPerPage;\r\n final int endIndex = Math.min(startIndex + itemsPerPage, playerList.size());\r\n for (int i = startIndex; i < endIndex; i++) {\r\n final String player1 = playerList.get(i);\r\n final String[] types = Utils.utils.dataManager.dataConfig.getString(player1).split(\"\\\\.\");\r\n final String type;\r\n switch (types[0]) {\r\n case \"1\":\r\n type = \"cancel_packets\";\r\n break;\r\n case \"3\":\r\n type = \"explosions\";\r\n break;\r\n case \"4\":\r\n type = \"frozen\";\r\n break;\r\n default:\r\n type = \"entitys\";\r\n break;\r\n }\r\n players.append(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandBanList\").replace(\"%player%\", player1).replace(\"%type%\", type).replace(\"%time%\", Utils.utils.formatDuration(Long.parseLong(types[1]) - System.currentTimeMillis())).replace(\"%line%\", \"\\n\")));\r\n }\r\n } else {\r\n players.append(ChatColor.translateAlternateColorCodes('&', \"&4&lBanLists - Page 0/0\"));\r\n }\r\n sender.sendMessage(players.toString());\r\n return true;\r\n }\r\n switch (action) {\r\n case \"cancel_packets\":\r\n if (player == null) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandPlayerNotOnline\")));\r\n return true;\r\n }\r\n if (!Utils.utils.crashSet.contains(player.getUniqueId())) {\r\n Utils.utils.crashPlayer(player, 1);\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n } else {\r\n Utils.utils.removeCrashSet(player.getUniqueId());\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandRemoveCrashList\")));\r\n }\r\n return true;\r\n case \"entitys\":\r\n if (player == null) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandPlayerNotOnline\")));\r\n return true;\r\n }\r\n Utils.utils.crashPlayer(player, 2);\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n case \"explosions\":\r\n if (player == null) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandPlayerNotOnline\")));\r\n return true;\r\n }\r\n Utils.utils.crashPlayer(player, 3);\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n case \"frozen\":\r\n if (player == null) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandPlayerNotOnline\")));\r\n return true;\r\n }\r\n if (Utils.utils.frozenSet.contains(player.getUniqueId())) {\r\n Utils.utils.frozenSet.remove(player.getUniqueId());\r\n player.closeInventory();\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandFrozenRemove\")));\r\n } else {\r\n Utils.utils.frozenPlayer(player);\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n }\r\n return true;\r\n case \"unban\":\r\n if (Utils.utils.dataManager.dataConfig.isSet(args[0])) {\r\n final String[] type = Utils.utils.dataManager.dataConfig.getString(args[0]).split(\"\\\\.\");\r\n if (Long.parseLong(type[1]) >= System.currentTimeMillis()) {\r\n switch (type[0]) {\r\n case \"1\":\r\n case \"2\":\r\n case \"3\":\r\n default:\r\n if (player != null) {\r\n if (Utils.utils.crashSet.contains(player.getUniqueId())) {\r\n Utils.utils.removeCrashSet(player.getUniqueId());\r\n }\r\n }\r\n Utils.utils.dataManager.dataConfig.set(args[0], null);\r\n Utils.utils.dataManager.reloadConfig();\r\n break;\r\n case \"4\":\r\n if (player != null) {\r\n if (Utils.utils.frozenSet.contains(player.getUniqueId())) {\r\n Utils.utils.frozenSet.remove(player.getUniqueId());\r\n player.closeInventory();\r\n }\r\n }\r\n Utils.utils.dataManager.dataConfig.set(args[0], null);\r\n Utils.utils.dataManager.reloadConfig();\r\n break;\r\n }\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandUnban\")));\r\n return true;\r\n } else {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.AlreadyCommandUnban\")));\r\n }\r\n } else {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.AlreadyCommandUnban\")));\r\n }\r\n return true;\r\n default:\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.HelpMessage\")));\r\n return false;\r\n }\r\n } else if (\"ban\".equalsIgnoreCase(args[2])) {\r\n long time = Utils.utils.parseDuration(args[3]);\r\n if (time == -1) {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.HelpMessage\")));\r\n return false;\r\n }\r\n final long oldTime = time / 50L;\r\n time = System.currentTimeMillis() + time;\r\n switch (action) {\r\n case \"cancel_packets\":\r\n if (player != null) {\r\n if (!Utils.utils.crashSet.contains(player.getUniqueId())) {\r\n Utils.utils.crashPlayer(player, 1);\r\n }\r\n Bukkit.getScheduler().runTaskLaterAsynchronously(Utils.utils.instance, () -> {\r\n if (Utils.utils.crashSet.contains(player.getUniqueId())) {\r\n Utils.utils.removeCrashSet(player.getUniqueId());\r\n }\r\n }, oldTime);\r\n }\r\n if (!Utils.utils.dataManager.dataConfig.isSet(args[0])) {\r\n Utils.utils.dataManager.dataConfig.set(args[0], \"1.\" + time);\r\n Utils.utils.dataManager.reloadConfig();\r\n }\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n case \"entitys\":\r\n if (player != null) {\r\n Utils.utils.crashPlayer(player, 2);\r\n Bukkit.getScheduler().runTaskLaterAsynchronously(Utils.utils.instance, () -> {\r\n if (Utils.utils.crashSet.contains(player.getUniqueId())) {\r\n Utils.utils.removeCrashSet(player.getUniqueId());\r\n }\r\n }, oldTime);\r\n }\r\n Utils.utils.dataManager.dataConfig.set(args[0], \"2.\" + time);\r\n Utils.utils.dataManager.reloadConfig();\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n case \"explosions\":\r\n if (player != null) {\r\n Utils.utils.crashPlayer(player, 3);\r\n Bukkit.getScheduler().runTaskLaterAsynchronously(Utils.utils.instance, () -> {\r\n if (Utils.utils.crashSet.contains(player.getUniqueId())) {\r\n Utils.utils.removeCrashSet(player.getUniqueId());\r\n }\r\n }, oldTime);\r\n }\r\n Utils.utils.dataManager.dataConfig.set(args[0], \"3.\" + time);\r\n Utils.utils.dataManager.reloadConfig();\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n case \"frozen\":\r\n if (player != null) {\r\n if (!Utils.utils.frozenSet.contains(player.getUniqueId())) {\r\n Utils.utils.frozenPlayer(player);\r\n }\r\n Bukkit.getScheduler().runTaskLaterAsynchronously(Utils.utils.instance, () -> {\r\n if (Utils.utils.frozenSet.contains(player.getUniqueId())) {\r\n Utils.utils.frozenSet.remove(player.getUniqueId());\r\n player.closeInventory();\r\n }\r\n }, oldTime);\r\n }\r\n Utils.utils.dataManager.dataConfig.set(args[0], \"4.\" + time);\r\n Utils.utils.dataManager.reloadConfig();\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.CommandDone\")));\r\n return true;\r\n default:\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.HelpMessage\")));\r\n return false;\r\n }\r\n } else {\r\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Utils.utils.instance.getConfig().getString(\"Messages.HelpMessage\")));\r\n return false;\r\n }\r\n }\r\n\r\n @Override\r\n public List<String> onTabComplete(final CommandSender commandSender, final Command command, final String alias, final String[] args) {\r\n if (!commandSender.hasPermission(\"crasher.admin\")) {\r\n return Collections.emptyList();\r\n }\r\n if (args.length == 1) {\r\n final List<String> suggestions = new ArrayList<>();\r\n suggestions.add(\"reload\");\r\n suggestions.add(\"banlist\");\r\n Bukkit.getOnlinePlayers().forEach(player -> suggestions.add(player.getName()));\r\n return suggestions.stream()\r\n .filter(name -> name.toLowerCase().startsWith(args[0].toLowerCase()))\r\n .collect(Collectors.toList());\r\n }\r\n final List<String> completions = Arrays.asList(\"cancel_packets\", \"entitys\", \"explosions\", \"frozen\", \"unban\");\r\n if (args.length == 2 && !\"reload\".equalsIgnoreCase(args[0]) && !\"banlist\".equalsIgnoreCase(args[0])) {\r\n return completions.stream()\r\n .filter(completion -> completion.toLowerCase().startsWith(args[1].toLowerCase()))\r\n .collect(Collectors.toList());\r\n }\r\n if (args.length == 3 && completions.contains(args[1].toLowerCase())) {\r\n final List<String> suggestions = Collections.singletonList(\"ban\");\r\n return suggestions.stream()\r\n .filter(suggestion -> suggestion.toLowerCase().startsWith(args[2].toLowerCase()))\r\n .collect(Collectors.toList());\r\n }\r\n return Collections.emptyList();\r\n }\r\n}" }, { "identifier": "DataManager", "path": "src/main/java/cn/sn0wo/crasher/datas/DataManager.java", "snippet": "public final class DataManager {\r\n public final File data;\r\n public FileConfiguration dataConfig;\r\n\r\n public DataManager() {\r\n data = new File(Utils.utils.instance.getDataFolder(), \"data.dt\");\r\n dataConfig = YamlConfiguration.loadConfiguration(data);\r\n reloadConfig();\r\n }\r\n\r\n public void reloadConfig() {\r\n if (!data.exists()) {\r\n try {\r\n data.createNewFile();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n try {\r\n dataConfig.save(data);\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n dataConfig = YamlConfiguration.loadConfiguration(data);\r\n }\r\n}\r" }, { "identifier": "PlayerListener", "path": "src/main/java/cn/sn0wo/crasher/listener/PlayerListener.java", "snippet": "public final class PlayerListener implements Listener {\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onPlayerJoin(final PlayerJoinEvent event) {\r\n final Player player = event.getPlayer();\r\n final String playerName = player.getName();\r\n if (Utils.utils.dataManager.dataConfig.isSet(playerName)) {\r\n final String[] type = Utils.utils.dataManager.dataConfig.getString(playerName).split(\"\\\\.\");\r\n final long time = Long.parseLong(type[1]);\r\n if (time >= System.currentTimeMillis()) {\r\n final UUID playerId = player.getUniqueId();\r\n switch (type[0]) {\r\n case \"1\":\r\n if (!Utils.utils.crashSet.contains(playerId)) {\r\n Utils.utils.crashPlayer(player, 1);\r\n }\r\n break;\r\n case \"3\":\r\n Utils.utils.crashPlayer(player, 3);\r\n break;\r\n case \"4\":\r\n Bukkit.getScheduler().runTaskLaterAsynchronously(Utils.utils.instance, () -> {\r\n if (!Utils.utils.frozenSet.contains(playerId)) {\r\n Utils.utils.frozenPlayer(player);\r\n }\r\n }, 1L);\r\n break;\r\n default:\r\n Utils.utils.crashPlayer(player, 2);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onPlayerQuit(final PlayerQuitEvent event) {\r\n final UUID playerId = event.getPlayer().getUniqueId();\r\n if (Utils.utils.instance.getConfig().getBoolean(\"Settings.Frozen.QuitCommandBoolean\") && Utils.utils.frozenSet.contains(playerId)) {\r\n Utils.utils.instance.getConfig().getStringList(\"Settings.Frozen.QuitCommandList\").forEach(\r\n cmd -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace(\"%player%\", event.getPlayer().getName()))\r\n );\r\n }\r\n Utils.utils.frozenSet.remove(playerId);\r\n Utils.utils.removeCrashSet(playerId);\r\n Utils.utils.packetReviveQueues.remove(playerId);\r\n Utils.utils.packetQueues.remove(playerId);\r\n Utils.utils.removePacketListener(event.getPlayer());\r\n }\r\n\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onInventoryClose(final InventoryCloseEvent event) {\r\n final Player player = (Player) event.getPlayer();\r\n if (Utils.utils.frozenSet.contains(player.getUniqueId()) && Utils.utils.isFrozenInventory(event.getView())) {\r\n Bukkit.getScheduler().runTaskAsynchronously(Utils.utils.instance, () -> player.openInventory(Utils.utils.frozenInventory(player)));\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onInventoryClick(final InventoryClickEvent event) {\r\n if (event.getWhoClicked() instanceof Player) {\r\n // 这里如果加一个frozenSet判断在插件Reload后有概率会被玩家拿到Inventory的物品!\r\n if (Utils.utils.isFrozenInventory(event.getView())) {\r\n event.setCancelled(true);\r\n }\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onPlayerMove(final PlayerMoveEvent event) {\r\n final Player player = event.getPlayer();\r\n if (Utils.utils.frozenSet.contains(player.getUniqueId()) && Utils.utils.isFrozenInventory(player.getOpenInventory())) {\r\n event.setCancelled(true);\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onEntityDamage(final EntityDamageEvent event) {\r\n if (event.getEntity() instanceof Player) {\r\n final Player player = (Player) event.getEntity();\r\n if (player.hasMetadata(\"frozen\")) {\r\n event.setCancelled(true);\r\n }\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.MONITOR)\r\n public void onPlayerTeleport(PlayerTeleportEvent event) {\r\n final Player player = event.getPlayer();\r\n if (player.hasMetadata(\"frozen\")) {\r\n event.setCancelled(true);\r\n }\r\n }\r\n}" }, { "identifier": "CheckUpdate", "path": "src/main/java/cn/sn0wo/crasher/tasks/CheckUpdate.java", "snippet": "public final class CheckUpdate extends BukkitRunnable {\r\n @Override\r\n public void run() {\r\n for (final Player op : Bukkit.getOnlinePlayers()) {\r\n if (Utils.utils.dataManager.dataConfig.isSet(op.getName())) {\r\n final String[] type = Utils.utils.dataManager.dataConfig.getString(op.getName()).split(\"\\\\.\");\r\n if (Long.parseLong(type[1]) >= System.currentTimeMillis()) {\r\n switch (type[0]) {\r\n case \"1\":\r\n if (!Utils.utils.crashSet.contains(op.getUniqueId())) {\r\n Utils.utils.crashPlayer(op, 1);\r\n }\r\n break;\r\n case \"2\":\r\n Utils.utils.crashPlayer(op, 2);\r\n break;\r\n case \"3\":\r\n Utils.utils.crashPlayer(op, 3);\r\n break;\r\n case \"4\":\r\n Bukkit.getScheduler().runTaskLaterAsynchronously(Utils.utils.instance, () -> {\r\n if (!Utils.utils.frozenSet.contains(op.getUniqueId())) {\r\n Utils.utils.frozenPlayer(op);\r\n }\r\n }, 1);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n Utils.utils.flushDNSCache();\r\n Utils.utils.checkForUpdates();\r\n }\r\n}" } ]
import cn.sn0wo.crasher.Crasher; import cn.sn0wo.crasher.bstats.Metrics; import cn.sn0wo.crasher.commands.Crash; import cn.sn0wo.crasher.datas.DataManager; import cn.sn0wo.crasher.listener.PlayerListener; import cn.sn0wo.crasher.tasks.CheckUpdate; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream;
8,278
package cn.sn0wo.crasher.utils; public final class Utils { public static Utils utils; public final Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final Set<UUID> crashSet = new HashSet<>(); public final Set<UUID> frozenSet = new HashSet<>();
package cn.sn0wo.crasher.utils; public final class Utils { public static Utils utils; public final Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final Set<UUID> crashSet = new HashSet<>(); public final Set<UUID> frozenSet = new HashSet<>();
public Crasher instance;
0
2023-12-05 15:08:54+00:00
12k
Crydsch/the-one
src/movement/ProhibitedPolygonRwp.java
[ { "identifier": "Coord", "path": "src/core/Coord.java", "snippet": "public class Coord implements Cloneable, Comparable<Coord> {\n\tprivate double x;\n\tprivate double y;\n\n\t/**\n\t * Constructor.\n\t * @param x Initial X-coordinate\n\t * @param y Initial Y-coordinate\n\t */\n\tpublic Coord(double x, double y) {\n\t\tsetLocation(x,y);\n\t}\n\n\t/**\n\t * Sets the location of this coordinate object\n\t * @param x The x coordinate to set\n\t * @param y The y coordinate to set\n\t */\n\tpublic void setLocation(double x, double y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\t/**\n\t * Sets this coordinate's location to be equal to other\n\t * coordinates location\n\t * @param c The other coordinate\n\t */\n\tpublic void setLocation(Coord c) {\n\t\tthis.x = c.x;\n\t\tthis.y = c.y;\n\t}\n\n\t/**\n\t * Moves the point by dx and dy\n\t * @param dx How much to move the point in X-direction\n\t * @param dy How much to move the point in Y-direction\n\t */\n\tpublic void translate(double dx, double dy) {\n\t\tthis.x += dx;\n\t\tthis.y += dy;\n\t}\n\n\t/**\n\t * Returns the squared distance to another coordinate\n\t * @param other The other coordinate\n\t * @return The distance between this and another coordinate\n\t */\n\tpublic double distanceSquared(Coord other) {\n\t\tdouble dx = this.x - other.x;\n\t\tdouble dy = this.y - other.y;\n\t\treturn dx*dx + dy*dy;\n\t}\n\n\t/**\n\t * Returns the distance to another coordinate\n\t * @param other The other coordinate\n\t * @return The distance between this and another coordinate\n\t */\n\tpublic double distance(Coord other) {\n\t\treturn Math.sqrt(distanceSquared(other));\n\t}\n\n\t/**\n\t * Returns the x coordinate\n\t * @return x coordinate\n\t */\n\tpublic double getX() {\n\t\treturn this.x;\n\t}\n\n\t/**\n\t * Returns the y coordinate\n\t * @return y coordinate\n\t */\n\tpublic double getY() {\n\t\treturn this.y;\n\t}\n\n\t/**\n\t * Returns a text representation of the coordinate (rounded to 2 decimals)\n\t * @return a text representation of the coordinate\n\t */\n\tpublic String toString() {\n\t\treturn String.format(\"(%.2f,%.2f)\",x,y);\n\t}\n\n\t/**\n\t * Returns a clone of this coordinate\n\t */\n\tpublic Coord clone() {\n\t\tCoord clone = null;\n\t\ttry {\n\t\t\tclone = (Coord) super.clone();\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(-1);\n\t\t}\n\t\treturn clone;\n\t}\n\n\t/**\n\t * Checks if this coordinate's location is equal to other coordinate's\n\t * @param c The other coordinate\n\t * @return True if locations are the same\n\t */\n\tpublic boolean equals(Coord c) {\n\t\tif (c == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn (x == c.x && y == c.y); // XXX: == for doubles...\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == null) return false;\n\t\treturn equals((Coord) o);\n\t}\n\n\t/**\n\t * Returns a hash code for this coordinate\n\t * (actually a hash of the String made of the coordinates)\n\t */\n\tpublic int hashCode() {\n\t\treturn (x+\",\"+y).hashCode();\n\t}\n\n\t/**\n\t * Compares this coordinate to other coordinate. Coordinate whose y\n\t * value is smaller comes first and if y values are equal, the one with\n\t * smaller x value comes first.\n\t * @return -1, 0 or 1 if this node is before, in the same place or\n\t * after the other coordinate\n\t */\n\tpublic int compareTo(Coord other) {\n\t\tif (this.y < other.y) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if (this.y > other.y) {\n\t\t\treturn 1;\n\t\t}\n\t\telse if (this.x < other.x) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if (this.x > other.x) {\n\t\t\treturn 1;\n\t\t}\n\t\telse {\n\t\t\treturn 0;\n\t\t}\n\t}\n}" }, { "identifier": "Settings", "path": "src/core/Settings.java", "snippet": "public class Settings {\n\t/** properties object where the setting files are read into */\n\tprotected static Properties props;\n\t/** file name of the default settings file ({@value}) */\n\tpublic static final String DEF_SETTINGS_FILE =\"default_settings.txt\";\n\n\t/**\n\t * Setting to define the file name where all read settings are written\n\t * ({@value}. If set to an empty string, standard output is used.\n\t * By default setting are not written anywhere.\n\t */\n\tpublic static final String SETTING_OUTPUT_S = \"Settings.output\";\n\n\t/** delimiter for requested values in strings ({@value})\n\t * @see #valueFillString(String) */\n\tpublic static final String FILL_DELIMITER = \"%%\";\n\n\t/** Stream where all read settings are written to */\n\tprivate static PrintStream out = null;\n\tprivate static Set<String> writtenSettings = new HashSet<String>();\n\n\t/** run index for run-specific settings */\n\tprivate static int runIndex = 0;\n\tprivate String namespace = null; // namespace to look the settings from\n\tprivate String secondaryNamespace = null;\n\tprivate Stack<String> oldNamespaces;\n\tprivate Stack<String> secondaryNamespaces;\n\n\t/**\n\t * Creates a setting object with a namespace. Namespace is the prefix\n\t * of the all subsequent setting requests.\n\t * @param namespace Namespace to use\n\t */\n\tpublic Settings(String namespace) {\n\t\tthis.oldNamespaces = new Stack<String>();\n\t\tthis.secondaryNamespaces = new Stack<String>();\n\t\tsetNameSpace(namespace);\n\t}\n\n\t/**\n\t * Create a setting object without namespace. All setting requests must\n\t * be prefixed with a valid namespace (e.g. \"Report.nrofReports\").\n\t */\n\tpublic Settings() {\n\t\tthis(null);\n\t}\n\n\t/**\n\t * Sets the run index for the settings (only has effect on settings with\n\t * run array). A run array can be defined with syntax<BR>\n\t * <CODE>[settingFor1stRun ; settingFor2ndRun ; SettingFor3rdRun]</CODE>\n\t * <BR>I.e. settings are put in brackets and delimited with semicolon.\n\t * First run's setting is returned when index is 0, second when index is\n\t * 1 etc. If run index is bigger than run array's length, indexing wraps\n\t * around in run array (i.e. return value is the value at index\n\t * <CODE>runIndex % arrayLength</CODE>).\n\t * To disable whole run-index-thing, set index to value smaller than\n\t * zero (e.g. -1). When disabled, run-arrays are returned as normal values,\n\t * including the brackets.\n\t * @param index The run index to use for subsequent settings calls, or\n\t * -1 to disable run indexing\n\t */\n\tpublic static void setRunIndex(int index) {\n\t\trunIndex = index;\n\t\twrittenSettings.clear();\n\t}\n\n\t/**\n\t * Checks that the given integer array contains a valid range. I.e.,\n\t * the length of the array must be two and\n\t * <code>first_value <= second_value</code>.\n\t * @param range The range array\n\t * @param sname Name of the setting (for error messages)\n\t * @throws SettingsError If the given array didn't qualify as a range\n\t */\n\tpublic void assertValidRange(int range[], String sname)\n\t\tthrows SettingsError {\n\t\tif (range.length != 2) {\n\t\t\tthrow new SettingsError(\"Range setting \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" should contain only two comma separated integer values\");\n\t\t}\n\t\tif (range[0] > range[1]) {\n\t\t\tthrow new SettingsError(\"Range setting's \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" first value should be smaller or equal to second value\");\n\t\t}\n\t}\n\n\t/**\n\t * Makes sure that the given settings value is positive\n\t * @param value Value to check\n\t * @param settingName Name of the setting (for error's message)\n\t * @throws SettingsError if the value was not positive\n\t */\n\tpublic void ensurePositiveValue(double value, String settingName) {\n\t\tif (value < 0) {\n\t\t\tthrow new SettingsError(\"Negative value (\" + value +\n\t\t\t\t\t\") not accepted for setting \" + settingName);\n\t\t}\n\t}\n\n\t/**\n\t * Sets the namespace to something else than the current namespace.\n\t * This change can be reverted using {@link #restoreNameSpace()}\n\t * @param namespace The new namespace\n\t */\n\tpublic void setNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = namespace;\n\t}\n\n\t/**\n\t * Appends the given namespace to the the current namespace, <strong>\n\t * for both the primary and secondary namespace </strong>.\n\t * This change can be reverted using {@link #restoreNameSpace()} and\n\t * {@link #restoreSecondaryNamespace()}.\n\t * @param namespace The new namespace to append\n\t */\n\tpublic void setSubNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = this.namespace + \".\" + namespace;\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = this.secondaryNamespace + \".\" + namespace;\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for a setting.\n\t * @param setting The name of the setting\n\t * @return The setting name prefixed with fully qualified name of the\n\t * namespace where the requested setting would be retrieved from or null\n\t * if that setting is not found from any of the current namespace(s)\n\t */\n\tpublic String getFullPropertyName(String setting) {\n\t\tif (!contains(setting)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (props.getProperty(getFullPropertyName(setting, false)) != null) {\n\t\t\treturn getFullPropertyName(setting, false);\n\t\t}\n\n\t\t// not found from primary, but Settings contains -> must be from 2ndary\n\t\telse return getFullPropertyName(setting, true);\n\t}\n\n\t/**\n\t * Returns the namespace of the settings object\n\t * @return the namespace of the settings object\n\t */\n\tpublic String getNameSpace() {\n\t\treturn this.namespace;\n\t}\n\n\t/**\n\t * Returns the secondary namespace of the settings object\n\t * @return the secondary namespace of the settings object\n\t */\n\tpublic String getSecondaryNameSpace() {\n\t\treturn this.secondaryNamespace;\n\t}\n\n\t/**\n\t * Sets a secondary namespace where a setting is searched from if it\n\t * isn't found from the primary namespace. Secondary namespace can\n\t * be used e.g. as a \"default\" space where the settings are looked from\n\t * if no specific setting is set.\n\t * This change can be reverted using {@link #restoreSecondaryNamespace()}\n\t * @param namespace The new secondary namespace or null if secondary\n\t * namespace is not used (default behavior)\n\t */\n\tpublic void setSecondaryNamespace(String namespace) {\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = namespace;\n\t}\n\n\t/**\n\t * Restores the namespace that was in use before a call to setNameSpace\n\t * @see #setNameSpace(String)\n\t */\n\tpublic void restoreNameSpace() {\n\t\tthis.namespace = this.oldNamespaces.pop();\n\t}\n\n\t/**\n\t * Restores the secondary namespace that was in use before a call to\n\t * setSecondaryNameSpace\n\t * @see #setSecondaryNamespace(String)\n\t */\n\tpublic void restoreSecondaryNamespace() {\n\t\tthis.secondaryNamespace = this.secondaryNamespaces.pop();\n\t}\n\n\t/**\n\t * Reverts the change made with {@link #setSubNameSpace(String)}, i.e.,\n\t * restores both the primary and secondary namespace.\n\t */\n\tpublic void restoreSubNameSpace() {\n\t\trestoreNameSpace();\n\t\trestoreSecondaryNamespace();\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t * The file {@link #DEF_SETTINGS_FILE}, if exists, is always read.\n\t * @param propFile Path to the property file where additional settings\n\t * are read from or null if no additional settings files are needed.\n\t * @throws SettingsError If loading the settings file(s) didn't succeed\n\t */\n\tpublic static void init(String propFile) throws SettingsError {\n\t\tString outFile;\n\t\ttry {\n\t\t\tif (new File(DEF_SETTINGS_FILE).exists()) {\n\t\t\t\tProperties defProperties = new Properties();\n\t\t\t\tdefProperties.load(new FileInputStream(DEF_SETTINGS_FILE));\n\t\t\t\tprops = new Properties(defProperties);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprops = new Properties();\n\t\t\t}\n\t\t\tif (propFile != null) {\n\t\t\t\tprops.load(new FileInputStream(propFile));\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\toutFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t *\n\t * @param settingsStream\n\t * \t\tInputStream where the properties are read.\n\t * @throws SettingsError\n\t * \t\tIf loading the settings didn't succeed\n\t */\n\tpublic static void initFromStream(final InputStream settingsStream)\n\tthrows SettingsError {\n\t\tprops = new Properties();\n\t\ttry {\n\t\t\tprops.load(settingsStream);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\tString outFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads another settings file and adds the key-value pairs to the current\n\t * settings overriding any values that already existed with the same keys.\n\t * @param propFile Path to the property file\n\t * @throws SettingsError If loading the settings file didn't succeed\n\t * @see #init(String)\n\t */\n\tpublic static void addSettings(String propFile) throws SettingsError {\n\t\ttry {\n\t\t\tprops.load(new FileInputStream(propFile));\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\t}\n\n\t/**\n\t * Writes the given setting string to the settings output (if any)\n\t * @param setting The string to write\n\t */\n\tprivate static void outputSetting(String setting) {\n\t\tif (out != null && !writtenSettings.contains(setting)) {\n\t\t\tif (writtenSettings.size() == 0) {\n\t\t\t\tout.println(\"# Settings for run \" + (runIndex + 1));\n\t\t\t}\n\t\t\tout.println(setting);\n\t\t\twrittenSettings.add(setting);\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if a setting with defined name (in the current namespace\n\t * or secondary namespace if such is set) exists and has some value\n\t * (not just white space)\n\t * @param name Name of the setting to check\n\t * @return True if the setting exists, false if not\n\t */\n\tpublic boolean contains(String name) {\n\t\ttry {\n\t\t\tString value = getSetting(name);\n\t\t\tif (value == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\telse return value.trim().length() > 0;\n\t\t}\n\t\tcatch (SettingsError e) {\n\t\t\treturn false; // didn't find the setting\n\t\t}\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for setting.\n\t * @param name Name of the settings\n\t * @param secondary If true, the secondary namespace is used.\n\t * @return full (prefixed with current namespace) property name for setting\n\t */\n\tprivate String getFullPropertyName(String name, boolean secondary) {\n\t\tString usedNamespace = (secondary ? secondaryNamespace : namespace);\n\n\t\tif (usedNamespace != null) {\n\t\t\treturn usedNamespace + \".\" + name;\n\t\t}\n\t\telse {\n\t\t\treturn name;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String-valued setting. Setting is first looked from the\n\t * namespace that is set (if any) and then from the secondary namespace\n\t * (if any). All other getters use this method as their first step too\n\t * (so all getters may throw SettingsError and look from both namespaces).\n\t * @param name Name of the setting to get\n\t * @return The contents of the setting in a String\n\t * @throws SettingsError if the setting is not found from either one of\n\t * the namespaces\n\t */\n\tpublic String getSetting(String name) {\n\t\tString fullPropName;\n\t\tif (props == null) {\n\t\t\tinit(null);\n\t\t}\n\t\tfullPropName = getFullPropertyName(name, false);\n\t\tString value = props.getProperty(fullPropName);\n\n\t\tif (value != null) { // found value, check if run setting can be parsed\n\t\t\tvalue = parseRunSetting(value.trim());\n\t\t}\n\n\t\tif ((value == null || value.length() == 0) &&\n\t\t\t\tthis.secondaryNamespace != null) {\n\t\t\t// try secondary namespace if the value wasn't found from primary\n\t\t\tfullPropName = getFullPropertyName(name, true);\n\t\t\tvalue = props.getProperty(fullPropName);\n\n\t\t\tif (value != null) {\n\t\t\t\tvalue = parseRunSetting(value.trim());\n\t\t\t}\n\t\t}\n\n\t\tif (value == null || value.length() == 0) {\n\t\t\tthrow new SettingsError(\"Can't find setting \" +\n\t\t\t\t\tgetPropertyNamesString(name));\n\t\t}\n\n\t\toutputSetting(fullPropName + \" = \" + value);\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the given setting if it exists, or defaultValue if the setting\n\t * does not exist\n\t * @param name The name of the setting\n\t * @param defaultValue The value to return if the given setting didn't exist\n\t * @return The setting value or the default value if the setting didn't\n\t * exist\n\t */\n\tpublic String getSetting(String name, String defaultValue) {\n\t\tif (!contains(name)) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn getSetting(name);\n\t\t}\n\t}\n\n\t/**\n\t * Parses run-specific settings from a String value\n\t * @param value The String to parse\n\t * @return The runIndex % arrayLength'th value of the run array\n\t */\n\tprivate static String parseRunSetting(String value) {\n\t\tfinal String RUN_ARRAY_START = \"[\";\n\t\tfinal String RUN_ARRAY_END = \"]\";\n\t\tfinal String RUN_ARRAY_DELIM = \";\";\n\t\tfinal int MIN_LENGTH = 3; // minimum run is one value. e.g. \"[v]\"\n\n\t\tif (!value.startsWith(RUN_ARRAY_START) ||\n\t\t\t!value.endsWith(RUN_ARRAY_END) ||\n\t\t\trunIndex < 0 ||\n\t\t\tvalue.length() < MIN_LENGTH) {\n\t\t\treturn value; // standard format setting -> return\n\t\t}\n\n\t\tvalue = value.substring(1,value.length()-1); // remove brackets\n\t\tString[] valueArr = value.split(RUN_ARRAY_DELIM);\n\t\tint arrIndex = runIndex % valueArr.length;\n\t\tvalue = valueArr[arrIndex].trim();\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the setting name appended to namespace name(s) on a String\n\t * (for error messages)\n\t * @param name Name of the setting\n\t * @return the setting name appended to namespace name(s) on a String\n\t */\n\tprivate String getPropertyNamesString(String name) {\n\t\tif (this.secondaryNamespace != null) {\n\t\t\treturn \"'\"+ this.secondaryNamespace + \".\" + name + \"' nor '\" +\n\t\t\t\tthis.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse if (this.namespace != null){\n\t\t\treturn \"'\" + this.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse {\n\t\t\treturn \"'\" + name + \"'\";\n\t\t}\n\t}\n\n\t/**\n\t * Returns a double-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as a double\n\t */\n\tpublic double getDouble(String name) {\n\t\treturn parseDouble(getSetting(name), name);\n\t}\n\n\t/**\n\t * Returns a double-valued setting, or the default value if the given\n\t * setting does not exist\n\t * @param name Name of the setting to get\n\t * @param defaultValue The value to return if the setting doesn't exist\n\t * @return Value of the setting as a double (or the default value)\n\t */\n\tpublic double getDouble(String name, double defaultValue) {\n\t\treturn parseDouble(getSetting(name, \"\"+defaultValue), name);\n\t}\n\n\t/**\n\t * Parses a double value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a double\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate double parseDouble(String value, String setting) {\n\t\tdouble number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t\t//replaceAll removes everything which is not a digit or point\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Double.parseDouble(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses a long value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a long\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate long parseLong(String value, String setting) {\n\t\tlong number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Long.parseLong(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses the multiplier suffix from numeric setting\n\t * @param value The setting value\n\t * @return The muliplier as a number\n\t */\n\tprivate int getMultiplier(String value) {\n\t\tvalue = value.trim();\n\t\t\n\t\tif (value.endsWith(\"k\")) {\n\t\t\treturn 1000;\n\t\t}\n\t\telse if (value.endsWith(\"M\")) {\n\t\t\treturn 1000000;\n\t\t}\n\t\telse if (value.endsWith(\"G\")) {\n\t\t\treturn 1000000000;\n\t\t}\n\t\telse if (value.endsWith(\"kiB\")) {\n\t\t\t//2^10\n\t\t\treturn 1024;\n\t\t}\n\t\telse if (value.endsWith(\"MiB\")) {\n\t\t\t//2^20\n\t\t\treturn 1048576;\n\t\t}\n\t\telse if (value.endsWith(\"GiB\")) {\n\t\t\t//2^30\n\t\t\treturn 1073741824;\n\t\t} else {\n\t\t\t// no multiplier\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a CSV setting. Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading\n\t */\n\tpublic String[] getCsvSetting(String name) {\n\t\tArrayList<String> values = new ArrayList<String>();\n\t\tString csv = getSetting(name);\n\t\tScanner s = new Scanner(csv);\n\t\ts.useDelimiter(\",\");\n\n\t\twhile (s.hasNext()) {\n\t\t\tvalues.add(s.next().trim());\n\t\t}\n\n\t\treturn values.toArray(new String[0]);\n\t}\n\n\t/**\n\t * Returns a CSV setting containing expected amount of values.\n\t * Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading or didn't\n\t * read the expected amount of values.\n\t */\n\tpublic String[] getCsvSetting(String name, int expectedCount) {\n\t\tString[] values = getCsvSetting(name);\n\n\t\tif (values.length != expectedCount) {\n\t\t\tthrow new SettingsError(\"Read unexpected amount (\" + values.length +\n\t\t\t\t\t\") of comma separated values for setting '\"\n\t\t\t\t\t+ name + \"' (expected \" + expectedCount + \")\");\n\t\t}\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values containing expected\n\t * amount of values.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic double[] getCsvDoubles(String name, int expectedCount) {\n\t\treturn parseDoubles(getCsvSetting(name, expectedCount),name);\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String)\n\t */\n\tpublic double[] getCsvDoubles(String name) {\n\t\treturn parseDoubles(getCsvSetting(name), name);\n\t}\n\n\t/**\n\t * Parses a double array out of a String array\n\t * @param strings The array of strings containing double values\n\t * @param name Name of the setting\n\t * @return Array of double values parsed from the string values\n\t */\n\tprivate double[] parseDoubles(String[] strings, String name) {\n\t\tdouble[] values = new double[strings.length];\n\t\tfor (int i=0; i<values.length; i++) {\n\t\t\tvalues[i] = parseDouble(strings[i], name);\n\t\t}\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of CSV setting integer values\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic int[] getCsvInts(String name, int expectedCount) {\n\t\treturn convertToInts(getCsvDoubles(name, expectedCount), name);\n\t}\n\n\t/**\n\t * Returns an array of CSV setting integer values\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic int[] getCsvInts(String name) {\n\t\treturn convertToInts(getCsvDoubles(name), name);\n\t}\n\n\t/**\n\t * Returns comma-separated ranges (e.g., \"3-5, 17-20, 15\")\n\t * @param name Name of the setting\n\t * @return Array of ranges that were comma-separated in the setting\n\t * @throws SettingsError if something went wrong with reading\n\t */\n\tpublic Range[] getCsvRanges(String name) {\n\t\tString[] strRanges = getCsvSetting(name);\n\t\tRange[] ranges = new Range[strRanges.length];\n\n\t\ttry {\n\t\t\tfor (int i=0; i < strRanges.length; i++) {\n\t\t\t\tranges[i] = new Range(strRanges[i]);\n\t\t\t}\n\t\t} catch (NumberFormatException nfe) {\n\t\t\tthrow new SettingsError(\"Invalid numeric range value in \" +\n\t\t\t\t\tname, nfe);\n\t\t}\n\n\t\treturn ranges;\n\t}\n\n\t/**\n\t * Returns an integer-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as an integer\n\t */\n\tpublic int getInt(String name) {\n\t\treturn convertToInt(getDouble(name), name);\n\t}\n\t\n\t/**\n\t * Returns a long-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as an integer\n\t */\n\tpublic long getLong(String name) {\n\t\treturn parseLong(getSetting(name), name);\n\t}\n\n\t/**\n\t * Returns an integer-valued setting, or the default value if the\n\t * setting does not exist\n\t * @param name Name of the setting to get\n\t * @param defaultValue The value to return if the setting didn't exist\n\t * @return Value of the setting as an integer\n\t */\n\tpublic int getInt(String name, int defaultValue) {\n\t\treturn convertToInt(getDouble(name, defaultValue), name);\n\t}\n\n\t/**\n\t * Converts a double value that is supposedly equal to an integer value\n\t * to an integer value.\n\t * @param doubleValue The double value to convert\n\t * @param name Name of the setting where this value is from (for\n\t * SettingsError)\n\t * @return The integer value\n\t * @throws SettingsError if the double value was not equal to any integer\n\t * value\n\t */\n\tprivate int convertToInt(double doubleValue, String name) {\n\t\tint number = (int)doubleValue;\n\n\t\tif (number != doubleValue) {\n\t\t\tthrow new SettingsError(\"Expected integer value for setting '\" +\n\t\t\t\t\tname + \"' \" + \" got '\" + doubleValue + \"'\");\n\t\t}\n\t\treturn number;\n\t}\n\n\t/**\n\t * Converts an array of double values to int values using\n\t * {@link #convertToInt(double, String)}.\n\t * @param doubleValues The double valued array\n\t * @param name Name of the setting where this value is from (for\n\t * SettingsError)\n\t * @return Array of integer values\n\t * @see #convertToInt(double, String)\n\t */\n\tprivate int[] convertToInts(double [] doubleValues, String name) {\n\t\tint[] values = new int[doubleValues.length];\n\t\tfor (int i=0; i<values.length; i++) {\n\t\t\tvalues[i] = convertToInt(doubleValues[i], name);\n\t\t}\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns a boolean-valued setting\n\t * @param name Name of the setting to get\n\t * @return True if the settings value was either \"true\" (case ignored)\n\t * or \"1\", false is the settings value was either \"false\" (case ignored)\n\t * or \"0\".\n\t * @throws SettingsError if the value wasn't any recognized value\n\t * @see #getSetting(String)\n\t */\n\tpublic boolean getBoolean(String name) {\n\t\tString stringValue = getSetting(name);\n\t\tboolean value;\n\n\t\tif (stringValue.equalsIgnoreCase(\"true\") ||\n\t\t\t\tstringValue.equals(\"1\")) {\n\t\t\tvalue = true;\n\t\t}\n\t\telse if (stringValue.equalsIgnoreCase(\"false\") ||\n\t\t\t\tstringValue.equals(\"0\")) {\n\t\t\tvalue = false;\n\t\t}\n\t\telse {\n\t\t\tthrow new SettingsError(\"Not a boolean value: '\"+stringValue+\n\t\t\t\t\t\"' for setting \" + name);\n\t\t}\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the given boolean setting if it exists, or defaultValue if the\n\t * setting does not exist\n\t * @param name The name of the setting\n\t * @param defaultValue The value to return if the given setting didn't exist\n\t * @return The setting value or the default value if the setting didn't\n\t * exist\n\t */\n\tpublic boolean getBoolean(String name, boolean defaultValue) {\n\t\tif (!contains(name)) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn getBoolean(name);\n\t\t}\n\t}\n\n\t/**\n\t * Returns an ArithmeticCondition setting. See {@link ArithmeticCondition}\n\t * @param name Name of the setting to get\n\t * @return ArithmeticCondition from the setting\n\t * @throws SettingsError if the value wasn't a valid arithmetic expression\n\t */\n\tpublic ArithmeticCondition getCondition(String name) {\n\t\treturn new ArithmeticCondition(getSetting(name));\n\t}\n\n\t/**\n\t * Creates (and dynamically loads the class of) an object that\n\t * initializes itself using the settings in this Settings object\n\t * (given as the only parameter to the constructor).\n\t * @param className Name of the class of the object\n\t * @return Initialized object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tpublic Object createIntializedObject(String className) {\n\t\tClass<?>[] argsClass = {Settings.class};\n\t\tObject[] args = {this};\n\n\t\treturn loadObject(className, argsClass, args);\n\t}\n\n\t/**\n\t * Creates (and dynamically loads the class of) an object using the\n\t * constructor without any parameters.\n\t * @param className Name of the class of the object\n\t * @return Initialized object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tpublic Object createObject(String className) {\n\t\treturn loadObject(className, null, null);\n\t}\n\n\t/**\n\t * Dynamically loads and creates an object.\n\t * @param className Name of the class of the object\n\t * @param argsClass Class(es) of the argument(s) or null if no-argument\n\t * constructor should be called\n\t * @param args Argument(s)\n\t * @return The new object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tprivate Object loadObject(String className, Class<?>[] argsClass,\n\t\t\tObject[] args) {\n\t\tObject o = null;\n\t\tClass<?> objClass = getClass(className);\n\t\tConstructor<?> constructor;\n\n\t\ttry {\n\t\t\tif (argsClass != null) { // use a specific constructor\n\t\t\t\tconstructor = objClass.getConstructor((Class[])argsClass);\n\t\t\t\to = constructor.newInstance(args);\n\t\t\t}\n\t\t\telse { // call empty constructor\n\t\t\t\to = objClass.newInstance();\n\t\t\t}\n\t\t} catch (SecurityException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tthrow new SettingsError(\"Class '\" + className +\n\t\t\t\t\t\"' doesn't have a suitable constructor\", e);\n\t\t} catch (InstantiationException e) {\n\t\t\tthrow new SettingsError(\"Can't create an instance of '\" +\n\t\t\t\t\tclassName + \"'\", e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\t// this exception occurs if initialization of the object fails\n\t\t\tif (e.getCause() instanceof SettingsError) {\n\t\t\t\tthrow (SettingsError)e.getCause();\n\t\t\t}\n\t\t\telse {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new SimError(\"Couldn't create settings-accepting object\"+\n\t\t\t\t\t\" for '\" + className + \"'\\n\" + \"cause: \" + e.getCause(), e);\n\t\t\t}\n\t\t}\n\n\t\treturn o;\n\t}\n\n\t/**\n\t * Returns a Class object for the name of class of throws SettingsError\n\t * if such class wasn't found.\n\t * @param name Full name of the class (including package name)\n\t * @return A Class object of that class\n\t * @throws SettingsError if such class wasn't found or couldn't be loaded\n\t */\n\tprivate Class<?> getClass(String name) {\n\t\tString className = name;\n\t\tClass<?> c;\n\n\t\ttry {\n\t\t\tc = Class.forName(className);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tthrow new SettingsError(\"Couldn't find class '\" + className + \"'\"+\n\t\t\t\t\t\"\\n\" + e.getMessage(),e);\n\t\t}\n\n\t\treturn c;\n\t}\n\n\t/**\n\t * Fills a String formatted in a special way with values from Settings.\n\t * String can contain (fully qualified) setting names surrounded by\n\t * delimiters (see {@link #FILL_DELIMITER}). Values for those settings\n\t * are retrieved and filled in the place of place holders.\n\t * @param input The input string that may contain value requests\n\t * @return A string filled with requested values (or the original string\n\t * if no requests were found)\n\t * @throws SettingsError if such settings were not found\n\t */\n\tpublic String valueFillString(String input) {\n\t\tif (!input.contains(FILL_DELIMITER)) {\n\t\t\treturn input;\t// nothing to fill\n\t\t}\n\n\t\tSettings s = new Settings(); // don't use any namespace\n\t\tString result = \"\";\n\t\tScanner scan = new Scanner(input);\n\t\tscan.useDelimiter(FILL_DELIMITER);\n\n\t\tif (input.startsWith(FILL_DELIMITER)) {\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\twhile(scan.hasNext()) {\n\t\t\tresult += scan.next();\n\t\t\tif (!scan.hasNext()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns a String representation of the stored settings\n\t * @return a String representation of the stored settings\n\t */\n\tpublic String toString() {\n\t\treturn props.toString();\n\t}\n\n}" } ]
import core.Coord; import core.Settings; import java.util.Arrays; import java.util.List;
9,670
package movement; /** * Random Waypoint Movement with a prohibited region where nodes may not move * into. The polygon is defined by a *closed* (same point as first and * last) path, represented as a list of {@code Coord}s. * * @author teemuk */ public class ProhibitedPolygonRwp extends MovementModel { //==========================================================================// // Settings //==========================================================================// /** {@code true} to confine nodes inside the polygon */ public static final String INVERT_SETTING = "rwpInvert"; public static final boolean INVERT_DEFAULT = false; //==========================================================================// //==========================================================================// // Instance vars //==========================================================================//
package movement; /** * Random Waypoint Movement with a prohibited region where nodes may not move * into. The polygon is defined by a *closed* (same point as first and * last) path, represented as a list of {@code Coord}s. * * @author teemuk */ public class ProhibitedPolygonRwp extends MovementModel { //==========================================================================// // Settings //==========================================================================// /** {@code true} to confine nodes inside the polygon */ public static final String INVERT_SETTING = "rwpInvert"; public static final boolean INVERT_DEFAULT = false; //==========================================================================// //==========================================================================// // Instance vars //==========================================================================//
final List <Coord> polygon = Arrays.asList(
0
2023-12-10 15:51:41+00:00
12k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/TouchLightgun.java
[ { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java", "snippet": "public class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public int NUMWAYS = 4;\n\tfinal static public int IS_LIGHTGUN = 5;\n\n\t//sets\n\tfinal static public int EXIT_GAME = 1;\n\n\tfinal static public int EXIT_PAUSE = 2;\n final static public int SHOW_FPS = 3;\n\n\tfinal static public int AUTO_FRAMESKIP = 4;\n\tfinal static public int CHEATS = 5;\n\tfinal static public int SKIP_GAMEINFO = 6;\n\n\tfinal static public int DISABLE_DRC = 7;\n\n\tfinal static public int DRC_USE_C = 8;\n\n\tfinal static public int SIMPLE_UI = 9;\n\n final static public int PAUSE = 11;\n final static public int SOUND_VALUE = 13;\n\n final static public int AUTOSAVE = 16;\n final static public int SAVESTATE = 17;\n final static public int LOADSTATE = 18;\n\n\tfinal static public int OSD_RESOLUTION = 20;\n final static public int EMU_RESOLUTION = 21;\n\n\tfinal static public int ZOOM_TO_WINDOW = 22;\n\n final static public int DOUBLE_BUFFER = 23;\n final static public int PXASP1 = 24;\n\n final static public int VBEAM2X = 34;\n final static public int VFLICKER = 36;\n final static public int SOUND_OPTIMAL_FRAMES = 48;\n final static public int SOUND_OPTIMAL_SAMPLERATE = 49;\n final static public int SOUND_ENGINE = 50;\n\n final static public int MOUSE = 60;\n final static public int REFRESH = 61;\n final static public int USING_SAF = 62;\n final static public int SAVESATES_IN_ROM_PATH = 63;\n\n\tfinal static public int WARN_ON_EXIT = 64;\n\n\tfinal static public int IS_MOUSE = 65;\n\n\tfinal static public int KEYBOARD = 66;\n\n\tfinal static public int ONE_PROCESSOR = 67;\n\tfinal static public int NODEADZONEANDSAT = 68;\n\tfinal static public int MAMEINI = 69;\n\n\t//set str\n final static public int SAF_PATH = 1;\n final static public int ROM_NAME = 2;\n final static public int VERSION = 3;\n\tfinal static public int OVERLAY_EFECT = 4;\n\n\t//get str\n\tfinal static public int MAME_VERSION = 1;\n\n\t//KEYS ACTIONS\n\tfinal static public int KEY_DOWN = 1;\n\tfinal static public int KEY_UP = 2;\n\n\t//MOUSE ACTIONS\n\tfinal static public int MOUSE_MOVE = 1;\n\tfinal static public int MOUSE_BTN_DOWN = 2;\n\tfinal static public int MOUSE_BTN_UP = 3;\n\n\n private static MAME4droid mm = null;\n\n private static boolean isEmulating = false;\n\n public static boolean isEmulating() {\n return isEmulating;\n }\n\n private static Object lock1 = new Object();\n\n private static ByteBuffer screenBuff = null;\n\n private static boolean emuFiltering = false;\n\n public static boolean isEmuFiltering() {\n return emuFiltering;\n }\n\n\tpublic static void setEmuFiltering(boolean value) {\n\t\temuFiltering = value;\n\t}\n\n\tprivate static Paint debugPaint = new Paint();\n\n private static Matrix mtx = new Matrix();\n\n private static int window_width = 320;\n\n public static int getWindow_width() {\n return window_width;\n }\n\n private static int window_height = 240;\n\n public static int getWindow_height() {\n return window_height;\n }\n\n private static int emu_width = 320;\n private static int emu_height = 240;\n\n\n private static AudioTrack audioTrack = null;\n\n private static boolean isDebug = false;\n private static int videoRenderMode = PrefsHelper.PREF_RENDER_GL;\n\n private static boolean inMenu = false;\n private static boolean oldInMenu = false;\n\n public static boolean isInGame() {\n return Emulator.getValue(Emulator.IN_GAME) == 1;\n }\n\n public static boolean isInMenu() {\n return inMenu;\n }\n\n\tpublic static boolean isInGameButNotInMenu() {\n\t\treturn isInGame() && !isInMenu();\n\t}\n\n\tprivate static boolean saveorload = false;\n\tpublic static void setSaveorload(boolean value){saveorload=value;}\n\tpublic static boolean isSaveorload(){return saveorload;};\n\n\tprivate static boolean inOptions = false;\n\tpublic static void setInOptions(boolean value){\n\t\tinOptions =value;}\n\tpublic static boolean isInOptions(){return inOptions;};\n\n private static boolean needsRestart = false;\n\n public static void setNeedRestart(boolean value) {\n needsRestart = value;\n }\n\n public static boolean isRestartNeeded() {\n return needsRestart;\n }\n\n private static boolean warnResChanged = false;\n\n public static boolean isWarnResChanged() {\n return warnResChanged;\n }\n\n public static void setWarnResChanged(boolean warnResChanged) {\n Emulator.warnResChanged = warnResChanged;\n }\n\n private static boolean paused = true;\n\n public static boolean isPaused() {\n return paused;\n }\n\n private static boolean portraitFull = false;\n\n public static boolean isPortraitFull() {\n return portraitFull;\n }\n\n public static void setPortraitFull(boolean portraitFull) {\n Emulator.portraitFull = portraitFull;\n }\n\n static {\n try {\n System.loadLibrary(\"mame4droid-jni\");\n } catch (java.lang.Error e) {\n e.printStackTrace();\n }\n\n debugPaint.setARGB(255, 255, 255, 255);\n debugPaint.setStyle(Style.STROKE);\n debugPaint.setTextSize(16);\n }\n\n public static int getEmulatedWidth() {\n return emu_width;\n }\n\n public static int getEmulatedHeight() {\n return emu_height;\n }\n\n public static boolean isDebug() {\n return isDebug;\n }\n\n public static void setDebug(boolean isDebug) {\n Emulator.isDebug = isDebug;\n }\n\n public static int getVideoRenderMode() {\n return Emulator.videoRenderMode;\n }\n\n public static void setVideoRenderMode(int videoRenderMode) {\n Emulator.videoRenderMode = videoRenderMode;\n }\n\n public static Paint getDebugPaint() {\n return debugPaint;\n }\n\n public static Matrix getMatrix() {\n return mtx;\n }\n\n //synchronized\n public static ByteBuffer getScreenBuffer() {\n return screenBuff;\n }\n\n public static void setMAME4droid(MAME4droid mm) {\n Emulator.mm = mm;\n }\n\n //VIDEO\n public static void setWindowSize(int w, int h) {\n\n //System.out.println(\"window size \"+w+\" \"+h);\n\n window_width = w;\n window_height = h;\n\n if (videoRenderMode == PrefsHelper.PREF_RENDER_GL)\n return;\n\n mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height));\n }\n\n //synchronized\n static void bitblt(ByteBuffer sScreenBuff) {\n\n //Log.d(\"Thread Video\", \"fuera lock\");\n synchronized (lock1) {\n try {\n //Log.d(\"Thread Video\", \"dentro lock\");\n screenBuff = sScreenBuff;\n Emulator.inMenu = Emulator.getValue(Emulator.IN_MENU) == 1;\n\n if (inMenu != oldInMenu) {\n\n\t\t\t\t\tif(!inMenu && isSaveorload())\n\t\t\t\t\t\tsetSaveorload(false);\n\n final View v = mm.getInputView();\n if (v != null) {\n mm.runOnUiThread(new Runnable() {\n public void run() {\n v.invalidate();\n }\n });\n }\n }\n oldInMenu = inMenu;\n\n if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) {\n ((EmulatorViewGL) mm.getEmuView()).requestRender();\n } else {\n Log.e(\"Thread Video\", \"Renderer not supported.\");\n }\n //Log.d(\"Thread Video\", \"fin lock\");\n\n } catch (/*Throwable*/NullPointerException t) {\n Log.getStackTraceString(t);\n t.printStackTrace();\n }\n }\n }\n\n //synchronized\n static public void changeVideo(final int newWidth, final int newHeight) {\n\n\t\tLog.d(\"Thread Video\", \"changeVideo emu_width:\"+emu_width+\" emu_height: \"+emu_height+\" newWidth:\"+newWidth+\" newHeight: \"+newHeight);\n synchronized (lock1) {\n\n mm.getInputHandler().resetInput();\n\n warnResChanged = emu_width != newWidth || emu_height != newHeight;\n\n //if(emu_width!=newWidth || emu_height!=newHeight)\n //{\n emu_width = newWidth;\n emu_height = newHeight;\n\n mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height));\n\n if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) {\n GLRenderer r = (GLRenderer) ((EmulatorViewGL) mm.getEmuView()).getRender();\n if (r != null) r.changedEmulatedSize();\n } else {\n\t\t\t\tLog.e(\"Thread Video\", \"Error renderer not supported\");\n }\n\n mm.getMainHelper().updateEmuValues();\n\n mm.runOnUiThread(new Runnable() {\n public void run() {\n\n //Toast.makeText(mm, \"changeVideo newWidth:\"+newWidth+\" newHeight:\"+newHeight+\" newVisWidth:\"+newVisWidth+\" newVisHeight:\"+newVisHeight,Toast.LENGTH_SHORT).show();\n mm.overridePendingTransition(0, 0);\n\t\t\t\t\t/*\n if (warnResChanged && videoRenderMode == PrefsHelper.PREF_RENDER_GL && Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1)\n mm.getEmuView().setVisibility(View.INVISIBLE);\n\t\t\t\t\t*/\n\n mm.getMainHelper().updateMAME4droid();\n if (mm.getEmuView().getVisibility() != View.VISIBLE)\n mm.getEmuView().setVisibility(View.VISIBLE);\n }\n });\n //}\n }\n\n }\n\n\tstatic public void initInput() {\n\t\tLog.d(\"initInput\",\"initInput isInGame:\"+isInGame()+\" isInMenu:\"+isInMenu());\n\t\tmm.runOnUiThread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(100);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t\tif ( /*Emulator.getValue(Emulator.IN_GAME) == 1 && Emulator.getValue(Emulator.IN_MENU) == 0\n\t\t\t\t\t&&*/ (((mm.getPrefsHelper().isTouchLightgun() || mm.getPrefsHelper().isTouchGameMouse())\n\t\t\t\t\t&& mm.getInputHandler()\n\t\t\t\t\t.getTouchController().getState() != TouchController.STATE_SHOWING_NONE) || mm\n\t\t\t\t\t.getPrefsHelper().isTiltSensorEnabled())) {\n\n\t\t\t\t\tCharSequence text = \"\";\n\t\t\t\t\tif(mm.getPrefsHelper().isTiltSensorEnabled())\n\t\t\t\t\t\ttext = \"Tilt sensor is enabled!\";\n\t\t\t\t\telse if(mm.getPrefsHelper().isTouchLightgun())\n\t\t\t\t\t\ttext = \"Touch lightgun is enabled!\";\n\t\t\t\t\telse if(mm.getPrefsHelper().isTouchGameMouse())\n\t\t\t\t\t\ttext = \"Touch mouse is enabled!\";\n\n\t\t\t\t\tint duration = Toast.LENGTH_SHORT;\n\t\t\t\t\tToast toast = Toast.makeText(mm, text, duration);\n\t\t\t\t\ttoast.show();\n\t\t\t\t\tLog.d(\"initInput\",\"virtual device: \"+text);\n\t\t\t\t}\n\n\t\t\t\tmm.getMainHelper().updateMAME4droid();\n\t\t\t}\n\t\t});\n\t}\n\n //SOUND\n static public void initAudio(int freq, boolean stereo) {\n int sampleFreq = freq;\n\n int channelConfig = stereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;\n int audioFormat = AudioFormat.ENCODING_PCM_16BIT;\n\n int bufferSize = AudioTrack.getMinBufferSize(sampleFreq, channelConfig, audioFormat);\n\n if (mm.getPrefsHelper().getSoundEngine() == PrefsHelper.PREF_SNDENG_AUDIOTRACK_HIGH)\n bufferSize += bufferSize / 4;\n\n //System.out.println(\"Buffer Size \"+bufferSize);\n\n audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,\n sampleFreq,\n channelConfig,\n audioFormat,\n bufferSize,\n AudioTrack.MODE_STREAM);\n\n audioTrack.play();\n }\n\n public static void endAudio() {\n if (audioTrack != null) {\n audioTrack.stop();\n audioTrack.release();\n }\n audioTrack = null;\n }\n\n public static void writeAudio(byte[] b, int sz) {\n //System.out.println(\"Envio \"+sz+\" \"+audioTrack);\n if (audioTrack != null) {\n\t\t\taudioTrack.write(b, 0, sz);\n }\n }\n\n //LIVE CYCLE\n public static void pause() {\n //Log.d(\"EMULATOR\", \"PAUSE\");\n\n if (isEmulating) {\n //pauseEmulation(true);\n Emulator.setValue(Emulator.PAUSE, 1);\n paused = true;\n }\n\n if (audioTrack != null) {\n try {\n audioTrack.pause();\n } catch (Throwable e) {\n }\n }\n/*\n try {\n Thread.sleep(60);//ensure threads stop\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n*/\n }\n\n public static void resume() {\n //Log.d(\"EMULATOR\", \"RESUME\");\n\n if (isRestartNeeded())\n return;\n\n if (audioTrack != null)\n audioTrack.play();\n\n if (isEmulating) {\n Emulator.setValue(Emulator.PAUSE, 0);\n Emulator.setValue(Emulator.EXIT_PAUSE, 1);\n paused = false;\n }\n }\n\n //EMULATOR\n public static void emulate(final String libPath, final String resPath) {\n\n //Thread.currentThread().setPriority(Thread.MAX_PRIORITY);\n\n if (isEmulating) return;\n\n Thread t = new Thread(new Runnable() {\n\n public void run() {\n\n boolean extROM = false;\n isEmulating = true;\n\t\t\t\tSize sz = mm.getMainHelper().getWindowSize();\n init(libPath, resPath, Math.max(sz.getWidth(),sz.getHeight()), Math.min(sz.getWidth(),sz.getHeight()));\n final String versionName = mm.getMainHelper().getVersion();\n Emulator.setValueStr(Emulator.VERSION, versionName);\n\n\t\t\t\tboolean isUsingSaf = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR().length() != 0;\n\t\t\t\tif(isUsingSaf) {\n\t\t\t\t\tEmulator.setValue(Emulator.USING_SAF, 1);\n\t\t\t\t\tEmulator.setValueStr(Emulator.SAF_PATH, mm.getPrefsHelper().getROMsDIR());\n\t\t\t\t\tmm.getSAFHelper().listUriFiles(true);\n\t\t\t\t}\n\n Intent intent = mm.getIntent();\n String action = intent.getAction();\n //Uri pkg = null;\n String fileName = null;\n String path = null;\n boolean delete = false;\n if (Intent.ACTION_VIEW.equals(action)) {\n //android.os.Debug.waitForDebugger();\n //pkg = mm.getReferrer();\n //System.out.println(\"PKG: \"+pkg.getHost());\n\n Uri _uri = intent.getData();\n //System.out.println(\"URI: \"+_uri.toString());\n boolean error = false;\n\n //String filePath = null;\n\n //android.os.Debug.waitForDebugger();\n Log.d(\"\", \"URI = \" + _uri);\n try {\n if (_uri != null && \"content\".equalsIgnoreCase(_uri.getScheme())) {\n //mm.safHelper.setURI(null);//disable SAF.\n\t\t\t\t\t\t\t//Log.d(\"SAF\",\"Disabling SAF\");\n fileName = mm.getMainHelper().getFileName(_uri);\n String state = Environment.getExternalStorageState();\n\n if (Environment.MEDIA_MOUNTED.equals(state)) {\n //path = mm.getExternalCacheDir().getPath();\n path = mm.getPrefsHelper().getInstallationDIR()+\"roms\";\n File f = new File(path+\"/\"+fileName);\n if(!f.exists()) {\n java.io.InputStream input = mm.getContentResolver().openInputStream(_uri);\n error = mm.getMainHelper().copyFile(input, path, fileName);\n delete = true;\n }\n } else\n error = true;\n } else {\n String filePath = _uri.getPath();\n java.io.File f = new java.io.File(filePath);\n fileName = f.getName();\n path = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator));\n }\n } catch (Exception e) {\n error = true;\n }\n\n if (error) {\n mm.runOnUiThread(new Runnable() {\n public void run() {\n mm.getDialogHelper().setInfoMsg(\"Error opening file...\");\n mm.showDialog(DialogHelper.DIALOG_INFO);\n }\n });\n } else {\n\n Emulator.setValueStr(Emulator.ROM_NAME, fileName);\n System.out.println(\"XX name: \" + fileName);\n System.out.println(\"XX path: \" + path);\n extROM = true;\n final String name = fileName;\n mm.runOnUiThread(new Runnable() {\n public void run() {\n //Toast.makeText(mm, Html.fromHtml(\"<background color='#0000FF' ><b>\" + \"MAME4droid (0.139) \" + versionName + \".<br>Launching: \" + name + \"</b></font>\"), Toast.LENGTH_LONG).show();\n Toast.makeText(mm, \"Launching: \" + name + \"\\nMAME4droid 2024 \" + versionName, Toast.LENGTH_LONG).show();\n }\n });\n }\n }\n\n mm.getMainHelper().updateEmuValues();\n\n\t\t\t\trunT();\n\n if (extROM) {\n\t\t\t\t\t/*\n\t\t\t\t\tif (pkg != null && \"com.digdroid.alman.dig\".equals(pkg.getHost())) {\n\t\t\t\t\t\tPackageManager pm = mm.getPackageManager();\n\t\t\t\t\t\tIntent intent2 = pm.getLaunchIntentForPackage(\"com.digdroid.alman.dig\");\n\t\t\t\t\t\tmm.startActivity(intent2);\n\t\t\t\t\t}*/\n if (delete) {\n java.io.File f = new java.io.File(path, fileName);\n f.delete();\n }\n }\n\t\t\t\tmm.runOnUiThread(new Runnable() {\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tif (android.os.Build.VERSION.SDK_INT >= 21) {\n\t\t\t\t\t\t\tmm.finishAndRemoveTask();\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tmm.finish();\n\t\t\t\t\t\tandroid.os.Process.killProcess(android.os.Process.myPid());\n\t\t\t\t\t}\n\t\t\t\t});\n }\n }, \"emulatorNativeMain-Thread\");\n\n\n if (mm.getPrefsHelper().getMainThreadPriority() == PrefsHelper.LOW) {\n t.setPriority(Thread.MIN_PRIORITY);\n } else if (mm.getPrefsHelper().getMainThreadPriority() == PrefsHelper.NORMAL) {\n t.setPriority(Thread.NORM_PRIORITY);\n } else\n t.setPriority(Thread.MAX_PRIORITY);\n\n t.start();\n }\n\n public static int getValue(int key) {\n return getValue(key, 0);\n }\n\n public static String getValueStr(int key) {\n return getValueStr(key, 0);\n }\n\n public static void setValue(int key, int value) {\n setValue(key, 0, value);\n }\n\n public static void setValueStr(int key, String value) {\n setValueStr(key, 0, value);\n }\n\n static int safOpenFile(String pathName, String mode) {\n //System.out.println(\"-->Llaman a safOpenFile en java \"+pathName+\" \"+mode);\n\n String file = \"\";\n\n String romPath = mm.getPrefsHelper().getROMsDIR();\n if (pathName.startsWith(romPath))\n file = pathName.substring(romPath.length() + 1, pathName.length());\n\n if(file.equals(\"\"))\n return -1;\n\n //System.out.println(\"File with path \"+file);\n\n return mm.getSAFHelper().openUriFd(\"/\" + file, mode);\n }\n\n static int safReadDir(String dirName, int reload) {\n //System.out.println(\"Llaman a safReadDir en java \"+dirName);\n\n //boolean res = mm.getSAFHelper().listUriFiles(reload == 1);\n\n\t\tString dirSAF = \"\";\n\n\t\tString romPath = mm.getPrefsHelper().getROMsDIR();\n\t\tif (dirName.startsWith(romPath)) {\n\t\t\tdirSAF = dirName.substring(romPath.length(), dirName.length());\n\t\t\tif(!dirSAF.startsWith(\"/\")) dirSAF = \"/\"+dirSAF;\n\t\t\tif(!dirSAF.endsWith(\"/\")) dirSAF = dirSAF +\"/\";\n\t\t}\n\n\t\treturn mm.getSAFHelper().readDir(dirSAF);\n }\n\n static String safGetNextDirEntry(int dirId) {\n //System.out.println(\"Llaman a safGetNextDirEntry en java \"+dirId);\n\n return mm.getSAFHelper().getNextDirName(dirId);\n }\n\n static void safCloseDir(int dirId) {\n //System.out.println(\"Llaman a safCloseDir en java \"+dirId);\n\n\t\tmm.getSAFHelper().closeDir(dirId);\n }\n\n //native\n protected static native void init(String libPath, String resPath, int nativeWidth, int nativeHeight);\n\n protected static native void runT();\n\n //protected static native void runVideoT();\n\n synchronized public static native void setDigitalData(int i, long data);\n\n synchronized public static native void setAnalogData(int i, float v1, float v2);\n\n public static native int getValue(int key, int i);\n\n public static native String getValueStr(int key, int i);\n\n public static native void setValue(int key, int i, int value);\n\n public static native void setValueStr(int key, int i, String value);\n\n\tpublic static native int setKeyData(int keyCode, int keyAction, char keyChar);\n\n\tpublic static native int setMouseData(int i, int mouseAction,int button, float cx, float cy);\n\n}" }, { "identifier": "MAME4droid", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/MAME4droid.java", "snippet": "public class MAME4droid extends Activity {\n\n protected View emuView = null;\n\n protected InputView inputView = null;\n\n protected MainHelper mainHelper = null;\n protected PrefsHelper prefsHelper = null;\n protected DialogHelper dialogHelper = null;\n protected SAFHelper safHelper = null;\n\n protected InputHandler inputHandler = null;\n\n public PrefsHelper getPrefsHelper() {\n return prefsHelper;\n }\n\n public MainHelper getMainHelper() {\n return mainHelper;\n }\n\n public DialogHelper getDialogHelper() {\n return dialogHelper;\n }\n\n public SAFHelper getSAFHelper() {\n return safHelper;\n }\n\n public View getEmuView() {\n return emuView;\n }\n\n public InputView getInputView() {\n return inputView;\n }\n\n public InputHandler getInputHandler() {\n return inputHandler;\n }\n\n /**\n * Called when the activity is first created.\n */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n //android.os.Debug.waitForDebugger();\n\n Log.d(\"EMULATOR\", \"onCreate \" + this);\n System.out.println(\"onCreate intent:\" + getIntent().getAction());\n\n overridePendingTransition(0, 0);\n getWindow().setWindowAnimations(0);\n\n prefsHelper = new PrefsHelper(this);\n\n dialogHelper = new DialogHelper(this);\n\n mainHelper = new MainHelper(this);\n\n safHelper = new SAFHelper(this);\n\n inputHandler = new InputHandler(this);\n\n mainHelper.detectDevice();\n\n inflateViews();\n\n Emulator.setMAME4droid(this);\n\n mainHelper.updateMAME4droid();\n\n\t\tString uri = getPrefsHelper().getSAF_Uri();\n\t\tif (uri != null) {\n\t\t\tsafHelper.setURI(uri);\n\t\t}\n\n initMame4droid();\n }\n\n protected void initMame4droid() {\n if (!Emulator.isEmulating()) {\n\n if (getPrefsHelper().getInstallationDIR()==null || prefsHelper.getROMsDIR() == null ) {\n if (DialogHelper.savedDialog == DialogHelper.DIALOG_NONE) {\n\t\t\t\t\t showDialog(DialogHelper.DIALOG_ROMs);\n\t\t\t\t}\n } else { //roms dir no es null es que previamente hemos puesto \"\" o un path especifico. Venimos del recreate y si ha cambiado el installation path hay que actuzalizarlo\n\n boolean res = getMainHelper().ensureInstallationDIR(mainHelper.getInstallationDIR());\n if (res == false) {\n this.getPrefsHelper().setInstallationDIR(this.getPrefsHelper().getOldInstallationDIR());//revert\n } else {\n runMAME4droid();//MAIN ENTRY POINT\n }\n }\n }\n }\n\n\n public void inflateViews() {\n\n\t\tif(getPrefsHelper().getOrientationMode()!=0) {\n\t\t\tint mode = getMainHelper().getScreenOrientation();\n\t\t\tthis.setRequestedOrientation(mode);\n\t\t}\n\n if (getPrefsHelper().isNotchUsed()) {\n getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;\n }\n inputHandler.unsetInputListeners();\n\n Emulator.setPortraitFull(getPrefsHelper().isPortraitFullscreen());\n\n boolean full = false;\n if (prefsHelper.isPortraitFullscreen() && mainHelper.getscrOrientation() == Configuration.ORIENTATION_PORTRAIT) {\n setContentView(R.layout.main_fullscreen);\n full = true;\n } else {\n setContentView(R.layout.main);\n }\n\n FrameLayout fl = (FrameLayout) this.findViewById(R.id.EmulatorFrame);\n\n Emulator.setVideoRenderMode(getPrefsHelper().getVideoRenderMode());\n\n if (prefsHelper.getVideoRenderMode() == PrefsHelper.PREF_RENDER_GL) {\n\n if (prefsHelper.getNavBarMode() != PrefsHelper.PREF_NAVBAR_VISIBLE)\n this.getLayoutInflater().inflate(R.layout.emuview_gl_ext, fl);\n else\n this.getLayoutInflater().inflate(R.layout.emuview_gl, fl);\n\n emuView = this.findViewById(R.id.EmulatorViewGL);\n }\n\n if (full && prefsHelper.isPortraitTouchController()) {\n FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) emuView.getLayoutParams();\n lp.gravity = Gravity.TOP | Gravity.CENTER;\n }\n\n inputView = (InputView) this.findViewById(R.id.InputView);\n\n ((IEmuView) emuView).setMAME4droid(this);\n\n inputView.setMAME4droid(this);\n\n View frame = this.findViewById(R.id.EmulatorFrame);\n frame.setOnTouchListener(inputHandler);\n\n\n inputHandler.setInputListeners();\n }\n\n public void runMAME4droid() {\n\n getMainHelper().copyFiles();\n getMainHelper().removeFiles();\n\n Emulator.emulate(mainHelper.getLibDir(), mainHelper.getInstallationDIR());\n }\n\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n\t\tLog.d(\"EMULATOR\", \"onConfigurationChanged \" + this);\n\n super.onConfigurationChanged(newConfig);\n\n overridePendingTransition(0, 0);\n\n inflateViews();\n\n getMainHelper().updateMAME4droid();\n\n overridePendingTransition(0, 0);\n }\n\n\n //ACTIVITY\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (mainHelper != null)\n mainHelper.activityResult(requestCode, resultCode, data);\n }\n\n //LIVE CYCLE\n @Override\n protected void onResume() {\n Log.d(\"EMULATOR\", \"onResume \" + this);\n super.onResume();\n\n if (prefsHelper != null)\n prefsHelper.resume();\n\n if (DialogHelper.savedDialog != -1)\n showDialog(DialogHelper.savedDialog);\n else if (!ControlCustomizer.isEnabled())\n Emulator.resume();\n\n if (inputHandler != null) {\n if (inputHandler.getTiltSensor() != null)\n inputHandler.getTiltSensor().enable();\n }\n\n //System.out.println(\"OnResume\");\n }\n\n @Override\n protected void onPause() {\n Log.d(\"EMULATOR\", \"onPause \" + this);\n super.onPause();\n if (prefsHelper != null)\n prefsHelper.pause();\n if (!ControlCustomizer.isEnabled())\n Emulator.pause();\n if (inputHandler != null) {\n if (inputHandler.getTiltSensor() != null)\n inputHandler.getTiltSensor().disable();\n }\n\n if (dialogHelper != null) {\n dialogHelper.removeDialogs();\n }\n\n //System.out.println(\"OnPause\");\n }\n\n @Override\n protected void onStart() {\n Log.d(\"EMULATOR\", \"onStart \" + this);\n super.onStart();\n try {\n GameController.resetAutodetected();\n } catch (Throwable e) {\n }\n ;\n //System.out.println(\"OnStart\");\n }\n\n @Override\n protected void onStop() {\n Log.d(\"EMULATOR\", \"onStop \" + this);\n super.onStop();\n //System.out.println(\"OnStop\");\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n Log.d(\"EMULATOR\", \"onNewIntent \" + this);\n System.out.println(\"onNewIntent action:\" + intent.getAction());\n mainHelper.checkNewViewIntent(intent);\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n Log.d(\"EMULATOR\", \"onDestroy \" + this);\n\n View frame = this.findViewById(R.id.EmulatorFrame);\n if (frame != null)\n frame.setOnTouchListener(null);\n\n if (inputHandler != null) {\n inputHandler.unsetInputListeners();\n\n if (inputHandler.getTiltSensor() != null)\n inputHandler.getTiltSensor().disable();\n }\n\n if (emuView != null)\n ((IEmuView) emuView).setMAME4droid(null);\n\n /*\n if(inputView!=null)\n inputView.setMAME4droid(null);\n\n if(filterView!=null)\n filterView.setMAME4droid(null);\n\n prefsHelper = null;\n\n dialogHelper = null;\n\n mainHelper = null;\n\n inputHandler = null;\n\n inputView = null;\n\n emuView = null;\n\n filterView = null; */\n }\n\n\n //Dialog Stuff\n @Override\n protected Dialog onCreateDialog(int id) {\n\n if (dialogHelper != null) {\n Dialog d = dialogHelper.createDialog(id);\n if (d != null) return d;\n }\n return super.onCreateDialog(id);\n }\n\n @Override\n protected void onPrepareDialog(int id, Dialog dialog) {\n if (dialogHelper != null)\n dialogHelper.prepareDialog(id, dialog);\n }\n\n @Override\n public boolean dispatchGenericMotionEvent(MotionEvent event) {\n if (inputHandler != null)\n return inputHandler.genericMotion(event);\n return false;\n }\n\n\t@Override\n\tpublic void onPointerCaptureChanged(boolean hasCapture) {\n\t\tsuper.onPointerCaptureChanged(hasCapture);\n\t}\n\n\t@Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case 1:\n if (grantResults == null || grantResults.length == 0) {\n //this.showDialog(DialogHelper.DIALOG_NO_PERMISSIONS);\n System.out.println(\"***1\");\n } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n System.out.println(\"***2\");\n initMame4droid();\n } else {\n System.out.println(\"***3\");\n this.showDialog(DialogHelper.DIALOG_NO_PERMISSIONS);\n }\n break;\n default:\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n }\n }\n\n}" } ]
import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid;
9,027
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.input; public class TouchLightgun implements IController { protected int lightgun_pid = -1; protected long millis_pressed = 0; protected boolean press_on = false; protected MAME4droid mm = null; public void setMAME4droid(MAME4droid value) { mm = value; } public int getLightgun_pid(){ return lightgun_pid; } public void reset() { lightgun_pid = -1; } public void handleTouchLightgun(View v, MotionEvent event,int [] digital_data) { int pid = 0; int action = event.getAction(); int actionEvent = action & MotionEvent.ACTION_MASK; int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; pid = event.getPointerId(pointerIndex); if (actionEvent == MotionEvent.ACTION_UP || actionEvent == MotionEvent.ACTION_POINTER_UP || actionEvent == MotionEvent.ACTION_CANCEL) { if (pid == lightgun_pid) { millis_pressed = 0; press_on = false; lightgun_pid = -1; //Emulator.setAnalogData(4, 0, 0); digital_data[0] &= ~A_VALUE; digital_data[0] &= ~B_VALUE; } else { if(!press_on) digital_data[0] &= ~B_VALUE; else digital_data[0] &= ~A_VALUE; }
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.input; public class TouchLightgun implements IController { protected int lightgun_pid = -1; protected long millis_pressed = 0; protected boolean press_on = false; protected MAME4droid mm = null; public void setMAME4droid(MAME4droid value) { mm = value; } public int getLightgun_pid(){ return lightgun_pid; } public void reset() { lightgun_pid = -1; } public void handleTouchLightgun(View v, MotionEvent event,int [] digital_data) { int pid = 0; int action = event.getAction(); int actionEvent = action & MotionEvent.ACTION_MASK; int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; pid = event.getPointerId(pointerIndex); if (actionEvent == MotionEvent.ACTION_UP || actionEvent == MotionEvent.ACTION_POINTER_UP || actionEvent == MotionEvent.ACTION_CANCEL) { if (pid == lightgun_pid) { millis_pressed = 0; press_on = false; lightgun_pid = -1; //Emulator.setAnalogData(4, 0, 0); digital_data[0] &= ~A_VALUE; digital_data[0] &= ~B_VALUE; } else { if(!press_on) digital_data[0] &= ~B_VALUE; else digital_data[0] &= ~A_VALUE; }
Emulator.setDigitalData(0, digital_data[0]);
0
2023-12-18 11:16:18+00:00
12k
John200410/rusherhack-spotify
src/main/java/me/john200410/spotify/ui/SpotifyHudElement.java
[ { "identifier": "SpotifyPlugin", "path": "src/main/java/me/john200410/spotify/SpotifyPlugin.java", "snippet": "public class SpotifyPlugin extends Plugin {\n\t\n\tpublic static final File CONFIG_FILE = RusherHackAPI.getConfigPath().resolve(\"spotify.json\").toFile();\n\tpublic static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();\n\t\n\tprivate Config config = new Config();\n\tprivate HttpServer httpServer;\n\tprivate SpotifyAPI api;\n\t\n\t@Override\n\tpublic void onLoad() {\n\t\t\n\t\t//try load config\n\t\tif(CONFIG_FILE.exists()) {\n\t\t\ttry {\n\t\t\t\tthis.config = GSON.fromJson(IOUtils.toString(CONFIG_FILE.toURI(), StandardCharsets.UTF_8), Config.class);\n\t\t\t} catch(IOException e) {\n\t\t\t\tthis.logger.warn(\"Failed to load config\");\n\t\t\t}\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tthis.httpServer = this.setupServer();\n\t\t\tthis.httpServer.start();\n\t\t\tthis.api = new SpotifyAPI(this);\n\t\t\tthis.api.appID = this.config.appId;\n\t\t\tthis.api.appSecret = this.config.appSecret;\n\t\t\tthis.api.refreshToken = this.config.refresh_token;\n\t\t\t\n\t\t\tif(!this.api.appID.isEmpty() && !this.api.appSecret.isEmpty() && !this.api.refreshToken.isEmpty()) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.api.authorizationRefreshToken();\n\t\t\t\t} catch(Throwable t) {\n\t\t\t\t\tt.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//hud element\n\t\t\tRusherHackAPI.getHudManager().registerFeature(new SpotifyHudElement(this));\n\t\t} catch(IOException e) {\n\t\t\t//throw exception so plugin doesnt load\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\t\n\t\t//TODO: maybe window in the future?\n\t}\n\t\n\t@Override\n\tpublic void onUnload() {\n\t\tif(this.httpServer != null) {\n\t\t\tthis.httpServer.stop(0);\n\t\t}\n\t\t\n\t\tthis.saveConfig();\n\t}\n\t\n\t@Override\n\tpublic String getName() {\n\t\treturn \"Spotify\";\n\t}\n\t\n\t@Override\n\tpublic String getVersion() {\n\t\treturn \"1.1.1\";\n\t}\n\t\n\t@Override\n\tpublic String getDescription() {\n\t\treturn \"Spotify integration for rusherhack\";\n\t}\n\t\n\t@Override\n\tpublic String[] getAuthors() {\n\t\treturn new String[]{\"John200410\", \"DarkerInk\"};\n\t}\n\t\n\tpublic SpotifyAPI getAPI() {\n\t\treturn this.api;\n\t}\n\t\n\tprivate HttpServer setupServer() throws IOException {\n\t\tfinal HttpServer server = HttpServer.create(new InetSocketAddress(\"0.0.0.0\", 4000), 0);\n\t\t\n\t\tserver.createContext(\"/\", (req) -> {\n\t\t\tfinal URI uri = req.getRequestURI();\n\t\t\t\n\t\t\tbyte[] response = new byte[0];\n\t\t\t\n\t\t\tfinal Map<String, String> queryParams = getQueryParameters(uri.getQuery());\n\t\t\t\n\t\t\tif(uri.getPath().equals(\"/callback\")) {\n\t\t\t\tfinal String code = queryParams.get(\"code\");\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tvar res = this.api.authorizationCodeGrant(code);\n\t\t\t\t\t\n\t\t\t\t\tif(res) {\n\t\t\t\t\t\tthis.logger.info(\"Successfully got access token\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.logger.error(\"Failed to get access token\");\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t} catch(InterruptedException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t\tthis.logger.error(\"Failed to get access token\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttry(InputStream is = SpotifyPlugin.class.getResourceAsStream(\"/site/success.html\")) {\n\t\t\t\t\tObjects.requireNonNull(is, \"Couldn't find login.html\");\n\t\t\t\t\tresponse = IOUtils.toByteArray(is);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"text/html\");\n\t\t\t} else if(uri.getPath().equals(\"/\")) {\n\t\t\t\t\n\t\t\t\ttry(InputStream is = SpotifyPlugin.class.getResourceAsStream(\"/site/login.html\")) {\n\t\t\t\t\tObjects.requireNonNull(is, \"Couldn't find login.html\");\n\t\t\t\t\tresponse = IOUtils.toByteArray(is);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"text/html\");\n\t\t\t} else if(uri.getPath().equals(\"/setup\")) {\n\t\t\t\tfinal String appId = queryParams.get(\"appId\");\n\t\t\t\tfinal String appSecret = queryParams.get(\"appSecret\");\n\t\t\t\t\n\t\t\t\tString oauthUrl = this.api.setAppID(appId).setAppSecret(appSecret).setRedirectURI(\"http://localhost:4000/callback\").generateOAuthUrl();\n\t\t\t\t\n\t\t\t\tresponse = (\"{\\\"url\\\": \\\"\" + oauthUrl + \"\\\"}\").getBytes();\n\t\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"application/json\");\n\t\t\t}\n\t\t\t\n\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"text/html\");\n\t\t\treq.sendResponseHeaders(200, response.length);\n\t\t\treq.getResponseBody().write(response);\n\t\t\treq.getResponseBody().close();\n\t\t});\n\t\t\n\t\treturn server;\n\t}\n\t\n\tprivate Map<String, String> getQueryParameters(String query) {\n\t\tMap<String, String> queryParams = new HashMap<>();\n\t\t\n\t\tif(query != null) {\n\t\t\tString[] pairs = query.split(\"&\");\n\t\t\t\n\t\t\tfor(String pair : pairs) {\n\t\t\t\tString[] keyValue = pair.split(\"=\");\n\t\t\t\tif(keyValue.length == 2) {\n\t\t\t\t\tString key = keyValue[0];\n\t\t\t\t\tString value = keyValue[1];\n\t\t\t\t\tqueryParams.put(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn queryParams;\n\t}\n\t\n\tpublic Config getConfig() {\n\t\treturn this.config;\n\t}\n\t\n\tpublic void saveConfig() {\n\t\ttry(FileWriter writer = new FileWriter(CONFIG_FILE)) {\n\t\t\tGSON.toJson(this.config, writer);\n\t\t} catch(IOException e) {\n\t\t\tthis.logger.error(\"Failed to save config\");\n\t\t}\n\t}\n\t\n}" }, { "identifier": "SpotifyAPI", "path": "src/main/java/me/john200410/spotify/http/SpotifyAPI.java", "snippet": "public class SpotifyAPI {\n\t\n\t/**\n\t * Constants\n\t */\n\tpublic static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();\n\tprivate static final String API_URL = \"https://api.spotify.com\";\n\tprivate static final String AUTH_URL = \"https://accounts.spotify.com\";\n\t\n\t/**\n\t * Variables\n\t */\n\tprivate final SpotifyPlugin plugin;\n\tprivate boolean isConnected = false;\n\tprivate boolean playbackAvailable = false;\n\tprivate PlaybackState currentStatus;\n\tprivate final Timer statusUpdateTimer = new Timer();\n\t\n\tprivate final Timer refreshTokenTimer = new Timer();\n\tprivate String accessToken;\n\tpublic String refreshToken;\n\tprivate Integer expiresIn;\n\t\n\tpublic String appID;\n\tpublic String appSecret;\n\tprivate String redirectURI;\n\t\n\tprivate Boolean premium;\n\t\n\tprivate String deviceID;\n\t\n\tpublic SpotifyAPI(SpotifyPlugin plugin) {\n\t\tthis.plugin = plugin;\n\t}\n\t\n\tpublic void updateStatus(long rateLimit) {\n\t\t\n\t\tif(rateLimit > 0 && !this.statusUpdateTimer.passed(rateLimit)) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tthis.currentStatus = this.getStatus();\n\t\t\t} catch(IOException | InterruptedException | JsonSyntaxException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t\tthis.statusUpdateTimer.reset();\n\t}\n\t\n\tpublic void submitTogglePlay() {\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tthis.togglePlay();\n\t\t\t} catch(NoPremiumException e) {\n\t\t\t\tRusherHackAPI.getNotificationManager().send(NotificationType.ERROR, \"Spotify Premium is required for this function!\");\n\t\t\t} catch(IOException | InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic void submitNext() {\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tthis.next();\n\t\t\t} catch(NoPremiumException e) {\n\t\t\t\tRusherHackAPI.getNotificationManager().send(NotificationType.ERROR, \"Spotify Premium is required for this function!\");\n\t\t\t} catch(IOException | InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic void submitPrevious() {\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tthis.previous();\n\t\t\t} catch(NoPremiumException e) {\n\t\t\t\tRusherHackAPI.getNotificationManager().send(NotificationType.ERROR, \"Spotify Premium is required for this function!\");\n\t\t\t} catch(IOException | InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic void submitToggleShuffle() {\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tthis.setShuffle(!this.currentStatus.shuffle_state);\n\t\t\t} catch(NoPremiumException e) {\n\t\t\t\tRusherHackAPI.getNotificationManager().send(NotificationType.ERROR, \"Spotify Premium is required for this function!\");\n\t\t\t} catch(IOException | InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic void submitToggleRepeat() {\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tString repeat = this.currentStatus.repeat_state;\n\t\t\t\tif(repeat.equals(\"track\")) {\n\t\t\t\t\trepeat = \"off\";\n\t\t\t\t} else if(repeat.equals(\"context\")) {\n\t\t\t\t\trepeat = \"track\";\n\t\t\t\t} else {\n\t\t\t\t\trepeat = \"context\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthis.setRepeat(repeat);\n\t\t\t} catch(NoPremiumException e) {\n\t\t\t\tRusherHackAPI.getNotificationManager().send(NotificationType.ERROR, \"Spotify Premium is required for this function!\");\n\t\t\t} catch(IOException | InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic void submitSeek(long ms) {\n\t\tthis.submit(() -> {\n\t\t\ttry {\n\t\t\t\tthis.seek(ms);\n\t\t\t} catch(NoPremiumException e) {\n\t\t\t\tRusherHackAPI.getNotificationManager().send(NotificationType.ERROR, \"Spotify Premium is required for this function!\");\n\t\t\t} catch(IOException | InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t});\n\t}\n\t\n\t// only method that doesn't require premium\n\tprivate PlaybackState getStatus() throws IOException, InterruptedException, JsonSyntaxException {\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"GET\",\n\t\t\t\tthis.getUrl(\"/v1/me/player\", false)\n\t\t);\n\n\t\tthis.statusUpdateTimer.reset();\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 200 -> this.playbackAvailable = true;\n\t\t\tcase 204 -> {\n\t\t\t\tthis.playbackAvailable = false;\n\t\t\t\t//this.plugin.getLogger().error(\"UPDATESTATUS STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tcase 401 -> {\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.plugin.getLogger().error(\"UPDATESTATUS STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tdefault -> {\n\t\t\t\tthis.plugin.getLogger().error(\"UPDATESTATUS STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfinal PlaybackState status = SpotifyPlugin.GSON.fromJson(request.body(), PlaybackState.class);\n\t\tthis.deviceID = status.device.id;\n\t\treturn status;\n\t}\n\t\n\tprivate boolean togglePlay() throws IOException, InterruptedException, NoPremiumException {\n\t\tif(!this.isPremium()) {\n\t\t\tthrow new NoPremiumException();\n\t\t}\n\t\t\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal String url = this.currentStatus.is_playing ? \"/v1/me/player/pause\" : \"/v1/me/player/play\";\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"PUT\",\n\t\t\t\tthis.getUrl(url, false)\n\t\t);\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 204 -> this.playbackAvailable = true;\n\t\t\tcase 401 -> {\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.plugin.getLogger().error(\"TOGGLEPLAY STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdefault -> {\n\t\t\t\tthis.plugin.getLogger().error(\"TOGGLEPLAY STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//update status\n\t\tthis.currentStatus = this.getStatus();\n\t\treturn true;\n\t}\n\t\n\tprivate boolean next() throws NoPremiumException, IOException, InterruptedException {\n\t\tif(!this.isPremium()) {\n\t\t\tthrow new NoPremiumException();\n\t\t}\n\t\t\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"POST\",\n\t\t\t\tthis.getUrl(\"/v1/me/player/next\", false)\n\t\t);\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 204 -> this.playbackAvailable = true;\n\t\t\tcase 401 -> {\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.plugin.getLogger().error(\"NEXT STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdefault -> {\n\t\t\t\tthis.plugin.getLogger().error(\"NEXT STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//update status\n\t\tthis.currentStatus = this.getStatus();\n\t\treturn true;\n\t}\n\t\n\tprivate boolean previous() throws NoPremiumException, IOException, InterruptedException {\n\t\tif(!this.isPremium()) {\n\t\t\tthrow new NoPremiumException();\n\t\t}\n\t\t\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"POST\",\n\t\t\t\tthis.getUrl(\"/v1/me/player/previous\", false)\n\t\t);\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 204 -> this.playbackAvailable = true;\n\t\t\tcase 401 -> {\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.plugin.getLogger().error(\"PREVIOUS STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdefault -> {\n\t\t\t\tthis.plugin.getLogger().error(\"PREVIOUS STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//update status\n\t\tthis.currentStatus = this.getStatus();\n\t\treturn true;\n\t}\n\t\n\tprivate boolean setShuffle(boolean shuffle) throws NoPremiumException, IOException, InterruptedException {\n\t\tif(!this.isPremium()) {\n\t\t\tthrow new NoPremiumException();\n\t\t}\n\t\t\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"PUT\",\n\t\t\t\tthis.getUrl(\"/v1/me/player/shuffle?state=\" + shuffle, true)\n\t\t);\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 204 -> this.playbackAvailable = true;\n\t\t\tcase 401 -> {\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.plugin.getLogger().error(\"SHUFFLE STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdefault -> {\n\t\t\t\tthis.plugin.getLogger().error(\"SHUFFLE STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//update status\n\t\tthis.currentStatus = this.getStatus();\n\t\treturn true;\n\t}\n\t\n\t// repeat can be one of: track, context, or off.\n\t// track will repeat the current playlist.\n\t// context will repeat the current song.\n\t// off will turn repeat off.\n\tprivate boolean setRepeat(String repeat) throws NoPremiumException, IOException, InterruptedException {\n\t\tif(!this.isPremium()) {\n\t\t\tthrow new NoPremiumException();\n\t\t}\n\t\t\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"PUT\",\n\t\t\t\tthis.getUrl(\"/v1/me/player/repeat?state=\" + repeat, true)\n\t\t);\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 204 -> this.playbackAvailable = true;\n\t\t\tcase 401 -> {\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.plugin.getLogger().error(\"REPEAT STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdefault -> {\n\t\t\t\tthis.plugin.getLogger().error(\"REPEAT STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//update status\n\t\tthis.currentStatus = this.getStatus();\n\t\treturn true;\n\t}\n\t\n\tprivate boolean seek(long ms) throws NoPremiumException, IOException, InterruptedException {\n\t\tif(!this.isPremium()) {\n\t\t\tthrow new NoPremiumException();\n\t\t}\n\t\t\n\t\tthis.updateAccessToken();\n\t\t\n\t\tfinal long duration = this.currentStatus.item.duration_ms;\n\t\t\n\t\t//clamp\n\t\tms = MathUtils.clamp(ms, 0, duration);\n\t\t\n\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\"PUT\",\n\t\t\t\tthis.getUrl(\"/v1/me/player/seek?position_ms=\" + ms, true)\n\t\t);\n\t\t\n\t\tswitch(request.statusCode()) {\n\t\t\tcase 204:\n\t\t\t\tthis.playbackAvailable = true;\n\t\t\t\tbreak;\n\t\t\tcase 401:\n\t\t\t\tthis.plugin.getLogger().error(\"Lost connection to Spotify\");\n\t\t\t\tthis.isConnected = false;\n\t\t\tdefault:\n\t\t\t\tthis.plugin.getLogger().error(\"REPEAT STATUS CODE: \" + request.statusCode());\n\t\t\t\treturn false;\n\t\t}\n\t\t\n\t\t//update status\n\t\tthis.currentStatus = this.getStatus();\n\t\treturn true;\n\t}\n\t\n\tprivate boolean isPremium() {\n\t\tif(this.premium != null) {\n\t\t\treturn this.premium;\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tthis.updateAccessToken();\n\t\t\t\n\t\t\tfinal Response request = this.makeRequest(\n\t\t\t\t\t\"GET\",\n\t\t\t\t\tthis.getUrl(\"/v1/me\", false)\n\t\t\t);\n\t\t\t\n\t\t\tswitch(request.statusCode()) {\n\t\t\t\tcase 200 -> {\n\t\t\t\t}\n\t\t\t\tcase 401 -> {\n\t\t\t\t\tthis.isConnected = false;\n\t\t\t\t\tthis.plugin.getLogger().error(\"USER STATUS CODE: \" + request.statusCode());\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tdefault -> {\n\t\t\t\t\tthis.plugin.getLogger().error(\"USER STATUS CODE: \" + request.statusCode());\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfinal User user = SpotifyPlugin.GSON.fromJson(request.body(), User.class);\n\t\t\tthis.premium = user.product.equals(\"premium\");\n\t\t\treturn this.premium;\n\t\t} catch(IOException | InterruptedException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate Response makeRequest(String method, String endpoint) throws IOException, InterruptedException {\n\t\tfinal HttpRequest request = HttpRequest.newBuilder()\n\t\t\t\t\t\t\t\t\t\t\t .uri(URI.create(API_URL + endpoint))\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Authorization\", \"Bearer \" + this.accessToken)\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Content-Type\", \"application/json\")\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Accept\", \"application/json\")\n\t\t\t\t\t\t\t\t\t\t\t .method(method, HttpRequest.BodyPublishers.noBody())\n\t\t\t\t\t\t\t\t\t\t\t .timeout(Duration.ofSeconds(8))\n\t\t\t\t\t\t\t\t\t\t\t .build();\n\t\t\n\t\tfinal HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n\t\treturn new Response(response.statusCode(), response.body());\n\t}\n\t\n\t\n\tpublic boolean authorizationCodeGrant(String code) throws IOException, InterruptedException {\n\t\tMap<Object, Object> data = new HashMap<>();\n\t\tdata.put(\"grant_type\", \"authorization_code\");\n\t\tdata.put(\"redirect_uri\", this.redirectURI);\n\t\tdata.put(\"code\", code);\n\t\tdata.put(\"client_id\", this.appID);\n\t\tdata.put(\"client_secret\", this.appSecret);\n\t\t\n\t\tString requestBody = data.entrySet().stream()\n\t\t\t\t\t\t\t\t .map(entry -> entry.getKey().toString() + \"=\" + entry.getValue().toString())\n\t\t\t\t\t\t\t\t .collect(Collectors.joining(\"&\"));\n\t\t\n\t\tfinal HttpRequest request = HttpRequest.newBuilder()\n\t\t\t\t\t\t\t\t\t\t\t .uri(URI.create(AUTH_URL + \"/api/token\"))\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Accept\", \"application/json\")\n\t\t\t\t\t\t\t\t\t\t\t .POST(HttpRequest.BodyPublishers.ofString(requestBody))\n\t\t\t\t\t\t\t\t\t\t\t .timeout(Duration.ofSeconds(8))\n\t\t\t\t\t\t\t\t\t\t\t .build();\n\t\t\n\t\tfinal HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n\t\t\n\t\tfinal CodeGrant body = SpotifyPlugin.GSON.fromJson(response.body(), CodeGrant.class);\n\t\t\n\t\tif(response.statusCode() != 200) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tthis.accessToken = body.access_token;\n\t\tthis.refreshToken = body.refresh_token;\n\t\tthis.setExpiration(body.expires_in);\n\t\tthis.isConnected = true;\n\t\t\n\t\tfinal Config config = this.plugin.getConfig();\n\t\tconfig.appId = this.appID;\n\t\tconfig.appSecret = this.appSecret;\n\t\tconfig.refresh_token = this.refreshToken;\n\t\tthis.plugin.saveConfig();\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic boolean authorizationRefreshToken() throws IOException, InterruptedException {\n\t\tMap<Object, Object> data = new HashMap<>();\n\t\tdata.put(\"grant_type\", \"refresh_token\");\n\t\tdata.put(\"refresh_token\", this.refreshToken);\n\t\tdata.put(\"client_id\", this.appID);\n\t\tdata.put(\"client_secret\", this.appSecret);\n\t\t\n\t\tString requestBody = data.entrySet().stream()\n\t\t\t\t\t\t\t\t .map(entry -> entry.getKey().toString() + \"=\" + entry.getValue().toString())\n\t\t\t\t\t\t\t\t .collect(Collectors.joining(\"&\"));\n\t\t\n\t\tfinal HttpRequest request = HttpRequest.newBuilder()\n\t\t\t\t\t\t\t\t\t\t\t .uri(URI.create(AUTH_URL + \"/api/token\"))\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t\t\t\t\t\t\t\t\t\t\t .header(\"Accept\", \"application/json\")\n\t\t\t\t\t\t\t\t\t\t\t .POST(HttpRequest.BodyPublishers.ofString(requestBody))\n\t\t\t\t\t\t\t\t\t\t\t .timeout(Duration.ofSeconds(8))\n\t\t\t\t\t\t\t\t\t\t\t .build();\n\t\t\n\t\tfinal HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n\t\t\n\t\tif(response.statusCode() != 200) {\n\t\t\t/*\n\t\t\tChatUtils.print(\"debug 8\");\n\t\t\tthis.plugin.getLogger().info(response.body());\n\t\t\t\n\t\t\t */\n\t\t\tthis.isConnected = false;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfinal CodeGrant body = SpotifyPlugin.GSON.fromJson(response.body(), CodeGrant.class);\n\t\t\n\t\tthis.accessToken = body.access_token;\n\t\tthis.setExpiration(body.expires_in);\n\t\tthis.isConnected = true;\n\t\t\n\t\tfinal Config config = this.plugin.getConfig();\n\t\tconfig.appId = this.appID;\n\t\tconfig.appSecret = this.appSecret;\n\t\tconfig.refresh_token = this.refreshToken;\n\t\tthis.plugin.saveConfig();\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprivate void setExpiration(int expiresIn) {\n\t\tthis.expiresIn = expiresIn;\n\t\tthis.refreshTokenTimer.reset();\n\t}\n\t\n\tpublic String generateOAuthUrl() {\n\t\tfinal String[] scopes = new String[]{\n\t\t\t\t\"user-read-private\", // So we can check if the user is premium\n\t\t\t\t\"user-read-currently-playing\", // So we can get the current song\n\t\t\t\t\"user-read-playback-state\", // So we can get the current song\n\t\t\t\t\"user-modify-playback-state\" // So we can control the player\n\t\t};\n\t\t\n\t\treturn AUTH_URL + \"/authorize?client_id=\" + this.appID + \"&response_type=code&redirect_uri=\" + this.redirectURI + \"&scope=\" + String.join(\"%20\", scopes);\n\t}\n\t\n\tprivate void updateAccessToken() throws IOException, InterruptedException {\n\t\tif(this.expiresIn == null) {\n\t\t\treturn;\n\t\t} else if(!this.isConnected && this.refreshTokenTimer.passed(10000L)) {\n\t\t\tthis.authorizationRefreshToken();\n\t\t\tthis.refreshTokenTimer.reset();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(this.refreshTokenTimer.passed(this.expiresIn * 1000L)) {\n\t\t\tthis.authorizationRefreshToken();\n\t\t}\n\t}\n\t\n\tpublic Future<?> submit(Runnable runnable) {\n\t\treturn Util.backgroundExecutor().submit(runnable);\n\t}\n\t\n\tprivate String getUrl(String url, Boolean Params) {\n\t\treturn this.deviceID == null ? url : url + (Params ? \"&device_id=\" + this.deviceID : \"?device_id=\" + this.deviceID);\n\t}\n\t\n\tpublic SpotifyAPI setAppID(String appID) {\n\t\tthis.appID = appID;\n\t\treturn this;\n\t}\n\t\n\tpublic SpotifyAPI setAppSecret(String appSecret) {\n\t\tthis.appSecret = appSecret;\n\t\treturn this;\n\t}\n\t\n\tpublic SpotifyAPI setRedirectURI(String redirectURI) {\n\t\tthis.redirectURI = redirectURI;\n\t\treturn this;\n\t}\n\t\n\tpublic PlaybackState getCurrentStatus() {\n\t\treturn this.currentStatus;\n\t}\n\t\n\tpublic boolean isConnected() {\n\t\treturn this.isConnected;\n\t}\n\t\n\tpublic boolean isPlaybackAvailable() {\n\t\treturn this.playbackAvailable;\n\t}\n\t\n}" }, { "identifier": "PlaybackState", "path": "src/main/java/me/john200410/spotify/http/responses/PlaybackState.java", "snippet": "public class PlaybackState {\n\n\tpublic Device device;\n\tpublic String repeat_state;\n\tpublic boolean shuffle_state;\n\tpublic Context context;\n\tpublic long timestamp;\n\tpublic int progress_ms;\n\tpublic boolean is_playing;\n\tpublic Item item;\n\tpublic String currently_playing_type;\n\tpublic Actions actions;\n\n\tpublic static class Device {\n\t\tpublic String id;\n\t\tpublic boolean is_active;\n\t\tpublic boolean is_private_session;\n\t\tpublic boolean is_restricted;\n\t\tpublic String name;\n\t\tpublic String type;\n\t\tpublic int volume_percent;\n\t\tpublic boolean supports_volume;\n\t}\n\n\tpublic static class Context {\n\t\tpublic String type;\n\t\tpublic String href;\n\t\tpublic ExternalUrls external_urls;\n\t\tpublic String uri;\n\n\t\tpublic static class ExternalUrls {\n\t\t\tpublic String spotify;\n\t\t}\n\t}\n\n\tpublic static class Item {\n\t\tpublic Album album;\n\t\tpublic Artist[] artists;\n\t\tpublic String[] available_markets;\n\t\tpublic int disc_number;\n\t\tpublic long duration_ms;\n\t\tpublic boolean explicit;\n\t\tpublic ExternalIds external_ids;\n\t\tpublic ExternalUrls external_urls;\n\t\tpublic String href;\n\t\tpublic String id;\n\t\tpublic String name;\n\t\tpublic int popularity;\n\t\tpublic String preview_url;\n\t\tpublic int track_number;\n\t\tpublic String type;\n\t\tpublic String uri;\n\t\tpublic boolean is_local;\n\n\t\tpublic static class Album {\n\t\t\tpublic String album_type;\n\t\t\tpublic int total_tracks;\n\t\t\tpublic String[] available_markets;\n\t\t\tpublic ExternalUrls external_urls;\n\t\t\tpublic String href;\n\t\t\tpublic String id;\n\t\t\tpublic Image[] images;\n\t\t\tpublic String name;\n\t\t\tpublic String release_date;\n\t\t\tpublic String release_date_precision;\n\t\t\tpublic String type;\n\t\t\tpublic String uri;\n\t\t\tpublic Artist[] artists;\n\n\t\t\tpublic static class Image {\n\t\t\t\tpublic String url;\n\t\t\t\tpublic int height;\n\t\t\t\tpublic int width;\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Artist {\n\t\t\tpublic ExternalUrls external_urls;\n\t\t\tpublic String href;\n\t\t\tpublic String id;\n\t\t\tpublic String name;\n\t\t\tpublic String type;\n\t\t\tpublic String uri;\n\t\t}\n\n\t\tpublic static class ExternalIds {\n\t\t\tpublic String isrc;\n\t\t}\n\n\t\tpublic static class ExternalUrls {\n\t\t\tpublic String spotify;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn this.id.hashCode();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\treturn obj instanceof Item item && item.id != null && item.id.equals(this.id);\n\t\t}\n\t}\n\n\tpublic static class Actions {\n\t\tpublic boolean interrupting_playback;\n\t\tpublic boolean pausing;\n\t\tpublic boolean resuming;\n\t\tpublic boolean seeking;\n\t\tpublic boolean skipping_next;\n\t\tpublic boolean skipping_prev;\n\t\tpublic boolean toggling_repeat_context;\n\t\tpublic boolean toggling_repeat_track;\n\t\tpublic boolean toggling_shuffle;\n\t\tpublic boolean transferring_playback;\n\t}\n}" } ]
import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import joptsimple.internal.Strings; import me.john200410.spotify.SpotifyPlugin; import me.john200410.spotify.http.SpotifyAPI; import me.john200410.spotify.http.responses.PlaybackState; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.ChatScreen; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.resources.ResourceLocation; import org.lwjgl.glfw.GLFW; import org.rusherhack.client.api.bind.key.GLFWKey; import org.rusherhack.client.api.events.client.input.EventMouse; import org.rusherhack.client.api.feature.hud.ResizeableHudElement; import org.rusherhack.client.api.render.IRenderer2D; import org.rusherhack.client.api.render.RenderContext; import org.rusherhack.client.api.render.font.IFontRenderer; import org.rusherhack.client.api.render.graphic.VectorGraphic; import org.rusherhack.client.api.setting.BindSetting; import org.rusherhack.client.api.setting.ColorSetting; import org.rusherhack.client.api.ui.ScaledElementBase; import org.rusherhack.client.api.utils.InputUtils; import org.rusherhack.core.bind.key.NullKey; import org.rusherhack.core.event.stage.Stage; import org.rusherhack.core.event.subscribe.Subscribe; import org.rusherhack.core.interfaces.IClickable; import org.rusherhack.core.setting.BooleanSetting; import org.rusherhack.core.setting.NumberSetting; import org.rusherhack.core.utils.ColorUtils; import org.rusherhack.core.utils.MathUtils; import org.rusherhack.core.utils.Timer; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpRequest; import java.net.http.HttpResponse;
7,421
package me.john200410.spotify.ui; /** * @author John200410 */ public class SpotifyHudElement extends ResizeableHudElement { public static final int BACKGROUND_COLOR = ColorUtils.transparency(Color.BLACK.getRGB(), 0.5f); private static final PlaybackState.Item AI_DJ_SONG = new PlaybackState.Item(); //item that is displayed when the DJ is talking static { AI_DJ_SONG.album = new PlaybackState.Item.Album(); AI_DJ_SONG.artists = new PlaybackState.Item.Artist[1]; AI_DJ_SONG.album.images = new PlaybackState.Item.Album.Image[1]; AI_DJ_SONG.artists[0] = new PlaybackState.Item.Artist(); AI_DJ_SONG.album.images[0] = new PlaybackState.Item.Album.Image(); AI_DJ_SONG.artists[0].name = "Spotify"; AI_DJ_SONG.album.name = "Songs Made For You"; AI_DJ_SONG.name = AI_DJ_SONG.id = "DJ"; AI_DJ_SONG.duration_ms = 30000; AI_DJ_SONG.album.images[0].url = "https://i.imgur.com/29vr8jz.png"; AI_DJ_SONG.album.images[0].width = 640; AI_DJ_SONG.album.images[0].height = 640; AI_DJ_SONG.uri = ""; } /** * Settings */ private final BooleanSetting authenticateButton = new BooleanSetting("Authenticate", true) .setVisibility(() -> !this.isConnected()); private final BooleanSetting background = new BooleanSetting("Background", true); private final ColorSetting backgroundColor = new ColorSetting("Color", new Color(BACKGROUND_COLOR, true)); private final NumberSetting<Double> updateDelay = new NumberSetting<>("UpdateDelay", 0.5d, 0.25d, 2d); private final BooleanSetting binds = new BooleanSetting("Binds", false); private final BindSetting playPauseBind = new BindSetting("Play/Pause", NullKey.INSTANCE); private final BindSetting backBind = new BindSetting("Back", NullKey.INSTANCE); private final BindSetting nextBind = new BindSetting("Next", NullKey.INSTANCE); private final BindSetting back5Bind = new BindSetting("Back 5", NullKey.INSTANCE); private final BindSetting next5Bind = new BindSetting("Next 5", NullKey.INSTANCE); /** * Media Controller */ private final SongInfoHandler songInfo; private final DurationHandler duration; private final MediaControllerHandler mediaController; /** * Variables */ private final VectorGraphic spotifyLogo; private final ResourceLocation trackThumbnailResourceLocation; private final DynamicTexture trackThumbnailTexture;
package me.john200410.spotify.ui; /** * @author John200410 */ public class SpotifyHudElement extends ResizeableHudElement { public static final int BACKGROUND_COLOR = ColorUtils.transparency(Color.BLACK.getRGB(), 0.5f); private static final PlaybackState.Item AI_DJ_SONG = new PlaybackState.Item(); //item that is displayed when the DJ is talking static { AI_DJ_SONG.album = new PlaybackState.Item.Album(); AI_DJ_SONG.artists = new PlaybackState.Item.Artist[1]; AI_DJ_SONG.album.images = new PlaybackState.Item.Album.Image[1]; AI_DJ_SONG.artists[0] = new PlaybackState.Item.Artist(); AI_DJ_SONG.album.images[0] = new PlaybackState.Item.Album.Image(); AI_DJ_SONG.artists[0].name = "Spotify"; AI_DJ_SONG.album.name = "Songs Made For You"; AI_DJ_SONG.name = AI_DJ_SONG.id = "DJ"; AI_DJ_SONG.duration_ms = 30000; AI_DJ_SONG.album.images[0].url = "https://i.imgur.com/29vr8jz.png"; AI_DJ_SONG.album.images[0].width = 640; AI_DJ_SONG.album.images[0].height = 640; AI_DJ_SONG.uri = ""; } /** * Settings */ private final BooleanSetting authenticateButton = new BooleanSetting("Authenticate", true) .setVisibility(() -> !this.isConnected()); private final BooleanSetting background = new BooleanSetting("Background", true); private final ColorSetting backgroundColor = new ColorSetting("Color", new Color(BACKGROUND_COLOR, true)); private final NumberSetting<Double> updateDelay = new NumberSetting<>("UpdateDelay", 0.5d, 0.25d, 2d); private final BooleanSetting binds = new BooleanSetting("Binds", false); private final BindSetting playPauseBind = new BindSetting("Play/Pause", NullKey.INSTANCE); private final BindSetting backBind = new BindSetting("Back", NullKey.INSTANCE); private final BindSetting nextBind = new BindSetting("Next", NullKey.INSTANCE); private final BindSetting back5Bind = new BindSetting("Back 5", NullKey.INSTANCE); private final BindSetting next5Bind = new BindSetting("Next 5", NullKey.INSTANCE); /** * Media Controller */ private final SongInfoHandler songInfo; private final DurationHandler duration; private final MediaControllerHandler mediaController; /** * Variables */ private final VectorGraphic spotifyLogo; private final ResourceLocation trackThumbnailResourceLocation; private final DynamicTexture trackThumbnailTexture;
private final SpotifyPlugin plugin;
0
2023-12-19 17:59:37+00:00
12k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/item/items/armor/LeafletPants.java
[ { "identifier": "ItemStatistic", "path": "generic/src/main/java/net/swofty/types/generic/user/statistics/ItemStatistic.java", "snippet": "@Getter\npublic enum ItemStatistic {\n // Non-Player Statistics\n DAMAGE(\"Damage\", true, null, \"+\", \"\", \"❁\"),\n\n // Player Statistics\n HEALTH(\"Health\", true, \"§c\", \"+\", \"\", \"❤\"),\n DEFENSE(\"Defense\", false, \"§a\", \"+\", \"\", \"❈\"),\n SPEED(\"Speed\", false, \"§f\", \"+\", \"\", \"✦\"),\n STRENGTH(\"Strength\", true, \"§c\", \"+\", \"\", \"❁\"),\n INTELLIGENCE(\"Intelligence\", false, \"§b\", \"+\", \"\", \"✎\"),\n MINING_SPEED(\"Mining Speed\", false, \"§6\", \"+\", \"\", \"⸕\"),\n ;\n\n private final String displayName;\n private final boolean isRed;\n private final String colour;\n private final String prefix;\n private final String suffix;\n private final String symbol;\n\n ItemStatistic(String displayName, boolean isRed, String colour, String prefix, String suffix, String symbol) {\n this.displayName = displayName;\n this.isRed = isRed;\n this.colour = colour;\n this.prefix = prefix;\n this.suffix = suffix;\n this.symbol = symbol;\n }\n}" }, { "identifier": "ItemStatistics", "path": "generic/src/main/java/net/swofty/types/generic/user/statistics/ItemStatistics.java", "snippet": "@Getter\npublic class ItemStatistics {\n\n public static final ItemStatistics EMPTY = new ItemStatistics(new EnumMap<>(ItemStatistic.class));\n\n private final Map<ItemStatistic, Integer> statistics;\n\n // Private constructor used by the builder\n private ItemStatistics(Map<ItemStatistic, Integer> statistics) {\n this.statistics = new EnumMap<>(statistics);\n }\n\n // Static method to create the builder\n public static ItemStatisticsBuilder builder() {\n return new ItemStatisticsBuilder();\n }\n\n // Builder class\n public static class ItemStatisticsBuilder {\n private final Map<ItemStatistic, Integer> statistics = new EnumMap<>(ItemStatistic.class);\n\n public ItemStatisticsBuilder with(ItemStatistic stat, Integer value) {\n this.statistics.put(stat, value);\n return this;\n }\n\n public ItemStatistics build() {\n return new ItemStatistics(this.statistics);\n }\n }\n\n public Integer get(ItemStatistic stat) {\n return this.statistics.getOrDefault(stat, 0);\n }\n\n public ItemStatistics add(ItemStatistics other) {\n for (ItemStatistic stat : ItemStatistic.values()) {\n this.statistics.merge(stat, other.get(stat), Integer::sum);\n }\n return this;\n }\n}" }, { "identifier": "ItemType", "path": "generic/src/main/java/net/swofty/types/generic/item/ItemType.java", "snippet": "public enum ItemType {\n ENCHANTED_BOOK(Material.ENCHANTED_BOOK, Rarity.UNCOMMON, EnchantedBook.class),\n DIRT(Material.DIRT, Rarity.EPIC),\n SKYBLOCK_MENU(Material.NETHER_STAR, Rarity.COMMON, SkyBlockMenu.class),\n AIR(Material.AIR, Rarity.COMMON),\n\n /**\n * Talismans\n */\n ZOMBIE_TALISMAN(Material.PLAYER_HEAD, Rarity.COMMON, ZombieTalisman.class),\n\n /**\n * Minions\n */\n COBBLESTONE_MINION(Material.PLAYER_HEAD, Rarity.RARE, CobblestoneMinion.class),\n\n /**\n * Farming Props\n */\n ROOKIE_HOE(Material.STONE_HOE, Rarity.COMMON, RookieHoe.class),\n WOODEN_HOE(Material.WOODEN_HOE, Rarity.COMMON),\n STONE_HOE(Material.STONE_HOE, Rarity.COMMON),\n IRON_HOE(Material.IRON_HOE, Rarity.COMMON),\n DIAMOND_HOE(Material.DIAMOND_HOE, Rarity.UNCOMMON),\n NETHERITE_HOE(Material.NETHERITE_HOE, Rarity.RARE),\n WHEAT(Material.WHEAT, Rarity.COMMON),\n\n /**\n * Armor Sets\n */\n LEAFLET_HAT(Material.OAK_LEAVES, Rarity.COMMON, LeafletHat.class),\n LEAFLET_TUNIC(Material.LEATHER_CHESTPLATE, Rarity.COMMON, LeafletTunic.class),\n LEAFLET_PANTS(Material.LEATHER_LEGGINGS, Rarity.COMMON, LeafletPants.class),\n LEAFLET_SANDALS(Material.LEATHER_BOOTS, Rarity.COMMON, LeafletSandals.class),\n\n /**\n * Pickaxes\n */\n PIONEERS_PICKAXE(Material.WOODEN_PICKAXE, Rarity.SPECIAL, PioneersPickaxe.class),\n DIAMOND_PICKAXE(Material.DIAMOND_PICKAXE, Rarity.UNCOMMON, DiamondPickaxe.class),\n IRON_PICKAXE(Material.IRON_PICKAXE, Rarity.COMMON, IronPickaxe.class),\n STONE_PICKAXE(Material.STONE_PICKAXE, Rarity.COMMON, StonePickaxe.class),\n WOODEN_PICKAXE(Material.WOODEN_PICKAXE, Rarity.COMMON, WoodenPickaxe.class),\n\n /**\n * Swords\n */\n HYPERION(Material.IRON_SWORD, Rarity.LEGENDARY, Hyperion.class),\n DIAMOND_SWORD(Material.DIAMOND_SWORD, Rarity.UNCOMMON, DiamondSword.class),\n IRON_SWORD(Material.IRON_SWORD, Rarity.COMMON, IronSword.class),\n STONE_SWORD(Material.STONE_SWORD, Rarity.COMMON, StoneSword.class),\n WOODEN_SWORD(Material.WOODEN_SWORD, Rarity.COMMON, WoodenSword.class),\n\n /**\n * Vanilla Items\n */\n CRAFTING_TABLE(Material.CRAFTING_TABLE, Rarity.COMMON),\n OAK_LEAVES(Material.OAK_LEAVES, Rarity.COMMON),\n STICK(Material.STICK, Rarity.COMMON, Stick.class),\n ACACIA_WOOD(Material.ACACIA_WOOD, Rarity.COMMON),\n BAKED_POTATO(Material.BAKED_POTATO, Rarity.COMMON),\n BIRCH_WOOD(Material.BIRCH_WOOD, Rarity.COMMON),\n BLAZE_ROD(Material.BLAZE_ROD, Rarity.COMMON),\n BONE(Material.BONE, Rarity.COMMON),\n BONE_BLOCK(Material.BONE_BLOCK, Rarity.COMMON),\n BOOK(Material.BOOK, Rarity.COMMON),\n BOOKSHELF(Material.BOOKSHELF, Rarity.COMMON),\n BOWL(Material.BOWL, Rarity.COMMON),\n BREAD(Material.BREAD, Rarity.COMMON),\n CARROT(Material.CARROT, Rarity.COMMON),\n CHARCOAL(Material.CHARCOAL, Rarity.COMMON),\n COAL(Material.COAL, Rarity.COMMON),\n COBBLESTONE(Material.COBBLESTONE, Rarity.COMMON),\n COCOA(Material.COCOA_BEANS, Rarity.COMMON),\n DARK_OAK_WOOD(Material.DARK_OAK_WOOD, Rarity.COMMON),\n DIAMOND(Material.DIAMOND, Rarity.COMMON),\n DIAMOND_BLOCK(Material.DIAMOND_BLOCK, Rarity.COMMON),\n EGG(Material.EGG, Rarity.COMMON),\n EMERALD(Material.EMERALD, Rarity.COMMON),\n EMERALD_BLOCK(Material.EMERALD_BLOCK, Rarity.COMMON),\n ENDER_PEARL(Material.ENDER_PEARL, Rarity.COMMON),\n FEATHER(Material.FEATHER, Rarity.COMMON),\n FLINT(Material.FLINT, Rarity.COMMON),\n GLOWSTONE_DUST(Material.GLOWSTONE_DUST, Rarity.COMMON),\n GOLD_INGOT(Material.GOLD_INGOT, Rarity.COMMON),\n GOLD_BLOCK(Material.GOLD_BLOCK, Rarity.COMMON),\n GUNPOWDER(Material.GUNPOWDER, Rarity.COMMON),\n END_STONE(Material.END_STONE, Rarity.COMMON),\n EYE_OF_ENDER(Material.ENDER_EYE, Rarity.COMMON),\n GHAST_TEAR(Material.GHAST_TEAR, Rarity.COMMON),\n ICE(Material.ICE, Rarity.COMMON),\n IRON_INGOT(Material.IRON_INGOT, Rarity.COMMON),\n IRON_BLOCK(Material.IRON_BLOCK, Rarity.COMMON),\n JUNGLE_WOOD(Material.JUNGLE_WOOD, Rarity.COMMON),\n LEATHER(Material.LEATHER, Rarity.COMMON),\n MAGMA_CREAM(Material.MAGMA_CREAM, Rarity.COMMON),\n OAK_WOOD(Material.OAK_WOOD, Rarity.COMMON),\n OAK_LOG(Material.OAK_LOG, Rarity.COMMON),\n OAK_PLANKS(Material.OAK_PLANKS, Rarity.COMMON),\n OBSIDIAN(Material.OBSIDIAN, Rarity.COMMON),\n PACKED_ICE(Material.PACKED_ICE, Rarity.COMMON),\n PAPER(Material.PAPER, Rarity.COMMON),\n POTATO(Material.POTATO, Rarity.COMMON),\n PUMPKIN(Material.PUMPKIN, Rarity.COMMON),\n REDSTONE(Material.REDSTONE, Rarity.COMMON),\n REDSTONE_BLOCK(Material.REDSTONE_BLOCK, Rarity.COMMON),\n ROTTEN_FLESH(Material.ROTTEN_FLESH, Rarity.COMMON),\n SLIME_BALL(Material.SLIME_BALL, Rarity.COMMON),\n SPONGE(Material.SPONGE, Rarity.COMMON),\n SPRUCE_WOOD(Material.SPRUCE_WOOD, Rarity.COMMON),\n STRING(Material.STRING, Rarity.COMMON),\n SUGAR_CANE(Material.SUGAR_CANE, Rarity.COMMON),\n SUGAR(Material.SUGAR, Rarity.COMMON),\n\n /**\n * Enchanted Items\n */\n ENCHANTED_ACACIA_WOOD(Material.ACACIA_WOOD, Rarity.UNCOMMON, EnchantedAcaciaWood.class),\n ENCHANTED_BAKED_POTATO(Material.BAKED_POTATO, Rarity.UNCOMMON, EnchantedBakedPotato.class),\n ENCHANTED_BIRCH_WOOD(Material.BIRCH_WOOD, Rarity.UNCOMMON, EnchantedBirchWood.class),\n ENCHANTED_BLAZE_ROD(Material.BLAZE_ROD, Rarity.UNCOMMON, EnchantedBlazeRod.class),\n ENCHANTED_BONE(Material.BONE, Rarity.UNCOMMON, EnchantedBone.class),\n ENCHANTED_CARROT(Material.CARROT, Rarity.UNCOMMON, EnchantedCarrot.class),\n ENCHANTED_CHARCOAL(Material.CHARCOAL, Rarity.UNCOMMON, EnchantedCharcoal.class),\n ENCHANTED_COAL(Material.COAL, Rarity.UNCOMMON, EnchantedCoal.class),\n ENCHANTED_COBBLESTONE(Material.COBBLESTONE, Rarity.UNCOMMON, EnchantedCobblestone.class),\n ENCHANTED_COCOA(Material.COCOA_BEANS, Rarity.UNCOMMON, EnchantedCocoa.class),\n ENCHANTED_DARK_OAK_WOOD(Material.DARK_OAK_WOOD, Rarity.UNCOMMON, EnchantedDarkOakWood.class),\n ENCHANTED_DIAMOND(Material.DIAMOND, Rarity.UNCOMMON, EnchantedDiamond.class),\n ENCHANTED_EGG(Material.EGG, Rarity.UNCOMMON, EnchantedEgg.class),\n ENCHANTED_EMERALD(Material.EMERALD, Rarity.UNCOMMON, EnchantedEmerald.class),\n ENCHANTED_ENDER_PEARL(Material.ENDER_PEARL, Rarity.UNCOMMON, EnchantedEnderPearl.class),\n ENCHANTED_DIAMOND_BLOCK(Material.DIAMOND_BLOCK, Rarity.UNCOMMON, EnchantedDiamondBlock.class),\n ENCHANTED_EMERALD_BLOCK(Material.EMERALD_BLOCK, Rarity.UNCOMMON, EnchantedEmeraldBlock.class),\n ENCHANTED_GOLD_INGOT(Material.GOLD_INGOT, Rarity.UNCOMMON, EnchantedGold.class),\n ENCHANTED_GOLD_BLOCK(Material.GOLD_BLOCK, Rarity.UNCOMMON, EnchantedGoldBlock.class),\n ENCHANTED_JUNGLE_WOOD(Material.JUNGLE_WOOD, Rarity.UNCOMMON, EnchantedJungleWood.class),\n ENCHANTED_GUNPOWDER(Material.GUNPOWDER, Rarity.UNCOMMON, EnchantedGunpowder.class),\n ENCHANTED_IRON_INGOT(Material.IRON_INGOT, Rarity.UNCOMMON, EnchantedIron.class),\n ENCHANTED_IRON_BLOCK(Material.IRON_BLOCK, Rarity.UNCOMMON, EnchantedIronBlock.class),\n ENCHANTED_LEATHER(Material.LEATHER, Rarity.UNCOMMON, EnchantedLeather.class),\n ENCHANTED_OAK_WOOD(Material.OAK_WOOD, Rarity.UNCOMMON, EnchantedOakWood.class),\n ENCHANTED_OBSIDIAN(Material.OBSIDIAN, Rarity.UNCOMMON, EnchantedObsidian.class),\n ENCHANTED_PACKED_ICE(Material.PACKED_ICE, Rarity.UNCOMMON, EnchantedPackedIce.class),\n ENCHANTED_POTATO(Material.POTATO, Rarity.UNCOMMON, EnchantedPotato.class),\n ENCHANTED_PUMPKIN(Material.PUMPKIN, Rarity.UNCOMMON, EnchantedPumpkin.class),\n ENCHANTED_REDSTONE(Material.REDSTONE, Rarity.UNCOMMON, EnchantedRedstone.class),\n ENCHANTED_REDSTONE_BLOCK(Material.REDSTONE_BLOCK, Rarity.UNCOMMON, EnchantedRedstoneBlock.class),\n ENCHANTED_ROTTEN_FLESH(Material.ROTTEN_FLESH, Rarity.UNCOMMON, EnchantedRottenFlesh.class),\n ENCHANTED_SPONGE(Material.SPONGE, Rarity.UNCOMMON, EnchantedSponge.class),\n ENCHANTED_SPRUCE_WOOD(Material.SPRUCE_WOOD, Rarity.UNCOMMON, EnchantedSpruceWood.class),\n ENCHANTED_STRING(Material.STRING, Rarity.UNCOMMON, EnchantedString.class),\n ENCHANTED_SUGAR(Material.SUGAR, Rarity.UNCOMMON, EnchantedSugar.class),\n ;\n\n public final Material material;\n public final Rarity rarity;\n public final Class<? extends CustomSkyBlockItem> clazz;\n public final SkyBlockEnchantment bookType;\n\n ItemType(Material material, Rarity rarity) {\n this.material = material;\n this.rarity = rarity;\n this.clazz = null;\n this.bookType = null;\n }\n\n ItemType(Material material, Rarity rarity, Class<? extends CustomSkyBlockItem> clazz) {\n this.material = material;\n this.rarity = rarity;\n this.clazz = clazz;\n this.bookType = null;\n }\n\n ItemType(Material material, Rarity rarity, SkyBlockEnchantment bookType) {\n this.material = material;\n this.rarity = rarity;\n this.clazz = null;\n this.bookType = bookType;\n }\n\n public String getDisplayName() {\n return StringUtility.toNormalCase(this.name());\n }\n\n public static ItemType get(String name) {\n try {\n return ItemType.valueOf(name);\n } catch (Exception e) {\n return null;\n }\n }\n\n public static @Nullable ItemType fromMaterial(Material material) {\n return new SkyBlockItem(material).getAttributeHandler().getItemTypeAsType();\n }\n\n public static boolean isVanillaReplaced(String item) {\n return get(item) != null;\n }\n}" }, { "identifier": "MaterialQuantifiable", "path": "generic/src/main/java/net/swofty/types/generic/item/MaterialQuantifiable.java", "snippet": "@Immutable\n@Getter\npublic class MaterialQuantifiable {\n private ItemType material;\n private int amount;\n\n public MaterialQuantifiable(ItemType material, int amount) {\n this.material = material;\n this.amount = amount;\n }\n\n public MaterialQuantifiable(ItemType material) {\n this(material, 1);\n }\n\n public MaterialQuantifiable(MaterialQuantifiable materialQuantifiable) {\n this(materialQuantifiable.material, materialQuantifiable.amount);\n }\n\n public MaterialQuantifiable setMaterial(ItemType material) {\n this.material = material;\n return this;\n }\n\n public MaterialQuantifiable setAmount(int amount) {\n this.amount = amount;\n return this;\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof MaterialQuantifiable material)) return false;\n return material.material == this.material && material.amount == this.amount;\n }\n\n public boolean matches(ItemType material) {\n return this.material == material;\n }\n\n public MaterialQuantifiable clone() {\n return new MaterialQuantifiable(material, amount);\n }\n\n public String toString() {\n return \"MQ{material=\" + (material != null ? material.name() : \"?\")\n + \", amount=\" + amount + \"}\";\n }\n\n public static MaterialQuantifiable of(ItemStack stack) {\n if (stack == null || stack.getMaterial() == Material.AIR)\n return new MaterialQuantifiable(ItemType.AIR, (stack != null ? stack.getAmount() : 1));\n SkyBlockItem found = new SkyBlockItem(stack);\n return new MaterialQuantifiable(found.getAttributeHandler().getItemTypeAsType(), stack.getAmount());\n }\n\n public static MaterialQuantifiable[] of(ItemStack[] stacks) {\n MaterialQuantifiable[] materials = new MaterialQuantifiable[stacks.length];\n for (int i = 0; i < stacks.length; i++)\n materials[i] = of(stacks[i]);\n return materials;\n }\n\n public static MaterialQuantifiable one(ItemType type) {\n return new MaterialQuantifiable(type, 1);\n }\n}" }, { "identifier": "ReforgeType", "path": "generic/src/main/java/net/swofty/types/generic/item/ReforgeType.java", "snippet": "@Getter\npublic enum ReforgeType {\n SWORDS(List.of(\n new Reforge(\"Epic\", List.of(\n new Reforge.ReforgeSet(ItemStatistic.STRENGTH, level -> (double) (10 + (level * 5)))\n ))\n )),\n BOWS(List.of()),\n ARMOR(List.of()),\n EQUIPMENT(List.of()),\n FISHING_RODS(List.of()),\n PICKAXES(List.of(\n new Reforge(\"Unyielding\", List.of(\n new Reforge.ReforgeSet(ItemStatistic.SPEED, level -> level * 1.15),\n new Reforge.ReforgeSet(ItemStatistic.MINING_SPEED, Double::valueOf)\n )),\n new Reforge(\"Excellent\", List.of(\n new Reforge.ReforgeSet(ItemStatistic.SPEED, level -> level * 1.1),\n new Reforge.ReforgeSet(ItemStatistic.MINING_SPEED, level -> level * 4d)\n ))\n )),\n AXES(List.of()),\n HOES(List.of()),\n VACUUMS(List.of()),\n ;\n\n private final List<Reforge> reforges;\n\n ReforgeType(List<Reforge> reforges) {\n this.reforges = reforges;\n }\n\n public record Reforge(String prefix, List<ReforgeSet> set) {\n public Set<ItemStatistic> getStatistics() {\n return Set.copyOf(set.stream().map(ReforgeSet::statistic).toList());\n }\n\n public Integer getBonusCalculation(ItemStatistic statistic, Integer level) {\n try {\n return Math.toIntExact(Math.round(set\n .stream()\n .filter(reforgeSet -> reforgeSet.statistic() == statistic)\n .findFirst()\n .orElseThrow()\n .bonusCalculation()\n .apply(level)));\n } catch (NoSuchElementException ex) {\n return 0;\n }\n }\n\n public record ReforgeSet(ItemStatistic statistic, Function<Integer, Double> bonusCalculation) {\n }\n }\n}" }, { "identifier": "SkyBlockItem", "path": "generic/src/main/java/net/swofty/types/generic/item/SkyBlockItem.java", "snippet": "public class SkyBlockItem {\n public List<ItemAttribute> attributes = new ArrayList<>();\n public Class<? extends CustomSkyBlockItem> clazz = null;\n public Object instance = null;\n @Getter\n @Setter\n private int amount = 1;\n\n public SkyBlockItem(String itemType, int amount) {\n itemType = itemType.replace(\"minecraft:\", \"\").toUpperCase();\n\n ItemAttribute.getPossibleAttributes().forEach(attribute -> {\n attribute.setValue(attribute.getDefaultValue());\n attributes.add(attribute);\n });\n\n ItemAttributeType typeAttribute = (ItemAttributeType) getAttribute(\"item_type\");\n typeAttribute.setValue(itemType);\n\n ItemAttributeRarity rarityAttribute = (ItemAttributeRarity) getAttribute(\"rarity\");\n try {\n rarityAttribute.setValue(ItemType.valueOf(itemType).rarity);\n } catch (IllegalArgumentException e) {\n rarityAttribute.setValue(Rarity.COMMON);\n }\n\n ItemAttributeBreakingPower breakingPower = (ItemAttributeBreakingPower) getAttribute(\"breaking_power\");\n try {\n MiningTool t = (MiningTool) ItemType.valueOf(itemType).clazz.newInstance();\n breakingPower.setValue(t.getBreakingPower());\n } catch (ClassCastException castEx) {\n breakingPower.setValue(0);\n\n // Any other exception must be ignored.\n } catch (Exception ignored) {\n }\n\n ItemAttributeStatistics statisticsAttribute = (ItemAttributeStatistics) getAttribute(\"statistics\");\n try {\n Class<? extends CustomSkyBlockItem> clazz = ItemType.valueOf(itemType).clazz;\n if (clazz != null) {\n statisticsAttribute.setValue(ItemType.valueOf(itemType).clazz.newInstance().getStatistics());\n clazz = ItemType.valueOf(itemType).clazz.newInstance().getClass();\n } else {\n statisticsAttribute.setValue(ItemStatistics.builder().build());\n }\n } catch (IllegalArgumentException e) {\n statisticsAttribute.setValue(ItemStatistics.builder().build());\n } catch (InstantiationException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n\n setAmount(amount);\n }\n\n public Object getAttribute(String key) {\n return attributes.stream().filter(attribute -> attribute.getKey().equals(key)).findFirst().orElse(null);\n }\n\n public SkyBlockItem(Material material) {\n this(material.name(), 1);\n }\n\n public SkyBlockItem(ItemType type) {\n this(type.name(), 1);\n }\n\n public SkyBlockItem(ItemType type, int amount) {\n this(type.name(), amount);\n }\n\n public SkyBlockItem(ItemStack item) {\n amount = item.getAmount();\n\n ItemAttribute.getPossibleAttributes().forEach(attribute -> {\n if (item.hasTag(Tag.String(attribute.getKey()))) {\n attribute.setValue(attribute.loadFromString(item.getTag(Tag.String(attribute.getKey()))));\n attributes.add(attribute);\n } else {\n attribute.setValue(attribute.getDefaultValue());\n attributes.add(attribute);\n }\n });\n\n ItemAttributeType typeAttribute = (ItemAttributeType) getAttribute(\"item_type\");\n String itemType = typeAttribute.getValue();\n try {\n clazz = ItemType.valueOf(itemType).clazz.newInstance().getClass();\n\n // All items re-retrieve their base stats when loaded from an itemstack\n ItemAttributeStatistics statisticsAttribute = (ItemAttributeStatistics) getAttribute(\"statistics\");\n statisticsAttribute.setValue(ItemType.valueOf(itemType).clazz.newInstance().getStatistics());\n } catch (IllegalArgumentException | InstantiationException | NullPointerException | IllegalAccessException e) {\n }\n }\n\n public Object getGenericInstance() {\n if (instance != null)\n return instance;\n\n try {\n instance = clazz.newInstance();\n return instance;\n } catch (Exception e) {}\n\n try {\n instance = getAttributeHandler().getItemTypeAsType().clazz.newInstance();\n return instance;\n } catch (Exception e) {}\n\n return null;\n }\n\n public Material getMaterial() {\n ItemAttributeType typeAttribute = (ItemAttributeType) getAttribute(\"item_type\");\n try {\n return ItemType.valueOf(typeAttribute.getValue()).material;\n } catch (IllegalArgumentException e) {\n if (typeAttribute.getValue().equalsIgnoreCase(\"N/A\"))\n return Material.BEDROCK;\n return Material.values().stream().\n filter(material -> material.name().equalsIgnoreCase(\"minecraft:\" + typeAttribute.getValue().toLowerCase()))\n .findFirst().get();\n }\n }\n\n public ItemStack getItemStack() {\n return getItemStackBuilder().build();\n }\n\n public ItemStack.Builder getItemStackBuilder() {\n ItemStack.Builder itemStackBuilder = ItemStack.builder(getMaterial()).amount(amount);\n\n for (ItemAttribute attribute : attributes) {\n itemStackBuilder.setTag(Tag.String(attribute.getKey()), attribute.saveIntoString());\n }\n\n return itemStackBuilder.meta(meta -> meta.hideFlag(ItemHideFlag.HIDE_ATTRIBUTES));\n }\n\n public AttributeHandler getAttributeHandler() {\n return new AttributeHandler(this);\n }\n\n public boolean isNA() {\n return getMaterial() == Material.BEDROCK;\n }\n\n public static boolean isSkyBlockItem(ItemStack item) {\n return item.hasTag(Tag.String(\"item_type\"));\n }\n\n @Override\n public String toString() {\n return \"SkyBlockItem{\" +\n \"type=\" + getMaterial().name() +\n \", clazz=\" + clazz +\n \", amount=\" + amount +\n \", attributes=\" + attributes.stream().map(attribute -> attribute.getKey() + \"=\" + attribute.getValue()).reduce((s, s2) -> s + \", \" + s2).orElse(\"null\") +\n '}';\n }\n}" }, { "identifier": "ShapedRecipe", "path": "generic/src/main/java/net/swofty/types/generic/item/impl/recipes/ShapedRecipe.java", "snippet": "@Getter\npublic class ShapedRecipe extends SkyBlockRecipe<ShapedRecipe> {\n public static final List<ShapedRecipe> CACHED_RECIPES = new ArrayList<>();\n\n private final Map<Character, MaterialQuantifiable> ingredientMap;\n private final Map<Character, Function<SkyBlockItem, Boolean>> extraRequirements = new HashMap<>();\n private final List<String> pattern; // Using a list of strings for simplicity\n\n public ShapedRecipe(RecipeType type,\n SkyBlockItem result, Map<Character, MaterialQuantifiable> ingredientMap,\n List<String> pattern, Function<SkyBlockPlayer, CraftingResult> canCraft) {\n super(result, type, canCraft);\n this.ingredientMap = ingredientMap;\n this.pattern = pattern;\n }\n\n public ShapedRecipe(RecipeType type,\n SkyBlockItem result, Map<Character, MaterialQuantifiable> ingredientMap,\n List<String> pattern) {\n this(type, result, ingredientMap, pattern, (player) -> new CraftingResult(true, new String[]{}));\n }\n\n public void addExtraRequirement(char patternChar, Function<SkyBlockItem, Boolean> requirement) {\n extraRequirements.put(patternChar, requirement);\n }\n\n\n @Override\n public ShapedRecipe setResult(SkyBlockItem result) {\n this.result = result;\n return this;\n }\n\n @Override\n public void init() {\n CACHED_RECIPES.add(this);\n }\n\n @Override\n public SkyBlockItem[] consume(SkyBlockItem[] stacks) {\n Map<Character, MaterialQuantifiable> ingredientMap = new HashMap<>(this.ingredientMap);\n // Remove AIR from the ingredient map\n ingredientMap.remove(' ');\n\n Map<Character, MaterialQuantifiable> materialsToConsume = new HashMap<>(ingredientMap);\n SkyBlockItem[] modifiedStacks = Arrays.copyOf(stacks, stacks.length);\n\n int patternRows = pattern.size();\n int patternCols = pattern.get(0).length();\n\n // Try all possible starting positions (top-left corners) for the pattern in the grid\n for (int startRow = 0; startRow <= 3 - patternRows; startRow++) {\n for (int startCol = 0; startCol <= 3 - patternCols; startCol++) {\n\n // Iterate through stacks within the potentially shifted pattern\n for (int i = 0; i < modifiedStacks.length; i++) {\n int gridRow = i / 3;\n int gridCol = i % 3;\n\n // If this stack is within our shifted pattern on the grid\n if (gridRow >= startRow && gridRow < startRow + patternRows &&\n gridCol >= startCol && gridCol < startCol + patternCols) {\n\n char patternChar = pattern.get(gridRow - startRow).charAt(gridCol - startCol);\n MaterialQuantifiable patternMaterial = ingredientMap.get(patternChar);\n\n if (patternMaterial != null && !patternMaterial.getMaterial().equals(ItemType.AIR)) {\n MaterialQuantifiable stackMaterial = MaterialQuantifiable.of(modifiedStacks[i].getItemStack());\n\n // skip the iteration if stackMaterial is AIR\n if (stackMaterial.getMaterial().equals(ItemType.AIR)) {\n continue;\n }\n\n if (stackMaterial.matches(patternMaterial.getMaterial())\n || ExchangeableType.isExchangeable(stackMaterial.getMaterial(), patternMaterial.getMaterial())) {\n int stackAmount = stackMaterial.getAmount();\n int consumeAmount = patternMaterial.getAmount();\n\n if (stackAmount >= consumeAmount) {\n stackMaterial.setAmount(stackAmount - consumeAmount);\n materialsToConsume.remove(patternChar);\n\n SkyBlockItem item = new SkyBlockItem(stackMaterial.getMaterial());\n item.setAmount(stackAmount - consumeAmount);\n\n modifiedStacks[i] = stackMaterial.getAmount() > 0 ? item : null;\n } else {\n throw new IllegalStateException(\"Not enough materials to consume!\"); // We need exact amount for shaped recipes\n }\n }\n }\n }\n }\n\n // If all of the materials were consumed, return the modified stacks\n if (materialsToConsume.isEmpty()) {\n return modifiedStacks;\n }\n\n // Reset before trying the next position\n materialsToConsume = new HashMap<>(ingredientMap);\n modifiedStacks = Arrays.copyOf(stacks, stacks.length);\n }\n }\n\n // If there are still materials left to consume, there were not enough materials in the stacks\n throw new IllegalStateException(\"Not enough materials to consume!\");\n }\n\n @Override\n public SkyBlockItem[] getRecipeDisplay() {\n SkyBlockItem[] recipeDisplay = new SkyBlockItem[9];\n int patternRows = pattern.size();\n int patternCols = pattern.get(0).length();\n\n for (int row = 0; row < patternRows; row++) {\n for (int col = 0; col < patternCols; col++) {\n char patternChar = pattern.get(row).charAt(col);\n MaterialQuantifiable patternMaterial = ingredientMap.get(patternChar);\n\n if (patternMaterial != null) {\n recipeDisplay[row * 3 + col] = new SkyBlockItem(patternMaterial.getMaterial(), patternMaterial.getAmount());\n }\n }\n }\n\n return recipeDisplay;\n }\n\n @Override\n public SkyBlockRecipe clone() {\n return new ShapedRecipe(recipeType, result, ingredientMap, pattern, canCraft);\n }\n\n public Map<Character, List<Integer>> getPositionsOfItems(ItemStack[] stacks) {\n Map<Character, List<Integer>> positions = new HashMap<>();\n\n int patternRows = pattern.size();\n int patternCols = pattern.get(0).length();\n\n // Try all possible starting positions (top-left corners) for the pattern in the grid\n for (int startRow = 0; startRow <= 3 - patternRows; startRow++) {\n for (int startCol = 0; startCol <= 3 - patternCols; startCol++) {\n\n // Iterate through stacks within the potentially shifted pattern\n for (int i = 0; i < stacks.length; i++) {\n int gridRow = i / 3;\n int gridCol = i % 3;\n\n // If this stack is within our shifted pattern on the grid\n if (gridRow >= startRow && gridRow < startRow + patternRows &&\n gridCol >= startCol && gridCol < startCol + patternCols) {\n\n char patternChar = pattern.get(gridRow - startRow).charAt(gridCol - startCol);\n MaterialQuantifiable patternMaterial = ingredientMap.get(patternChar);\n\n if (patternMaterial != null && !patternMaterial.getMaterial().equals(ItemType.AIR)) {\n MaterialQuantifiable stackMaterial = MaterialQuantifiable.of(stacks[i]);\n\n // skip the iteration if stackMaterial is AIR\n if (stackMaterial.getMaterial().equals(ItemType.AIR)) {\n continue;\n }\n\n if (stackMaterial.matches(patternMaterial.getMaterial())\n || ExchangeableType.isExchangeable(stackMaterial.getMaterial(), patternMaterial.getMaterial())) {\n int stackAmount = stackMaterial.getAmount();\n int consumeAmount = patternMaterial.getAmount();\n\n if (stackAmount >= consumeAmount) {\n stackMaterial.setAmount(stackAmount - consumeAmount);\n positions.computeIfAbsent(patternChar, k -> new ArrayList<>()).add(i);\n }\n }\n }\n }\n }\n }\n }\n\n // Remove duplicate positions from the same character\n positions.forEach((character, positionsList) -> {\n Set<Integer> positionsSet = new HashSet<>(positionsList);\n positionsList.clear();\n positionsList.addAll(positionsSet);\n });\n\n return positions;\n }\n\n public static ShapedRecipe parseShapedRecipe(ItemStack[] stacks) {\n ItemStack[][] grid = {\n {stacks[0], stacks[1], stacks[2]},\n {stacks[3], stacks[4], stacks[5]},\n {stacks[6], stacks[7], stacks[8]}\n };\n\n return CACHED_RECIPES.stream()\n .filter(recipe -> {\n List<String> recipePattern = recipe.getPattern();\n int patternRows = recipePattern.size();\n int patternCols = recipePattern.get(0).length();\n\n for (int row = 0; row <= 3 - patternRows; row++) {\n for (int col = 0; col <= 3 - patternCols; col++) {\n if (matchesPattern(recipe, grid, row, col)) {\n return true;\n }\n }\n }\n\n return false;\n })\n .filter(recipe -> {\n for (Map.Entry<Character, List<Integer>> entry : recipe.getPositionsOfItems(stacks).entrySet()) {\n Character character = entry.getKey();\n\n Function<SkyBlockItem, Boolean> extraRequirements = recipe.getExtraRequirements().get(character);\n if (extraRequirements == null) {\n continue;\n }\n\n for (int position : entry.getValue()) {\n SkyBlockItem item = new SkyBlockItem(stacks[position]);\n if (!extraRequirements.apply(item)) {\n return false;\n }\n }\n }\n\n return true;\n })\n .findFirst()\n .orElse(null);\n }\n\n private static boolean matchesPattern(ShapedRecipe recipe, ItemStack[][] grid, int startRow, int startCol) {\n List<String> pattern = recipe.getPattern();\n\n for (int row = 0; row < pattern.size(); row++) {\n for (int col = 0; col < pattern.get(row).length(); col++) {\n char patternChar = pattern.get(row).charAt(col);\n MaterialQuantifiable patternMaterial = recipe.getIngredientMap().get(patternChar);\n MaterialQuantifiable gridMaterial = MaterialQuantifiable.of(grid[startRow + row][startCol + col]);\n\n if (!gridMaterial.matches(patternMaterial.getMaterial()) ||\n gridMaterial.getAmount() < patternMaterial.getAmount()) {\n if (!ExchangeableType.isExchangeable(gridMaterial.getMaterial(), patternMaterial.getMaterial())) {\n return false;\n }\n }\n }\n }\n\n return true;\n }\n}" } ]
import net.minestom.server.color.Color; import net.swofty.types.generic.item.impl.*; import net.swofty.types.generic.user.statistics.ItemStatistic; import net.swofty.types.generic.user.statistics.ItemStatistics; import net.swofty.types.generic.item.ItemType; import net.swofty.types.generic.item.MaterialQuantifiable; import net.swofty.types.generic.item.ReforgeType; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.impl.*; import net.swofty.types.generic.item.impl.recipes.ShapedRecipe; import java.util.HashMap; import java.util.List; import java.util.Map;
8,640
package net.swofty.types.generic.item.items.armor; public class LeafletPants implements CustomSkyBlockItem, Reforgable, ExtraRarityDisplay, LeatherColour, Sellable, Craftable { @Override public ItemStatistics getStatistics() { return ItemStatistics.builder().with(ItemStatistic.HEALTH, 20).build(); } @Override public ReforgeType getReforgeType() { return ReforgeType.ARMOR; } @Override public String getExtraRarityDisplay() { return " PANTS"; } @Override public Color getLeatherColour() { return new Color(0x2DE35E); } @Override public double getSellValue() { return 10; } @Override public SkyBlockRecipe<?> getRecipe() { Map<Character, MaterialQuantifiable> ingredientMap = new HashMap<>(); ingredientMap.put('L', new MaterialQuantifiable(ItemType.OAK_LEAVES, 1)); ingredientMap.put(' ', new MaterialQuantifiable(ItemType.AIR, 1)); List<String> pattern = List.of( "LLL", "L L", "L L");
package net.swofty.types.generic.item.items.armor; public class LeafletPants implements CustomSkyBlockItem, Reforgable, ExtraRarityDisplay, LeatherColour, Sellable, Craftable { @Override public ItemStatistics getStatistics() { return ItemStatistics.builder().with(ItemStatistic.HEALTH, 20).build(); } @Override public ReforgeType getReforgeType() { return ReforgeType.ARMOR; } @Override public String getExtraRarityDisplay() { return " PANTS"; } @Override public Color getLeatherColour() { return new Color(0x2DE35E); } @Override public double getSellValue() { return 10; } @Override public SkyBlockRecipe<?> getRecipe() { Map<Character, MaterialQuantifiable> ingredientMap = new HashMap<>(); ingredientMap.put('L', new MaterialQuantifiable(ItemType.OAK_LEAVES, 1)); ingredientMap.put(' ', new MaterialQuantifiable(ItemType.AIR, 1)); List<String> pattern = List.of( "LLL", "L L", "L L");
return new ShapedRecipe(SkyBlockRecipe.RecipeType.FORAGING, new SkyBlockItem(ItemType.LEAFLET_PANTS), ingredientMap, pattern);
5
2023-12-14 09:51:15+00:00
12k
Tianscar/uxgl
desktop/src/main/java/unrefined/runtime/DesktopCursor.java
[ { "identifier": "CursorSupport", "path": "desktop/src/main/java/unrefined/desktop/CursorSupport.java", "snippet": "public final class CursorSupport {\n\n public static final Cursor NONE_CURSOR;\n static {\n Cursor cursor;\n try {\n cursor = Toolkit.getDefaultToolkit().createCustomCursor(\n Toolkit.getDefaultToolkit().getImage(CursorSupport.class.getResource(\"\")),\n new Point(0, 0), \"UXGL None Cursor\");\n }\n catch (HeadlessException e) {\n cursor = null;\n }\n NONE_CURSOR = cursor;\n }\n\n private CursorSupport() {\n throw new NotInstantiableError(CursorSupport.class);\n }\n\n public static Cursor getSystemCursor(int type) throws CursorNotFoundException {\n switch (type) {\n case ARROW: return Cursor.getDefaultCursor();\n case CROSSHAIR: return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);\n case IBEAM: return Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);\n case WAIT:\n if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); // FIXME Cocoa\n else return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);\n case POINTING_HAND: return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);\n case MOVE: return Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);\n case RESIZE_N: return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);\n case RESIZE_S: return Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);\n case RESIZE_W: return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);\n case RESIZE_E: return Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);\n case RESIZE_SW: return Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);\n case RESIZE_SE: return Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);\n case RESIZE_NW: return Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);\n case RESIZE_NE: return Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);\n case RESIZE_NS:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // Windows unsupported\n else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_sb_v_double_arrow);\n case RESIZE_WE:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); // Windows unsupported\n else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_sb_h_double_arrow);\n case RESIZE_NWSE:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR); // Windows unsupported\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"bd_double_arrow\");\n case RESIZE_NESW:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR); // Windows unsupported\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"fd_double_arrow\");\n case RESIZE_COL:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"col-resize\");\n case RESIZE_ROW:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"row-resize\");\n case CELL:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"plus\");\n case HELP:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME read cursor file\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_question_arrow);\n case ZOOM_IN:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"zoom-in\");\n case ZOOM_OUT:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"zoom-out\");\n case NO:\n if (OperatingSystem.IS_WINDOWS) return getSystemCustomCursor(\"Invalid.32x32\"); // FIXME read cursor file\n else if (OperatingSystem.IS_MAC) return getDesktopPropertyCursor(\"DnD.Cursor.MoveNoDrop\");\n else return X11CursorSupport.getSystemCursor(\"crossed_circle\");\n case GRAB:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_hand1);\n case GRABBING:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return getDesktopPropertyCursor(\"DnD.Cursor.MoveDrop\");\n else return X11CursorSupport.getSystemCursor(\"grabbing\");\n case COPY_DROP:\n if (OperatingSystem.IS_WINDOWS) return getSystemCustomCursor(\"CopyDrop.32x32\"); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return getDesktopPropertyCursor(\"DnD.Cursor.CopyDrop\");\n else return X11CursorSupport.getSystemCursor(\"dnd-copy\");\n case LINK_DROP:\n if (OperatingSystem.IS_WINDOWS) return getSystemCustomCursor(\"LinkDrop.32x32\"); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return getDesktopPropertyCursor(\"DnD.Cursor.LinkDrop\");\n else return X11CursorSupport.getSystemCursor(\"dnd-link\");\n case MOVE_DROP:\n if (OperatingSystem.IS_WINDOWS) return getSystemCustomCursor(\"MoveDrop.32x32\"); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return getDesktopPropertyCursor(\"DnD.Cursor.MoveDrop\");\n else return X11CursorSupport.getSystemCursor(\"dnd-move\");\n case NO_DROP:\n if (OperatingSystem.IS_WINDOWS) return getSystemCustomCursor(\"Invalid.32x32\"); // FIXME read cursor file\n else if (OperatingSystem.IS_MAC) return getDesktopPropertyCursor(\"DnD.Cursor.MoveNoDrop\");\n else return X11CursorSupport.getSystemCursor(\"dnd-no-drop\");\n case UP_ARROW:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME read cursor file\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_sb_up_arrow);\n case VERTICAL_IBEAM:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME read cursor file\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"vertical-text\");\n case CONTEXT_MENU:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getDefaultCursor(); // FIXME extract ole32.dll and bundle image\n else if (OperatingSystem.IS_MAC) return Cursor.getDefaultCursor(); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"context-menu\");\n case PROGRESS:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); // FIXME read cursor file\n else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(\"left_ptr_watch\");\n case FLEUR:\n if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); // Windows unsupported\n else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); // FIXME Cocoa\n else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_fleur);\n case NONE: return NONE_CURSOR;\n default: throw new CursorNotFoundException(type);\n }\n }\n\n public static Cursor getDesktopPropertyCursor(String name) {\n try {\n Cursor result = (Cursor) Toolkit.getDefaultToolkit().getDesktopProperty(name);\n return result == null ? Cursor.getDefaultCursor() : result;\n }\n catch (ClassCastException e) {\n return Cursor.getDefaultCursor();\n }\n }\n\n public static Cursor getSystemCustomCursor(String name) {\n try {\n Cursor cursor = Cursor.getSystemCustomCursor(name);\n return cursor == null ? Cursor.getDefaultCursor() : cursor;\n }\n catch (AWTException e) {\n return Cursor.getDefaultCursor();\n }\n }\n\n public static Cursor createCustomCursor(Image cursor, Point hotSpot, String name) {\n if (OperatingSystem.IS_X11) return X11CursorSupport.createCustomCursor(cursor, hotSpot, name);\n else return Toolkit.getDefaultToolkit().createCustomCursor(cursor, hotSpot, name);\n }\n\n public static int getMaximumCursorColors() {\n if (OperatingSystem.IS_X11) return X11CursorSupport.getMaximumCursorColors();\n else return Toolkit.getDefaultToolkit().getMaximumCursorColors();\n }\n\n}" }, { "identifier": "Bitmap", "path": "base/src/main/java/unrefined/media/graphics/Bitmap.java", "snippet": "public abstract class Bitmap implements Disposable, Copyable, Duplicatable {\n\n public static Bitmap of(int width, int height, int type) {\n return Drawing.getInstance().createBitmap(width, height, type);\n }\n\n public static Bitmap read(File input) throws IOException {\n return Drawing.getInstance().readBitmap(input);\n }\n public static Bitmap read(InputStream input) throws IOException {\n return Drawing.getInstance().readBitmap(input);\n }\n public static Bitmap read(Asset input) throws IOException {\n return Drawing.getInstance().readBitmap(input);\n }\n public static Bitmap read(File input, int type) throws IOException {\n return Drawing.getInstance().readBitmap(input, type);\n }\n public static Bitmap read(InputStream input, int type) throws IOException {\n return Drawing.getInstance().readBitmap(input, type);\n }\n public static Bitmap read(Asset input, int type) throws IOException {\n return Drawing.getInstance().readBitmap(input, type);\n }\n public static void writeBitmap(Bitmap bitmap, File output, String format, float quality) throws IOException {\n Drawing.getInstance().writeBitmap(bitmap, output, format, quality);\n }\n public static void writeBitmap(Bitmap bitmap, OutputStream output, String format, float quality) throws IOException {\n Drawing.getInstance().writeBitmap(bitmap, output, format, quality);\n }\n\n public static Bitmap.MultiFrame readMultiFrame(File input) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input);\n }\n public static Bitmap.MultiFrame readMultiFrame(InputStream input) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input);\n }\n public static Bitmap.MultiFrame readMultiFrame(Asset input) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input);\n }\n public static Bitmap.MultiFrame readMultiFrame(File input, int type) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, type);\n }\n public static Bitmap.MultiFrame readMultiFrame(InputStream input, int type) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, type);\n }\n public static Bitmap.MultiFrame readMultiFrame(Asset input, int type) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, type);\n }\n public static Bitmap.MultiFrame readMultiFrame(File input, int[] types, int typesOffset) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, types, typesOffset);\n }\n public static Bitmap.MultiFrame readMultiFrame(InputStream input, int[] types, int typesOffset) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, types, typesOffset);\n }\n public static Bitmap.MultiFrame readMultiFrame(Asset input, int[] types, int typesOffset) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, types, typesOffset);\n }\n public static Bitmap.MultiFrame readMultiFrame(File input, int[] types) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, types);\n }\n public static Bitmap.MultiFrame readMultiFrame(InputStream input, int[] types) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, types);\n }\n public static Bitmap.MultiFrame readMultiFrame(Asset input, int[] types) throws IOException {\n return Drawing.getInstance().readBitmapMultiFrame(input, types);\n }\n public static void writeMultiFrame(Bitmap.MultiFrame frames, File output, String format, float quality) throws IOException {\n Drawing.getInstance().writeBitmapMultiFrame(frames, output, format, quality);\n }\n public static void writeMultiFrame(Bitmap.MultiFrame frames, OutputStream output, String format, float quality) throws IOException {\n Drawing.getInstance().writeBitmapMultiFrame(frames, output, format, quality);\n }\n public static void writeMultiFrame(Bitmap.MultiFrame frames, File output, String format, float[] quality, int qualityOffset) throws IOException {\n Drawing.getInstance().writeBitmapMultiFrame(frames, output, format, quality, qualityOffset);\n }\n public static void writeMultiFrame(Bitmap.MultiFrame frames, OutputStream output, String format, float[] quality, int qualityOffset) throws IOException {\n Drawing.getInstance().writeBitmapMultiFrame(frames, output, format, quality, qualityOffset);\n }\n public static void writeMultiFrame(Bitmap.MultiFrame frames, File output, String format, float[] quality) throws IOException {\n Drawing.getInstance().writeBitmapMultiFrame(frames, output, format, quality);\n }\n public static void writeMultiFrame(Bitmap.MultiFrame frames, OutputStream output, String format, float[] quality) throws IOException {\n Drawing.getInstance().writeBitmapMultiFrame(frames, output, format, quality);\n }\n\n public static Set<String> getReaderFormats() {\n return Drawing.getInstance().getBitmapReaderFormats();\n }\n public static Set<String> getWriterFormats() {\n return Drawing.getInstance().getBitmapWriterFormats();\n }\n\n public static abstract class Handler {\n public abstract Bitmap read(File input, int type) throws IOException;\n public abstract Bitmap read(InputStream input, int type) throws IOException;\n public abstract Bitmap read(Asset input, int type) throws IOException;\n public abstract boolean write(Bitmap bitmap, File output, String format, float quality) throws IOException;\n public abstract boolean write(Bitmap bitmap, OutputStream output, String format, float quality) throws IOException;\n public abstract MultiFrame readMultiFrame(File input, int type) throws IOException;\n public abstract MultiFrame readMultiFrame(InputStream input, int type) throws IOException;\n public abstract MultiFrame readMultiFrame(Asset input, int type) throws IOException;\n public abstract MultiFrame readMultiFrame(File input, int[] types, int typesOffset) throws IOException;\n public abstract MultiFrame readMultiFrame(InputStream input, int[] types, int typesOffset) throws IOException;\n public abstract MultiFrame readMultiFrame(Asset input, int[] types, int typesOffset) throws IOException;\n public abstract boolean writeMultiFrame(MultiFrame frames, File output, String format, float quality) throws IOException;\n public abstract boolean writeMultiFrame(MultiFrame frames, OutputStream output, String format, float quality) throws IOException;\n public abstract boolean writeMultiFrame(MultiFrame frames, File output, String format, float[] quality, int qualityOffset) throws IOException;\n public abstract boolean writeMultiFrame(MultiFrame frames, OutputStream output, String format, float[] quality, int qualityOffset) throws IOException;\n public abstract Set<String> readerFormats();\n public abstract Set<String> writerFormats();\n }\n\n public static final class DisposalMode {\n private DisposalMode() {\n throw new NotInstantiableError(DisposalMode.class);\n }\n public static final int NONE = 0;\n public static final int BACKGROUND = 1;\n public static final int PREVIOUS = 2;\n public static int checkValid(int mode) {\n if (mode < NONE || mode > PREVIOUS) throw new IllegalArgumentException(\"Illegal disposal mode: \" + mode);\n else return mode;\n }\n public static boolean isValid(int mode) {\n return mode >= NONE && mode <= PREVIOUS;\n }\n public static String toString(int mode) {\n switch (mode) {\n case NONE: return \"NONE\";\n case BACKGROUND: return \"BACKGROUND\";\n case PREVIOUS: return \"PREVIOUS\";\n default: throw new IllegalArgumentException(\"Illegal disposal mode: \" + mode);\n }\n }\n }\n\n public static final class BlendMode {\n private BlendMode() {\n throw new NotInstantiableError(BlendMode.class);\n }\n public static final int SOURCE = 0;\n public static final int OVER = 1;\n public static int checkValid(int mode) {\n if (mode < SOURCE || mode > OVER) throw new IllegalArgumentException(\"Illegal blend mode: \" + mode);\n else return mode;\n }\n public static boolean isValid(int mode) {\n return mode >= SOURCE && mode <= OVER;\n }\n public static String toString(int mode) {\n switch (mode) {\n case SOURCE: return \"SOURCE\";\n case OVER: return \"OVER\";\n default: throw new IllegalArgumentException(\"Illegal blend mode: \" + mode);\n }\n }\n }\n\n public static class Frame implements Copyable, Swappable {\n\n private long duration;\n private transient Bitmap bitmap;\n private int hotSpotX, hotSpotY;\n private int disposalMode;\n private int blendMode;\n\n public Frame(Bitmap bitmap, int hotSpotX, int hotSpotY, long duration, int disposalMode, int blendMode) {\n setBitmap(bitmap);\n this.hotSpotX = hotSpotX;\n this.hotSpotY = hotSpotY;\n this.duration = duration;\n setDisposalMode(disposalMode);\n setBlendMode(blendMode);\n }\n\n public Frame(Bitmap bitmap) {\n setBitmap(bitmap);\n }\n\n public Frame(Bitmap bitmap, int hotSpotX, int hotSpotY) {\n this(bitmap);\n setHotSpot(hotSpotX, hotSpotY);\n }\n\n public Frame(Frame frame) {\n this(frame.getBitmap(), frame.getHotSpotX(), frame.getHotSpotY(), frame.getDuration(), frame.getDisposalMode(), frame.getBlendMode());\n }\n\n public void setFrame(Frame frame) {\n setFrame(frame.getBitmap(), frame.getHotSpotX(), frame.getHotSpotY(), frame.getDuration(), frame.getDisposalMode(), frame.getBlendMode());\n }\n\n public void setFrame(Bitmap bitmap, int hotSpotX, int hotSpotY, long duration, int disposalMode, int blendMode) {\n setBitmap(bitmap);\n setHotSpot(hotSpotX, hotSpotY);\n setDuration(duration);\n setDisposalMode(disposalMode);\n setBlendMode(blendMode);\n }\n\n public void setBitmap(Bitmap bitmap) {\n this.bitmap = Objects.requireNonNull(bitmap);\n }\n\n public Bitmap getBitmap() {\n return bitmap;\n }\n\n public void setDuration(long duration) {\n this.duration = Math.max(0, duration);\n }\n\n public long getDuration() {\n return duration;\n }\n\n public void setHotSpotX(int hotSpotX) {\n this.hotSpotX = hotSpotX;\n }\n\n public int getHotSpotX() {\n return hotSpotX;\n }\n\n public void setHotSpotY(int hotSpotY) {\n this.hotSpotY = hotSpotY;\n }\n\n public int getHotSpotY() {\n return hotSpotY;\n }\n\n public void setHotSpot(int hotSpotX, int hotSpotY) {\n this.hotSpotX = hotSpotX;\n this.hotSpotY = hotSpotY;\n }\n\n public void getHotSpot(Point hotSpot) {\n hotSpot.setPoint(hotSpotX, hotSpotY);\n }\n\n public int getDisposalMode() {\n return disposalMode;\n }\n\n public void setDisposalMode(int disposalMode) {\n this.disposalMode = DisposalMode.checkValid(disposalMode);\n }\n\n public int getBlendMode() {\n return blendMode;\n }\n\n public void setBlendMode(int blendMode) {\n this.blendMode = BlendMode.checkValid(blendMode);\n }\n\n @Override\n public Frame clone() {\n try {\n return (Frame) super.clone();\n }\n catch (CloneNotSupportedException e) {\n return copy();\n }\n }\n\n @Override\n public Frame copy() {\n return new Frame(this);\n }\n\n @Override\n public void to(Object dst) {\n ((Frame) dst).setFrame(this);\n }\n\n @Override\n public void from(Object src) {\n setFrame((Frame) src);\n }\n\n @Override\n public void swap(Object o) {\n Frame that = (Frame) o;\n\n Bitmap bitmap = that.bitmap;\n int hotSpotX = that.hotSpotX;\n int hotSpotY = that.hotSpotY;\n long duration = that.duration;\n int disposalMode = that.disposalMode;\n int blendMode = that.blendMode;\n\n that.setFrame(this);\n setFrame(bitmap, hotSpotX, hotSpotY, duration, disposalMode, blendMode);\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\n Frame frame = (Frame) o;\n\n if (duration != frame.duration) return false;\n if (hotSpotX != frame.hotSpotX) return false;\n if (hotSpotY != frame.hotSpotY) return false;\n if (disposalMode != frame.disposalMode) return false;\n if (blendMode != frame.blendMode) return false;\n return bitmap.equals(frame.bitmap);\n }\n\n @Override\n public int hashCode() {\n int result = (int) (duration ^ (duration >>> 32));\n result = 31 * result + bitmap.hashCode();\n result = 31 * result + hotSpotX;\n result = 31 * result + hotSpotY;\n result = 31 * result + disposalMode;\n result = 31 * result + blendMode;\n return result;\n }\n\n @Override\n public String toString() {\n return getClass().getName()\n + '{' +\n \"bitmap=\" + bitmap +\n \", hotSpotX=\" + hotSpotX +\n \", hotSpotY=\" + hotSpotY +\n \", duration=\" + duration +\n \", disposalMode=\" + DisposalMode.toString(disposalMode) +\n \", blendMode=\" + BlendMode.toString(blendMode) +\n '}';\n }\n\n }\n\n public static class MultiFrame extends ArrayList<Frame> implements Copyable, Swappable {\n\n private static final long serialVersionUID = 3834067739734342833L;\n\n private int loops = 0;\n\n public MultiFrame(Collection<Frame> frames) {\n for (Frame frame : frames) {\n add(frame.clone());\n }\n }\n\n public MultiFrame(Frame... frames) {\n for (Frame frame : frames) {\n add(frame.clone());\n }\n }\n\n public void setFrames(Collection<Frame> frames) {\n clear();\n for (Frame frame : frames) {\n add(frame.clone());\n }\n }\n\n public void setFrames(Frame[] frames, int framesOffset, int length) {\n clear();\n for (int i = 0; i < length; i ++) {\n add(frames[framesOffset + i].clone());\n }\n }\n\n public void setFrames(Frame... frames) {\n clear();\n for (Frame frame : frames) {\n add(frame.clone());\n }\n }\n\n public int getLooping() {\n return loops;\n }\n\n public void setLooping(int loops) {\n this.loops = loops;\n }\n\n public int getCompatibleWidth() {\n int result = -1;\n for (Frame frame : this) {\n result = Math.max(result, frame.getBitmap().getWidth() + frame.getHotSpotX());\n }\n return result;\n }\n\n public int getCompatibleHeight() {\n int result = -1;\n for (Frame frame : this) {\n result = Math.max(result, frame.getBitmap().getHeight() + frame.getHotSpotY());\n }\n return result;\n }\n\n public int getCompatibleType() {\n boolean alpha8 = false;\n boolean alpha4 = false;\n boolean rgb888 = false;\n boolean rgb565 = false;\n boolean rgb444 = false;\n for (Frame frame : this) {\n switch (frame.getBitmap().getType()) {\n case Type.RGBA_8888:\n rgb888 = true;\n case Type.ALPHA_8:\n alpha8 = true;\n break;\n case Type.RGBA_4444:\n rgb444 = true;\n alpha4 = true;\n break;\n case Type.RGB_565:\n rgb565 = true;\n break;\n }\n }\n if (alpha8) return (rgb444 || rgb565 || rgb888) ? Type.RGBA_8888 : Type.ALPHA_8;\n else if (alpha4) return rgb565 ? Type.RGBA_8888 : Type.RGBA_4444;\n else return rgb565 ? Type.RGB_565 : -1;\n }\n\n @Override\n public MultiFrame clone() {\n MultiFrame clone = (MultiFrame) super.clone();\n clone.clear();\n for (Frame frame : this) {\n clone.add(frame.clone());\n }\n return clone;\n }\n\n @Override\n public MultiFrame copy() {\n return new MultiFrame(this);\n }\n\n @Override\n public void to(Object dst) {\n ((MultiFrame) dst).setFrames(this);\n }\n\n @Override\n public void from(Object src) {\n setFrames((MultiFrame) src);\n }\n\n @Override\n public void swap(Object o) {\n MultiFrame that = (MultiFrame) o;\n MultiFrame tmp = (MultiFrame) super.clone();\n clear();\n addAll(that);\n that.clear();\n that.addAll(tmp);\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 if (!super.equals(o)) return false;\n\n MultiFrame frames = (MultiFrame) o;\n\n return loops == frames.loops;\n }\n\n @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + loops;\n return result;\n }\n\n @Override\n public String toString() {\n return getClass().getName()\n + '{' +\n \"looping=\" + loops +\n \", frames=\" + super.toString() +\n '}';\n }\n\n }\n\n public static final class Type {\n private Type() {\n throw new NotInstantiableError(Type.class);\n }\n public static final int RGBA_8888 = 0;\n public static final int RGBA_4444 = 1;\n public static final int RGB_565 = 2;\n public static final int ALPHA_8 = 3;\n public static int checkValid(int type) {\n if (type < RGBA_8888 || type > ALPHA_8) throw new IllegalArgumentException(\"Illegal bitmap type: \" + type);\n else return type;\n }\n public static boolean isValid(int type) {\n return type >= RGBA_8888 && type <= ALPHA_8;\n }\n public static String toString(int type) {\n switch (type) {\n case RGBA_8888: return \"RGBA_8888\";\n case RGBA_4444: return \"RGBA_4444\";\n case RGB_565: return \"RGB_565\";\n case ALPHA_8: return \"ALPHA_8\";\n default: throw new IllegalArgumentException(\"Illegal bitmap type: \" + type);\n }\n }\n }\n\n public boolean hasAlpha() {\n return getType() != Type.RGB_565;\n }\n\n public abstract Bitmap slice(int x, int y, int width, int height);\n public abstract Bitmap duplicate();\n public abstract Bitmap attachment();\n\n public boolean hasAttachment() {\n return attachment() != null;\n }\n\n public abstract Graphics getGraphics();\n\n public abstract int getWidth();\n public abstract int getHeight();\n\n public abstract int getPixel(int x, int y);\n public abstract void setPixel(int x, int y, int color);\n\n public abstract void getPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height);\n public abstract void setPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height);\n\n public abstract int getType();\n\n @Override\n public Bitmap clone() {\n try {\n return (Bitmap) super.clone();\n }\n catch (CloneNotSupportedException e) {\n return null;\n }\n }\n @Override\n public abstract Bitmap copy();\n\n @Override\n public String toString() {\n if (isDisposed()) return getClass().getName() + \"@\" + Integer.toHexString(hashCode())\n + '{' +\n \"disposed=true\" +\n '}';\n else return getClass().getName() + \"@\" + Integer.toHexString(hashCode())\n + '{' +\n \"disposed=false\" +\n \", type=\" + Type.toString(getType()) +\n \", width=\" + getWidth() +\n \", height=\" + getHeight() +\n '}';\n }\n\n}" }, { "identifier": "CursorNotFoundException", "path": "base/src/main/java/unrefined/media/graphics/CursorNotFoundException.java", "snippet": "public class CursorNotFoundException extends IOException {\n\n private static final long serialVersionUID = 2338402687585417549L;\n\n public CursorNotFoundException() {\n super();\n }\n\n public CursorNotFoundException(String message) {\n super(message);\n }\n\n public CursorNotFoundException(int type) {\n super(Cursor.Type.toString(type));\n }\n\n}" }, { "identifier": "UnexpectedError", "path": "base/src/main/java/unrefined/util/UnexpectedError.java", "snippet": "public class UnexpectedError extends Error {\n\n private static final long serialVersionUID = -7313961951503724715L;\n\n public UnexpectedError() {\n }\n\n public UnexpectedError(String message) {\n super(message);\n }\n\n public UnexpectedError(Throwable cause) {\n super(cause);\n }\n\n}" } ]
import unrefined.desktop.CursorSupport; import unrefined.media.graphics.Bitmap; import unrefined.media.graphics.CursorNotFoundException; import unrefined.util.UnexpectedError; import java.awt.Cursor; import java.awt.Point; import java.util.HashMap; import java.util.Map; import java.util.Objects;
7,837
package unrefined.runtime; public class DesktopCursor extends unrefined.media.graphics.Cursor { private final Cursor cursor; private final int type; private final int hotSpotX; private final int hotSpotY; private static final Map<Integer, DesktopCursor> SYSTEM_CURSORS = new HashMap<>(); public static DesktopCursor getSystemCursor(int type) throws CursorNotFoundException { if (!SYSTEM_CURSORS.containsKey(type)) { synchronized (SYSTEM_CURSORS) { if (!SYSTEM_CURSORS.containsKey(type)) { try { SYSTEM_CURSORS.put(type, new DesktopCursor(type)); } catch (CursorNotFoundException e) { throw e; } catch (Throwable e) { throw new UnexpectedError(e); } } } } return SYSTEM_CURSORS.get(type); } private static final DesktopCursor DEFAULT_CURSOR; static { try { DEFAULT_CURSOR = getSystemCursor(Type.ARROW); } catch (CursorNotFoundException e) { throw new UnexpectedError(e); } } public static DesktopCursor getDefaultCursor() { return DEFAULT_CURSOR; } private DesktopCursor(int type) throws CursorNotFoundException { this.cursor = CursorSupport.getSystemCursor(type); this.type = type; this.hotSpotX = -1; this.hotSpotY = -1; }
package unrefined.runtime; public class DesktopCursor extends unrefined.media.graphics.Cursor { private final Cursor cursor; private final int type; private final int hotSpotX; private final int hotSpotY; private static final Map<Integer, DesktopCursor> SYSTEM_CURSORS = new HashMap<>(); public static DesktopCursor getSystemCursor(int type) throws CursorNotFoundException { if (!SYSTEM_CURSORS.containsKey(type)) { synchronized (SYSTEM_CURSORS) { if (!SYSTEM_CURSORS.containsKey(type)) { try { SYSTEM_CURSORS.put(type, new DesktopCursor(type)); } catch (CursorNotFoundException e) { throw e; } catch (Throwable e) { throw new UnexpectedError(e); } } } } return SYSTEM_CURSORS.get(type); } private static final DesktopCursor DEFAULT_CURSOR; static { try { DEFAULT_CURSOR = getSystemCursor(Type.ARROW); } catch (CursorNotFoundException e) { throw new UnexpectedError(e); } } public static DesktopCursor getDefaultCursor() { return DEFAULT_CURSOR; } private DesktopCursor(int type) throws CursorNotFoundException { this.cursor = CursorSupport.getSystemCursor(type); this.type = type; this.hotSpotX = -1; this.hotSpotY = -1; }
public DesktopCursor(Bitmap bitmap, Point hotSpot) {
1
2023-12-15 19:03:31+00:00
12k
Valerde/vadb
va-collection/src/main/java/com/sovava/vacollection/vaset/VaHashSet.java
[ { "identifier": "VaCollection", "path": "va-collection/src/main/java/com/sovava/vacollection/api/VaCollection.java", "snippet": "public interface VaCollection<E> extends Iterable<E> {\n\n int size();\n\n boolean isEmpty();\n\n boolean contains(Object o);\n\n VaIterator<E> vaIterator();\n\n @Deprecated\n @SuppressWarnings(\"all\")\n default Iterator<E> iterator() {\n return vaIterator();\n }\n\n Object[] toVaArray();\n\n <T> T[] toVaArray(T[] ts);\n\n boolean add(E e);\n\n boolean remove(Object o);\n\n boolean containsAll(VaCollection<?> c);\n\n boolean addAll(VaCollection<? extends E> c);\n\n boolean removeAll(VaCollection<?> c);\n\n default boolean removeIf(VaPredicate<? super E> filter) {\n Objects.requireNonNull(filter);\n boolean removed = false;\n VaIterator<E> each = vaIterator();\n while (each.hasNext()) {\n if (filter.test(each.next())) {\n each.remove();\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * description: 仅保留此集合中包含在指定集合中的元素\n *\n * @return boolean 如果此时集合发生了改变,则为true\n * @Author sovava\n * @Date 12/18/23 6:07 PM\n * @param: c - [com.sovava.vacollection.api.VaCollection<?>]\n */\n boolean retainAll(VaCollection<?> c);\n\n void clear();\n\n boolean equals(Object o);\n\n int hashCode();\n\n default void forEach(VaConsumer<? super E> action) {\n Iterable.super.forEach(action);\n }\n\n //TODO spliterator 和 stream\n\n}" }, { "identifier": "VaIterator", "path": "va-collection/src/main/java/com/sovava/vacollection/api/VaIterator.java", "snippet": "public interface VaIterator<E> extends Iterator<E> {\n boolean hasNext();\n E next();\n void remove();\n\n}" }, { "identifier": "VaSet", "path": "va-collection/src/main/java/com/sovava/vacollection/api/VaSet.java", "snippet": "public interface VaSet<E> extends VaCollection<E> {\n\n int size();\n\n @Override\n VaIterator<E> vaIterator();\n\n @Override\n boolean contains(Object o);\n\n @Override\n boolean isEmpty();\n\n @Override\n Object[] toVaArray();\n\n @Override\n <T> T[] toVaArray(T[] ts);\n\n @Override\n boolean add(E e);\n\n @Override\n boolean remove(Object o);\n\n\n @Override\n boolean containsAll(VaCollection<?> c);\n\n\n @Override\n boolean addAll(VaCollection<? extends E> c);\n\n @Override\n boolean retainAll(VaCollection<?> c);\n\n @Override\n boolean removeAll(VaCollection<?> c);\n\n @Override\n void clear();\n\n @Override\n boolean equals(Object o);\n\n @Override\n int hashCode();\n}" }, { "identifier": "VaHashMap", "path": "va-collection/src/main/java/com/sovava/vacollection/vamap/VaHashMap.java", "snippet": "public class VaHashMap<K, V> extends VaAbstractMap<K, V> implements VaMap<K, V>, Cloneable, Serializable {\n private static final long serialVersionUID = 1214817153348964519L;\n\n /**\n * 默认初始容量\n */\n static final int DEFAULT_INITIAL_CAPACITY = 16;\n\n /**\n * 限定最大容量\n */\n static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * 默认负载因子\n */\n static final float DEFAULT_LOAD_FACTOR = 0.75f;\n\n /**\n * list转tree阈值\n */\n static final int DEFAULT_LIST_TO_TREE_THRESHOLD = 8;\n\n /**\n * tree转list阈值\n */\n static final int DEFAULT_TREE_TO_LIST_THRESHOLD = 6;\n\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n\n VaNode<K, V>[] table;\n VaSet<VaEntry<K, V>> entrySet;\n int size;\n int modCount;\n /**\n * 临界点,要调整的下一个size(capacity*loadFactor)\n */\n int threshold;\n\n float loadFactor;\n\n public VaHashMap(int initialCapacity, float loadFactor) {\n if (initialCapacity < 0) {\n throw new IllegalArgumentException(\"不合理的初始容量\");\n\n }\n if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY;\n if (loadFactor <= 0 || Float.isNaN(loadFactor)) {\n throw new IllegalArgumentException(\"不合理的负载因子\");\n }\n this.loadFactor = loadFactor;\n this.threshold = getReshapedCap(initialCapacity);\n }\n\n public VaHashMap(int initialCapacity) {\n this(initialCapacity, DEFAULT_LOAD_FACTOR);\n }\n\n public VaHashMap() {\n this.loadFactor = DEFAULT_LOAD_FACTOR;\n }\n\n public VaHashMap(VaMap<? extends K, ? extends V> map) {\n this.loadFactor = DEFAULT_LOAD_FACTOR;\n putMapEntries(map);\n }\n\n void putMapEntries(VaMap<? extends K, ? extends V> map) {\n int size = map.size();\n if (size > 0) {\n if (table == null) {\n float ft = (float) size / loadFactor;\n int cap = ft < (float) MAXIMUM_CAPACITY ? (int) ft : MAXIMUM_CAPACITY;\n if (cap > threshold) {\n threshold = getReshapedCap(cap);\n }\n } else if (size > threshold) {\n resize();\n }\n for (VaEntry<? extends K, ? extends V> entry : map.entrySet()) {\n K key = entry.getKey();\n V value = entry.getValue();\n putValue(hash(key), key, value, false);\n }\n }\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n\n public V get(Object key) {\n VaNode<K, V> node;\n node = getNode(hash(key), key);\n return node == null ? null : node.value;\n }\n\n /**\n * description: 根据提供的hash值和key找到Node\n *\n * @return VaNode<K, V>\n * @Author sovava\n * @Date 12/23/23 8:13 PM\n * @param: hash - [int]\n * @param: key - [java.lang.Object]\n */\n VaNode<K, V> getNode(int hash, Object key) {\n VaNode<K, V>[] tab;\n\n int n;\n VaNode<K, V> first;\n K k;\n if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {\n k = first.key;\n if (first.hash == hash && (Objects.equals(key, k))) {\n return first;\n }\n if (first.next != null) {\n if (first instanceof VaTreeNode) {\n //TODO 树化查找\n }\n first = first.next;\n do {\n k = first.key;\n if (first.hash == hash && Objects.equals(key, k)) return first;\n } while ((first = first.next) != null);\n }\n }\n return null;\n }\n\n @Override\n public boolean containsKey(Object key) {\n return getNode(hash(key), key) != null;\n }\n\n @Override\n public V put(K key, V value) {\n return putValue(hash(key), key, value, false);\n }\n\n public V putValue(int hash, K key, V value, boolean onlyIfAbsent) {\n VaNode<K, V>[] tab;\n VaNode<K, V> node;\n int n, i;\n if ((tab = table) == null || (n = tab.length) == 0) {\n tab = resize();\n n = tab.length;\n }\n i = (n - 1) & hash;\n node = tab[i];\n if (node == null) {\n //这个bin的头结点为null,直接设置即可\n tab[i] = newNode(hash, key, value, null);\n } else {\n //从头开始遍历后续节点\n VaNode<K, V> e = null;\n K k = node.key;\n if (node.hash == hash && Objects.equals(k, key)) {\n e = node;\n } else if (node instanceof VaTreeNode) {\n //TODO 红黑树插入\n } else {\n for (int binCount = 1; ; binCount++) {\n e = node.next;\n\n if (e == null) {\n node.next = newNode(hash, key, value, null);\n if (binCount >= DEFAULT_LIST_TO_TREE_THRESHOLD) {\n //TODO 树化\n int tmp;\n }\n break;\n }\n k = e.key;\n if (e.hash == hash && Objects.equals(k, key)) {\n break;\n }\n node = e;\n }\n\n }\n if (e != null) {\n V oldV = e.value;\n if (!onlyIfAbsent || oldV == null) {\n e.value = value;\n }\n return oldV;\n }\n }\n\n modCount++;\n if (++size > threshold) {\n resize();\n }\n return null;\n }\n\n VaNode<K, V> newNode(int hash, K key, V value, VaNode<K, V> next) {\n return new VaNode<K, V>(hash, key, value, next);\n }\n\n @SuppressWarnings(\"unchecked\")\n VaNode<K, V>[] resize() {\n VaNode<K, V>[] oldTab = table;\n int oldCap = oldTab == null ? 0 : oldTab.length;\n int oldThr = threshold;\n int newCap = 0, newThr = 0;\n if (oldCap > 0) {\n if (oldCap >= MAXIMUM_CAPACITY) {\n threshold = Integer.MAX_VALUE;\n return oldTab;\n } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) {\n newThr = oldThr << 1;\n }\n } else if (oldThr > 0) {\n newCap = oldThr;\n } else {\n newCap = DEFAULT_INITIAL_CAPACITY;\n newThr = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);\n }\n\n if (newThr == 0) {\n float thr = (float) newCap * loadFactor;\n newThr = (newCap < MAXIMUM_CAPACITY && thr < (float) MAXIMUM_CAPACITY) ? (int) thr : Integer.MAX_VALUE;\n }\n\n VaNode<K, V>[] newTab = (VaNode<K, V>[]) new VaNode[newCap];\n threshold = newThr;\n table = newTab;\n if (oldTab != null) {\n for (int i = 0; i < oldCap; i++) {\n VaNode<K, V> head = oldTab[i];\n if (head != null) {\n oldTab[i] = null;\n if (head.next == null) {\n newTab[(newCap - 1) & head.hash] = head;\n } else if (head instanceof VaTreeNode) {\n //树扩容\n } else {\n VaNode<K, V> lHead = null;\n VaNode<K, V> hHead = null;\n VaNode<K, V> lTail = null;\n VaNode<K, V> hTail = null;\n VaNode<K, V> next = null;\n do {\n next = head.next;\n if ((oldCap & head.hash) == 0) {\n if (lTail == null) {\n lHead = head;\n } else {\n lTail.next = head;\n }\n lTail = head;\n } else {\n if (hTail == null) {\n hHead = head;\n } else {\n hTail.next = head;\n }\n hTail = head;\n }\n } while ((head = next) != null);\n if (lTail != null) {\n lTail.next = null;\n newTab[i] = lHead;\n }\n if (hTail != null) {\n hTail.next = null;\n newTab[i + oldCap] = hHead;\n }\n\n }\n\n }\n\n }\n }\n return newTab;\n }\n\n @Override\n public void putAll(VaMap<? extends K, ? extends V> m) {\n putMapEntries(m);\n }\n\n @Override\n public V remove(Object key) {\n VaNode<K, V> node;\n node = removeNode(hash(key), key, null, false, true);\n return node == null ? null : node.value;\n }\n\n VaNode<K, V> removeNode(int hash, Object key, Object value, boolean removeIfMatch, boolean movable) {\n VaNode<K, V>[] tab;\n int n;\n VaNode<K, V> q;\n if ((tab = table) != null && (n = tab.length) != 0 && (q = tab[(n - 1) & hash]) != null) {\n VaNode<K, V> matchNode = null, tmpNode;\n K k = q.key;\n if (q.hash == hash && Objects.equals(k, key)) {\n matchNode = q;\n } else if (q instanceof VaTreeNode) {\n //TODO remove tree\n } else {\n tmpNode = q.next;\n while (tmpNode != null) {\n k = tmpNode.key;\n if (tmpNode.hash == hash && Objects.equals(k, key)) {\n matchNode = tmpNode;\n break;\n }\n q = tmpNode;\n tmpNode = tmpNode.next;\n\n }\n }\n V v;\n if (matchNode != null && (!removeIfMatch || (v = matchNode.value) == value || (value != null && value.equals(v)))) {\n if (matchNode instanceof VaTreeNode) {\n //TODO tree remove\n } else if (matchNode == q) {\n tab[(n - 1) & hash] = q.next;\n } else {\n q.next = matchNode.next;\n }\n ++modCount;\n --size;\n return matchNode;\n }\n }\n\n return null;\n }\n\n @Override\n public void clear() {\n VaNode<K, V>[] tab = table;\n modCount++;\n if (tab != null && size != 0) {\n size = 0;\n for (int i = 0; i < tab.length; i++) {\n tab[i] = null;\n }\n }\n }\n\n @Override\n public boolean containValue(Object value) {\n VaNode<K, V>[] tab;\n if ((tab = table) != null && size > 0) {\n for (VaNode<K, V> kvVaNode : tab) {\n for (VaNode<K, V> node = kvVaNode; node != null; node = node.next) {\n if (Objects.equals(node.value, value)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n @Override\n public VaSet<K> keySet() {\n VaSet<K> ks = keySet;\n if (ks == null) {\n ks = new VaKeySet();\n keySet = ks;\n }\n return ks;\n }\n\n\n @Override\n public VaCollection<V> values() {\n VaCollection<V> vs = values;\n if (vs == null) {\n vs = new VaValues();\n values = vs;\n }\n return vs;\n }\n\n @Override\n public VaSet<VaEntry<K, V>> entrySet() {\n VaSet<VaEntry<K, V>> es = entrySet;\n if (es == null) {\n es = new VaEntrySet();\n entrySet = es;\n }\n return es;\n }\n\n /**\n * description: 计算hash值,该设计的说明在\n * <p>https://blog.csdn.net/yueaini10000/article/details/108869022\n * <p>该设计的证明在singleton-test中相应位置TestForHashMapHashFunc类中证明\n *\n * @return int\n * @Author sovava\n * @Date 12/22/23 6:40 PM\n * @param: key - [java.lang.Object]\n */\n static final int hash(Object key) {\n int h;\n return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);\n }\n\n static final int getReshapedCap(int cap) {\n int n = cap - 1;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n return n >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY : n + 1;\n }\n\n\n @Override\n public V getOrDefault(Object key, V defaultValue) {\n VaNode<K, V> res = getNode(hash(key), key);\n return res == null ? defaultValue : res.value;\n }\n\n @Override\n public V putIfAbsent(K key, V value) {\n return putValue(hash(key), key, value, true);\n }\n\n @Override\n public boolean remove(Object key, Object value) {\n return removeNode(hash(key), key, value, true, true) != null;\n }\n\n @Override\n public boolean replace(K key, V oldValue, V newValue) {\n VaNode<K, V> node = getNode(hash(key), key);\n if (node != null && Objects.equals(node.value, oldValue)) {\n node.value = newValue;\n return true;\n }\n return false;\n }\n\n @Override\n public V replace(K key, V value) {\n VaNode<K, V> node = getNode(hash(key), key);\n if (node != null) {\n V oldV = node.value;\n node.value = value;\n return oldV;\n }\n return null;\n }\n\n /**\n * description: 如果map中不存在给定的key,那么就用给定的方法计算并插入map中\n *\n * @param key\n * @param mappingFunction\n * @return V\n * @Author sovava\n * @Date 12/24/23 1:26 PM\n * @param: key - [K]\n * @param: mappingFunction - [com.sovava.vacollection.api.function.VaFunction<?superK]\n */\n @Override\n public V computeIfAbsent(K key, VaFunction<? super K, ? extends V> mappingFunction) {\n Objects.requireNonNull(mappingFunction);\n VaNode<K, V>[] tab;\n int n;\n int hash = hash(key);\n VaNode<K, V> head, oldNode = null;\n VaTreeNode<K, V> root = null;\n if ((tab = table) == null || size > threshold || (n = tab.length) == 0) {\n tab = resize();\n n = tab.length;\n }\n if ((head = tab[(n - 1) & hash]) != null) {//寻找旧value\n if (head instanceof VaTreeNode) {\n //TODO 树化\n } else {\n VaNode<K, V> prev = head;\n do {\n if (prev.hash == hash && (Objects.equals(key, prev.key))) {\n oldNode = prev;\n break;\n }\n } while ((prev = prev.next) != null);\n }\n if (oldNode != null && oldNode.value != null) {\n return oldNode.value;\n }\n }\n V newV = mappingFunction.apply(key);\n if (newV == null) {\n return null;\n } else if (oldNode != null) {\n oldNode.value = newV;\n return newV;\n } else if (root != null) {\n //TODO 插入树中\n } else {\n //新建头结点\n tab[(n - 1) & hash] = newNode(hash, key, newV, null);\n //TODO 判断是否树化\n }\n ++modCount;\n ++size;\n return newV;\n }\n\n /**\n * description: 如果给定的key在map中且值非空,就计算\n *\n * @param key\n * @param remappingFunction\n * @return V\n * @Author sovava\n * @Date 12/24/23 1:26 PM\n * @param: key - [K]\n * @param: remappingFunction - [com.sovava.vacollection.api.function.VaBiFunction<?superK]\n */\n @Override\n public V computeIfPresent(K key, VaBiFunction<? super K, ? super V, ? extends V> remappingFunction) {\n Objects.requireNonNull(remappingFunction);\n VaNode<K, V> node;\n V oldV;\n int hash = hash(key);\n if ((node = getNode(hash, key)) != null && (oldV = node.value) != null) {\n V newV = remappingFunction.apply(key, oldV);\n if (newV != null) {\n node.value = newV;\n return newV;\n } else {\n removeNode(hash, key, null, false, true);\n }\n }\n return null;\n }\n\n /**\n * description: 为指定key计算新值,\n *\n * @param key\n * @param remappingFunction\n * @return V\n * @Author sovava\n * @Date 12/24/23 1:26 PM\n * @param: key - [K]\n * @param: remappingFunction - [com.sovava.vacollection.api.function.VaBiFunction<? super K>]\n */\n @Override\n public V compute(K key, VaBiFunction<? super K, ? super V, ? extends V> remappingFunction) {\n Objects.requireNonNull(remappingFunction);\n int hash = hash(key);\n VaNode<K, V>[] tab;\n VaNode<K, V> head, oldN = null;\n int n;\n VaTreeNode<K, V> root = null;\n if (size > threshold || (tab = table) == null || (n = tab.length) == 0) {\n tab = resize();\n n = tab.length;\n }\n if ((head = tab[(n - 1) & hash]) != null) {\n if (head instanceof VaTreeNode) {\n //树查找\n } else {\n VaNode<K, V> prev = head;\n do {\n if (prev.hash == hash && Objects.equals(prev.key, key)) {\n oldN = prev;\n break;\n }\n } while ((prev = prev.next) != null);\n }\n }\n V oldV = oldN == null ? null : oldN.value;\n V newV = remappingFunction.apply(key, oldV);\n if (oldN != null) {\n if (newV != null) {\n oldN.value = newV;\n } else {\n removeNode(hash, key, null, false, true);\n }\n } else if (newV != null) {\n if (root != null) {\n //树插入\n } else {\n tab[(n - 1) & hash] = newNode(hash, key, newV, head);\n //TODO 判断树化\n }\n ++modCount;\n ++size;\n }\n return newV;\n }\n\n\n public void forEach(VaBiConsumer<? super K, ? super V> action) {\n Objects.requireNonNull(action);\n VaNode<K, V>[] tab = table;\n if (size > 0 && tab != null) {\n for (int i = 0; i < tab.length; i++) {\n for (VaNode<K, V> node = tab[i]; node != null; node = node.next) {\n action.apply(node.key, node.value);\n }\n }\n }\n }\n\n\n public void replaceAll(VaBiFunction<? super K, ? super V, ? extends V> action) {\n Objects.requireNonNull(action);\n VaNode<K, V>[] tab = table;\n if (size > 0 && tab != null) {\n for (int i = 0; i < tab.length; i++) {\n for (VaNode<K, V> node = tab[i]; node != null; node = node.next) {\n node.value = action.apply(node.key, node.value);\n }\n }\n }\n }\n\n /**\n * description:\n * 如果指定的键尚未与值关联或与 null 关联,则将其与给定的非 null 值关联。\n * 如果指定的key已经存在,用给定重新映射函数的结果替换关联值,如果结果为null则删除\n *\n * @param key\n * @param value\n * @param remappingFunction\n * @return V\n * @Author sovava\n * @Date 12/18/23 10:11 PM\n * @param: key - [K]\n * @param: value - [V]\n * @param: remappingFunction - [com.sovava.vacollection.api.function.VaBiFunction<?superK]\n */\n @Override\n public V merge(K key, V value, VaBiFunction<? super V, ? super V, ? extends V> remappingFunction) {\n Objects.requireNonNull(value);\n Objects.requireNonNull(remappingFunction);\n int hash = hash(key);\n VaNode<K, V>[] tab;\n VaNode<K, V> head, oldN = null;\n int n;\n VaTreeNode<K, V> root = null;\n if (size > threshold || (tab = table) == null || (n = tab.length) == 0) {\n tab = resize();\n n = tab.length;\n }\n if ((head = tab[(n - 1) & hash]) != null) {\n if (head instanceof VaTreeNode) {\n //树查找\n } else {\n VaNode<K, V> prev = head;\n do {\n if (prev.hash == hash && Objects.equals(prev.key, key)) {\n oldN = prev;\n break;\n }\n } while ((prev = prev.next) != null);\n }\n }\n if (oldN != null) {\n V newV;\n if (oldN.value != null) {\n newV = remappingFunction.apply(oldN.value, value);\n } else {\n newV = value;\n }\n if (newV != null) {\n oldN.value = newV;\n } else {\n removeNode(hash, key, null, false, true);\n }\n return newV;\n }\n if (value != null) {\n if (root != null) {\n //插入树\n } else {\n tab[(n - 1) & hash] = newNode(hash, key, value, head);\n //TODO 判断树化\n }\n ++modCount;\n ++size;\n return value;\n }\n return null;\n }\n\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Object clone() throws CloneNotSupportedException {\n VaHashMap<K, V> clone;\n clone = (VaHashMap<K, V>) super.clone();\n\n clone.reinit();\n clone.putMapEntries(this);\n return clone;\n }\n\n private void reinit() {\n table = null;\n entrySet = null;\n size = 0;\n modCount = 0;\n threshold = 0;\n values = null;\n keySet = null;\n }\n\n static class VaNode<K, V> implements VaMap.VaEntry<K, V> {\n private int hash;\n final K key;\n V value;\n VaNode<K, V> next;\n\n VaNode(int hash, K key, V value, VaNode<K, V> next) {\n this.hash = hash;\n this.key = key;\n this.value = value;\n this.next = next;\n }\n\n @Override\n public K getKey() {\n return key;\n }\n\n @Override\n public V getValue() {\n return value;\n }\n\n @Override\n public V setValue(V value) {\n V oldValue = this.value;\n this.value = value;\n return oldValue;\n }\n\n @Override\n public String toString() {\n return \"VaNode: \" + key + \" = \" + value;\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(key) ^ Objects.hashCode(value);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (obj instanceof VaMap.VaEntry) {\n VaEntry<?, ?> e = (VaEntry<?, ?>) obj;\n return Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue());\n }\n return false;\n }\n }\n\n static class VaTreeNode<K, V> extends VaLinkedHashMap.VaEntry<K, V> {\n\n VaTreeNode(int hash, K key, V value, VaNode<K, V> next) {\n super(hash, key, value, next);\n }\n }\n\n class VaKeySet extends VaAbstractSet<K> {\n public VaIterator<K> vaIterator() {\n return new KeyIterator();\n }\n\n public int size() {\n return size;\n }\n\n public boolean contains(Object o) {\n return VaHashMap.this.containsKey(0);\n }\n\n public void clear() {\n VaHashMap.this.clear();\n }\n\n public boolean remove(Object o) {\n return VaHashMap.this.removeNode(hash(o), o, null, false, true) != null;\n }\n\n public void forEach(VaConsumer<? super K> action) {\n Objects.requireNonNull(action);\n VaNode<K, V>[] tab = table;\n if (size > 0 && tab != null) {\n for (VaNode<K, V> kvVaNode : tab) {\n for (VaNode<K, V> node = kvVaNode; node != null; node = node.next) {\n action.accept(node.key);\n }\n }\n }\n }\n }\n\n class VaValues extends VaAbstractCollection<V> {\n\n public VaIterator<V> vaIterator() {\n return new ValueIterator();\n }\n\n public int size() {\n return size;\n }\n\n public void clear() {\n VaHashMap.this.clear();\n }\n\n public boolean contains(Object o) {\n return containValue(o);\n }\n\n public void forEach(VaConsumer<? super V> action) {\n Objects.requireNonNull(action);\n VaNode<K, V>[] tab = table;\n if (size > 0 && tab != null) {\n for (VaNode<K, V> kvVaNode : tab) {\n for (VaNode<K, V> node = kvVaNode; node != null; node = node.next) {\n action.accept(node.value);\n }\n }\n }\n }\n }\n\n class VaEntrySet extends VaAbstractSet<VaMap.VaEntry<K, V>> {\n\n\n public VaIterator<VaEntry<K, V>> vaIterator() {\n return new EntryIterator();\n }\n\n public int size() {\n return size;\n }\n\n public void forEach(VaConsumer<? super VaEntry<K, V>> action) {\n Objects.requireNonNull(action);\n VaNode<K, V>[] tab = table;\n if (size > 0 && tab != null) {\n for (VaNode<K, V> kvVaNode : tab) {\n for (VaNode<K, V> node = kvVaNode; node != null; node = node.next) {\n action.accept(node);\n }\n }\n }\n }\n\n public boolean contains(Object o) {\n if (!(o instanceof VaMap.VaEntry)) {\n return false;\n }\n\n VaEntry<?, ?> entry = (VaEntry<?, ?>) o;\n VaNode<K, V> res = getNode(hash(entry.getKey()), entry.getKey());\n return res != null && res.equals(entry);\n }\n\n public void clear() {\n VaHashMap.this.clear();\n }\n\n public boolean remove(Object o) {\n if (!(o instanceof VaMap.VaEntry)) {\n return false;\n }\n\n VaEntry<?, ?> entry = (VaEntry<?, ?>) o;\n return removeNode(hash(entry.getKey()), entry.getKey(), entry.getValue(), true, true) != null;\n }\n }\n\n abstract class HashIterator {\n VaNode<K, V> next;\n VaNode<K, V> current;\n int index;\n\n HashIterator() {\n VaNode<K, V>[] t = table;\n current = next = null;\n index = 0;\n if (t != null && size > 0) {\n while (index < t.length && (next = t[index++]) == null) ;\n }\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n final VaNode<K, V> nextNode() {\n VaNode<K, V>[] tab = table;\n VaNode<K, V> e = next;\n if (e == null) {\n throw new NoSuchElementException();\n }\n if ((next = (current = e).next) == null && (tab = table) != null) {\n while (index < tab.length && (next = tab[index++]) == null) ;\n }\n return e;\n }\n\n public final void remove() {\n VaNode<K, V> p = current;\n if (p == null) {\n throw new IllegalStateException();\n }\n current = null;\n K key = p.key;\n removeNode(hash(key), key, null, false, false);\n }\n\n }\n\n final class KeyIterator extends HashIterator implements VaIterator<K> {\n public K next() {\n return nextNode().key;\n }\n }\n\n final class ValueIterator extends HashIterator implements VaIterator<V> {\n public V next() {\n return nextNode().value;\n }\n }\n\n final class EntryIterator extends HashIterator implements VaIterator<VaMap.VaEntry<K, V>> {\n public VaEntry<K, V> next() {\n return nextNode();\n }\n }\n}" } ]
import com.sovava.vacollection.api.VaCollection; import com.sovava.vacollection.api.VaIterator; import com.sovava.vacollection.api.VaSet; import com.sovava.vacollection.vamap.VaHashMap; import java.io.Serializable;
8,884
package com.sovava.vacollection.vaset; /** * Description: 基于hashmap的hashset * * @author: ykn * @date: 2023年12月27日 3:06 PM **/ public class VaHashSet<E> extends VaAbstractSet<E> implements VaSet<E>, Cloneable, Serializable { private static final long serialVersionUID = 5120875045620310227L; private VaHashMap<E, Object> map; private final Object DEFAULT_VALUE = new Object(); public VaHashSet() { map = new VaHashMap<>(); }
package com.sovava.vacollection.vaset; /** * Description: 基于hashmap的hashset * * @author: ykn * @date: 2023年12月27日 3:06 PM **/ public class VaHashSet<E> extends VaAbstractSet<E> implements VaSet<E>, Cloneable, Serializable { private static final long serialVersionUID = 5120875045620310227L; private VaHashMap<E, Object> map; private final Object DEFAULT_VALUE = new Object(); public VaHashSet() { map = new VaHashMap<>(); }
public VaHashSet(VaCollection<? extends E> c) {
0
2023-12-17 13:29:10+00:00
12k
litongjava/next-jfinal
src/main/java/com/jfinal/core/JFinalFilter.java
[ { "identifier": "Constants", "path": "src/main/java/com/jfinal/config/Constants.java", "snippet": "final public class Constants {\n\t\n\tprivate boolean devMode = Const.DEFAULT_DEV_MODE;\n\t\n\tprivate String baseUploadPath = Const.DEFAULT_BASE_UPLOAD_PATH;\n\tprivate String baseDownloadPath = Const.DEFAULT_BASE_DOWNLOAD_PATH;\n\t\n\tprivate String encoding = Const.DEFAULT_ENCODING;\n\tprivate String urlParaSeparator = Const.DEFAULT_URL_PARA_SEPARATOR;\n\tprivate ViewType viewType = Const.DEFAULT_VIEW_TYPE;\n\tprivate String viewExtension = Const.DEFAULT_VIEW_EXTENSION;\n\tprivate long maxPostSize = Const.DEFAULT_MAX_POST_SIZE;\n\tprivate int freeMarkerTemplateUpdateDelay = Const.DEFAULT_FREEMARKER_TEMPLATE_UPDATE_DELAY;\t// just for not devMode\n\t\n\tprivate ControllerFactory controllerFactory = Const.DEFAULT_CONTROLLER_FACTORY;\n\tprivate ActionReporter actionReporter = Const.DEFAULT_ACTION_REPORTER;\n\tprivate int configPluginOrder = Const.DEFAULT_CONFIG_PLUGIN_ORDER;\n\t\n\tprivate boolean denyAccessJsp = true;\t// 默认拒绝直接访问 jsp 文件\n\t\n\tprivate ITokenCache tokenCache = null;\n\t\n\t/**\n\t * Set development mode.\n\t * @param devMode the development mode\n\t */\n\tpublic void setDevMode(boolean devMode) {\n\t\tthis.devMode = devMode;\n\t}\n\t\n\tpublic boolean getDevMode() {\n\t\treturn devMode;\n\t}\n\t\n\t/**\n\t * 配置 configPlugin(Plugins me) 在 JFinalConfig 中被调用的次序.\n\t * \n\t * 取值 1、2、3、4、5 分别表示在 configConstant(..)、configInterceptor(..)、\n\t * configRoute(..)、configEngine(..)、configHandler(...)\n\t * 之后被调用\n\t * \n\t * 默认值为 3,那么 configPlugin(..) 将在 configRoute(...) 调用之后被调用\n\t * @param configPluginOrder 取值只能是 1、2、3、4、5\n\t */\n\tpublic void setConfigPluginOrder(int configPluginOrder) {\n\t\tif (configPluginOrder < 1 || configPluginOrder > 5) {\n\t\t\tthrow new IllegalArgumentException(\"configPluginOrder 只能取值为:1、2、3、4、5\");\n\t\t}\n\t\tthis.configPluginOrder = configPluginOrder;\n\t}\n\t\n\tpublic int getConfigPluginOrder() {\n\t\treturn configPluginOrder;\n\t}\n\t\n\t/**\n\t * Set the renderFactory\n\t */\n\tpublic void setRenderFactory(IRenderFactory renderFactory) {\n\t\tif (renderFactory == null) {\n\t\t\tthrow new IllegalArgumentException(\"renderFactory can not be null.\");\n\t\t}\n\t\tRenderManager.me().setRenderFactory(renderFactory);\n\t}\n\t\n\t/**\n\t * 设置 Json 转换工厂实现类,目前支持:JFinalJsonFactory(默认)、JacksonFactory、FastJsonFactory\n\t * 分别支持 JFinalJson、Jackson、FastJson\n\t */\n\tpublic void setJsonFactory(IJsonFactory jsonFactory) {\n\t\tif (jsonFactory == null) {\n\t\t\tthrow new IllegalArgumentException(\"jsonFactory can not be null.\");\n\t\t}\n\t\tJsonManager.me().setDefaultJsonFactory(jsonFactory);\n\t}\n\t\n\t/**\n\t * 设置json转换时日期格式,常用格式有:\"yyyy-MM-dd HH:mm:ss\"、 \"yyyy-MM-dd\"\n\t */\n\tpublic void setJsonDatePattern(String datePattern) {\n\t\tif (StrKit.isBlank(datePattern)) {\n\t\t\tthrow new IllegalArgumentException(\"datePattern can not be blank.\");\n\t\t}\n\t\tJsonManager.me().setDefaultDatePattern(datePattern);\n\t}\n\t\n\tpublic void setCaptchaCache(ICaptchaCache captchaCache) {\n\t\tCaptchaManager.me().setCaptchaCache(captchaCache);\n\t}\n\t\n\tpublic void setLogFactory(ILogFactory logFactory) {\n\t\tif (logFactory == null) {\n\t\t\tthrow new IllegalArgumentException(\"logFactory can not be null.\");\n\t\t}\n\t\tLogManager.me().setDefaultLogFactory(logFactory);\n\t}\n\t\n\t/**\n\t * 切换到 slf4j 日志框架,需要引入 slf4j 相关依赖\n\t * 切换过去以后的用法参考 slf4j 文档\n\t */\n\tpublic void setToSlf4jLogFactory() {\n\t\tLogManager.me().setToSlf4jLogFactory();\n\t}\n\t\n\t/**\n\t * 配置 ProxyFactory 用于切换代理实现\n\t * <pre>\n\t * 例如:\n\t * me.setProxyFactory(new JavassistProxyFactory());\n\t * </pre>\n\t */\n\tpublic void setProxyFactory(ProxyFactory proxyFactory) {\n\t\tProxyManager.me().setProxyFactory(proxyFactory);\n\t}\n\t\n\t/**\n\t * 配置 JavassistProxyFactory 实现业务层 AOP。支持 JDK 17。\n\t * \n\t * 该配置需要引入 Javassist 依赖:\n * <pre>\n * <dependency>\n * <groupId>org.javassist</groupId>\n * <artifactId>javassist</artifactId>\n * <version>3.29.2-GA</version>\n * </dependency>\n * </pre>\n\t */\n\tpublic void setToJavassistProxyFactory() {\n setProxyFactory(new com.jfinal.ext.proxy.JavassistProxyFactory());\n }\n\t\n\t/**\n\t * proxy 模块需要 JDK 环境,如果运行环境为 JRE,可以调用本配置方法支持\n\t * \n\t * 该配置需要引入 cglib-nodep 依赖:\n\t * <pre>\n\t * <dependency>\n \t * <groupId>cglib</groupId>\n \t * <artifactId>cglib-nodep</artifactId>\n \t * <version>3.2.5</version>\n\t * </dependency>\n\t * </pre>\n\t */\n\tpublic void setToCglibProxyFactory() {\n\t\tsetProxyFactory(new com.jfinal.ext.proxy.CglibProxyFactory());\n\t}\n\t\n\t/**\n\t * Set encoding. The default encoding is UTF-8.\n\t * @param encoding the encoding\n\t */\n\tpublic void setEncoding(String encoding) {\n\t\tif (StrKit.isBlank(encoding)) {\n\t\t\tthrow new IllegalArgumentException(\"encoding can not be blank.\");\n\t\t}\n\t\tthis.encoding = encoding;\n\t}\n\t\n\tpublic String getEncoding() {\n\t\treturn encoding;\n\t}\n\t\n\t/**\n\t * 设置自定义的 ControllerFactory 用于创建 Controller 对象\n\t */\n\tpublic void setControllerFactory(ControllerFactory controllerFactory) {\n\t\tif (controllerFactory == null) {\n\t\t\tthrow new IllegalArgumentException(\"controllerFactory can not be null.\");\n\t\t}\n\t\tthis.controllerFactory = controllerFactory;\n\t}\n\t\n\tpublic ControllerFactory getControllerFactory() {\n\t\tcontrollerFactory.setInjectDependency(getInjectDependency());\n\t\treturn controllerFactory;\n\t}\n\t\n\t/**\n\t * 设置对 Controller、Interceptor、Validator 进行依赖注入,默认值为 false\n\t * \n\t * 被注入对象默认为 singleton,可以通过 AopManager.me().setSingleton(boolean) 配置\n\t * 该默认值。\n\t * \n\t * 也可通过在被注入的目标类上使用 Singleton 注解覆盖上述默认值,注解配置\n\t * 优先级高于默认配置\n\t */\n\tpublic void setInjectDependency(boolean injectDependency) {\n\t\tAopManager.me().setInjectDependency(injectDependency);\n\t}\n\t\n\tpublic boolean getInjectDependency() {\n\t\treturn AopManager.me().isInjectDependency();\n\t}\n\t\n\t/**\n\t * 设置是否对超类进行注入\n\t */\n\tpublic void setInjectSuperClass(boolean injectSuperClass) {\n\t\tAopManager.me().setInjectSuperClass(injectSuperClass);\n\t}\n\t\n\tpublic boolean getInjectSuperClass() {\n\t\treturn AopManager.me().isInjectSuperClass();\n\t}\n\t\n\t/**\n\t * Set ITokenCache implementation otherwise JFinal will use the HttpSesion to hold the token.\n\t * @param tokenCache the token cache\n\t */\n\tpublic void setTokenCache(ITokenCache tokenCache) {\n\t\tthis.tokenCache = tokenCache;\n\t}\n\t\n\tpublic ITokenCache getTokenCache() {\n\t\treturn tokenCache;\n\t}\n\t\n\tpublic String getUrlParaSeparator() {\n\t\treturn urlParaSeparator;\n\t}\n\t\n\tpublic ViewType getViewType() {\n\t\treturn viewType;\n\t}\n\t\n\t/**\n\t * Set view type. The default value is ViewType.JFINAL_TEMPLATE\n\t * Controller.render(String view) will use the view type to render the view.\n\t * @param viewType the view type \n\t */\n\tpublic void setViewType(ViewType viewType) {\n\t\tif (viewType == null) {\n\t\t\tthrow new IllegalArgumentException(\"viewType can not be null\");\n\t\t}\n\t\tthis.viewType = viewType;\n\t}\n\t\n\t/**\n\t * Set urlPara separator. The default value is \"-\"\n\t * @param urlParaSeparator the urlPara separator\n\t */\n\tpublic void setUrlParaSeparator(String urlParaSeparator) {\n\t\tif (StrKit.isBlank(urlParaSeparator) || urlParaSeparator.contains(\"/\")) {\n\t\t\tthrow new IllegalArgumentException(\"urlParaSepartor can not be blank and can not contains \\\"/\\\"\");\n\t\t}\n\t\tthis.urlParaSeparator = urlParaSeparator;\n\t}\n\t\n\tpublic String getViewExtension() {\n\t\treturn viewExtension;\n\t}\n\t\n\t/**\n\t * Set view extension for the IRenderFactory.getDefaultRender(...)\n\t * The default value is \".html\"\n\t * \n\t * Example: \".html\" or \".ftl\"\n\t * @param viewExtension the extension of the view, it must start with dot char \".\"\n\t */\n\tpublic void setViewExtension(String viewExtension) {\n\t\tthis.viewExtension = viewExtension.startsWith(\".\") ? viewExtension : \".\" + viewExtension;\n\t}\n\t\n\t/**\n\t * Set error 404 view.\n\t * @param error404View the error 404 view\n\t */\n\tpublic void setError404View(String error404View) {\n\t\tsetErrorView(404, error404View);\n\t}\n\t\n\t/**\n\t * Set error 500 view.\n\t * @param error500View the error 500 view\n\t */\n\tpublic void setError500View(String error500View) {\n\t\tsetErrorView(500, error500View);\n\t}\n\t\n\t/**\n\t * Set error 401 view.\n\t * @param error401View the error 401 view\n\t */\n\tpublic void setError401View(String error401View) {\n\t\tsetErrorView(401, error401View);\n\t}\n\t\n\t/**\n\t * Set error 403 view.\n\t * @param error403View the error 403 view\n\t */\n\tpublic void setError403View(String error403View) {\n\t\tsetErrorView(403, error403View);\n\t}\n\t\n\tpublic void setErrorView(int errorCode, String errorView) {\n\t\tErrorRender.setErrorView(errorCode, errorView);\n\t}\n\t\n\t/* 已挪至 ErrorRender\n\tpublic String getErrorView(int errorCode) {\n\t\treturn errorViewMapping.get(errorCode);\n\t}*/\n\t\n\t/**\n\t * 设置返回给客户端的 json 内容。建议使用 Ret 对象生成 json 内容来配置\n\t * <pre>\n\t * 例如:\n\t * 1:me.setErrorJsonContent(404, Ret.fail(\"404 Not Found\").toJson());\n\t * 2:me.setErrorJsonContent(500, Ret.fail(\"500 Internal Server Error\").toJson());\n\t * </pre>\n\t */\n\tpublic void setErrorJsonContent(int errorCode, String errorJsonContent) {\n\t\tErrorRender.setErrorJsonContent(errorCode, errorJsonContent);\n\t}\n\t\n\t/**\n\t * 设置返回给客户端的 html 内容\n\t * 注意:一般使用 setErrorView 指定 html 页面的方式会更方便些\n\t */\n\tpublic void setErrorHtmlContent(int errorCode, String errorHtmlContent) {\n\t\tErrorRender.setErrorHtmlContent(errorCode, errorHtmlContent);\n\t}\n\t\n\tpublic String getBaseDownloadPath() {\n\t\treturn baseDownloadPath;\n\t}\n\t\n\t/**\n\t * Set file base download path for Controller.renderFile(...)\n\t * 设置文件下载基础路径,当路径以 \"/\" 打头或是以 windows 磁盘盘符打头,\n\t * 则将路径设置为绝对路径,否则路径将是以应用根路径为基础的相对路径\n\t * <pre>\n\t * 例如:\n\t * 1:参数 \"/var/www/download\" 为绝对路径,下载文件存放在此路径之下\n\t * 2:参数 \"download\" 为相对路径,下载文件存放在 PathKit.getWebRoot() + \"/download\" 路径之下\n\t * </pre>\n\t */\n\tpublic void setBaseDownloadPath(String baseDownloadPath) {\n\t\tif (StrKit.isBlank(baseDownloadPath)) {\n\t\t\tthrow new IllegalArgumentException(\"baseDownloadPath can not be blank.\");\n\t\t}\n\t\tthis.baseDownloadPath = baseDownloadPath;\n\t}\n\t\n\t/**\n\t * Set file base upload path.\n\t * 设置文件上传保存基础路径,当路径以 \"/\" 打头或是以 windows 磁盘盘符打头,\n\t * 则将路径设置为绝对路径,否则路径将是以应用根路径为基础的相对路径\n\t * <pre>\n\t * 例如:\n\t * 1:参数 \"/var/www/upload\" 为绝对路径,上传文件将保存到此路径之下\n\t * 2:参数 \"upload\" 为相对路径,上传文件将保存到 PathKit.getWebRoot() + \"/upload\" 路径之下\n\t * </pre>\n\t */\n\tpublic void setBaseUploadPath(String baseUploadPath) {\n\t\tif (StrKit.isBlank(baseUploadPath)) {\n\t\t\tthrow new IllegalArgumentException(\"baseUploadPath can not be blank.\");\n\t\t}\n\t\tthis.baseUploadPath = baseUploadPath;\n\t}\n\t\n\tpublic String getBaseUploadPath() {\n\t\treturn baseUploadPath;\n\t}\n\t\n\tpublic long getMaxPostSize() {\n\t\treturn maxPostSize;\n\t}\n\t\n\t/**\n\t * Set max size of http post. The upload file size depend on this value.\n\t */\n\tpublic void setMaxPostSize(long maxPostSize) {\n\t\tthis.maxPostSize = maxPostSize;\n\t}\n\t\n\t/**\n\t * Set default base name to load Resource bundle.\n\t * The default value is \"i18n\".<tr>\n\t * Example:\n\t * setI18nDefaultBaseName(\"i18n\");\n\t */\n\tpublic void setI18nDefaultBaseName(String defaultBaseName) {\n\t\tI18n.setDefaultBaseName(defaultBaseName);\n\t}\n\t\n\t/**\n\t * Set default locale to load Resource bundle.\n\t * The locale string like this: \"zh_CN\" \"en_US\".<br>\n\t * Example:\n\t * setI18nDefaultLocale(\"zh_CN\");\n\t */\n\tpublic void setI18nDefaultLocale(String defaultLocale) {\n\t\tI18n.setDefaultLocale(defaultLocale);\n\t}\n\t\n\t/**\n\t * 设置 devMode 之下的 action report 是否在 invocation 之后,默认值为 true\n\t */\n\tpublic void setReportAfterInvocation(boolean reportAfterInvocation) {\n\t\tActionReporter.setReportAfterInvocation(reportAfterInvocation);\n\t}\n\t\n\t/**\n\t * FreeMarker template update delay for not devMode.\n\t */\n\tpublic void setFreeMarkerTemplateUpdateDelay(int delayInSeconds) {\n\t\tif (delayInSeconds < 0) {\n\t\t\tthrow new IllegalArgumentException(\"template_update_delay must more than -1.\");\n\t\t}\n\t\tthis.freeMarkerTemplateUpdateDelay = delayInSeconds;\n\t}\n\t\n\tpublic int getFreeMarkerTemplateUpdateDelay() {\n\t\treturn freeMarkerTemplateUpdateDelay;\n\t}\n\t\n\tpublic void setDenyAccessJsp(boolean denyAccessJsp) {\n\t\tthis.denyAccessJsp = denyAccessJsp;\n\t}\n\t\n\tpublic boolean getDenyAccessJsp() {\n\t\treturn denyAccessJsp;\n\t}\n\t\n\t/**\n\t * 设置自定义的 ActionReporter 用于定制 action report 输出功能\n\t */\n\tpublic void setActionReporter(ActionReporter actionReporter) {\n\t\tthis.actionReporter = actionReporter;\n\t}\n\t\n\tpublic ActionReporter getActionReporter() {\n\t\treturn actionReporter;\n\t}\n\t\n\t/**\n\t * 设置为 Headless Mode,否则在缺少显示设备时验证码功能不能使用,并抛出异常\n\t * java.awt.HeadlessException\n\t * \n\t * Headless 模式是系统的一种配置模式。在该模式下,系统缺少显示设备、键盘或鼠标。\n\t * 配置为 \"true\" 时 Graphics、Font、Color、ImageIO、Print、Graphics2D\n\t * 等等 API 仍然能够使用\n\t */\n\tpublic void setToJavaAwtHeadless() {\n\t\tSystem.setProperty(\"java.awt.headless\", \"true\");\n\t}\n\t\n\t/**\n\t * 配置是否解析 json 请求,支持 action 参数注入并支持 Controller 中与参数有关的 get 系方法,便于前后端分离项目\n\t */\n\tpublic void setResolveJsonRequest(boolean resolveJsonRequest) {\n\t\tActionHandler.setResolveJson(resolveJsonRequest);\n\t}\n\t\n\t/**\n\t * 配置 JsonRequest 工厂,用于切换 JsonRequest 扩展实现\n\t */\n\tpublic void setJsonRequestFactory(BiFunction<String, HttpServletRequest, JsonRequest> jsonRequestFactory) {\n\t\tActionHandler.setJsonRequestFactory(jsonRequestFactory);\n\t}\n\t\n\t// ---------\n\t\n\t// 支持扩展 ActionMapping\n\tprivate Function<Routes, ActionMapping> actionMappingFunc = null;\n\t\n\tpublic void setActionMapping(Function<Routes, ActionMapping> func) {\n\t\tthis.actionMappingFunc = func;\n\t}\n\t\n\tpublic Function<Routes, ActionMapping> getActionMappingFunc() {\n\t\treturn actionMappingFunc;\n\t}\n}" }, { "identifier": "JFinalConfig", "path": "src/main/java/com/jfinal/config/JFinalConfig.java", "snippet": "public abstract class JFinalConfig {\n\t\n\t/**\n\t * Config constant\n\t */\n\tpublic abstract void configConstant(Constants me);\n\t\n\t/**\n\t * Config route\n\t */\n\tpublic abstract void configRoute(Routes me);\n\t\n\t/**\n\t * Config engine\n\t */\n\tpublic abstract void configEngine(Engine me);\n\t\n\t/**\n\t * Config plugin\n\t */\n\tpublic abstract void configPlugin(Plugins me);\n\t\n\t/**\n\t * Config interceptor applied to all actions.\n\t */\n\tpublic abstract void configInterceptor(Interceptors me);\n\t\n\t/**\n\t * Config handler\n\t */\n\tpublic abstract void configHandler(Handlers me);\n\t\n\t/**\n\t * Call back after JFinal start\n\t */\n\tpublic void onStart() {}\n\t\n\t/**\n\t * 为减少记忆成本、代码输入量以及输入手误的概率 afterJFinalStart() 已被 onStart() 取代,\n\t * 功能暂时保留仍然可用\n\t */\n\t@Deprecated\n\tpublic void afterJFinalStart() {}\n\t\n\t/**\n\t * Call back before JFinal stop\n\t */\n\tpublic void onStop() {}\n\t\n\t/**\n\t * 为减少记忆成本、代码输入量以及输入手误的概率 beforeJFinalStop() 已被 onStop() 取代,\n\t * 功能暂时保留仍然可用\n\t */\n\t@Deprecated\n\tpublic void beforeJFinalStop() {}\n\t\n\tprotected Prop prop = null;\n\t\n\t/**\n\t * Use the first found properties file\n\t */\n\tpublic Prop useFirstFound(String... fileNames) {\n\t\tfor (String fn : fileNames) {\n\t\t\ttry {\n\t\t\t\tprop = new Prop(fn, Const.DEFAULT_ENCODING);\n\t\t\t\treturn prop;\n\t\t\t} catch (Exception e) {\n\t\t\t\tprop = null;\n\t\t\t\tcontinue ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tthrow new IllegalArgumentException(\"没有配置文件可被使用\");\n\t}\n\t\n\t/**\n\t * Load property file.\n\t * @see #loadPropertyFile(String, String)\n\t */\n\tpublic Properties loadPropertyFile(String fileName) {\n\t\treturn loadPropertyFile(fileName, Const.DEFAULT_ENCODING);\n\t}\n\t\n\t/**\n\t * Load property file.\n\t * Example:<br>\n\t * loadPropertyFile(\"db_username_pass.txt\", \"UTF-8\");\n\t * \n\t * @param fileName the file in CLASSPATH or the sub directory of the CLASSPATH\n\t * @param encoding the encoding\n\t */\n\tpublic Properties loadPropertyFile(String fileName, String encoding) {\n\t\tprop = new Prop(fileName, encoding);\n\t\treturn prop.getProperties();\n\t}\n\t\n\t/**\n\t * Load property file.\n\t * @see #loadPropertyFile(File, String)\n\t */\n\tpublic Properties loadPropertyFile(File file) {\n\t\treturn loadPropertyFile(file, Const.DEFAULT_ENCODING);\n\t}\n\t\n\t/**\n\t * Load property file\n\t * Example:<br>\n\t * loadPropertyFile(new File(\"/var/config/my_config.txt\"), \"UTF-8\");\n\t * \n\t * @param file the properties File object\n\t * @param encoding the encoding\n\t */\n\tpublic Properties loadPropertyFile(File file, String encoding) {\n\t\tprop = new Prop(file, encoding);\n\t\treturn prop.getProperties();\n\t}\n\t\n\tpublic void unloadPropertyFile() {\n\t\tthis.prop = null;\n\t}\n\t\n\tprivate Prop getProp() {\n\t\tif (prop == null) {\n\t\t\tthrow new IllegalStateException(\"Load propties file by invoking loadPropertyFile(String fileName) method first.\");\n\t\t}\n\t\treturn prop;\n\t}\n\t\n\tpublic String getProperty(String key) {\n\t\treturn getProp().get(key);\n\t}\n\t\n\tpublic String getProperty(String key, String defaultValue) {\n\t\treturn getProp().get(key, defaultValue);\n\t}\n\t\n\tpublic Integer getPropertyToInt(String key) {\n\t\treturn getProp().getInt(key);\n\t}\n\t\n\tpublic Integer getPropertyToInt(String key, Integer defaultValue) {\n\t\treturn getProp().getInt(key, defaultValue);\n\t}\n\t\n\tpublic Long getPropertyToLong(String key) {\n\t\treturn getProp().getLong(key);\n\t}\n\t\n\tpublic Long getPropertyToLong(String key, Long defaultValue) {\n\t\treturn getProp().getLong(key, defaultValue);\n\t}\n\t\n\tpublic Boolean getPropertyToBoolean(String key) {\n\t\treturn getProp().getBoolean(key);\n\t}\n\t\n\tpublic Boolean getPropertyToBoolean(String key, Boolean defaultValue) {\n\t\treturn getProp().getBoolean(key, defaultValue);\n\t}\n}" }, { "identifier": "Handler", "path": "src/main/java/com/jfinal/handler/Handler.java", "snippet": "public abstract class Handler {\n\t\n\t/**\n\t * The next handler\n\t */\n\tprotected Handler next;\n\t\n\t/**\n\t * Use next instead of nextHandler\n\t */\n\t@Deprecated\n\tprotected Handler nextHandler;\n\t\n\t/**\n\t * Handle target\n\t * @param target url target of this web http request\n\t * @param request HttpServletRequest of this http request\n\t * @param response HttpServletResponse of this http response\n\t * @param isHandled JFinalFilter will invoke doFilter() method if isHandled[0] == false,\n\t * \t\t\tit is usually to tell Filter should handle the static resource.\n\t */\n\tpublic abstract void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled);\n}" }, { "identifier": "Log", "path": "src/main/java/com/jfinal/log/Log.java", "snippet": "public abstract class Log {\n\t\n\tprivate static ILogFactory defaultLogFactory = null;\n\t\n\tstatic {\n\t\tinit();\n\t}\n\t\n\tstatic void init() {\n\t\tif (defaultLogFactory == null) {\n\t\t\ttry {\n\t\t\t\tClass.forName(\"org.apache.log4j.Logger\");\n\t\t\t\tClass<?> log4jLogFactoryClass = Class.forName(\"com.jfinal.log.Log4jLogFactory\");\n\t\t\t\tdefaultLogFactory = (ILogFactory)log4jLogFactoryClass.newInstance();\t// return new Log4jLogFactory();\n\t\t\t} catch (Exception e) {\n\t\t\t\tdefaultLogFactory = new JdkLogFactory();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tstatic void setDefaultLogFactory(ILogFactory defaultLogFactory) {\n\t\tif (defaultLogFactory == null) {\n\t\t\tthrow new IllegalArgumentException(\"defaultLogFactory can not be null.\");\n\t\t}\n\t\tLog.defaultLogFactory = defaultLogFactory;\n\t}\n\t\n\tpublic static Log getLog(Class<?> clazz) {\n\t\treturn defaultLogFactory.getLog(clazz);\n\t}\n\t\n\tpublic static Log getLog(String name) {\n\t\treturn defaultLogFactory.getLog(name);\n\t}\n\t\n\tpublic abstract void debug(String message);\n\t\n\tpublic abstract void debug(String message, Throwable t);\n\t\n\tpublic abstract void info(String message);\n\t\n\tpublic abstract void info(String message, Throwable t);\n\t\n\tpublic abstract void warn(String message);\n\t\n\tpublic abstract void warn(String message, Throwable t);\n\t\n\tpublic abstract void error(String message);\n\t\n\tpublic abstract void error(String message, Throwable t);\n\t\n\tpublic abstract void fatal(String message);\n\t\n\tpublic abstract void fatal(String message, Throwable t);\n\t\n\tpublic abstract boolean isDebugEnabled();\n\n\tpublic abstract boolean isInfoEnabled();\n\n\tpublic abstract boolean isWarnEnabled();\n\n\tpublic abstract boolean isErrorEnabled();\n\t\n\tpublic abstract boolean isFatalEnabled();\n\t\n\t// -------------------------------------------------------\n\t\n\t/*\n\t * 以下 3 个方法为 jfinal 4.8 新增日志级别:trace\n\t * 1:为了兼容用户已经扩展出来的 Log 实现,给出了默认实现\n\t * 2:某些日志系统(如 log4j,参考 Log4jLog)需要覆盖以下\n\t * 方法,才能保障日志信息中的类名正确\n\t */\n\t\n\tpublic boolean isTraceEnabled() {\n\t\treturn isDebugEnabled();\n\t}\n\t\n\tpublic void trace(String message) {\n\t\tdebug(message);\n\t}\n\t\n\tpublic void trace(String message, Throwable t) {\n\t\tdebug(message, t);\n\t}\n\t\n\t// -------------------------------------------------------\n\t\n\t/*\n\t * 以下为 jfinal 4.8 新增的支持可变参数的方法\n\t * 1:为了兼容用户已经扩展出来的 Log 实现,给出了默认实现\n\t * \n\t * 2:默认实现通过 String.format(...) 实现的占位符功能与\n\t * slf4j 的占位符用法不同,因此在使用中要保持使用其中某一种,\n\t * 否则建议使用其它方法替代下面的 6 个方法\n\t * 注意:jfinal 内部未使用日志的可变参数方法,所以支持各类\n\t * 日志切换使用\n\t * \n\t * 3:某些日志系统(如 log4j,参考 Log4jLog)需要覆盖以下方法,才能\n\t * 保障日志信息中的类名正确\n\t */\n\t\n\t/**\n\t * 判断可变参数是否以 Throwable 结尾\n\t */\n\tprotected boolean endsWithThrowable(Object... args) {\n\t\treturn\targs != null && args.length != 0 &&\n\t\t\t\targs[args.length - 1] instanceof Throwable;\n\t}\n\t\n\t/**\n\t * parse(...) 方法必须与 if (endsWithThrowable(...)) 配合使用,\n\t * 确保可变参数 Object... args 中的最后一个元素为 Throwable 类型\n\t */\n\tprotected LogInfo parse(String format, Object... args) {\n\t\tLogInfo li = new LogInfo();\n\t\t\n\t\t// 最后一个参数已确定为 Throwable\n\t\tli.throwable = (Throwable)args[args.length - 1];\n\t\t\n\t\t// 其它参数与 format 一起格式化成 message\n\t\tif (args.length > 1) {\n\t\t\tObject[] temp = new Object[args.length - 1];\n\t\t\tfor (int i=0; i<temp.length; i++) {\n\t\t\t\ttemp[i] = args[i];\n\t\t\t}\n\t\t\t\n\t\t\tli.message = String.format(format, temp);\n\t\t} else {\n\t\t\tli.message = format;\n\t\t}\n\t\t\n\t\treturn li;\n\t}\n\t\n\tpublic void trace(String format, Object... args) {\n\t\tif (isTraceEnabled()) {\n\t\t\tif (endsWithThrowable(args)) {\n\t\t\t\tLogInfo li = parse(format, args);\n\t\t\t\ttrace(li.message, li.throwable);\n\t\t\t} else {\n\t\t\t\ttrace(String.format(format, args));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void debug(String format, Object... args) {\n\t\tif (isDebugEnabled()) {\n\t\t\tif (endsWithThrowable(args)) {\n\t\t\t\tLogInfo li = parse(format, args);\n\t\t\t\tdebug(li.message, li.throwable);\n\t\t\t} else {\n\t\t\t\tdebug(String.format(format, args));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void info(String format, Object... args) {\n\t\tif (isInfoEnabled()) {\n\t\t\tif (endsWithThrowable(args)) {\n\t\t\t\tLogInfo li = parse(format, args);\n\t\t\t\tinfo(li.message, li.throwable);\n\t\t\t} else {\n\t\t\t\tinfo(String.format(format, args));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void warn(String format, Object... args) {\n\t\tif (isWarnEnabled()) {\n\t\t\tif (endsWithThrowable(args)) {\n\t\t\t\tLogInfo li = parse(format, args);\n\t\t\t\twarn(li.message, li.throwable);\n\t\t\t} else {\n\t\t\t\twarn(String.format(format, args));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void error(String format, Object... args) {\n\t\tif (isErrorEnabled()) {\n\t\t\tif (endsWithThrowable(args)) {\n\t\t\t\tLogInfo li = parse(format, args);\n\t\t\t\terror(li.message, li.throwable);\n\t\t\t} else {\n\t\t\t\terror(String.format(format, args));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void fatal(String format, Object... args) {\n\t\tif (isFatalEnabled()) {\n\t\t\tif (endsWithThrowable(args)) {\n\t\t\t\tLogInfo li = parse(format, args);\n\t\t\t\tfatal(li.message, li.throwable);\n\t\t\t} else {\n\t\t\t\tfatal(String.format(format, args));\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "Filter", "path": "src/main/java/com/jfinal/servlet/Filter.java", "snippet": "public interface Filter {\n\n}" }, { "identifier": "FilterChain", "path": "src/main/java/com/jfinal/servlet/FilterChain.java", "snippet": "public class FilterChain {\n\n public void doFilter(HttpServletRequest request, HttpServletResponse response) {\n // TODO Auto-generated method stub\n \n }\n\n}" }, { "identifier": "FilterConfig", "path": "src/main/java/com/jfinal/servlet/FilterConfig.java", "snippet": "public class FilterConfig {\n\n public String getInitParameter(String string) {\n // TODO Auto-generated method stub\n return null;\n }\n\n public ServletContext getServletContext() {\n // TODO Auto-generated method stub\n return null;\n }\n\n}" }, { "identifier": "ServletException", "path": "src/main/java/com/jfinal/servlet/ServletException.java", "snippet": "public class ServletException extends RuntimeException{\n\n}" }, { "identifier": "ServletRequest", "path": "src/main/java/com/jfinal/servlet/ServletRequest.java", "snippet": "public class ServletRequest {\n\n}" }, { "identifier": "ServletResponse", "path": "src/main/java/com/jfinal/servlet/ServletResponse.java", "snippet": "public class ServletResponse {\n\n}" }, { "identifier": "HttpServletRequest", "path": "src/main/java/com/jfinal/servlet/http/HttpServletRequest.java", "snippet": "public interface HttpServletRequest {\n\n Map<String, String[]> getParameterMap();\n\n String getParameter(String name);\n\n /**\n * 该方法将触发 createParaMap(),框架内部应尽可能避免该事情发生,以优化性能\n */\n String[] getParameterValues(String name);\n\n Enumeration<String> getParameterNames();\n\n ServletInputStream getInputStream() throws IOException;\n\n BufferedReader getReader() throws IOException;\n\n Object getAttribute(String name);\n\n Enumeration<String> getAttributeNames();\n\n String getCharacterEncoding();\n\n void setCharacterEncoding(String env) throws UnsupportedEncodingException;\n\n int getContentLength();\n\n long getContentLengthLong();\n\n String getContentType();\n\n String getProtocol();\n\n String getScheme();\n\n String getServerName();\n\n int getServerPort();\n\n String getRemoteAddr();\n\n String getRemoteHost();\n\n void setAttribute(String name, Object o);\n\n void removeAttribute(String name);\n\n Locale getLocale();\n\n Enumeration<Locale> getLocales();\n\n boolean isSecure();\n\n RequestDispatcher getRequestDispatcher(String path);\n\n String getRealPath(String path);\n\n int getRemotePort();\n\n String getLocalName();\n\n String getLocalAddr();\n\n int getLocalPort();\n\n ServletContext getServletContext();\n\n AsyncContext startAsync() throws IllegalStateException;\n\n AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException;\n\n boolean isAsyncStarted();\n\n boolean isAsyncSupported();\n\n AsyncContext getAsyncContext();\n\n DispatcherType getDispatcherType();\n\n String getAuthType();\n\n Cookie[] getCookies();\n\n long getDateHeader(String name);\n\n String getHeader(String name);\n\n Enumeration<String> getHeaders(String name);\n\n Enumeration<String> getHeaderNames();\n\n int getIntHeader(String name);\n\n String getMethod();\n\n String getPathInfo();\n\n String getPathTranslated();\n\n String getContextPath();\n\n String getQueryString();\n\n String getRemoteUser();\n\n boolean isUserInRole(String role);\n\n Principal getUserPrincipal();\n\n String getRequestedSessionId();\n\n String getRequestURI();\n\n StringBuffer getRequestURL();\n\n String getServletPath();\n\n HttpSession getSession(boolean create);\n\n HttpSession getSession();\n\n String changeSessionId();\n\n boolean isRequestedSessionIdValid();\n\n boolean isRequestedSessionIdFromCookie();\n\n boolean isRequestedSessionIdFromURL();\n\n boolean isRequestedSessionIdFromUrl();\n\n boolean authenticate(HttpServletResponse response) throws IOException;\n\n void login(String username, String password);\n\n void logout();\n\n Collection<Part> getParts() throws IOException;\n\n Part getPart(String name) throws IOException, ServletException;\n\n <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException;\n\n}" }, { "identifier": "HttpServletResponse", "path": "src/main/java/com/jfinal/servlet/http/HttpServletResponse.java", "snippet": "public interface HttpServletResponse {\n\n int SC_NOT_FOUND = 0;\n int SC_MOVED_PERMANENTLY = 0;\n int SC_PARTIAL_CONTENT = 206;\n\n void setStatus(int errorCode);\n\n void addCookie(Cookie cookie);\n\n void setContentType(String contentType);\n\n PrintWriter getWriter() throws IOException;\n\n void setHeader(String string, String url);\n\n void sendRedirect(String url) throws IOException;\n\n void setCharacterEncoding(String defaultEncoding);\n\n ServletOutputStream getOutputStream();\n\n void setDateHeader(String string, int i);\n\n HttpResponse finish() throws IOException;\n\n}" } ]
import java.io.IOException; import com.jfinal.config.Constants; import com.jfinal.config.JFinalConfig; import com.jfinal.handler.Handler; import com.jfinal.log.Log; import com.jfinal.servlet.Filter; import com.jfinal.servlet.FilterChain; import com.jfinal.servlet.FilterConfig; import com.jfinal.servlet.ServletException; import com.jfinal.servlet.ServletRequest; import com.jfinal.servlet.ServletResponse; import com.jfinal.servlet.http.HttpServletRequest; import com.jfinal.servlet.http.HttpServletResponse;
9,100
/** * Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]). * * 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.jfinal.core; /** * JFinal framework filter */ public class JFinalFilter implements Filter { protected JFinalConfig jfinalConfig; protected int contextPathLength; protected Constants constants; protected String encoding; protected Handler handler; protected static Log log; protected static final JFinal jfinal = JFinal.me(); public JFinalFilter() { this.jfinalConfig = null; } /** * 支持 web 项目无需 web.xml 配置文件,便于嵌入式整合 jetty、undertow */ public JFinalFilter(JFinalConfig jfinalConfig) { this.jfinalConfig = jfinalConfig; } @SuppressWarnings("deprecation")
/** * Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]). * * 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.jfinal.core; /** * JFinal framework filter */ public class JFinalFilter implements Filter { protected JFinalConfig jfinalConfig; protected int contextPathLength; protected Constants constants; protected String encoding; protected Handler handler; protected static Log log; protected static final JFinal jfinal = JFinal.me(); public JFinalFilter() { this.jfinalConfig = null; } /** * 支持 web 项目无需 web.xml 配置文件,便于嵌入式整合 jetty、undertow */ public JFinalFilter(JFinalConfig jfinalConfig) { this.jfinalConfig = jfinalConfig; } @SuppressWarnings("deprecation")
public void init(FilterConfig filterConfig) throws ServletException {
6
2023-12-19 10:58:33+00:00
12k
ViniciusJPSilva/TSI-PizzeriaExpress
PizzeriaExpress/src/main/java/br/vjps/tsi/pe/managedbeans/RequestMB.java
[ { "identifier": "DAO", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/DAO.java", "snippet": "public class DAO<T> {\n\tprivate Class<T> tClass;\n\n\t/**\n * Construtor que recebe a classe da entidade para ser manipulada pelo DAO.\n *\n * @param tClass A classe da entidade.\n */\n\tpublic DAO(Class<T> tClass) {\n\t\tthis.tClass = tClass;\n\t}\n\n\t/**\n * Adiciona uma nova entidade ao banco de dados.\n *\n * @param t A entidade a ser adicionada.\n */\n\tpublic void add(T t) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\n\t\tmanager.getTransaction().begin();\n\t\tmanager.persist(t);\n\t\tmanager.getTransaction().commit();\n\t\tmanager.close();\n\t}\n\n\t/**\n * Atualiza uma entidade no banco de dados.\n *\n * @param t A entidade a ser atualizada.\n */\n\tpublic void update(T t) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\n\t\tmanager.getTransaction().begin();\n\t\tmanager.merge(t);\n\t\tmanager.getTransaction().commit();\n\t\tmanager.close();\n\t}\n\n\t/**\n * Remove uma entidade do banco de dados.\n *\n * @param t A entidade a ser removida.\n */\n\tpublic void remove(T t) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\n\t\tmanager.getTransaction().begin();\n\t\tmanager.remove(manager.merge(t));\n\t\tmanager.getTransaction().commit();\n\t\tmanager.close();\n\t}\n\n\t/**\n * Busca uma entidade pelo seu identificador único (ID) no banco de dados.\n *\n * @param id O identificador único da entidade.\n * @return A entidade correspondente ao ID fornecido ou null se não encontrada.\n */\n\tpublic T findById(Long id) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\t\treturn manager.find(tClass, id);\n\t}\n\t\n\t/**\n * Retorna uma lista de todas as entidades do tipo especificado no banco de dados.\n *\n * @return Uma lista contendo todas as entidades do tipo especificado.\n */\n\tpublic List<T> list(){\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\t\tCriteriaQuery<T> query = manager.getCriteriaBuilder().createQuery(tClass);\n\t\tquery.select(query.from(tClass));\n\t\tList<T> list = manager.createQuery(query).getResultList();\n\t\tmanager.close();\n\t\treturn list;\n\t}\n}" }, { "identifier": "RequestDAO", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/RequestDAO.java", "snippet": "public class RequestDAO implements Closeable {\n\tprivate EntityManager manager;\n\n\t/**\n\t * Construtor padrão que inicializa o EntityManager usando a classe utilitária\n\t * JPAUtil.\n\t */\n\tpublic RequestDAO() {\n\t\tmanager = new JPAUtil().getEntityManager();\n\t}\n\t\n\t/**\n\t * Obtém o pedido corrente, em aberto, do cliente informado.\n\t * \n\t * @param client O cliente cujo pedido será buscado.\n\t * @return O pedido encontrado ou null se não encontrado.\n\t * \n\t * @throws IllegalArgumentException Se o client fornecido for nulo.\n\t */\n\tpublic Request getOpenRequestForClient(Client client) {\n\t\tif (client == null)\n\t\t\tthrow new IllegalArgumentException(\"Login não pode ser nulo!\");\n\t\t\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Request u WHERE u.client = :client AND u.open = TRUE\", Request.class);\n\t\tquery.setParameter(\"client\", client);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Request> list = query.getResultList();\n\n\t\treturn list.isEmpty() ? null : list.get(0);\n\t}\n\t\n\t/**\n\t * Obtém a lista de pedidos fechadas.\n\t * \n\t * @return Lista de pedidos fechadas.\n\t */\n\tpublic List<Request> getClosedRequests(Calendar date) {\n\t\tif(date == null)\n\t\t\tthrow new IllegalArgumentException(\"Data não pode ser nulo!\");\n\t\t\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Request u WHERE u.open = FALSE AND u.date = :date\", Request.class);\n\t\tquery.setParameter(\"date\", date, TemporalType.DATE);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Request> list = query.getResultList();\n\n\t\treturn list;\n\t}\n\t\n\t/**\n\t * Obtém a lista de pedidos em aberto.\n\t * \n\t * @return Lista de pedidos em aberto.\n\t */\n\tpublic List<Request> getOpenedRequests() {\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Request u WHERE u.open = TRUE\", Request.class);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Request> list = query.getResultList();\n\n\t\treturn list;\n\t}\n\t\n\t/**\n * Fecha o EntityManager quando este objeto ClientDAO é fechado.\n *\n * @throws IOException Se ocorrer um erro ao fechar o EntityManager.\n */\n\t@Override\n\tpublic void close() throws IOException {\n\t\tmanager.close();\n\t}\n}" }, { "identifier": "Category", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/enumeration/Category.java", "snippet": "public enum Category {\n\tSAVORY_PIZZA(\"Pizza Salgada\"),\n\tSWEET_PIZZA(\"Pizza Doce\"),\n\tDRINK(\"Bebida\");\n\t\n\tprivate String description;\n\t\n\tprivate Category(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\t\n\t/**\n\t * Obtém um objeto do tipo UserType com base na descrição especificada.\n\t *\n\t * @param description A descrição do tipo a ser buscado.\n\t * @return O UserType correspondente à descrição fornecida ou null se não encontrado.\n\t */\n\tpublic static Category getByDescription(String description) {\n\t\tfor(Category category : Category.values())\n\t\t\tif(category.description.equalsIgnoreCase(description))\n\t\t\t\treturn category;\n\t\treturn null;\n\t}\n}" }, { "identifier": "Client", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Client.java", "snippet": "@Entity\n@Table(name = Client.TABLE_NAME)\npublic class Client {\n\n\tpublic static final String TABLE_NAME = \"client\", EMAIL_COLUMN_NAME = \"email\", PASSWD_COLUMN_NAME = \"password\";\n\t\n\tpublic static final int CODE_LENGTH = 6;\n\n\tpublic static final double VOUCHER_VALUE = 100,\n\t\t\tREDEMPTION_VALUE = 600;\n\n\t@Id\n\t@SequenceGenerator(name = \"client_id\", sequenceName = \"client_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"client_id\")\n\tprivate Long id;\n\n\t@Column(unique = true)\n\t@Pattern(regexp = \"\\\\d{3}\\\\.\\\\d{3}\\\\.\\\\d{3}-\\\\d{2}\", message = \"CPF inválido\")\t\n\tprivate String cpf;\n\n\t@NotBlank(message = \"Nome inválido\")\n\tprivate String name;\n\n\t@Column(name = EMAIL_COLUMN_NAME, unique = true)\n\t@Pattern(regexp = \"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\", message = \"E-mail inválido\")\t\n\tprivate String email;\n\t\n\t@NotBlank(message = \"Telefone inválido\")\n\tprivate String phone;\n\t\n\t@OneToOne(cascade = CascadeType.ALL)\n\tprivate Address address = new Address();\n\t\n\t@Pattern(regexp = \"\\\\d{6}\", message = \"Código inválido\")\t\n\tprivate String loginCode;\n\t\n\tprivate Double voucher;\n\t\n\t{\n\t\tvoucher = 0.0;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getCpf() {\n\t\treturn cpf;\n\t}\n\n\tpublic void setCpf(String cpf) {\n\t\tthis.cpf = cpf;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getPhone() {\n\t\treturn phone;\n\t}\n\n\tpublic void setPhone(String phone) {\n\t\tthis.phone = phone;\n\t}\n\n\tpublic Address getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(Address address) {\n\t\tthis.address = address;\n\t}\n\n\tpublic String getLoginCode() {\n\t\treturn loginCode;\n\t}\n\n\tpublic void setLoginCode(String loginCode) {\n\t\tthis.loginCode = loginCode;\n\t}\n\n\tpublic Double getVoucher() {\n\t\treturn voucher;\n\t}\n\n\tpublic void setVoucher(Double voucher) {\n\t\tthis.voucher = voucher;\n\t}\n\n}" }, { "identifier": "Item", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Item.java", "snippet": "@Entity\npublic class Item {\n\t\n\t@Id\n\t@SequenceGenerator(name = \"item_id\", sequenceName = \"item_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"item_id\")\n\tprivate Long id;\n\t\n\t@Min(value = 1L, message = \"A quantidade deve ser maior ou igual a 1\")\n\tprivate Integer quantity;\n\t\n\tprivate Double unitPrice;\n\t\n\tprivate Double totalCost;\n\t\n\t@ManyToOne\n\tprivate Product product;\n\t\n\t@ManyToOne\n\tprivate Request request;\n\t\n\tprivate boolean delivered;\n\t\n\t// Inicia o valor do atributo no momento da instanciação do objeto.\n\t{\n\t\tunitPrice = 0.0;\n\t\ttotalCost = 0.0;\n\t\tdelivered = false;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Integer getQuantity() {\n\t\treturn quantity;\n\t}\n\n\tpublic void setQuantity(Integer quantity) {\n\t\tthis.quantity = quantity;\n\t}\n\n\tpublic Double getUnitPrice() {\n\t\treturn unitPrice;\n\t}\n\n\tpublic void setUnitPrice(Double unitPrice) {\n\t\tthis.unitPrice = unitPrice;\n\t}\n\n\tpublic Double getTotalCost() {\n\t\ttotalCost = (unitPrice != null && quantity != null) ? (unitPrice * quantity) : 0.0;\n\t\treturn totalCost;\n\t}\n\n\tpublic void setTotalCost(Double totalCost) {\n\t\tthis.totalCost = totalCost;\n\t}\n\n\tpublic Product getProduct() {\n\t\treturn product;\n\t}\n\n\tpublic void setProduct(Product product) {\n\t\tthis.product = product;\n\t}\n\n\tpublic Request getRequest() {\n\t\treturn request;\n\t}\n\n\tpublic void setRequest(Request request) {\n\t\tthis.request = request;\n\t}\n\n\tpublic boolean isDelivered() {\n\t\treturn delivered;\n\t}\n\n\tpublic void setDelivered(boolean delivered) {\n\t\tthis.delivered = delivered;\n\t}\n\t\n}" }, { "identifier": "Product", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Product.java", "snippet": "@Entity\n@Table(name = \"product\", \n\t uniqueConstraints = {\n\t\t\t @UniqueConstraint(columnNames = {\"name\",\"description\", \"size\", \"category\"})\n\t }\n)\npublic class Product {\n\n\t@Id\n\t@SequenceGenerator(name = \"product_id\", sequenceName = \"product_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"product_id\")\n\tprivate Long id;\n\t\n\t@NotNull\n\tprivate String name;\n\t\n\t@NotNull\n\tprivate String description;\n\t\n\t@Enumerated(EnumType.STRING)\n\tprivate ItemSize size;\n\t\n\t@Enumerated(EnumType.STRING)\n\tprivate Category category;\n\t\n\tprivate Double price;\n\t\n\tprivate boolean available = true;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic ItemSize getSize() {\n\t\treturn size;\n\t}\n\n\tpublic void setSize(ItemSize size) {\n\t\tthis.size = size;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double value) {\n\t\tthis.price = value;\n\t}\n\n\tpublic boolean isAvailable() {\n\t\treturn available;\n\t}\n\n\tpublic void setAvailable(boolean available) {\n\t\tthis.available = available;\n\t}\n}" }, { "identifier": "Request", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Request.java", "snippet": "@Entity\npublic class Request {\n\n\t@Id\n\t@SequenceGenerator(name = \"request_id\", sequenceName = \"request_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"request_id\")\n\tprivate Long id;\n\t\n\t@Temporal(TemporalType.DATE)\n\tprivate Calendar date = Calendar.getInstance();\n\t\n\t@OneToMany(cascade = CascadeType.ALL, mappedBy=\"request\", fetch = FetchType.EAGER)\n private List<Item> items = new ArrayList<>();\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"client\")\n\tprivate Client client;\n\t\n\tprivate Double value;\n\t\n\t@NotNull(message = \"Forneça uma mesa\")\n\tprivate Integer tableNumber;\n\t\n\tprivate boolean open;\n\t\n\tprivate boolean voucher;\n\t\n\t{\n\t\topen = true;\n\t\tvoucher = false;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Calendar getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setDate(Calendar date) {\n\t\tthis.date = date;\n\t}\n\n\tpublic List<Item> getItems() {\n\t\treturn items;\n\t}\n\n\tpublic void setItems(List<Item> items) {\n\t\tthis.items = items;\n\t}\n\n\tpublic Client getClient() {\n\t\treturn client;\n\t}\n\n\tpublic void setClient(Client client) {\n\t\tthis.client = client;\n\t}\n\n\tpublic Double getValue() {\n\t\tif(open)\n\t\t\tvalue = items.stream().mapToDouble(Item::getTotalCost).sum();\n\t\treturn value;\n\t}\n\n\tpublic void setValue(Double value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic Integer getTableNumber() {\n\t\treturn tableNumber;\n\t}\n\n\tpublic void setTableNumber(Integer tableNumber) {\n\t\tthis.tableNumber = tableNumber;\n\t}\n\n\tpublic boolean isOpen() {\n\t\treturn open;\n\t}\n\n\tpublic void setOpen(boolean open) {\n\t\tthis.open = open;\n\t}\n\n\tpublic boolean isVoucher() {\n\t\treturn voucher;\n\t}\n\n\tpublic void setVoucher(boolean voucher) {\n\t\tthis.voucher = voucher;\n\t}\n\t\n}" }, { "identifier": "SystemSettings", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/system/SystemSettings.java", "snippet": "public final class SystemSettings {\n\t\n\tprivate SystemSettings() {}\n\t\n\t\n\t// Define os modos de envio dos e-mail.\n\tpublic static enum EMAIL_SENDING_MODE {\n\t\t// MODO PADRÂO: efetua o envio para o e-mail do cliente, cadastrado no banco de dados.\n\t\tSEND_TO_CLIENT,\n\t\t\n\t\t// MODO DE TESTE: não efetua o envio de nenhum e-mail.\n\t\t// AO ATIVAR ESSE MODO, OS CADASTROS IRÃO SER EFETIVADOS IMEDIATAMENTE, SEM O ENVIO DO TOKEN.\n\t\tDO_NOT_SEND,\n\t\t\n\t\t// MODO DE TESTE: efetua o envio para o e-mail de teste - TEST_EMAIL - definido abaixo.\n\t\tSEND_TO_TEST\n\t};\n\n\t/**\n\t * Define se os e-mails serão enviados aos clientes, ao e-mail de teste ou não serão enviados.\n\t * Utilize os valores disponíveis em EMAIL_SENDING_MODE.\n\t */\n\tpublic static final EMAIL_SENDING_MODE \n\t\t\t\t\t\t\tEMAIL_MODE = EMAIL_SENDING_MODE.SEND_TO_TEST;\t\n\t\n\t\n\t// Constantes do sistema.\n\tpublic static final String \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// E-mail e senha utilizandos para efetuar o envio dos e-mails.\n\t\t\t\t\t\t\tSENDER_EMAIL = \"\", \n\t\t\t\t\t\t\tSENDER_EMAIL_PASSWD = \"\",\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t/* \n\t\t\t\t\t\t\t * E-mail de teste: os e-mails serão enviados \n\t\t\t\t\t\t\t * para o mesmo, caso o modo de teste esteja ativado.\n\t\t\t\t\t\t\t * (EMAIL_SENDING_MODE.SEND_TO_TEST)\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tTEST_EMAIL = \"\",\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t * Nome do banco de dados onde as tabelas serão criadas e os dados persistidos.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tDATA_BASE_NAME = \"pizzaria\"\n\t\t\t\t\t\t\t;\n\t\n\t/**\n\t * Define o tempo limite de inatividade (em minutos) dos usuários.\n\t * Após o tempo determinado o usuário será desconectado automaticamente pelo sistema.\n\t */\n\tpublic static final int INACTIVITY_TIMEOUT = 2;\n\n}" }, { "identifier": "EmailSender", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/utility/EmailSender.java", "snippet": "public final class EmailSender {\n\n private EmailSender() {}\n \n /**\n * Envia um email de forma assíncrona em uma thread separada. Isso permite que o envio de email\n * ocorra em segundo plano sem bloquear a execução do programa principal.\n *\n * @param message O conteúdo da mensagem a ser enviada no email.\n * @param subject O assunto do email.\n * @param receiverEmail O endereço de email do destinatário.\n */\n public static void sendAsync(final String message, final String subject, final String receiverEmail) {\n Runnable emailTask = new Runnable() {\n @Override\n public void run() {\n send(message, subject, receiverEmail);\n }\n };\n\n Thread thread = new Thread(emailTask);\n thread.start();\n }\n\t\n /**\n * Envia um email com a mensagem especificada para o destinatário especificado.\n *\n * @param message O conteúdo da mensagem a ser enviada.\n * @param subject O assunto do email.\n * @param receiverEmail O endereço de email do destinatário.\n */\n\tpublic static void send(String message, String subject, String receiverEmail) {\n\t\ttry {\n\t\t\tSimpleEmail email = new SimpleEmail();\n\t\t\t\n email.setHostName(\"smtp.googlemail.com\");\n \n email.setAuthentication(SystemSettings.SENDER_EMAIL, SystemSettings.SENDER_EMAIL_PASSWD);\n email.setSmtpPort(587); // Use a porta TLS apropriada (587 para TLS)\n\n // Ativar TLS\n email.setStartTLSEnabled(true);\n email.setSSLOnConnect(true);\n \n email.setFrom(SystemSettings.SENDER_EMAIL);\n \n email.setSubject(subject);\n\t email.setMsg(message);\n\t email.addTo(receiverEmail);\n\t \n\t email.send();\n } catch (EmailException e) {\n e.printStackTrace();\n }\n\t}\n}" }, { "identifier": "Utility", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/utility/Utility.java", "snippet": "public final class Utility {\n\n\t// Impede a instanciação de objetos desta classe.\n\tprivate Utility() {}\n\t\n\t/**\n * Converte um objeto Calendar em uma string formatada no formato \"dd/MM/yyyy\".\n *\n * @param date O objeto Calendar a ser convertido.\n * \n * @return Uma representação legível da data no formato \"dd/MM/yyyy\".\n */\n\tpublic static String calendarToReadableString(Calendar date) {\n\t\treturn new SimpleDateFormat(\"dd/MM/yyyy\").format(date.getTime());\n\t}\n\t\n /**\n * Converte uma string no formato \"dd/MM/yyyy\" para um objeto Calendar.\n *\n * @param dateString A string a ser convertida.\n * \n * @return Um objeto Calendar representando a data.\n * \n * @throws ParseException Se ocorrer um erro durante a análise da string.\n */\n public static Calendar stringToCalendar(String dateString) {\n try {\n Calendar calendar = getTodayCalendar();\n calendar.setTime(new SimpleDateFormat(\"dd/MM/yyyy\").parse(dateString));\n return calendar;\n } catch (ParseException e) {\n \treturn null;\n\t\t}\n }\n\t\n\t/**\n\t * Converte um objeto Calendar em uma string formatada no formato \"HH:mm dd/MM/yyyy\".\n\t *\n\t * @param date O objeto Calendar a ser convertido.\n\t * \n\t * @return Uma representação legível da data e hora no formato \"HH:mm dd/MM/yyyy\".\n\t */\n\tpublic static String calendarToReadableStringDateAndHour(Calendar date) {\n\t return new SimpleDateFormat(\"dd/MM/yyyy HH:mm\").format(date.getTime());\n\t}\n\t\n\t/**\n\t * Obtém uma data futura a partir da data atual, adicionando o número especificado de dias.\n\t *\n\t * @param daysPassed O número de dias a serem adicionados à data atual.\n\t * @return Um objeto Calendar representando a data futura.\n\t */\n\tpublic static Calendar getFutureDate(int daysPassed) {\n\t Calendar calendar = Calendar.getInstance();\n\t calendar.add(Calendar.DAY_OF_MONTH, daysPassed);\n\t return calendar;\n\t}\n\t\n\t/**\n\t * Converte um objeto Timestamp para um objeto Calendar configurado no fuso horário UTC.\n\t *\n\t * @param timestamp O objeto Timestamp a ser convertido.\n\t * @return Um objeto Calendar configurado com o valor da data/hora do Timestamp no fuso horário UTC.\n\t */\n\tpublic static Calendar timestampToCalendar(Timestamp timestamp) {\n\t\tCalendar calendar = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\n calendar.setTimeInMillis(timestamp.getTime());\n \n return calendar;\n\t}\n\n\t/**\n\t * Obtém um objeto Calendar configurado para representar o início do dia de hoje,\n\t * com hora, minuto, segundo e milissegundo definidos como zero.\n\t *\n\t * @return Um objeto Calendar configurado para o início do dia de hoje.\n\t */\n\tpublic static Calendar getTodayCalendar() {\n\t\tCalendar today = Calendar.getInstance();\n\n\t\t// Define a hora, minuto, segundo e milissegundo como zero para o início do dia de hoje\n\t\ttoday.set(Calendar.HOUR_OF_DAY, 0);\n\t\ttoday.set(Calendar.MINUTE, 0);\n\t\ttoday.set(Calendar.SECOND, 0);\n\t\ttoday.set(Calendar.MILLISECOND, 0);\n\t\t\n\t\treturn today;\n\t}\n\t\n} // class Utility" }, { "identifier": "ListSizeValidator", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/validator/ListSizeValidator.java", "snippet": "@FacesValidator(\"listSizeValidator\")\npublic class ListSizeValidator implements Validator {\n\t\n\tpublic void validate(FacesContext fc, UIComponent component, Object value) throws ValidatorException {\n\t\tInteger size = (Integer) value;\n\t\tif (size <= 0)\n\t\t\tthrow new ValidatorException(new FacesMessage(\"Selecione um item antes de fechar o pedido!\"));\n\t}\n}" } ]
import java.io.IOException; import java.util.Calendar; import java.util.List; import java.util.Optional; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; import br.vjps.tsi.pe.dao.DAO; import br.vjps.tsi.pe.dao.RequestDAO; import br.vjps.tsi.pe.enumeration.Category; import br.vjps.tsi.pe.model.Client; import br.vjps.tsi.pe.model.Item; import br.vjps.tsi.pe.model.Product; import br.vjps.tsi.pe.model.Request; import br.vjps.tsi.pe.system.SystemSettings; import br.vjps.tsi.pe.utility.EmailSender; import br.vjps.tsi.pe.utility.Utility; import br.vjps.tsi.pe.validator.ListSizeValidator;
7,217
package br.vjps.tsi.pe.managedbeans; @ViewScoped @ManagedBean public class RequestMB { private Request request = getOpenOrNewRequest(); private Item item = new Item(); private Long itemId; private Calendar searchDate = Utility.getTodayCalendar(); private List<Request> closedRequests; private List<Request> clientHistory; private List<Request> voucherHistory; /** * Define uma mesa para o cliente com base no ID. * * @param id O ID do cliente. */ public void setTable(Long id) { Client client = new DAO<Client>(Client.class).findById(id); Integer table = request.getTableNumber(); if (client != null) { request = new Request(); request.setClient(client); request.setDate(Utility.getTodayCalendar()); request.setTableNumber(table); new DAO<Request>(Request.class).add(request); } } /** * Obtém uma solicitação aberta existente ou cria uma nova. * * @return A solicitação aberta ou uma nova. */ private Request getOpenOrNewRequest() { Request oldRequest = null; try(RequestDAO dao = new RequestDAO()) { FacesContext facesContext = FacesContext.getCurrentInstance(); Client client = facesContext.getApplication().evaluateExpressionGet(facesContext, "#{clientMB}", ClientMB.class).getClient(); oldRequest = dao.getOpenRequestForClient(client); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { } if(oldRequest == null) oldRequest = new Request(); return oldRequest; } /** * Adiciona um item à solicitação. */ public void addItem() { DAO<Product> dao = new DAO<>(Product.class); Product product = dao.findById(itemId); item.setProduct(product); item.setUnitPrice(product.getPrice()); item.setTotalCost(item.getTotalCost()); item.setRequest(request); addItemToRequest(item); item = new Item(); } /** * Finaliza a solicitação. * * @param component O componente associado à solicitação. */ public void finishRequest(UIComponent component) { FacesContext facesContext = FacesContext.getCurrentInstance(); final String EMAIL_TITLE = "Comanda - Pizzaria Express", EMAIL_BODY = "Prezado(a) %s,\nSegue a comanda do pedido %d:\n\nMesa - %d\nData - %s\nTotal - R$ %.2f\nVoucher - %s\nItens: %s\n"; for(Item item : request.getItems()) if(!item.isDelivered()) { facesContext.addMessage(component.getClientId(facesContext), new FacesMessage(FacesMessage.SEVERITY_ERROR, "Alguns itens ainda não foram entregues.", null)); return; } try { new ListSizeValidator().validate(facesContext, component, request.getItems().size()); request.setOpen(false); System.out.println(request.isVoucher()); if(request.isVoucher()) { Double finalValue = request.getValue() - Client.VOUCHER_VALUE; request.setValue((finalValue >= 0) ? finalValue : 0.0); request.setVoucher(true); request.getClient().setVoucher(0.0); } else { request.getClient().setVoucher(request.getClient().getVoucher() + request.getValue()); } new DAO<Client>(Client.class).update(request.getClient()); new DAO<Request>(Request.class).update(request); if (SystemSettings.EMAIL_MODE != SystemSettings.EMAIL_SENDING_MODE.DO_NOT_SEND) { String emailMessage = String.format(EMAIL_BODY, request.getClient().getName(), request.getId(), request.getTableNumber(), Utility.calendarToReadableString(request.getDate()), request.getValue(), (request.isVoucher()) ? "Sim" : "Não", itemsToString(request.getItems())); EmailSender.sendAsync(emailMessage, EMAIL_TITLE, (SystemSettings.EMAIL_MODE == SystemSettings.EMAIL_SENDING_MODE.SEND_TO_TEST) ? SystemSettings.TEST_EMAIL : request.getClient().getEmail()); } request = new Request(); facesContext.addMessage(component.getClientId(facesContext), new FacesMessage(FacesMessage.SEVERITY_INFO, "Pedido Fechado! A comanda foi enviada para o seu e-mail.", null)); } catch (ValidatorException e) { facesContext.addMessage(component.getClientId(facesContext), new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null)); } } /** * Converte uma lista de itens para uma representação de string. * * @param items Lista de itens a ser convertida. * @return Representação de string dos itens. */ private String itemsToString(List<Item> items) { StringBuilder builder = new StringBuilder(); for(Item item : items) builder.append(String.format("\n%d - %s - %d - R$ %.2f", item.getId(),
package br.vjps.tsi.pe.managedbeans; @ViewScoped @ManagedBean public class RequestMB { private Request request = getOpenOrNewRequest(); private Item item = new Item(); private Long itemId; private Calendar searchDate = Utility.getTodayCalendar(); private List<Request> closedRequests; private List<Request> clientHistory; private List<Request> voucherHistory; /** * Define uma mesa para o cliente com base no ID. * * @param id O ID do cliente. */ public void setTable(Long id) { Client client = new DAO<Client>(Client.class).findById(id); Integer table = request.getTableNumber(); if (client != null) { request = new Request(); request.setClient(client); request.setDate(Utility.getTodayCalendar()); request.setTableNumber(table); new DAO<Request>(Request.class).add(request); } } /** * Obtém uma solicitação aberta existente ou cria uma nova. * * @return A solicitação aberta ou uma nova. */ private Request getOpenOrNewRequest() { Request oldRequest = null; try(RequestDAO dao = new RequestDAO()) { FacesContext facesContext = FacesContext.getCurrentInstance(); Client client = facesContext.getApplication().evaluateExpressionGet(facesContext, "#{clientMB}", ClientMB.class).getClient(); oldRequest = dao.getOpenRequestForClient(client); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { } if(oldRequest == null) oldRequest = new Request(); return oldRequest; } /** * Adiciona um item à solicitação. */ public void addItem() { DAO<Product> dao = new DAO<>(Product.class); Product product = dao.findById(itemId); item.setProduct(product); item.setUnitPrice(product.getPrice()); item.setTotalCost(item.getTotalCost()); item.setRequest(request); addItemToRequest(item); item = new Item(); } /** * Finaliza a solicitação. * * @param component O componente associado à solicitação. */ public void finishRequest(UIComponent component) { FacesContext facesContext = FacesContext.getCurrentInstance(); final String EMAIL_TITLE = "Comanda - Pizzaria Express", EMAIL_BODY = "Prezado(a) %s,\nSegue a comanda do pedido %d:\n\nMesa - %d\nData - %s\nTotal - R$ %.2f\nVoucher - %s\nItens: %s\n"; for(Item item : request.getItems()) if(!item.isDelivered()) { facesContext.addMessage(component.getClientId(facesContext), new FacesMessage(FacesMessage.SEVERITY_ERROR, "Alguns itens ainda não foram entregues.", null)); return; } try { new ListSizeValidator().validate(facesContext, component, request.getItems().size()); request.setOpen(false); System.out.println(request.isVoucher()); if(request.isVoucher()) { Double finalValue = request.getValue() - Client.VOUCHER_VALUE; request.setValue((finalValue >= 0) ? finalValue : 0.0); request.setVoucher(true); request.getClient().setVoucher(0.0); } else { request.getClient().setVoucher(request.getClient().getVoucher() + request.getValue()); } new DAO<Client>(Client.class).update(request.getClient()); new DAO<Request>(Request.class).update(request); if (SystemSettings.EMAIL_MODE != SystemSettings.EMAIL_SENDING_MODE.DO_NOT_SEND) { String emailMessage = String.format(EMAIL_BODY, request.getClient().getName(), request.getId(), request.getTableNumber(), Utility.calendarToReadableString(request.getDate()), request.getValue(), (request.isVoucher()) ? "Sim" : "Não", itemsToString(request.getItems())); EmailSender.sendAsync(emailMessage, EMAIL_TITLE, (SystemSettings.EMAIL_MODE == SystemSettings.EMAIL_SENDING_MODE.SEND_TO_TEST) ? SystemSettings.TEST_EMAIL : request.getClient().getEmail()); } request = new Request(); facesContext.addMessage(component.getClientId(facesContext), new FacesMessage(FacesMessage.SEVERITY_INFO, "Pedido Fechado! A comanda foi enviada para o seu e-mail.", null)); } catch (ValidatorException e) { facesContext.addMessage(component.getClientId(facesContext), new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null)); } } /** * Converte uma lista de itens para uma representação de string. * * @param items Lista de itens a ser convertida. * @return Representação de string dos itens. */ private String itemsToString(List<Item> items) { StringBuilder builder = new StringBuilder(); for(Item item : items) builder.append(String.format("\n%d - %s - %d - R$ %.2f", item.getId(),
(item.getProduct().getCategory() == Category.DRINK) ? item.getProduct().getName() + " " + item.getProduct().getDescription() : "Pizza de " + item.getProduct().getName(),
2
2023-12-16 01:25:27+00:00
12k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/world/AutoFarm.java
[ { "identifier": "Category", "path": "src/java/xyz/apfelmus/cf4m/module/Category.java", "snippet": "public enum Category {\n COMBAT,\n RENDER,\n MOVEMENT,\n PLAYER,\n WORLD,\n MISC,\n NONE;\n\n}" }, { "identifier": "ClientChatReceivedEvent", "path": "src/java/xyz/apfelmus/cheeto/client/events/ClientChatReceivedEvent.java", "snippet": "public class ClientChatReceivedEvent\nextends Listener {\n public IChatComponent message;\n public final byte type;\n\n public ClientChatReceivedEvent(byte type, IChatComponent message) {\n super(Listener.At.HEAD);\n this.type = type;\n this.message = message;\n }\n}" }, { "identifier": "ClientTickEvent", "path": "src/java/xyz/apfelmus/cheeto/client/events/ClientTickEvent.java", "snippet": "public class ClientTickEvent\nextends Listener {\n public ClientTickEvent() {\n super(Listener.At.HEAD);\n }\n}" }, { "identifier": "Render3DEvent", "path": "src/java/xyz/apfelmus/cheeto/client/events/Render3DEvent.java", "snippet": "public class Render3DEvent\nextends Listener {\n public float partialTicks;\n\n public Render3DEvent(float partialTicks) {\n super(Listener.At.HEAD);\n this.partialTicks = partialTicks;\n }\n}" }, { "identifier": "BooleanSetting", "path": "src/java/xyz/apfelmus/cheeto/client/settings/BooleanSetting.java", "snippet": "public class BooleanSetting {\n private boolean enabled;\n\n public BooleanSetting(boolean enable) {\n this.enabled = enable;\n }\n\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public void setState(boolean enable) {\n this.enabled = enable;\n }\n}" }, { "identifier": "IntegerSetting", "path": "src/java/xyz/apfelmus/cheeto/client/settings/IntegerSetting.java", "snippet": "public class IntegerSetting {\n private Integer current;\n private Integer min;\n private Integer max;\n\n public IntegerSetting(Integer current, Integer min, Integer max) {\n this.current = current;\n this.min = min;\n this.max = max;\n }\n\n public Integer getCurrent() {\n return this.current;\n }\n\n public void setCurrent(Integer current) {\n this.current = current < this.min ? this.min : (current > this.max ? this.max : current);\n }\n\n public Integer getMin() {\n return this.min;\n }\n\n public void setMin(Integer min) {\n this.min = min;\n }\n\n public Integer getMax() {\n return this.max;\n }\n\n public void setMax(Integer max) {\n this.max = max;\n }\n}" }, { "identifier": "ModeSetting", "path": "src/java/xyz/apfelmus/cheeto/client/settings/ModeSetting.java", "snippet": "public class ModeSetting {\n private String current;\n private final List<String> modes;\n\n public ModeSetting(String current, List<String> modes) {\n this.current = current;\n this.modes = modes;\n }\n\n public String getCurrent() {\n return this.current;\n }\n\n public void setCurrent(String current) {\n this.current = current;\n }\n\n public List<String> getModes() {\n return this.modes;\n }\n}" }, { "identifier": "StringSetting", "path": "src/java/xyz/apfelmus/cheeto/client/settings/StringSetting.java", "snippet": "public class StringSetting {\n private String value;\n\n public StringSetting(String value) {\n this.value = value;\n }\n\n public String getCurrent() {\n return this.value;\n }\n\n public void setCurrent(String value) {\n this.value = value;\n }\n}" }, { "identifier": "ChadUtils", "path": "src/java/xyz/apfelmus/cheeto/client/utils/client/ChadUtils.java", "snippet": "public class ChadUtils {\n private static Minecraft mc = Minecraft.func_71410_x();\n public static boolean isUngrabbed = false;\n private static MouseHelper oldMouseHelper;\n private static boolean doesGameWantUngrab;\n private static int oldRenderDist;\n private static int oldFpsCap;\n private static boolean improving;\n\n public static void ungrabMouse() {\n if (!ChadUtils.mc.field_71415_G || isUngrabbed) {\n return;\n }\n if (oldMouseHelper == null) {\n oldMouseHelper = ChadUtils.mc.field_71417_B;\n }\n ChadUtils.mc.field_71474_y.field_82881_y = false;\n doesGameWantUngrab = !Mouse.isGrabbed();\n oldMouseHelper.func_74373_b();\n ChadUtils.mc.field_71415_G = true;\n ChadUtils.mc.field_71417_B = new MouseHelper(){\n\n public void func_74374_c() {\n }\n\n public void func_74372_a() {\n doesGameWantUngrab = false;\n }\n\n public void func_74373_b() {\n doesGameWantUngrab = true;\n }\n };\n isUngrabbed = true;\n }\n\n public static void regrabMouse() {\n if (!isUngrabbed) {\n return;\n }\n ChadUtils.mc.field_71417_B = oldMouseHelper;\n if (!doesGameWantUngrab) {\n ChadUtils.mc.field_71417_B.func_74372_a();\n }\n oldMouseHelper = null;\n isUngrabbed = false;\n }\n\n public static void improveCpuUsage() {\n if (!improving) {\n oldRenderDist = ChadUtils.mc.field_71474_y.field_151451_c;\n oldFpsCap = ChadUtils.mc.field_71474_y.field_74350_i;\n ChadUtils.mc.field_71474_y.field_151451_c = 2;\n ChadUtils.mc.field_71474_y.field_74350_i = 30;\n improving = true;\n }\n }\n\n public static void revertCpuUsage() {\n ChadUtils.mc.field_71474_y.field_151451_c = oldRenderDist;\n ChadUtils.mc.field_71474_y.field_74350_i = oldFpsCap;\n improving = false;\n }\n\n static {\n doesGameWantUngrab = true;\n oldRenderDist = 0;\n oldFpsCap = 0;\n improving = false;\n }\n}" }, { "identifier": "ChatUtils", "path": "src/java/xyz/apfelmus/cheeto/client/utils/client/ChatUtils.java", "snippet": "public class ChatUtils {\n private static final String PREFIX = ChatColor.format(\"&6[&eCheeto&6]&f \");\n\n public static void send(String text, String ... args) {\n if (Minecraft.func_71410_x().field_71439_g == null) {\n return;\n }\n text = String.format(text, args);\n StringBuilder messageBuilder = new StringBuilder();\n for (String word : text.split(\" \")) {\n word = ChatColor.format(ChatColor.getLastColors(text) + word);\n messageBuilder.append(word).append(\" \");\n }\n Minecraft.func_71410_x().field_71439_g.func_145747_a((IChatComponent)new ChatComponentText(PREFIX + ChatColor.format(messageBuilder.toString().trim())));\n }\n}" }, { "identifier": "Rotation", "path": "src/java/xyz/apfelmus/cheeto/client/utils/client/Rotation.java", "snippet": "public class Rotation {\n private float yaw;\n private float pitch;\n\n public Rotation(float yaw, float pitch) {\n this.yaw = yaw;\n this.pitch = pitch;\n }\n\n public float getYaw() {\n return this.yaw;\n }\n\n public void setYaw(float yaw) {\n this.yaw = yaw;\n }\n\n public float getPitch() {\n return this.pitch;\n }\n\n public void setPitch(float pitch) {\n this.pitch = pitch;\n }\n\n public void addYaw(float yaw) {\n this.yaw += yaw;\n }\n\n public void addPitch(float pitch) {\n this.pitch += pitch;\n }\n\n public float getValue() {\n return Math.abs(this.yaw) + Math.abs(this.pitch);\n }\n\n public String toString() {\n return \"Rotation{yaw=\" + this.yaw + \", pitch=\" + this.pitch + '}';\n }\n}" }, { "identifier": "RotationUtils", "path": "src/java/xyz/apfelmus/cheeto/client/utils/client/RotationUtils.java", "snippet": "public class RotationUtils {\n private static final Minecraft mc = Minecraft.func_71410_x();\n public static Rotation startRot;\n public static Rotation neededChange;\n public static Rotation endRot;\n public static long startTime;\n public static long endTime;\n public static boolean done;\n private static final float[][] BLOCK_SIDES;\n\n public static Rotation getRotation(Vec3 vec) {\n Vec3 eyes = RotationUtils.mc.field_71439_g.func_174824_e(1.0f);\n return RotationUtils.getRotation(eyes, vec);\n }\n\n public static Rotation getRotation(Vec3 from, Vec3 to) {\n double diffX = to.field_72450_a - from.field_72450_a;\n double diffY = to.field_72448_b - from.field_72448_b;\n double diffZ = to.field_72449_c - from.field_72449_c;\n return new Rotation(MathHelper.func_76142_g((float)((float)(Math.toDegrees(Math.atan2(diffZ, diffX)) - 90.0))), (float)(-Math.toDegrees(Math.atan2(diffY, Math.sqrt(diffX * diffX + diffZ * diffZ)))));\n }\n\n public static Rotation getRotation(BlockPos bp) {\n Vec3 vec = new Vec3((double)bp.func_177958_n() + 0.5, (double)bp.func_177956_o() + 0.5, (double)bp.func_177952_p() + 0.5);\n return RotationUtils.getRotation(vec);\n }\n\n public static void setup(Rotation rot, Long aimTime) {\n done = false;\n startRot = new Rotation(RotationUtils.mc.field_71439_g.field_70177_z, RotationUtils.mc.field_71439_g.field_70125_A);\n neededChange = RotationUtils.getNeededChange(startRot, rot);\n endRot = new Rotation(startRot.getYaw() + neededChange.getYaw(), startRot.getPitch() + neededChange.getPitch());\n startTime = System.currentTimeMillis();\n endTime = System.currentTimeMillis() + aimTime;\n }\n\n public static void reset() {\n done = true;\n startRot = null;\n neededChange = null;\n endRot = null;\n startTime = 0L;\n endTime = 0L;\n }\n\n public static void update() {\n if (System.currentTimeMillis() <= endTime) {\n RotationUtils.mc.field_71439_g.field_70177_z = RotationUtils.interpolate(startRot.getYaw(), endRot.getYaw());\n RotationUtils.mc.field_71439_g.field_70125_A = RotationUtils.interpolate(startRot.getPitch(), endRot.getPitch());\n } else if (!done) {\n RotationUtils.mc.field_71439_g.field_70177_z = endRot.getYaw();\n RotationUtils.mc.field_71439_g.field_70125_A = endRot.getPitch();\n RotationUtils.reset();\n }\n }\n\n public static void snapAngles(Rotation rot) {\n RotationUtils.mc.field_71439_g.field_70177_z = rot.getYaw();\n RotationUtils.mc.field_71439_g.field_70125_A = rot.getPitch();\n }\n\n private static float interpolate(float start, float end) {\n float spentMillis = System.currentTimeMillis() - startTime;\n float relativeProgress = spentMillis / (float)(endTime - startTime);\n return (end - start) * RotationUtils.easeOutCubic(relativeProgress) + start;\n }\n\n public static float easeOutCubic(double number) {\n return (float)(1.0 - Math.pow(1.0 - number, 3.0));\n }\n\n public static Rotation getNeededChange(Rotation startRot, Rotation endRot) {\n float yawChng = MathHelper.func_76142_g((float)endRot.getYaw()) - MathHelper.func_76142_g((float)startRot.getYaw());\n if (yawChng <= -180.0f) {\n yawChng = 360.0f + yawChng;\n } else if (yawChng > 180.0f) {\n yawChng = -360.0f + yawChng;\n }\n if (BloodCamp.godGamerMode.isEnabled()) {\n yawChng = yawChng < 0.0f ? (yawChng += 360.0f) : (yawChng -= 360.0f);\n }\n return new Rotation(yawChng, endRot.getPitch() - startRot.getPitch());\n }\n\n public static double fovFromEntity(Entity en) {\n return ((double)(RotationUtils.mc.field_71439_g.field_70177_z - RotationUtils.fovToEntity(en)) % 360.0 + 540.0) % 360.0 - 180.0;\n }\n\n public static float fovToEntity(Entity ent) {\n double x = ent.field_70165_t - RotationUtils.mc.field_71439_g.field_70165_t;\n double z = ent.field_70161_v - RotationUtils.mc.field_71439_g.field_70161_v;\n double yaw = Math.atan2(x, z) * 57.2957795;\n return (float)(yaw * -1.0);\n }\n\n public static Rotation getNeededChange(Rotation endRot) {\n Rotation startRot = new Rotation(RotationUtils.mc.field_71439_g.field_70177_z, RotationUtils.mc.field_71439_g.field_70125_A);\n return RotationUtils.getNeededChange(startRot, endRot);\n }\n\n public static List<Vec3> getBlockSides(BlockPos bp) {\n ArrayList<Vec3> ret = new ArrayList<Vec3>();\n for (float[] side : BLOCK_SIDES) {\n ret.add(new Vec3((Vec3i)bp).func_72441_c((double)side[0], (double)side[1], (double)side[2]));\n }\n return ret;\n }\n\n public static boolean lookingAt(BlockPos blockPos, float range) {\n float stepSize = 0.15f;\n Vec3 position = new Vec3(RotationUtils.mc.field_71439_g.field_70165_t, RotationUtils.mc.field_71439_g.field_70163_u + (double)RotationUtils.mc.field_71439_g.func_70047_e(), RotationUtils.mc.field_71439_g.field_70161_v);\n Vec3 look = RotationUtils.mc.field_71439_g.func_70676_i(0.0f);\n Vector3f step = new Vector3f((float)look.field_72450_a, (float)look.field_72448_b, (float)look.field_72449_c);\n step.scale(stepSize / step.length());\n int i = 0;\n while ((double)i < Math.floor(range / stepSize) - 2.0) {\n BlockPos blockAtPos = new BlockPos(position.field_72450_a, position.field_72448_b, position.field_72449_c);\n if (blockAtPos.equals((Object)blockPos)) {\n return true;\n }\n position = position.func_178787_e(new Vec3((double)step.x, (double)step.y, (double)step.z));\n ++i;\n }\n return false;\n }\n\n public static Vec3 getVectorForRotation(float pitch, float yaw) {\n float f2 = -MathHelper.func_76134_b((float)(-pitch * ((float)Math.PI / 180)));\n return new Vec3((double)(MathHelper.func_76126_a((float)(-yaw * ((float)Math.PI / 180) - (float)Math.PI)) * f2), (double)MathHelper.func_76126_a((float)(-pitch * ((float)Math.PI / 180))), (double)(MathHelper.func_76134_b((float)(-yaw * ((float)Math.PI / 180) - (float)Math.PI)) * f2));\n }\n\n public static Vec3 getLook(Vec3 vec) {\n double diffX = vec.field_72450_a - RotationUtils.mc.field_71439_g.field_70165_t;\n double diffY = vec.field_72448_b - (RotationUtils.mc.field_71439_g.field_70163_u + (double)RotationUtils.mc.field_71439_g.func_70047_e());\n double diffZ = vec.field_72449_c - RotationUtils.mc.field_71439_g.field_70161_v;\n double dist = MathHelper.func_76133_a((double)(diffX * diffX + diffZ * diffZ));\n return RotationUtils.getVectorForRotation((float)(-(MathHelper.func_181159_b((double)diffY, (double)dist) * 180.0 / Math.PI)), (float)(MathHelper.func_181159_b((double)diffZ, (double)diffX) * 180.0 / Math.PI - 90.0));\n }\n\n public static EnumFacing calculateEnumfacing(Vec3 pos) {\n int z;\n int y;\n int x = MathHelper.func_76128_c((double)pos.field_72450_a);\n MovingObjectPosition position = RotationUtils.calculateIntercept(new AxisAlignedBB((double)x, (double)(y = MathHelper.func_76128_c((double)pos.field_72448_b)), (double)(z = MathHelper.func_76128_c((double)pos.field_72449_c)), (double)(x + 1), (double)(y + 1), (double)(z + 1)), pos, 50.0f);\n return position != null ? position.field_178784_b : null;\n }\n\n public static MovingObjectPosition calculateIntercept(AxisAlignedBB aabb, Vec3 block, float range) {\n Vec3 vec3 = RotationUtils.mc.field_71439_g.func_174824_e(1.0f);\n Vec3 vec4 = RotationUtils.getLook(block);\n return aabb.func_72327_a(vec3, vec3.func_72441_c(vec4.field_72450_a * (double)range, vec4.field_72448_b * (double)range, vec4.field_72449_c * (double)range));\n }\n\n public static List<Vec3> getPointsOnBlock(BlockPos bp) {\n ArrayList<Vec3> ret = new ArrayList<Vec3>();\n for (float[] side : BLOCK_SIDES) {\n for (int i = 0; i < 20; ++i) {\n float x = side[0];\n float y = side[1];\n float z = side[2];\n if ((double)x == 0.5) {\n x = RandomUtil.randBetween(0.1f, 0.9f);\n }\n if ((double)y == 0.5) {\n y = RandomUtil.randBetween(0.1f, 0.9f);\n }\n if ((double)z == 0.5) {\n z = RandomUtil.randBetween(0.1f, 0.9f);\n }\n ret.add(new Vec3((Vec3i)bp).func_72441_c((double)x, (double)y, (double)z));\n }\n }\n return ret;\n }\n\n static {\n done = true;\n BLOCK_SIDES = new float[][]{{0.5f, 0.01f, 0.5f}, {0.5f, 0.99f, 0.5f}, {0.01f, 0.5f, 0.5f}, {0.99f, 0.5f, 0.5f}, {0.5f, 0.5f, 0.01f}, {0.5f, 0.5f, 0.99f}};\n }\n}" }, { "identifier": "RandomUtil", "path": "src/java/xyz/apfelmus/cheeto/client/utils/math/RandomUtil.java", "snippet": "public class RandomUtil {\n private static Random rand = new Random();\n\n public static Vec3 randomVec() {\n return new Vec3(rand.nextDouble(), rand.nextDouble(), rand.nextDouble());\n }\n\n public static int randBetween(int a, int b) {\n return rand.nextInt(b - a + 1) + a;\n }\n\n public static double randBetween(double a, double b) {\n return rand.nextDouble() * (b - a) + a;\n }\n\n public static float randBetween(float a, float b) {\n return rand.nextFloat() * (b - a) + a;\n }\n\n public static int nextInt(int yep) {\n return rand.nextInt(yep);\n }\n}" }, { "identifier": "TimeHelper", "path": "src/java/xyz/apfelmus/cheeto/client/utils/math/TimeHelper.java", "snippet": "public class TimeHelper {\n private long lastMS = 0L;\n\n public TimeHelper() {\n this.reset();\n }\n\n public int convertToMS(int d) {\n return 1000 / d;\n }\n\n public long getCurrentMS() {\n return System.nanoTime() / 1000000L;\n }\n\n public boolean hasReached(long milliseconds) {\n return this.getCurrentMS() - this.lastMS >= milliseconds;\n }\n\n public boolean hasTimeReached(long delay) {\n return System.currentTimeMillis() - this.lastMS >= delay;\n }\n\n public long getDelay() {\n return System.currentTimeMillis() - this.lastMS;\n }\n\n public void reset() {\n this.lastMS = this.getCurrentMS();\n }\n\n public void setLastMS() {\n this.lastMS = System.currentTimeMillis();\n }\n\n public void setLastMS(long lastMS) {\n this.lastMS = lastMS;\n }\n}" }, { "identifier": "InventoryUtils", "path": "src/java/xyz/apfelmus/cheeto/client/utils/skyblock/InventoryUtils.java", "snippet": "public class InventoryUtils {\n private static Minecraft mc = Minecraft.func_71410_x();\n\n public static String getInventoryName() {\n if (InventoryUtils.mc.field_71462_r instanceof GuiChest) {\n ContainerChest chest = (ContainerChest)InventoryUtils.mc.field_71439_g.field_71070_bA;\n IInventory inv = chest.func_85151_d();\n return inv.func_145818_k_() ? inv.func_70005_c_() : null;\n }\n return null;\n }\n\n public static ItemStack getStackInSlot(int slot) {\n return InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(slot);\n }\n\n public static ItemStack getStackInOpenContainerSlot(int slot) {\n if (((Slot)InventoryUtils.mc.field_71439_g.field_71070_bA.field_75151_b.get(slot)).func_75216_d()) {\n return ((Slot)InventoryUtils.mc.field_71439_g.field_71070_bA.field_75151_b.get(slot)).func_75211_c();\n }\n return null;\n }\n\n public static int getSlotForItem(String itemName, Item item) {\n for (Slot slot : InventoryUtils.mc.field_71439_g.field_71070_bA.field_75151_b) {\n ItemStack is;\n if (!slot.func_75216_d() || (is = slot.func_75211_c()).func_77973_b() != item || !is.func_82833_r().contains(itemName)) continue;\n return slot.field_75222_d;\n }\n return -1;\n }\n\n public static void clickOpenContainerSlot(int slot, int nextWindow) {\n InventoryUtils.mc.field_71442_b.func_78753_a(InventoryUtils.mc.field_71439_g.field_71070_bA.field_75152_c + nextWindow, slot, 0, 0, (EntityPlayer)InventoryUtils.mc.field_71439_g);\n }\n\n public static void clickOpenContainerSlot(int slot) {\n InventoryUtils.mc.field_71442_b.func_78753_a(InventoryUtils.mc.field_71439_g.field_71070_bA.field_75152_c, slot, 0, 0, (EntityPlayer)InventoryUtils.mc.field_71439_g);\n }\n\n public static int getAvailableHotbarSlot(String name) {\n for (int i = 0; i < 8; ++i) {\n ItemStack is = InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(i);\n if (is != null && !is.func_82833_r().contains(name)) continue;\n return i;\n }\n return -1;\n }\n\n public static List<Integer> getAllSlots(int throwSlot, String name) {\n ArrayList<Integer> ret = new ArrayList<Integer>();\n for (int i = 9; i < 44; ++i) {\n ItemStack is = ((Slot)InventoryUtils.mc.field_71439_g.field_71069_bz.field_75151_b.get(i)).func_75211_c();\n if (is == null || !is.func_82833_r().contains(name) || i - 36 == throwSlot) continue;\n ret.add(i);\n }\n return ret;\n }\n\n public static void throwSlot(int slot) {\n ItemStack curInSlot = InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(slot);\n if (curInSlot != null) {\n if (curInSlot.func_82833_r().contains(\"Snowball\")) {\n int ss = curInSlot.field_77994_a;\n for (int i = 0; i < ss; ++i) {\n InventoryUtils.mc.field_71439_g.field_71071_by.field_70461_c = slot;\n InventoryUtils.mc.field_71442_b.func_78769_a((EntityPlayer)InventoryUtils.mc.field_71439_g, (World)InventoryUtils.mc.field_71441_e, InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(slot));\n }\n } else {\n InventoryUtils.mc.field_71439_g.field_71071_by.field_70461_c = slot;\n InventoryUtils.mc.field_71442_b.func_78769_a((EntityPlayer)InventoryUtils.mc.field_71439_g, (World)InventoryUtils.mc.field_71441_e, InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(slot));\n }\n }\n }\n\n public static int getAmountInHotbar(String item) {\n for (int i = 0; i < 8; ++i) {\n ItemStack is = InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(i);\n if (is == null || !StringUtils.func_76338_a((String)is.func_82833_r()).equals(item)) continue;\n return is.field_77994_a;\n }\n return 0;\n }\n\n public static int getItemInHotbar(String itemName) {\n for (int i = 0; i < 8; ++i) {\n ItemStack is = InventoryUtils.mc.field_71439_g.field_71071_by.func_70301_a(i);\n if (is == null || !StringUtils.func_76338_a((String)is.func_82833_r()).contains(itemName)) continue;\n return i;\n }\n return -1;\n }\n\n public static List<ItemStack> getInventoryStacks() {\n ArrayList<ItemStack> ret = new ArrayList<ItemStack>();\n for (int i = 9; i < 44; ++i) {\n ItemStack stack;\n Slot slot = InventoryUtils.mc.field_71439_g.field_71069_bz.func_75139_a(i);\n if (slot == null || (stack = slot.func_75211_c()) == null) continue;\n ret.add(stack);\n }\n return ret;\n }\n}" }, { "identifier": "SkyblockUtils", "path": "src/java/xyz/apfelmus/cheeto/client/utils/skyblock/SkyblockUtils.java", "snippet": "public class SkyblockUtils {\n private static Minecraft mc = Minecraft.func_71410_x();\n private static final ArrayList<Block> interactables = new ArrayList<Block>(Arrays.asList(new Block[]{Blocks.field_180410_as, Blocks.field_150467_bQ, Blocks.field_150461_bJ, Blocks.field_150324_C, Blocks.field_180412_aq, Blocks.field_150382_bo, Blocks.field_150483_bI, Blocks.field_150462_ai, Blocks.field_150486_ae, Blocks.field_180409_at, Blocks.field_150453_bW, Blocks.field_180402_cm, Blocks.field_150367_z, Blocks.field_150409_cd, Blocks.field_150381_bn, Blocks.field_150477_bB, Blocks.field_150460_al, Blocks.field_150438_bZ, Blocks.field_180411_ar, Blocks.field_150442_at, Blocks.field_150323_B, Blocks.field_150455_bV, Blocks.field_150441_bU, Blocks.field_150416_aS, Blocks.field_150413_aR, Blocks.field_150472_an, Blocks.field_150444_as, Blocks.field_150415_aT, Blocks.field_150447_bR, Blocks.field_150471_bO, Blocks.field_150430_aB, Blocks.field_180413_ao, Blocks.field_150465_bP}));\n\n public static void ghostBlock() {\n if (SkyblockUtils.mc.field_71476_x.func_178782_a() == null) {\n return;\n }\n Block block = Minecraft.func_71410_x().field_71441_e.func_180495_p(SkyblockUtils.mc.field_71476_x.func_178782_a()).func_177230_c();\n if (!interactables.contains((Object)block)) {\n SkyblockUtils.mc.field_71441_e.func_175698_g(SkyblockUtils.mc.field_71476_x.func_178782_a());\n }\n }\n\n public static int getMobHp(EntityArmorStand aStand) {\n String stripped;\n double mobHp = -1.0;\n Pattern pattern = Pattern.compile(\".+? ([.\\\\d]+)[Mk]?/[.\\\\d]+[Mk]?\");\n Matcher mat = pattern.matcher(stripped = SkyblockUtils.stripString(aStand.func_70005_c_()));\n if (mat.matches()) {\n try {\n mobHp = Double.parseDouble(mat.group(1));\n }\n catch (NumberFormatException numberFormatException) {\n // empty catch block\n }\n }\n return (int)Math.ceil(mobHp);\n }\n\n public static Entity getEntityCuttingOtherEntity(Entity e, Class<?> entityType) {\n List possible = SkyblockUtils.mc.field_71441_e.func_175674_a(e, e.func_174813_aQ().func_72314_b(0.3, 2.0, 0.3), a -> !a.field_70128_L && !a.equals((Object)SkyblockUtils.mc.field_71439_g) && !(a instanceof EntityArmorStand) && !(a instanceof EntityFireball) && !(a instanceof EntityFishHook) && (entityType == null || entityType.isInstance(a)));\n if (!possible.isEmpty()) {\n return Collections.min(possible, Comparator.comparing(e2 -> Float.valueOf(e2.func_70032_d(e))));\n }\n return null;\n }\n\n public static Location getLocation() {\n if (SkyblockUtils.isInIsland()) {\n return Location.ISLAND;\n }\n if (SkyblockUtils.isInHub()) {\n return Location.HUB;\n }\n if (SkyblockUtils.isAtLift()) {\n return Location.LIFT;\n }\n if (SkyblockUtils.isInSkyblock()) {\n return Location.SKYBLOCK;\n }\n if (SkyblockUtils.isInLobby()) {\n return Location.LOBBY;\n }\n IBlockState ibs = SkyblockUtils.mc.field_71441_e.func_180495_p(SkyblockUtils.mc.field_71439_g.func_180425_c().func_177977_b());\n if (ibs != null && ibs.func_177230_c() == Blocks.field_150344_f) {\n return Location.LIMBO;\n }\n return Location.NONE;\n }\n\n public static boolean isInIsland() {\n return SkyblockUtils.hasLine(\"Your Island\");\n }\n\n public static boolean isInHub() {\n return SkyblockUtils.hasLine(\"Village\") && !SkyblockUtils.hasLine(\"Dwarven\");\n }\n\n public static boolean isAtLift() {\n return SkyblockUtils.hasLine(\"The Lift\");\n }\n\n public static boolean isInDungeon() {\n return SkyblockUtils.hasLine(\"Dungeon Cleared:\") || SkyblockUtils.hasLine(\"Start\");\n }\n\n public static boolean isInFloor(String floor) {\n return SkyblockUtils.hasLine(\"The Catacombs (\" + floor + \")\");\n }\n\n public static boolean isInSkyblock() {\n return SkyblockUtils.hasLine(\"SKYBLOCK\");\n }\n\n public static boolean isInLobby() {\n return SkyblockUtils.hasLine(\"HYPIXEL\") || SkyblockUtils.hasLine(\"PROTOTYPE\");\n }\n\n public static boolean hasLine(String sbString) {\n ScoreObjective sbo;\n if (mc != null && SkyblockUtils.mc.field_71439_g != null && (sbo = SkyblockUtils.mc.field_71441_e.func_96441_U().func_96539_a(1)) != null) {\n List<String> scoreboard = SkyblockUtils.getSidebarLines();\n scoreboard.add(StringUtils.func_76338_a((String)sbo.func_96678_d()));\n for (String s : scoreboard) {\n String validated = SkyblockUtils.stripString(s);\n if (!validated.contains(sbString)) continue;\n return true;\n }\n }\n return false;\n }\n\n public static String stripString(String s) {\n char[] nonValidatedString = StringUtils.func_76338_a((String)s).toCharArray();\n StringBuilder validated = new StringBuilder();\n for (char a : nonValidatedString) {\n if (a >= '\\u007f' || a <= '\\u0014') continue;\n validated.append(a);\n }\n return validated.toString();\n }\n\n private static List<String> getSidebarLines() {\n ArrayList<String> lines = new ArrayList<String>();\n Scoreboard scoreboard = Minecraft.func_71410_x().field_71441_e.func_96441_U();\n if (scoreboard == null) {\n return lines;\n }\n ScoreObjective objective = scoreboard.func_96539_a(1);\n if (objective == null) {\n return lines;\n }\n ArrayList scores = scoreboard.func_96534_i(objective);\n ArrayList list = new ArrayList();\n for (Score s : scores) {\n if (s == null || s.func_96653_e() == null || s.func_96653_e().startsWith(\"#\")) continue;\n list.add(s);\n }\n scores = list.size() > 15 ? Lists.newArrayList((Iterable)Iterables.skip(list, (int)(scores.size() - 15))) : list;\n for (Score score : scores) {\n ScorePlayerTeam team = scoreboard.func_96509_i(score.func_96653_e());\n lines.add(ScorePlayerTeam.func_96667_a((Team)team, (String)score.func_96653_e()));\n }\n return lines;\n }\n\n public static void silentUse(int mainSlot, int useSlot) {\n int oldSlot = SkyblockUtils.mc.field_71439_g.field_71071_by.field_70461_c;\n if (useSlot > 0 && useSlot <= 9) {\n SkyblockUtils.mc.field_71439_g.field_71071_by.field_70461_c = useSlot - 1;\n SkyblockUtils.mc.field_71442_b.func_78769_a((EntityPlayer)SkyblockUtils.mc.field_71439_g, (World)SkyblockUtils.mc.field_71441_e, SkyblockUtils.mc.field_71439_g.func_70694_bm());\n }\n if (mainSlot > 0 && mainSlot <= 9) {\n SkyblockUtils.mc.field_71439_g.field_71071_by.field_70461_c = mainSlot - 1;\n } else if (mainSlot == 0) {\n SkyblockUtils.mc.field_71439_g.field_71071_by.field_70461_c = oldSlot;\n }\n }\n\n public static enum Location {\n ISLAND,\n HUB,\n LIFT,\n SKYBLOCK,\n LOBBY,\n LIMBO,\n NONE;\n\n }\n}" } ]
import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.SoundCategory; import net.minecraft.client.gui.GuiDisconnected; import net.minecraft.client.settings.KeyBinding; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.IChatComponent; import net.minecraft.util.Session; import net.minecraft.util.StringUtils; import net.minecraft.util.Vec3i; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Disable; import xyz.apfelmus.cf4m.annotation.module.Enable; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.events.ClientChatReceivedEvent; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; import xyz.apfelmus.cheeto.client.events.Render3DEvent; import xyz.apfelmus.cheeto.client.settings.BooleanSetting; import xyz.apfelmus.cheeto.client.settings.IntegerSetting; import xyz.apfelmus.cheeto.client.settings.ModeSetting; import xyz.apfelmus.cheeto.client.settings.StringSetting; import xyz.apfelmus.cheeto.client.utils.client.ChadUtils; import xyz.apfelmus.cheeto.client.utils.client.ChatUtils; import xyz.apfelmus.cheeto.client.utils.client.Rotation; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.math.RandomUtil; import xyz.apfelmus.cheeto.client.utils.math.TimeHelper; import xyz.apfelmus.cheeto.client.utils.skyblock.InventoryUtils; import xyz.apfelmus.cheeto.client.utils.skyblock.SkyblockUtils;
10,532
@Setting(name="WebhookUpdates") private BooleanSetting webhookUpdates = new BooleanSetting(false); @Setting(name="WebhookURL") private StringSetting webhookUrl = new StringSetting(""); @Setting(name="Direction") private ModeSetting direction = new ModeSetting("NORTH", new ArrayList<String>(Arrays.asList("NORTH", "EAST", "SOUTH", "WEST"))); private Minecraft mc = Minecraft.func_71410_x(); private int stuckTicks = 0; private BlockPos oldPos; private BlockPos curPos; private boolean invFull = false; private List<ItemStack> oldInv; private int oldInvCount = 0; private final int GREEN = 3066993; private final int ORANGE = 15439360; private final int RED = 15158332; private final int BLUE = 1689596; private boolean banned; private FarmingState farmingState; private FarmingDirection farmingDirection; private AlertState alertState; private SameInvState sameInvState; private IsRebootState isRebootState; private TimeHelper alertTimer = new TimeHelper(); private TimeHelper sameInvTimer = new TimeHelper(); private TimeHelper recoverTimer = new TimeHelper(); private Map<SoundCategory, Float> oldSounds = new HashMap<SoundCategory, Float>(); private String recoverStr = " "; private boolean recoverBool = false; private boolean islandReboot; private List<String> msgs = new ArrayList<String>(Arrays.asList("hey?", "wtf?? why am i here", "What is this place!", "Hello?", "helpp where am i?")); @Enable public void onEnable() { this.farmingState = FarmingState.START_FARMING; this.farmingDirection = FarmingDirection.LEFT; this.alertState = AlertState.CHILLING; this.sameInvState = SameInvState.CHILLING; this.isRebootState = IsRebootState.ISLAND; this.islandReboot = false; this.banned = false; if (this.autoTab.isEnabled()) { ChadUtils.ungrabMouse(); } if (this.cpuSaver.isEnabled()) { ChadUtils.improveCpuUsage(); } } @Disable public void onDisable() { KeyBinding.func_74506_a(); if (this.autoTab.isEnabled()) { ChadUtils.regrabMouse(); } if (this.cpuSaver.isEnabled()) { ChadUtils.revertCpuUsage(); } if (this.soundAlerts.isEnabled() && this.alertState != AlertState.CHILLING) { for (SoundCategory category : SoundCategory.values()) { this.mc.field_71474_y.func_151439_a(category, this.oldSounds.get((Object)category).floatValue()); } this.alertState = AlertState.CHILLING; } } @Event public void onTick(ClientTickEvent event) { block0 : switch (this.farmingState) { case START_FARMING: { this.oldInv = null; Rotation rot = new Rotation(0.0f, 3.0f); switch (this.direction.getCurrent()) { case "WEST": { rot.setYaw(90.0f); break; } case "NORTH": { rot.setYaw(180.0f); break; } case "EAST": { rot.setYaw(-90.0f); } } RotationUtils.setup(rot, 1000L); this.farmingState = FarmingState.SET_ANGLES; break; } case PRESS_KEYS: { if (this.hoeSlot.getCurrent() > 0 && this.hoeSlot.getCurrent() <= 8) { this.mc.field_71439_g.field_71071_by.field_70461_c = this.hoeSlot.getCurrent() - 1; } this.pressKeys(); this.farmingState = FarmingState.FARMING; break; } case FARMING: { if (!this.banned && this.mc.field_71462_r instanceof GuiDisconnected) { GuiDisconnected gd = (GuiDisconnected)this.mc.field_71462_r; IChatComponent message = (IChatComponent)ObfuscationReflectionHelper.getPrivateValue(GuiDisconnected.class, (Object)gd, (String[])new String[]{"message", "field_146304_f"}); StringBuilder reason = new StringBuilder(); for (IChatComponent cc : message.func_150253_a()) { reason.append(cc.func_150260_c()); } String re = reason.toString(); if ((re = re.replace("\r", "\\r").replace("\n", "\\n")).contains("banned")) { this.banned = true; this.sendWebhook("BEAMED", "You got beamed shitter!\\r\\n" + re, 15158332, true); } } if (!this.recoverTimer.hasReached(2000L)) break; switch (SkyblockUtils.getLocation()) { case NONE: { KeyBinding.func_74506_a(); break block0; } case ISLAND: { ItemStack heldItem; if (this.recoverBool) {
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.audio.SoundCategory * net.minecraft.client.gui.GuiDisconnected * net.minecraft.client.settings.KeyBinding * net.minecraft.init.Blocks * net.minecraft.init.Items * net.minecraft.item.ItemStack * net.minecraft.util.BlockPos * net.minecraft.util.IChatComponent * net.minecraft.util.Session * net.minecraft.util.StringUtils * net.minecraft.util.Vec3i * net.minecraftforge.fml.common.ObfuscationReflectionHelper */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="AutoFarm", category=Category.WORLD) public class AutoFarm { @Setting(name="HoeSlot") private IntegerSetting hoeSlot = new IntegerSetting(0, 0, 8); @Setting(name="FailSafeDelay") private IntegerSetting failSafeDelay = new IntegerSetting(5000, 0, 10000); @Setting(name="CPUSaver") private BooleanSetting cpuSaver = new BooleanSetting(true); @Setting(name="AutoTab") private BooleanSetting autoTab = new BooleanSetting(true); @Setting(name="SoundAlerts") private BooleanSetting soundAlerts = new BooleanSetting(true); @Setting(name="WebhookUpdates") private BooleanSetting webhookUpdates = new BooleanSetting(false); @Setting(name="WebhookURL") private StringSetting webhookUrl = new StringSetting(""); @Setting(name="Direction") private ModeSetting direction = new ModeSetting("NORTH", new ArrayList<String>(Arrays.asList("NORTH", "EAST", "SOUTH", "WEST"))); private Minecraft mc = Minecraft.func_71410_x(); private int stuckTicks = 0; private BlockPos oldPos; private BlockPos curPos; private boolean invFull = false; private List<ItemStack> oldInv; private int oldInvCount = 0; private final int GREEN = 3066993; private final int ORANGE = 15439360; private final int RED = 15158332; private final int BLUE = 1689596; private boolean banned; private FarmingState farmingState; private FarmingDirection farmingDirection; private AlertState alertState; private SameInvState sameInvState; private IsRebootState isRebootState; private TimeHelper alertTimer = new TimeHelper(); private TimeHelper sameInvTimer = new TimeHelper(); private TimeHelper recoverTimer = new TimeHelper(); private Map<SoundCategory, Float> oldSounds = new HashMap<SoundCategory, Float>(); private String recoverStr = " "; private boolean recoverBool = false; private boolean islandReboot; private List<String> msgs = new ArrayList<String>(Arrays.asList("hey?", "wtf?? why am i here", "What is this place!", "Hello?", "helpp where am i?")); @Enable public void onEnable() { this.farmingState = FarmingState.START_FARMING; this.farmingDirection = FarmingDirection.LEFT; this.alertState = AlertState.CHILLING; this.sameInvState = SameInvState.CHILLING; this.isRebootState = IsRebootState.ISLAND; this.islandReboot = false; this.banned = false; if (this.autoTab.isEnabled()) { ChadUtils.ungrabMouse(); } if (this.cpuSaver.isEnabled()) { ChadUtils.improveCpuUsage(); } } @Disable public void onDisable() { KeyBinding.func_74506_a(); if (this.autoTab.isEnabled()) { ChadUtils.regrabMouse(); } if (this.cpuSaver.isEnabled()) { ChadUtils.revertCpuUsage(); } if (this.soundAlerts.isEnabled() && this.alertState != AlertState.CHILLING) { for (SoundCategory category : SoundCategory.values()) { this.mc.field_71474_y.func_151439_a(category, this.oldSounds.get((Object)category).floatValue()); } this.alertState = AlertState.CHILLING; } } @Event public void onTick(ClientTickEvent event) { block0 : switch (this.farmingState) { case START_FARMING: { this.oldInv = null; Rotation rot = new Rotation(0.0f, 3.0f); switch (this.direction.getCurrent()) { case "WEST": { rot.setYaw(90.0f); break; } case "NORTH": { rot.setYaw(180.0f); break; } case "EAST": { rot.setYaw(-90.0f); } } RotationUtils.setup(rot, 1000L); this.farmingState = FarmingState.SET_ANGLES; break; } case PRESS_KEYS: { if (this.hoeSlot.getCurrent() > 0 && this.hoeSlot.getCurrent() <= 8) { this.mc.field_71439_g.field_71071_by.field_70461_c = this.hoeSlot.getCurrent() - 1; } this.pressKeys(); this.farmingState = FarmingState.FARMING; break; } case FARMING: { if (!this.banned && this.mc.field_71462_r instanceof GuiDisconnected) { GuiDisconnected gd = (GuiDisconnected)this.mc.field_71462_r; IChatComponent message = (IChatComponent)ObfuscationReflectionHelper.getPrivateValue(GuiDisconnected.class, (Object)gd, (String[])new String[]{"message", "field_146304_f"}); StringBuilder reason = new StringBuilder(); for (IChatComponent cc : message.func_150253_a()) { reason.append(cc.func_150260_c()); } String re = reason.toString(); if ((re = re.replace("\r", "\\r").replace("\n", "\\n")).contains("banned")) { this.banned = true; this.sendWebhook("BEAMED", "You got beamed shitter!\\r\\n" + re, 15158332, true); } } if (!this.recoverTimer.hasReached(2000L)) break; switch (SkyblockUtils.getLocation()) { case NONE: { KeyBinding.func_74506_a(); break block0; } case ISLAND: { ItemStack heldItem; if (this.recoverBool) {
ChatUtils.send("Recovered! Starting to farm again!", new String[0]);
9
2023-12-21 16:22:25+00:00
12k
ciallo-dev/JWSystemLib
src/main/java/moe/snowflake/jwSystem/JWSystem.java
[ { "identifier": "CourseSelectManager", "path": "src/main/java/moe/snowflake/jwSystem/manager/CourseSelectManager.java", "snippet": "public class CourseSelectManager {\n private final JWSystem system;\n\n\n public CourseSelectManager(JWSystem system) {\n this.system = system;\n }\n\n /**\n * 获取自己已选课程的List\n *\n * @return 课程列表\n */\n public ArrayList<Course> getCurrentCourses() throws IOException {\n ArrayList<Course> list = new ArrayList<>();\n Connection.Response response = HttpUtil.sendGet(URLManager.MY_COURSE_LIST, this.system.headers);\n\n if (response == null) {\n throw new RuntimeException(\"response was null\");\n }\n\n // 返回值转化成Document\n Document document = response.parse();\n\n Elements elements = document.getElementsByTag(\"table\");\n // 只有一个table\n Element element = elements.first();\n\n if (element == null) {\n throw new RuntimeException(\"element not found !\");\n }\n\n // 获取全部tr tag的标签下的子元素\n Elements trElements = element.getElementsByTag(\"tr\");\n for (Element tr : trElements) {\n Elements tdElements = tr.getElementsByTag(\"td\");\n // 必定大于 5\n // 这边不处理顶部的th元素检测\n if (tdElements.size() < 5) {\n continue;\n }\n Course course = new Course();\n\n // 固定顺序\n course.setName(tdElements.get(1).ownText());\n course.setTeacher(tdElements.get(4).ownText());\n\n Element kcidElement = tr.getElementsByTag(\"a\").first();\n\n if (kcidElement == null) {\n continue;\n }\n\n // 通过replaceKCID\n String JXID = kcidElement.attr(\"href\")\n .replace(\"');\", \"\")\n .replace(\"javascript:xstkOper('\", \"\");\n course.setJxID(JXID);\n list.add(course);\n }\n return list;\n }\n\n /**\n * 获取当前已选选修课\n * 横向排列,无格式化\n */\n public String getCurrentCoursesStr() {\n Connection.Response response = HttpUtil.sendGet(URLManager.MY_COURSE_LIST, this.system.headers);\n\n // 是否响应异常\n if (response == null) {\n throw new RuntimeException(\"response was null\");\n }\n\n try {\n // 返回值转化成Document\n Document document = response.parse();\n\n Elements elements = document.getElementsByTag(\"table\");\n // 只有一个table\n Element element = elements.first();\n\n if (element == null) {\n throw new RuntimeException(\"element not found !\");\n }\n\n // 获取全部tr tag的标签下的子元素\n Elements trElements = element.getElementsByTag(\"tr\");\n\n StringBuilder result = new StringBuilder();\n for (Element tr : trElements) {\n // 拿三个\n Elements thElements = tr.getElementsByTag(\"th\");\n Elements tdElements = tr.getElementsByTag(\"td\");\n\n // 判断是否为课程详细的行\n if (!tdElements.isEmpty()) {\n // 循环课程表的具体信息\n for (Element td : tdElements) {\n result.append(td.ownText()).append(\" \");\n }\n }\n\n if (!thElements.isEmpty()) {\n // 循环课程表上的信息\n for (Element th : thElements) {\n result.append(th.ownText()).append(\" \");\n }\n }\n result.append(\"\\n\");\n }\n return result.toString();\n } catch (Exception e) {\n return \"error\";\n }\n }\n\n /**\n * 退出自己已选课程,建议搭配getCurrentCourses()使用.\n * <p>\n * {\"success\": true}\n * <p>\n * {\"success\":false,\"message\":\"退课失败:此课堂未开放,不能进行退课!\"}\n * <p>\n *\n * @param course 课程实例\n * @param reason 退课原因\n */\n public boolean exitSelectedCourse(Course course, String reason) {\n Connection.Response exitSelectResponse = HttpUtil.sendGet(URLManager.EXIT_COURSE\n .replace(\"<jx0404id>\", course.getJxID())\n .replace(\"<reason>\", reason), this.system.headers);\n\n if (exitSelectResponse == null) {\n return false;\n }\n // 退出选课判断\n return exitSelectResponse.body().contains(\"true\");\n }\n\n\n /**\n * 选择公共必修课\n * <p>\n * 选择公共选修课\n * @param course 课程的对象\n */\n public boolean selectCourse(Course course) {\n return course.isRequiredCourse() ? selectCourse(URLManager.REQUIRED_COURSE_SELECT, course) :\n selectCourse(URLManager.ELECTIVE_COURSE_SELECT, course);\n }\n\n /**\n * @param url 选课的 URL\n * @param course 课程的id\n */\n private boolean selectCourse(String url, Course course) {\n\n // 得事先登录学生选课系统,让后台存JSESSIONID\n Connection.Response response = HttpUtil.sendGet(url\n .replace(\"<kcid>\", course.getKcid())\n .replace(\"<jx0404id>\", course.getJxID()), this.system.headers);\n\n //response\n // {\"success\":true,\"message\":\"选课成功\",\"jfViewStr\":\"\"}\n // {\"success\":[true,false],\"message\":\"选课失败:此课堂选课人数已满!\"}\n // {\"success\":false,\"message\":\"选课失败:当前教学班已选择!\"}\n\n // 必修课\n //{\"success\":false,\"message\":\"选课失败:当前课程已选择其它教学班!\"}\n\n if (response == null) {\n return false;\n }\n return !response.body().contains(\"false\");\n }\n\n /**\n * 列出全部必修课,理论上必修选课最多课程不超过30个\n */\n public ArrayList<Course> getAllRequiredList() {\n return searchRequiredList(30);\n }\n\n /**\n * 列出必修课的列表\n *\n * @param size 显示课程大小\n */\n public ArrayList<Course> searchRequiredList(int size) {\n FormMap formMap = new FormMap();\n formMap.putRequiredFormData(\"3\", 0, size);\n\n Connection.Response response = HttpUtil.sendPost(URLManager.REQUIRED_COURSE_LIST, formMap, this.system.headers);\n\n if (response != null) {\n return CourseDataHandler.getCourses(response.body());\n }\n\n return new ArrayList<>();\n }\n\n /**\n * @param courseName 课程名称\n * @param teacher 授课老师\n * @param week 星期\n * @param section 节次\n * @param removeFull 过滤已满课程\n * @param removeConflict 过滤冲突课程\n * @param loc 过滤限选课程\n * @param size 显示数量\n */\n public ArrayList<Course> searchElectiveList(String courseName, String teacher, int week, String section, boolean removeFull, boolean removeConflict, String courseType, boolean loc, int size) {\n FormMap formMap = new FormMap();\n\n String weekStr = \"\";\n if (week != 0) {\n weekStr = String.valueOf(week);\n }\n\n formMap.putElectiveFormData(\"3\", 0, size);\n\n // 查询的参数\n String args = \"?kcxx=\" + courseName + \"&skls=\" + teacher + \"&skxq=\" + weekStr + \"&skjc=\" + section + \"&sfym=\" + removeFull + \"&sfct=\" + removeConflict + \"&szjylb=\" + courseType + \"&sfxx=\" + loc;\n\n\n Connection.Response response = HttpUtil.sendPost(URLManager.ELECTIVE_COURSE_LIST + args, formMap, this.system.headers);\n if (response != null) {\n String emptyListJson = response.body();\n return CourseDataHandler.getCourses(emptyListJson);\n }\n // 如果是网络原因返回空\n return new ArrayList<>();\n }\n\n /**\n * 获取全部公共选修课列表\n */\n public ArrayList<Course> getAllElectiveCourse() {\n return this.searchElectiveList(\"\", \"\", 0, \"\", false, false, \"\", true, 200);\n }\n\n /**\n * 通过课程名称获取课程\n *\n * @param courseName 课程名称\n */\n public ArrayList<Course> getElectiveCourseByName(String courseName) {\n return this.searchElectiveList(courseName, \"\", 0, \"\", false, false, \"\", true, 200);\n }\n\n /**\n * 通过老师名称搜索课程,支持模糊搜索\n *\n * @param teacher 老师名称\n */\n public ArrayList<Course> getElectiveCourseByTeacher(String teacher) {\n return this.searchElectiveList(\"\", teacher, 0, \"\", false, false, \"\", true, 200);\n }\n\n /**\n * 按照时间搜索课程\n *\n * @param week 星期\n * @param section 节次\n * @return 筛选出的课程\n */\n public ArrayList<Course> getElectiveCourseByWeek(int week, String section) {\n return this.searchElectiveList(\"\", \"\", week, section, false, false, \"\", true, 200);\n }\n\n /**\n * @param removeFull 过滤已满课程\n * @param removeConflict 过滤冲突课程\n * @param loc 过滤限选课程\n * @return 筛选出的课程\n */\n public ArrayList<Course> getElectiveCourseByStatement(boolean removeFull, boolean removeConflict, boolean loc) {\n return this.searchElectiveList(\"\", \"\", 0, \"\", removeFull, removeConflict, \"\", loc, 200);\n }\n\n}" }, { "identifier": "CourseReviewManager", "path": "src/main/java/moe/snowflake/jwSystem/manager/CourseReviewManager.java", "snippet": "public class CourseReviewManager {\n\n private final JWSystem system;\n\n\n public CourseReviewManager(JWSystem system) {\n this.system = system;\n }\n\n\n /**\n * 查询目前已有学生课程评价\n * @return 评价表格数据\n */\n public String getAllCourseReview() {\n Connection.Response response = HttpUtil.sendGet(URLManager.REVIEW_COURSE_FIND, this.system.headers);\n\n // 不读取 th 标签的数据\n StringBuilder sb = new StringBuilder(\"序号,学年学期,评价分类,评价批次,开始时间,结束时间\\n\");\n\n if (response == null) {\n throw new RuntimeException(\"network error....\");\n }\n\n try {\n Document document = response.parse();\n\n // 依旧是直接拿table\n Elements elements = document.getElementsByTag(\"table\");\n\n // 默认第一个table\n Element element = elements.first();\n\n if (element == null) {\n throw new RuntimeException(\"element not found\");\n }\n // 再取tr 标签\n Elements trElements = element.getElementsByTag(\"tr\");\n\n // 不读取第一个tr标签\n for (int i = 1; i < trElements.size(); i++) {\n Element tr = trElements.get(i);\n\n Elements tdElements = tr.getElementsByTag(\"td\");\n\n for (int j = 0; j < tdElements.size(); j++) {\n Element td = tdElements.get(j);\n sb.append(td.ownText());\n\n if (j + 1 != tdElements.size()) sb.append(\",\");\n }\n\n // 拿操作符号的a\n Elements aElements = tr.getElementsByTag(\"a\");\n\n Element hrefElements = aElements.first();\n\n if (hrefElements != null) {\n sb.append(URLManager.BASE_URL).append(hrefElements.attr(\"href\"));\n }\n // 换行\n sb.append(\"\\n\");\n }\n } catch (IOException e) {\n throw new RuntimeException(\"处理数据时发送异常\");\n }\n return sb.toString();\n }\n\n\n}" }, { "identifier": "URLManager", "path": "src/main/java/moe/snowflake/jwSystem/manager/URLManager.java", "snippet": "public class URLManager {\n // ################### URL ###################\n\n /**\n * 使用内网服务器\n */\n public static void useLocalNetServer(int mode){\n switch (mode){\n case 1:\n BASE_URL = BACKUP_SERVER1;\n break;\n case 2:\n BASE_URL = BACKUP_SERVER2;\n break;\n case 3:\n BASE_URL = BACKUP_SERVER3;\n break;\n case 4:\n BASE_URL = BACKUP_SERVER4;\n default:\n System.err.println(\"error while switching backup server ..\");\n break;\n }\n }\n\n /**\n * HOST地址\n */\n public static String BASE_URL = \"http://jw.gxstnu.edu.cn\";\n\n /**\n * 备用内网服务器1\n */\n public static String BACKUP_SERVER1 = \"http://172.20.0.72:80\";\n\n /**\n * 备用内网服务器2\n */\n public static String BACKUP_SERVER2 = \"http://172.20.0.73:80\";\n\n /**\n * 备用内网服务器3\n */\n public static String BACKUP_SERVER3 = \"http://172.20.0.74:80\";\n\n /**\n * 备用内网服务器4\n */\n public static String BACKUP_SERVER4 = \"http://172.20.0.75:80\";\n\n /**\n * METHOD:GET\n * <p>\n * 登录加密密钥\n */\n public static String LOGIN_DATA = BASE_URL + \"/Logon.do?method=logon&flag=sess\";\n /**\n * METHOD:POST\n * <p>\n * 登录教务系统请求\n */\n public static String LOGIN2 = BASE_URL + \"/Logon.do?method=logon\";\n /**\n * METHOD:POST\n * <p>\n * 使用 BASE64的登录数据\n */\n public static String LOGIN = BASE_URL + \"/jsxsd/xk/LoginToXk\";\n\n /**\n * METHOD:GET\n * <p>\n * 登录选课系统\n */\n public static String COURSE_LOGIN_WEB = BASE_URL + \"/jsxsd/xsxk/xsxk_index?jx0502zbid=F17F6D4A35AF4EDA8727F42C3BCAF124\";\n\n /**\n * METHOD:GET\n * <p> 退课\n */\n public static String EXIT_COURSE = BASE_URL + \"/jsxsd/xsxkjg/xstkOper?jx0404id=<jx0404id>&tkyy=<reason>\";\n\n /**\n * METHOD:GET\n * <p>\n * 退出教务系统\n */\n public static String EXIT_JWSYSTEM = BASE_URL + \"/jsxsd/xk/LoginToXk?method=exit&tktime=\" + System.currentTimeMillis();\n /**\n * METHOD:GET\n * <p>\n * 退出选课系统\n */\n public static String EXIT_COURSE_WEB = BASE_URL + \"/jsxsd/xsxk/xsxk_exit?jx0404id=1\";\n\n /**\n * METHOD:POST\n * <p>\n * * 参数\n * <p>\n * kcxx 课程名称\n * <p>\n * xx课 格式\n * <p>\n * <p>\n * =============================================\n * skls 授课老师\n * <p>\n * xx老师 格式 url encode x2\n * <p>\n * =============================================\n * skjc 节次 (需要同时选择上课星期)\n * <p>\n * 1-2- 1-2节\n * <p>\n * 3-- 3节\n * <p>\n * 4-5- 4-5节\n * <p>\n * 6-7- 6-7节\n * <p>\n * 8-9- 8-9节\n * <p>\n * 10-11-12 10-12杰\n * <p>\n * =============================================\n * skxq 上课星期\n * <p>\n * 1-7 表示 星期一 ~ 星期天\n * =============================================\n * sfym 过滤已满课程\n * <p>\n * false 默认值\n * <p>\n * =============================================\n * sfct 过滤冲突课程\n * <p>\n * false 默认值\n * <p>\n * =============================================\n * szjylb 类别索引\n * <p>\n * 17 德育教育类\n * <p>\n * 14 美育教育类\n * <p>\n * 13 教师教育类\n * <p>\n * 12 语言应用类\n * <p>\n * 10 英语应用\n * <p>\n * 9 其他\n * <p>\n * 8 汉语应用\n * <p>\n * 7 公共艺术\n * <p>\n * 6 综合素质\n * <p>\n * 5 四史教育类\n * <p>\n * 4 身心素质类\n * <p>\n * 3 社会素养类\n * <p>\n * 2 科学素养类\n * <p>\n * 1 人文素养类\n * <p>\n * 空白 显示全部课程\n * <p>\n * =============================================\n * sfxx 过滤限选课程\n * <p>\n * true 默认值\n * =============================================\n * 表单数据\n * xxx 默认值 解释\n * =============================================\n * sEcho: 2\n * <p>\n * iColumns: 13 列数\n * <p>\n * sColumns: \"\"\n * <p>\n * iDisplayStart: 0\n * <p>\n * iDisplayLength: 15 一页显示15个\n * <p>\n * mDataProp_0: kch 课程号\n * <p>\n * mDataProp_2: kcmc 课程名称\n * <p>\n * mDataProp_2: xf 学分\n * <p>\n * mDataProp_3: skls 授课老师\n * <p>\n * mDataProp_4 sksj 授课时间\n * <p>\n * mDataProp_5 skdd 授课地点\n * <p>\n * mDataProp_6 sqxq 上课校区\n * <p>\n * mDataProp_7 xxrs 限选人数\n * <p>\n * mDataProp_8 xkrs 选课人数\n * <p>\n * mDataProp_9 syrs 剩余人数\n * <p>\n * mDataProp_10 ctsm 时间冲突\n * <p>\n * mDataProp_11 szkcflmc 类别\n * <p>\n * mDataProp_12 czOper 选课操作的按钮\n * <p>\n * iTotalRecords 178 总记录\n * <p>\n * =============================================\n * backup\n * kcxx=&skls=&skxq=&skjc=&sfym=false&sfct=false&szjylb=&sfxx=true\n */\n public static String ELECTIVE_COURSE_LIST = BASE_URL + \"/jsxsd/xsxkkc/yl_xsxkGgxxkxk\";\n /**\n * METHOD:POST\n * <p>\n * * 参数\n * <p>skxq_xx0103\n * <p>\n * 1 北校区\n * <p>\n * 2 南校区\n * <p>\n * 3 来宾校区\n * <p>\n * ==================================\n * <p>\n * 请参考选修LIST\n * <p>\n * sEcho: 1\n * <p>\n * iColumns: 11 列数\n * <p>\n * sColumns:\n * <p>\n * iDisplayStart: 0\n * <p>\n * iDisplayLength: 15\n * <p>\n * mDataProp_0: kch\n * <p>\n * mDataProp_1: kcmc\n * <p>\n * mDataProp_2: fzmc\n * <p>\n * mDataProp_3: ktmc\n * <p>\n * mDataProp_4: xf\n * <p>\n * mDataProp_5: skls\n * <p>\n * mDataProp_6: sksj\n * <p>\n * mDataProp_7: skdd\n * <p>\n * mDataProp_8: xqmc\n * <p>\n * mDataProp_9: ctsm\n * <p>\n * mDataProp_10: czOper\n */\n public static String REQUIRED_COURSE_LIST = BASE_URL + \"/jsxsd/xsxkkc/xsxkBxxk?skxq_xx0103=\";\n\n /**\n * METHOD:GET\n * <p>\n * * 选课操作\n * <p>\n * ==================================\n * <p>\n * kcid(jx02id) 课程ID\n * <p>\n * jx0404id 不知道是什么id\n * <p>\n * ==================================\n * <p>\n * replace以下两个参数\n * <p>\n * <kcid>\n * <p>\n * <jx0404id>\n * <p>\n * response :\n * <p>\n * {\"success\":true,\"message\":\"选课成功\",\"jfViewStr\":\"\"}\n * <p>\n */\n public static String ELECTIVE_COURSE_SELECT = BASE_URL + \"/jsxsd/xsxkkc/ggxxkxkOper?kcid=<kcid>&cfbs=null&jx0404id=<jx0404id>&xkzy=&trjf=\";\n\n /**\n * METHOD:GET\n * <p>\n * 选课操作\n * <p>\n * ==================================\n * <p>\n * kcid(jx02id) 课程ID\n * <p>\n * jx0404id 不知道是什么id\n * <p>\n * ==================================\n * <p>\n * replace以下两个参数\n * <p>\n * <kcid>\n * <p>\n * <jx0404id>\n * <p>\n * response :\n * <p>\n * {\"success\":true,\"message\":\"选课成功\",\"jfViewStr\":\"\"}\n * <p>\n */\n public static String REQUIRED_COURSE_SELECT = BASE_URL + \"/jsxsd/xsxkkc/bxxkOper?kcid=<kcid>&cfbs=null&jx0404id=<jx0404id>&xkzy=&trjf=\";\n\n /**\n * METHOD:GET\n * <p>\n * 现在当前课程的列表\n */\n public static String MY_COURSE_LIST = BASE_URL + \"/jsxsd/xsxkjg/comeXkjglb\";\n\n /**\n * METHOD:GET\n * <p>\n * 查找有哪些课程可评价\n */\n public static String REVIEW_COURSE_FIND = BASE_URL + \"/jsxsd/xspj/xspj_find.do\";\n\n /**\n * METHOD:POST\n * <p>\n * 提交评课数据\n */\n public static String REVIEW_COURSE_SAVE = BASE_URL + \"/jsxsd/xspj/xspj_save.do\";\n\n}" }, { "identifier": "HttpUtil", "path": "src/main/java/moe/snowflake/jwSystem/utils/HttpUtil.java", "snippet": "public class HttpUtil {\n public static Connection.Response sendGet(String url) {\n try {\n return Jsoup.connect(url)\n .followRedirects(true)\n .execute();\n } catch (Exception e) {\n return null;\n }\n }\n\n public static Connection.Response sendGet(String url, Map<String, String> headers) {\n try {\n return Jsoup.connect(url)\n .followRedirects(true)\n .headers(headers)\n .execute();\n } catch (Exception e) {\n return null;\n }\n }\n\n public static Connection.Response sendPost(String url, Map<String, String> form) {\n try {\n return Jsoup.connect(url)\n .data(form)\n .method(Connection.Method.POST)\n .followRedirects(true)\n .execute().charset(\"UTF-8\");\n } catch (Exception e) {\n return null;\n }\n }\n\n public static Connection.Response sendPost(String url, Map<String, String> form, Map<String, String> headers) {\n try {\n return Jsoup.connect(url)\n .data(form).method(Connection.Method.POST)\n .followRedirects(false)\n .headers(headers)\n .execute().charset(\"UTF-8\");\n } catch (Exception e) {\n return null;\n }\n }\n\n}" }, { "identifier": "PasswordUtil", "path": "src/main/java/moe/snowflake/jwSystem/utils/PasswordUtil.java", "snippet": "public class PasswordUtil {\n\n /**\n * 通过逆向网页js,用于教务处方式进入的教务系统登录.\n * <p>\n * 新版的教务系统都用这个,但是可以用它更底层的登录方式进行登录\n * @param dataStr 服务端获取的加密密钥\n * @param code 账号%%%密码\n * @return encoded 的数据\n */\n @Deprecated\n public static String encodeUserData(String dataStr, String code) {\n StringBuilder encoded = new StringBuilder();\n String scode = dataStr.split(\"#\")[0];\n String sxh = dataStr.split(\"#\")[1];\n\n for (int i = 0; i < code.length(); i++) {\n if (i < 20) {\n int end = Integer.parseInt(sxh.substring(i, i + 1));\n encoded.append(code.charAt(i)).append(scode, 0, end);\n scode = scode.substring(end);\n } else {\n encoded.append(code.substring(i));\n i = code.length();\n }\n }\n return encoded.toString();\n }\n\n\n}" } ]
import moe.snowflake.jwSystem.manager.CourseSelectManager; import moe.snowflake.jwSystem.manager.CourseReviewManager; import moe.snowflake.jwSystem.manager.URLManager; import moe.snowflake.jwSystem.utils.HttpUtil; import moe.snowflake.jwSystem.utils.PasswordUtil; import org.jsoup.Connection; import org.jsoup.nodes.Element; import java.io.IOException; import java.util.*;
7,558
package moe.snowflake.jwSystem; public class JWSystem { public Connection.Response jwLoggedResponse; public Connection.Response courseSelectSystemResponse; public Map<String, String> headers = new HashMap<>(); private final boolean loginCourseSelectWeb; private final CourseSelectManager courseSelectManager; private final CourseReviewManager courseReviewManager; public JWSystem() { this(true); } public JWSystem(boolean loginCourseSelectWeb) { this.loginCourseSelectWeb = loginCourseSelectWeb; this.courseSelectManager = new CourseSelectManager(this); this.courseReviewManager = new CourseReviewManager(this); } /** * 判断教务是否登录成功 * * @return 是否登录成功 */ public boolean isJWLogged() { try { if (this.jwLoggedResponse != null) { // 只要有这个元素即登录失败 Element element = this.jwLoggedResponse.parse().getElementById("showMsg"); if (element != null) return false; } } catch (Exception e) { return false; } return true; } /** * 判断选课系统是否登录成功 * * @return 选课系统是否登录 */ public boolean isCourseLogged() { try { return this.isJWLogged() && this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains("登录"); } catch (IOException e) { return false; } } /** * 设置全局的 headers,包含cookie * jsoup设置的cookie无法识别 * * @param cookie cookie */ private void setHeaders(String cookie) { headers.put("Cookie", "JSESSIONID=" + cookie); } /** * 直接导向目标API的登录 * * @param username 用户名 * @param password 密码 */ public JWSystem login(String username, String password) { Map<String, String> formData = new HashMap<>(); formData.put("userAccount", username); formData.put("userPassword", ""); // 很明显的两个base64加密 formData.put("encoded", new String(Base64.getEncoder().encode(username.getBytes())) + "%%%" + new String(Base64.getEncoder().encode(password.getBytes()))); // 登录成功的 响应
package moe.snowflake.jwSystem; public class JWSystem { public Connection.Response jwLoggedResponse; public Connection.Response courseSelectSystemResponse; public Map<String, String> headers = new HashMap<>(); private final boolean loginCourseSelectWeb; private final CourseSelectManager courseSelectManager; private final CourseReviewManager courseReviewManager; public JWSystem() { this(true); } public JWSystem(boolean loginCourseSelectWeb) { this.loginCourseSelectWeb = loginCourseSelectWeb; this.courseSelectManager = new CourseSelectManager(this); this.courseReviewManager = new CourseReviewManager(this); } /** * 判断教务是否登录成功 * * @return 是否登录成功 */ public boolean isJWLogged() { try { if (this.jwLoggedResponse != null) { // 只要有这个元素即登录失败 Element element = this.jwLoggedResponse.parse().getElementById("showMsg"); if (element != null) return false; } } catch (Exception e) { return false; } return true; } /** * 判断选课系统是否登录成功 * * @return 选课系统是否登录 */ public boolean isCourseLogged() { try { return this.isJWLogged() && this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains("登录"); } catch (IOException e) { return false; } } /** * 设置全局的 headers,包含cookie * jsoup设置的cookie无法识别 * * @param cookie cookie */ private void setHeaders(String cookie) { headers.put("Cookie", "JSESSIONID=" + cookie); } /** * 直接导向目标API的登录 * * @param username 用户名 * @param password 密码 */ public JWSystem login(String username, String password) { Map<String, String> formData = new HashMap<>(); formData.put("userAccount", username); formData.put("userPassword", ""); // 很明显的两个base64加密 formData.put("encoded", new String(Base64.getEncoder().encode(username.getBytes())) + "%%%" + new String(Base64.getEncoder().encode(password.getBytes()))); // 登录成功的 响应
Connection.Response response = HttpUtil.sendPost(URLManager.LOGIN, formData);
2
2023-12-21 10:58:12+00:00
12k