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 build...
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) <luck@lucko.me> * 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...
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 ...
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 Gov...
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 serialVersion...
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 fi...
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 ...
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 *...
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 ...
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...
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 recipeT...
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 = -48796772838...
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,...
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...
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 sour...
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 ...
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": ...
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 Strin...
import com.alibaba.fastjson.JSON; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.content.config.MultipartSupportConfig; import com.xuecheng.content.feignclient.MediaServiceClient; import com.xuecheng.content.feignclient.SearchServiceClient; import com.xuecheng.content.feignclient.po.CourseIndex; import com.xuecheng.content.mapper.CourseBaseMapper; import com.xuecheng.content.mapper.CourseMarketMapper; import com.xuecheng.content.mapper.CoursePublishMapper; import com.xuecheng.content.mapper.CoursePublishPreMapper; import com.xuecheng.content.model.dto.CourseBaseInfoDto; import com.xuecheng.content.model.dto.CoursePreviewDto; import com.xuecheng.content.model.dto.TeachplanDto; import com.xuecheng.content.model.po.CourseBase; import com.xuecheng.content.model.po.CourseMarket; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.content.model.po.CoursePublishPre; import com.xuecheng.content.service.CourseBaseInfoService; import com.xuecheng.content.service.CoursePublishService; import com.xuecheng.content.service.TeachplanService; import com.xuecheng.messagesdk.model.po.MqMessage; import com.xuecheng.messagesdk.service.MqMessageService; import freemarker.template.Configuration; import freemarker.template.Template; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
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 \...
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 ...
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/d...
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.res...
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 nod...
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": "...
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 = \"mq...
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)\...
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 Co...
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 ...
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...
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>, BiConsum...
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 I...
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 errorMe...
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 \...
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 =...
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 = ...
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> se...
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 @Crea...
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\tprivat...
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...
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軸位...
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)...
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 q...
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 fi...
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 emai...
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 pr...
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 withSimplificati...
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...
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 ...
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 hasPa...
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 L...
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/Dr...
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(Co...
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 ...
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/dr...
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.toUnmodifiableMa...
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...
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 ...
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, ...
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 ...
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(AMQPObservable...
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 privat...
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...
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 = GenerationTyp...
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 pri...
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\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment...
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 Intercep...
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\")\...
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.\...
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 }...
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 conf...
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...
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 @...
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 o...
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 retur...
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 Re...
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 ...
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) t...
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 ...
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...
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 = Sc...
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 emptyTextur...
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.na...
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 *...
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 in...
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 * ...
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...
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@Sub...
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 ...
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<>...
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 \" + getD...
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, ...
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 ...
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 = ne...
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(\"...
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().crea...
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 ...
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.DEF...
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 詹波 (jfinal@126.com). * * 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 詹波 (jfinal@126.com). * * 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 */...
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...
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 /...
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