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 |
---|---|---|---|---|---|---|---|---|---|---|
awesome-java-web/groovy-script-executor | src/main/java/com/github/awesome/scripting/groovy/GroovyScriptExecutor.java | [
{
"identifier": "LocalCacheManager",
"path": "src/main/java/com/github/awesome/scripting/groovy/cache/LocalCacheManager.java",
"snippet": "public class LocalCacheManager implements LocalCache {\n\n private LocalCache localCache;\n\n public static LocalCacheManager newBuilder() {\n return new LocalCacheManager();\n }\n\n public LocalCacheManager use(LocalCache localCache) {\n this.localCache = localCache;\n return this;\n }\n\n public LocalCacheManager useDefaultCache() {\n Cache<String, GroovyObject> defaultCache = Caffeine.newBuilder()\n .initialCapacity(1)\n .maximumSize(10)\n .expireAfterAccess(Duration.ofDays(1))\n .recordStats()\n .build();\n this.localCache = new CaffeineLocalCache(defaultCache);\n return this;\n }\n\n @Override\n public GroovyObject getIfPresent(String key) {\n return this.localCache.getIfPresent(key);\n }\n\n @Override\n public void put(String key, GroovyObject groovyObject) {\n this.localCache.put(key, groovyObject);\n }\n\n @Override\n public String stats() {\n return this.localCache.stats();\n }\n\n}"
},
{
"identifier": "GroovyObjectInvokeMethodException",
"path": "src/main/java/com/github/awesome/scripting/groovy/exception/GroovyObjectInvokeMethodException.java",
"snippet": "public class GroovyObjectInvokeMethodException extends RuntimeException {\n\n public GroovyObjectInvokeMethodException(String message) {\n super(message);\n }\n\n}"
},
{
"identifier": "GroovyScriptParseException",
"path": "src/main/java/com/github/awesome/scripting/groovy/exception/GroovyScriptParseException.java",
"snippet": "public class GroovyScriptParseException extends RuntimeException {\n\n public GroovyScriptParseException(String message) {\n super(message);\n }\n\n}"
},
{
"identifier": "InvalidGroovyScriptException",
"path": "src/main/java/com/github/awesome/scripting/groovy/exception/InvalidGroovyScriptException.java",
"snippet": "public class InvalidGroovyScriptException extends RuntimeException {\n\n public InvalidGroovyScriptException(String message) {\n super(message);\n }\n\n}"
},
{
"identifier": "DefaultGroovyScriptSecurityChecker",
"path": "src/main/java/com/github/awesome/scripting/groovy/security/DefaultGroovyScriptSecurityChecker.java",
"snippet": "public class DefaultGroovyScriptSecurityChecker implements GroovyScriptSecurityChecker {\n\n @Override\n public Collection<String> shouldInterceptKeywords() {\n DefaultShouldInterceptKeywords[] keywords = DefaultShouldInterceptKeywords.values();\n return Arrays.stream(keywords).map(DefaultShouldInterceptKeywords::getKeyword).collect(Collectors.toSet());\n }\n\n @Override\n public void checkOrThrow(String script) {\n Collection<String> keywords = shouldInterceptKeywords();\n for (String keyword : keywords) {\n if (script.contains(keyword)) {\n final String errorMessage = String.format(\n \"Groovy script contains potentially unsafe keyword: '%s', %s, please notice the following keywords are all considered unsafe: %s\",\n keyword, Objects.requireNonNull(DefaultShouldInterceptKeywords.fromKeyword(keyword)).getExplanation(), keywords\n );\n throw new GroovyScriptSecurityException(errorMessage);\n }\n }\n }\n\n}"
},
{
"identifier": "GroovyScriptSecurityChecker",
"path": "src/main/java/com/github/awesome/scripting/groovy/security/GroovyScriptSecurityChecker.java",
"snippet": "public interface GroovyScriptSecurityChecker {\n\n Collection<String> shouldInterceptKeywords();\n\n void checkOrThrow(String script);\n}"
},
{
"identifier": "Md5Utils",
"path": "src/main/java/com/github/awesome/scripting/groovy/util/Md5Utils.java",
"snippet": "public final class Md5Utils {\n\n private static final String MESSAGE_DIGEST_ALGORITHM_MD5 = \"MD5\";\n\n private Md5Utils() {\n throw new UnsupportedOperationException(\"Utility class should not be instantiated\");\n }\n\n public static byte[] md5(String input) {\n try {\n MessageDigest md5 = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5);\n return md5.digest(input.getBytes(StandardCharsets.UTF_8));\n } catch (NoSuchAlgorithmException e) {\n return new byte[0];\n }\n }\n\n public static String md5Hex(String input) {\n StringBuilder sb = new StringBuilder();\n byte[] digest = md5(input);\n for (byte b : digest) {\n sb.append(String.format(\"%02x\", b));\n }\n return sb.toString();\n }\n\n}"
}
] | import com.github.awesome.scripting.groovy.cache.LocalCacheManager;
import com.github.awesome.scripting.groovy.exception.GroovyObjectInvokeMethodException;
import com.github.awesome.scripting.groovy.exception.GroovyScriptParseException;
import com.github.awesome.scripting.groovy.exception.InvalidGroovyScriptException;
import com.github.awesome.scripting.groovy.security.DefaultGroovyScriptSecurityChecker;
import com.github.awesome.scripting.groovy.security.GroovyScriptSecurityChecker;
import com.github.awesome.scripting.groovy.util.Md5Utils;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.IOException; | 1,745 | package com.github.awesome.scripting.groovy;
public class GroovyScriptExecutor {
private LocalCacheManager localCacheManager;
private GroovyScriptSecurityChecker groovyScriptSecurityChecker;
public static GroovyScriptExecutor newBuilder() {
return new GroovyScriptExecutor();
}
public GroovyScriptExecutor() {
this.groovyScriptSecurityChecker = new DefaultGroovyScriptSecurityChecker();
}
public GroovyScriptExecutor withCacheManager(LocalCacheManager localCacheManager) {
this.localCacheManager = localCacheManager;
return this;
}
public GroovyScriptExecutor withSecurityChecker(GroovyScriptSecurityChecker groovyScriptSecurityChecker) {
this.groovyScriptSecurityChecker = groovyScriptSecurityChecker;
return this;
}
public LocalCacheManager getCacheManager() {
return localCacheManager;
}
public Object execute(final String classScript, final String function, final Object... parameters) {
if (classScript == null) {
throw new InvalidGroovyScriptException("Groovy script is null");
}
final String trimmedScript = classScript.trim();
if (trimmedScript.isEmpty()) {
throw new InvalidGroovyScriptException("Groovy script is empty");
}
// Check if the script contains any unsafe keywords
this.groovyScriptSecurityChecker.checkOrThrow(trimmedScript);
// Find groovy object from cache first
final String scriptCacheKey = Md5Utils.md5Hex(trimmedScript);
GroovyObject groovyObjectCache = this.localCacheManager.getIfPresent(scriptCacheKey);
// Parse the script and put it into cache instantly if it is not in cache
if (groovyObjectCache == null) {
groovyObjectCache = parseClassScript(trimmedScript);
this.localCacheManager.put(scriptCacheKey, groovyObjectCache);
}
// Script is parsed successfully
return invokeMethod(groovyObjectCache, function, parameters);
}
private GroovyObject parseClassScript(final String classScript) {
try (GroovyClassLoader groovyClassLoader = new GroovyClassLoader()) {
Class<?> scriptClass = groovyClassLoader.parseClass(classScript);
return (GroovyObject) scriptClass.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException e) {
throw new GroovyScriptParseException("Failed to parse groovy script, the nested exception is: " + e.getMessage());
}
}
private Object invokeMethod(GroovyObject groovyObject, String function, Object... parameters) {
try {
return groovyObject.invokeMethod(function, parameters);
} catch (Exception e) {
final String errorMessage = String.format("Failed to invoke groovy method '%s', the nested exception is: %s", function, e.getMessage()); | package com.github.awesome.scripting.groovy;
public class GroovyScriptExecutor {
private LocalCacheManager localCacheManager;
private GroovyScriptSecurityChecker groovyScriptSecurityChecker;
public static GroovyScriptExecutor newBuilder() {
return new GroovyScriptExecutor();
}
public GroovyScriptExecutor() {
this.groovyScriptSecurityChecker = new DefaultGroovyScriptSecurityChecker();
}
public GroovyScriptExecutor withCacheManager(LocalCacheManager localCacheManager) {
this.localCacheManager = localCacheManager;
return this;
}
public GroovyScriptExecutor withSecurityChecker(GroovyScriptSecurityChecker groovyScriptSecurityChecker) {
this.groovyScriptSecurityChecker = groovyScriptSecurityChecker;
return this;
}
public LocalCacheManager getCacheManager() {
return localCacheManager;
}
public Object execute(final String classScript, final String function, final Object... parameters) {
if (classScript == null) {
throw new InvalidGroovyScriptException("Groovy script is null");
}
final String trimmedScript = classScript.trim();
if (trimmedScript.isEmpty()) {
throw new InvalidGroovyScriptException("Groovy script is empty");
}
// Check if the script contains any unsafe keywords
this.groovyScriptSecurityChecker.checkOrThrow(trimmedScript);
// Find groovy object from cache first
final String scriptCacheKey = Md5Utils.md5Hex(trimmedScript);
GroovyObject groovyObjectCache = this.localCacheManager.getIfPresent(scriptCacheKey);
// Parse the script and put it into cache instantly if it is not in cache
if (groovyObjectCache == null) {
groovyObjectCache = parseClassScript(trimmedScript);
this.localCacheManager.put(scriptCacheKey, groovyObjectCache);
}
// Script is parsed successfully
return invokeMethod(groovyObjectCache, function, parameters);
}
private GroovyObject parseClassScript(final String classScript) {
try (GroovyClassLoader groovyClassLoader = new GroovyClassLoader()) {
Class<?> scriptClass = groovyClassLoader.parseClass(classScript);
return (GroovyObject) scriptClass.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException e) {
throw new GroovyScriptParseException("Failed to parse groovy script, the nested exception is: " + e.getMessage());
}
}
private Object invokeMethod(GroovyObject groovyObject, String function, Object... parameters) {
try {
return groovyObject.invokeMethod(function, parameters);
} catch (Exception e) {
final String errorMessage = String.format("Failed to invoke groovy method '%s', the nested exception is: %s", function, e.getMessage()); | throw new GroovyObjectInvokeMethodException(errorMessage); | 1 | 2023-12-11 03:30:22+00:00 | 4k |
IzanagiCraft/data-storage | src/test/java/tests/InMemoryDataRepositoryTest.java | [
{
"identifier": "DataRepository",
"path": "src/main/java/com/izanagicraft/storage/repository/DataRepository.java",
"snippet": "public interface DataRepository<T> {\n\n /**\n * Retrieves data associated with the specified key.\n *\n * @param key the key to retrieve data\n * @return the data associated with the key, or null if not found\n */\n T getData(String key);\n\n /**\n * Stores data with the specified key.\n *\n * @param key the key to store data\n * @param value the data to be stored\n * @return the stored data\n */\n T storeData(String key, T value);\n\n /**\n * Checks if data associated with the specified key is present in the storage.\n *\n * @param key the key to check for in the storage\n * @return true if the data is present in the cache, false otherwise\n */\n boolean isStored(String key);\n\n /**\n * Clears the storage, removing all stored data.\n */\n void clearStorage();\n\n /**\n * Asynchronously retrieves data associated with the specified key.\n *\n * @param key the key to retrieve data\n * @return a CompletableFuture that completes with the data associated with the key, or null if not found\n */\n default CompletableFuture<T> getDataAsync(String key) {\n return CompletableFuture.supplyAsync(() -> getData(key));\n }\n\n /**\n * Asynchronously stores data with the specified key.\n *\n * @param key the key to store data\n * @param value the data to be stored\n * @return a CompletableFuture that completes with the stored data\n */\n default CompletableFuture<T> storeDataAsync(String key, T value) {\n return CompletableFuture.supplyAsync(() -> storeData(key, value));\n }\n\n /**\n * Asynchronously checks if data associated with the specified key is present in the cache.\n *\n * @param key the key to check for in the cache\n * @return a CompletableFuture that completes with true if the data is present in the cache, false otherwise\n */\n default CompletableFuture<Boolean> isInCacheAsync(String key) {\n return CompletableFuture.supplyAsync(() -> isStored(key));\n }\n\n /**\n * Asynchronously clears the cache, removing all stored data.\n *\n * @return a CompletableFuture that completes when the cache is cleared\n */\n default CompletableFuture<Void> clearCacheAsync() {\n return CompletableFuture.runAsync(this::clearStorage);\n }\n\n\n}"
},
{
"identifier": "InMemoryDataRepository",
"path": "src/main/java/com/izanagicraft/storage/repository/InMemoryDataRepository.java",
"snippet": "public class InMemoryDataRepository<T> implements DataRepository<T> {\n\n private final Map<String, T> cache;\n\n /**\n * Constructs an {@code InMemoryDataRepository} with an internal {@link ConcurrentHashMap} to store data.\n */\n public InMemoryDataRepository() {\n this.cache = new ConcurrentHashMap<>();\n }\n\n\n @Override\n public T getData(String key) {\n return cache.get(key);\n }\n\n @Override\n public T storeData(String key, T value) {\n cache.put(key, value);\n return value;\n }\n\n @Override\n public boolean isStored(String key) {\n return cache.containsKey(key);\n }\n\n @Override\n public void clearStorage() {\n cache.clear();\n }\n\n}"
}
] | import com.izanagicraft.storage.repository.DataRepository;
import com.izanagicraft.storage.repository.InMemoryDataRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; | 1,829 | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package tests;
/**
* data-storage; tests:InMemoryDataRepositoryTest
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
class InMemoryDataRepositoryTest {
private DataRepository<String> stringRepository;
private DataRepository<Integer> integerRepository;
@BeforeEach
void setUp() {
// Initialize a new InMemoryDataRepository for String and Integer types before each test | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package tests;
/**
* data-storage; tests:InMemoryDataRepositoryTest
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
class InMemoryDataRepositoryTest {
private DataRepository<String> stringRepository;
private DataRepository<Integer> integerRepository;
@BeforeEach
void setUp() {
// Initialize a new InMemoryDataRepository for String and Integer types before each test | stringRepository = new InMemoryDataRepository<>(); | 1 | 2023-12-13 17:05:12+00:00 | 4k |
ItzOverS/CoReScreen | src/main/java/me/overlight/corescreen/ClientSettings/CSManager.java | [
{
"identifier": "ChatVisibility",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/Modules/ChatVisibility.java",
"snippet": "public class ChatVisibility extends CSModule {\n public ChatVisibility() {\n super(\"ChatVisibility\", \"chatvisibility\");\n }\n\n @Override\n public String getValue(Player player) {\n return ClientSettingsGrabber.getSettings(player).getChatVisibility().name();\n }\n}"
},
{
"identifier": "ClientVersion",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/Modules/ClientVersion.java",
"snippet": "public class ClientVersion extends CSModule {\n public ClientVersion() {\n super(\"ClientVersion\", \"clientversion\");\n }\n\n @Override\n public String getValue(Player player) {\n return PacketEvents.get().getPlayerUtils().getClientVersion(player).name().substring(2).replace(\"_\", \".\");\n }\n}"
},
{
"identifier": "Locale",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/Modules/Locale.java",
"snippet": "public class Locale extends CSModule {\n public Locale() {\n super(\"Locale\", \"locale\");\n }\n\n @Override\n public String getValue(Player player) {\n return ClientSettingsGrabber.getSettings(player).getLocale();\n }\n}"
},
{
"identifier": "RenderDistance",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/Modules/RenderDistance.java",
"snippet": "public class RenderDistance extends CSModule {\n public RenderDistance() {\n super(\"RenderDistance\", \"renderdistance\");\n }\n\n @Override\n public String getValue(Player player) {\n return String.valueOf(ClientSettingsGrabber.getSettings(player).getRenderDistance());\n }\n}"
},
{
"identifier": "TestCheck",
"path": "src/main/java/me/overlight/corescreen/Test/TestCheck.java",
"snippet": "public class TestCheck {\n private final String name;\n private final String[] alias;\n\n public String getName() {\n return name;\n }\n\n public String[] getAlias() {\n return alias;\n }\n\n public TestCheck(String name, String[] alias) {\n this.name = name;\n this.alias = alias;\n }\n\n public void handle(Player player, Player executor) {\n\n }\n}"
},
{
"identifier": "Knockback",
"path": "src/main/java/me/overlight/corescreen/Test/Tests/Knockback.java",
"snippet": "public class Knockback extends TestCheck {\n public Knockback() {\n super(\"Knockback\", new String[]{\"knockback\", \"kb\"});\n }\n\n public final static List<String> inTest = new ArrayList<>();\n\n private static double minAvg, maxAvg, MotionX, MotionY, MotionZ;\n private static int delay, rounds, sDelay;\n\n static {\n Bukkit.getScheduler().runTask(CoReScreen.getInstance(), () -> {\n minAvg = CoReScreen.getInstance().getConfig().getDouble(\"settings.test.knockback.average-check.min\");\n maxAvg = CoReScreen.getInstance().getConfig().getDouble(\"settings.test.knockback.average-check.max\");\n MotionX = CoReScreen.getInstance().getConfig().getDouble(\"settings.test.knockback.motion.x\");\n MotionY = CoReScreen.getInstance().getConfig().getDouble(\"settings.test.knockback.motion.y\");\n MotionZ = CoReScreen.getInstance().getConfig().getDouble(\"settings.test.knockback.motion.z\");\n delay = CoReScreen.getInstance().getConfig().getInt(\"settings.test.knockback.delay\");\n sDelay = Math.min(CoReScreen.getInstance().getConfig().getInt(\"settings.test.knockback.setback-delay\"), delay - 1);\n rounds = CoReScreen.getInstance().getConfig().getInt(\"settings.test.knockback.rounds\");\n });\n }\n\n @Override\n public void handle(Player player, Player executor) {\n executor.sendMessage(CoReScreen.translate(\"messages.test.knockback.perform\").replace(\"%player%\", player.getName()));\n inTest.add(player.getName());\n new BukkitRunnable() {\n int round;\n final List<Double> nums = new ArrayList<>();\n\n @Override\n public void run() {\n if (Bukkit.getOnlinePlayers().stream().noneMatch(r -> r.getName().equals(player.getName())) || !player.isOnline()) {\n cancel();\n return;\n }\n Location pos = player.getLocation().clone().clone();\n player.setVelocity(new Vector(MotionX, MotionY, MotionZ));\n Bukkit.getScheduler().runTaskLater(CoReScreen.getInstance(), () -> {\n if (Bukkit.getOnlinePlayers().stream().noneMatch(r -> r.getName().equals(player.getName())) || !player.isOnline()) return;\n nums.add(pos.distance(player.getLocation()));\n player.setFallDistance(0f);\n player.teleport(pos.clone());\n if (round >= rounds) {\n player.setVelocity(new Vector(0, 0, 0));\n double avg = nums.stream().mapToDouble(r -> r).average().getAsDouble();\n if (minAvg < avg && avg < maxAvg) executor.sendMessage(CoReScreen.translate(\"messages.test.knockback.success\").replace(\"%player%\", player.getName()));\n else executor.sendMessage(CoReScreen.translate(\"messages.test.knockback.failure\").replace(\"%player%\", player.getName()));\n Bukkit.getConsoleSender().sendMessage(\"Knockback test applied on \" + player.getName() + \". Average Velocity was \" + avg);\n inTest.remove(player.getName());\n }\n }, sDelay);\n round++;\n if (round >= rounds) {\n cancel();\n }\n }\n }.runTaskTimer(CoReScreen.getInstance(), 0, delay);\n }\n}"
},
{
"identifier": "Rotation",
"path": "src/main/java/me/overlight/corescreen/Test/Tests/Rotation.java",
"snippet": "public class Rotation extends TestCheck {\n public Rotation() {\n super(\"Rotation\", new String[]{\"rotate\", \"rotation\", \"rot\"});\n }\n\n @Override\n public void handle(Player player, Player executor) {\n executor.sendMessage(CoReScreen.translate(\"messages.test.rotate.perform\").replace(\"%player%\", player.getName()));\n final Location updateRot = player.getLocation().clone();\n updateRot.setYaw(new Random().nextInt(360) - 180);\n updateRot.setPitch(new Random().nextInt(180) - 90);\n player.teleport(updateRot);\n Bukkit.getScheduler().runTaskLater(CoReScreen.getInstance(), () -> {\n if (Bukkit.getOnlinePlayers().stream().noneMatch(r -> r.getName().equals(player.getName())) || !player.isOnline()) return;\n if (player.getLocation().getYaw() != updateRot.getYaw() || player.getLocation().getPitch() != updateRot.getPitch()) executor.sendMessage(CoReScreen.translate(\"messages.test.rotate.failure\").replace(\"%player%\", player.getName()));\n else executor.sendMessage(CoReScreen.translate(\"messages.test.rotate.success\").replace(\"%player%\", player.getName()));\n }, 3);\n }\n}"
},
{
"identifier": "Shuffle",
"path": "src/main/java/me/overlight/corescreen/Test/Tests/Shuffle.java",
"snippet": "public class Shuffle extends TestCheck {\n public Shuffle() {\n super(\"Shuffle\", new String[]{\"shuffle\"});\n }\n\n @Override\n public void handle(Player player, Player executor) {\n executor.sendMessage(CoReScreen.translate(\"messages.test.shuffle.perform\").replace(\"%player%\", player.getName()));\n final int shuffle = new Random().nextInt(9);\n player.getInventory().setHeldItemSlot(shuffle);\n Bukkit.getScheduler().runTaskLater(CoReScreen.getInstance(), () -> {\n if (player.getInventory().getHeldItemSlot() != shuffle) executor.sendMessage(CoReScreen.translate(\"messages.test.shuffle.failure\").replace(\"%player%\", player.getName()));\n else executor.sendMessage(CoReScreen.translate(\"messages.test.shuffle.success\").replace(\"%player%\", player.getName()));\n }, 3);\n }\n}"
}
] | import me.overlight.corescreen.ClientSettings.Modules.ChatVisibility;
import me.overlight.corescreen.ClientSettings.Modules.ClientVersion;
import me.overlight.corescreen.ClientSettings.Modules.Locale;
import me.overlight.corescreen.ClientSettings.Modules.RenderDistance;
import me.overlight.corescreen.Test.TestCheck;
import me.overlight.corescreen.Test.Tests.Knockback;
import me.overlight.corescreen.Test.Tests.Rotation;
import me.overlight.corescreen.Test.Tests.Shuffle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | 1,900 | package me.overlight.corescreen.ClientSettings;
public class CSManager {
public final static List<CSModule> modules = new ArrayList<>();
static { | package me.overlight.corescreen.ClientSettings;
public class CSManager {
public final static List<CSModule> modules = new ArrayList<>();
static { | modules.addAll(Arrays.asList(new ClientVersion(), new Locale(), new RenderDistance(), new ChatVisibility())); | 1 | 2023-12-07 16:34:39+00:00 | 4k |
Erdi-Topuzlu/RentACar_Tobeto_Project | src/main/java/com/tobeto/RentACar/services/concretes/CarManager.java | [
{
"identifier": "ModelMapperService",
"path": "src/main/java/com/tobeto/RentACar/core/mapper/ModelMapperService.java",
"snippet": "public interface ModelMapperService {\n ModelMapper entityToDto();\n ModelMapper dtoToEntity();\n}"
},
{
"identifier": "Car",
"path": "src/main/java/com/tobeto/RentACar/entities/concretes/Car.java",
"snippet": "@Entity\n@Table(name = \"cars\")\n@Data\npublic class Car extends BaseEntity {\n\n\n @Column(name = \"kilometer\")\n private int kilometer;\n\n @Column(name = \"plate\")\n private String plate;\n\n @Column(name = \"year\")\n private int year;\n\n @Column(name = \"daily_price\")\n private double dailyPrice;\n\n @ManyToOne\n @JoinColumn(name = \"color_id\")\n private Color color;\n\n @OneToMany(mappedBy = \"car\")\n @JsonIgnore\n private List<Rental> rentals;\n\n @ManyToOne\n @JoinColumn(name = \"model_id\")\n private Model model;\n\n}"
},
{
"identifier": "CarRepository",
"path": "src/main/java/com/tobeto/RentACar/repositories/CarRepository.java",
"snippet": "public interface CarRepository extends JpaRepository<Car, Integer> {\n boolean existsByPlate(String plate);\n boolean existsById(int id);\n\n}"
},
{
"identifier": "CarBusinessRulesService",
"path": "src/main/java/com/tobeto/RentACar/rules/car/CarBusinessRulesService.java",
"snippet": "public interface CarBusinessRulesService {\n void checkIfPlateNameExists(String plate);\n void checkIfColorIdExists(int id);\n void checkIfModelIdExists(int id);\n\n void checkIfByIdExists(int id);\n}"
},
{
"identifier": "CarService",
"path": "src/main/java/com/tobeto/RentACar/services/abstracts/CarService.java",
"snippet": "public interface CarService {\n\n void add(AddCarRequest request);\n\n void update(UpdateCarRequest request);\n\n DeleteCarRequest delete(int id);\n\n List<GetAllCarResponse> getAll();\n\n GetByIdCarResponse getById(int id);\n boolean existsById(int id);\n\n\n\n}"
},
{
"identifier": "AddCarRequest",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/requests/car/AddCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AddCarRequest {\n @NotNull(message = Messages.kilometerNotEmpty)\n @Positive(message = Messages.kilometerPositive)\n private int kilometer;\n\n @NotBlank(message = Messages.plateNotEmpty)\n @Pattern(regexp = \"^[1-8][0-9]{1}[a-zA-Z]{1,3}[0-9]{1,4}$\", message = Messages.invalidPlate)\n private String plate;\n\n public void setPlate(String plate) {\n this.plate = plate != null ? plate.replaceAll(\"\\\\s\", \"\") : null;\n }\n\n @NotNull(message = Messages.yearNotEmpty)\n @Min(value = 2005,message = Messages.minModelYear)\n @Max(value = 2024, message = Messages.maxModelYear)\n private int year;\n\n @NotNull(message = Messages.dailyPriceNotEmpty)\n @Positive(message = Messages.dailyPricePositive)\n private double dailyPrice;\n\n @NotNull(message = Messages.colorIdNotEmpty)\n @Positive(message = Messages.colorIdPositive)\n private int colorId;\n\n @NotNull(message = Messages.modelIdNotEmpty)\n @Positive(message = Messages.modelIdPositive)\n private int modelId;\n}"
},
{
"identifier": "DeleteCarRequest",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/requests/car/DeleteCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class DeleteCarRequest {\n private int id;\n}"
},
{
"identifier": "UpdateCarRequest",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/requests/car/UpdateCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UpdateCarRequest {\n private int id;\n\n @NotNull(message = Messages.kilometerNotEmpty)\n @Positive(message = Messages.kilometerPositive)\n private int kilometer;\n\n @NotBlank(message = Messages.plateNotEmpty)\n @Pattern(regexp = \"^[1-8][0-9]{1}[a-zA-Z]{1,3}[0-9]{1,4}$\", message = Messages.invalidPlate)\n private String plate;\n\n public void setPlate(String plate) {\n this.plate = plate != null ? plate.replaceAll(\"\\\\s\", \"\") : null;\n }\n\n @NotNull(message = Messages.yearNotEmpty)\n @Min(value = 2005,message = Messages.minModelYear)\n @Max(value = 2024, message = Messages.maxModelYear)\n private int year;\n\n @NotNull(message = Messages.dailyPriceNotEmpty)\n @Positive(message = Messages.dailyPricePositive)\n private double dailyPrice;\n\n @NotNull(message = Messages.colorIdNotEmpty)\n @Positive(message = Messages.colorIdPositive)\n private int colorId;\n\n @NotNull(message = Messages.modelIdNotEmpty)\n @Positive(message = Messages.modelIdPositive)\n private int modelId;\n}"
},
{
"identifier": "GetAllCarResponse",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/responses/car/GetAllCarResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetAllCarResponse {\n private int id;\n private int kilometer;\n private String plate;\n private int year;\n private double dailyPrice;\n private String colorName;\n private String modelName;\n}"
},
{
"identifier": "GetByIdCarResponse",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/responses/car/GetByIdCarResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetByIdCarResponse {\n private int kilometer;\n private String plate;\n private int year;\n private double dailyPrice;\n private String colorName;\n private String modelName;\n}"
}
] | import com.tobeto.RentACar.core.mapper.ModelMapperService;
import com.tobeto.RentACar.entities.concretes.Car;
import com.tobeto.RentACar.repositories.CarRepository;
import com.tobeto.RentACar.rules.car.CarBusinessRulesService;
import com.tobeto.RentACar.services.abstracts.CarService;
import com.tobeto.RentACar.services.dtos.requests.car.AddCarRequest;
import com.tobeto.RentACar.services.dtos.requests.car.DeleteCarRequest;
import com.tobeto.RentACar.services.dtos.requests.car.UpdateCarRequest;
import com.tobeto.RentACar.services.dtos.responses.car.GetAllCarResponse;
import com.tobeto.RentACar.services.dtos.responses.car.GetByIdCarResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List; | 1,870 | package com.tobeto.RentACar.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final CarBusinessRulesService carBusinessRulesService;
@Override
public void add(AddCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public void update(UpdateCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfByIdExists(request.getId());
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public DeleteCarRequest delete(int id) {
Car car = carRepository.findById(id).orElseThrow();
carRepository.deleteById(car.getId());
return modelMapperService.entityToDto().map(car, DeleteCarRequest.class);
}
@Override | package com.tobeto.RentACar.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final CarBusinessRulesService carBusinessRulesService;
@Override
public void add(AddCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public void update(UpdateCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfByIdExists(request.getId());
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public DeleteCarRequest delete(int id) {
Car car = carRepository.findById(id).orElseThrow();
carRepository.deleteById(car.getId());
return modelMapperService.entityToDto().map(car, DeleteCarRequest.class);
}
@Override | public List<GetAllCarResponse> getAll() { | 8 | 2023-12-11 08:33:34+00:00 | 4k |
Khoshimjonov/SalahTimes | src/main/java/uz/khoshimjonov/widget/SalahWidget.java | [
{
"identifier": "WidgetTextDto",
"path": "src/main/java/uz/khoshimjonov/dto/WidgetTextDto.java",
"snippet": "public class WidgetTextDto {\n\n private String nextSalah;\n private String remainingTime;\n private Color textColor;\n\n public WidgetTextDto(String nextSalah, String remainingTime, Color textColor) {\n this.nextSalah = nextSalah;\n this.remainingTime = remainingTime;\n this.textColor = textColor;\n }\n\n public String getNextSalah() {\n return nextSalah;\n }\n\n public void setNextSalah(String nextSalah) {\n this.nextSalah = nextSalah;\n }\n\n public String getRemainingTime() {\n return remainingTime;\n }\n\n public void setRemainingTime(String remainingTime) {\n this.remainingTime = remainingTime;\n }\n\n public Color getTextColor() {\n return textColor;\n }\n\n public void setTextColor(Color textColor) {\n this.textColor = textColor;\n }\n}"
},
{
"identifier": "ConfigurationManager",
"path": "src/main/java/uz/khoshimjonov/service/ConfigurationManager.java",
"snippet": "public class ConfigurationManager {\n\n private static final String CONFIG_FILE = \"config.properties\";\n\n private static Properties properties;\n\n private static volatile ConfigurationManager instance;\n\n public boolean apiSettingsUpdated = true;\n\n private ConfigurationManager() {\n properties = new Properties();\n loadConfig();\n }\n\n public static ConfigurationManager getInstance() {\n if (instance == null) {\n synchronized (ConfigurationManager.class) {\n if (instance == null) {\n instance = new ConfigurationManager();\n }\n }\n }\n return instance;\n }\n\n public int getSchool() {\n return Integer.parseInt(properties.getProperty(\"school\", \"1\"));\n }\n\n public void setSchool(int school) {\n properties.setProperty(\"school\", String.valueOf(school));\n saveConfig();\n }\n\n public int getMethod() {\n return Integer.parseInt(properties.getProperty(\"method\", \"14\"));\n }\n\n public void setMethod(int method) {\n properties.setProperty(\"method\", String.valueOf(method));\n saveConfig();\n }\n\n public double getLatitude() {\n return Double.parseDouble(properties.getProperty(\"latitude\", \"0.0\"));\n }\n\n public void setLatitude(double latitude) {\n properties.setProperty(\"latitude\", String.valueOf(latitude));\n saveConfig();\n }\n\n public double getLongitude() {\n return Double.parseDouble(properties.getProperty(\"longitude\", \"0.0\"));\n }\n\n public void setLongitude(double longitude) {\n properties.setProperty(\"longitude\", String.valueOf(longitude));\n saveConfig();\n }\n\n public boolean getLookAndFeelEnabled() {\n return Boolean.parseBoolean(properties.getProperty(\"lookAndFeelEnabled\", \"true\"));\n }\n\n public void setLookAndFeelEnabled(boolean lookAndFeelEnabled) {\n properties.setProperty(\"lookAndFeelEnabled\", String.valueOf(lookAndFeelEnabled));\n saveConfig();\n }\n\n public boolean isDraggable() {\n return Boolean.parseBoolean(properties.getProperty(\"draggable\", \"true\"));\n }\n\n public void setDraggable(boolean draggable) {\n properties.setProperty(\"draggable\", String.valueOf(draggable));\n saveConfig();\n }\n\n public boolean isAlwaysOnTop() {\n return Boolean.parseBoolean(properties.getProperty(\"alwaysOnTop\", \"true\"));\n }\n\n public void setAlwaysOnTop(boolean alwaysOnTop) {\n properties.setProperty(\"alwaysOnTop\", String.valueOf(alwaysOnTop));\n saveConfig();\n }\n\n public int getUpdateDelay() {\n return Integer.parseInt(properties.getProperty(\"updateDelay\", \"1\"));\n }\n\n public void setUpdateDelay(int updateDelay) {\n properties.setProperty(\"updateDelay\", String.valueOf(updateDelay));\n saveConfig();\n }\n\n public int getPointX() {\n return Integer.parseInt(properties.getProperty(\"pointX\", \"100\"));\n }\n\n public void setPointX(int pointX) {\n properties.setProperty(\"pointX\", String.valueOf(pointX));\n saveConfig();\n }\n\n public int getPointY() {\n return Integer.parseInt(properties.getProperty(\"pointY\", \"100\"));\n }\n\n public void setPointY(int pointY) {\n properties.setProperty(\"pointY\", String.valueOf(pointY));\n saveConfig();\n }\n\n public boolean isNotification() {\n return Boolean.parseBoolean(properties.getProperty(\"notification\", \"true\"));\n }\n\n public void setNotification(boolean notification) {\n properties.setProperty(\"notification\", String.valueOf(notification));\n saveConfig();\n }\n\n public String getUserLanguage() {\n return properties.getProperty(\"language\", \"en\");\n }\n\n public void setUserLanguage(String userLanguage) {\n properties.setProperty(\"language\", userLanguage);\n saveConfig();\n }\n\n public int getNotificationBeforeMinutes() {\n return Integer.parseInt(properties.getProperty(\"notificationBeforeMinutes\", \"30\"));\n }\n\n public void setNotificationBeforeMinutes(int minutes) {\n properties.setProperty(\"notificationBeforeMinutes\", String.valueOf(minutes));\n saveConfig();\n }\n\n private void loadConfig() {\n try {\n Path path = Path.of(CONFIG_FILE);\n if (!Files.exists(path)) {\n Files.createFile(path);\n }\n InputStream input = new FileInputStream(CONFIG_FILE);\n properties.load(input);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void saveConfig() {\n try (OutputStream output = new FileOutputStream(CONFIG_FILE)) {\n properties.store(output, \"Configuration File\");\n loadConfig();\n apiSettingsUpdated = true;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"identifier": "LanguageHelper",
"path": "src/main/java/uz/khoshimjonov/service/LanguageHelper.java",
"snippet": "public class LanguageHelper {\n private static final String BASE_NAME = \"messages\";\n private static ResourceBundle resourceBundle;\n\n private static final ConfigurationManager configurationManager = ConfigurationManager.getInstance();\n\n\n public static void setLocale(String languageCode) {\n Locale locale = Locale.of(languageCode);\n resourceBundle = ResourceBundle.getBundle(BASE_NAME, locale);\n }\n\n public static String getText(String key) {\n return internalGetText(key);\n }\n\n public static String[] getAvailableLocales() {\n Locale[] availableLocales = Locale.getAvailableLocales();\n Set<String> locales = new HashSet<>();\n for (Locale availableLocale : availableLocales) {\n String language = availableLocale.getLanguage();\n if (!language.trim().isEmpty() && propertiesFileExists(language)) {\n locales.add(language);\n }\n }\n return locales.toArray(new String[0]);\n }\n\n private static boolean propertiesFileExists(String languageCode) {\n String fileName = \"/messages_\" + languageCode + \".properties\";\n try (InputStream in = LanguageHelper.class.getResourceAsStream(fileName)) {\n return in != null;\n } catch (Exception e) {\n return false;\n }\n }\n\n\n private static String internalGetText(String key) {\n if (resourceBundle == null) {\n setLocale(configurationManager.getUserLanguage());\n }\n\n try {\n return resourceBundle.getString(key);\n } catch (Exception e) {\n return \"\";\n }\n }\n}"
},
{
"identifier": "SalahTimeService",
"path": "src/main/java/uz/khoshimjonov/service/SalahTimeService.java",
"snippet": "public class SalahTimeService {\n private final ConfigurationManager configurationManager = ConfigurationManager.getInstance();\n private final PrayerTimeScheduler prayerTimeScheduler = PrayerTimeScheduler.getInstance();\n private final Map<String, LocalTime> timings;\n private final DateTimeFormatter formatter;\n private final Api api;\n private LocalTime tomorrowFajr;\n private LocalDate currentDate;\n private Hijri hijriDate;\n\n public Map<String, LocalTime> getTimings() {\n return timings;\n }\n\n public Hijri getHijriDate() {\n return hijriDate;\n }\n\n public SalahTimeService() {\n api = new Api();\n formatter = DateTimeFormatter.ofPattern(\"dd-MM-yyyy\");\n currentDate = LocalDate.now();\n timings = new LinkedHashMap<>();\n }\n\n public WidgetTextDto getWidgetText(TrayIcon trayIcon) {\n try {\n LocalTime currentTime = LocalTime.now();\n getTimingsIfNeeded(trayIcon);\n if (timings.get(title(\"ishaTitle\")).isBefore(currentTime)){\n LocalDateTime tomorrow = LocalDateTime.of(LocalDate.now().plusDays(1), tomorrowFajr);\n LocalDateTime today = LocalDateTime.now();\n return getResultText(today.until(tomorrow, ChronoUnit.SECONDS), title(\"fajrTitle\"), tomorrowFajr);\n } else {\n for (Map.Entry<String, LocalTime> entry : timings.entrySet()) {\n if (currentTime.isBefore(entry.getValue())) {\n LocalTime nextPrayerTime = entry.getValue();\n return getResultText(currentTime.until(nextPrayerTime, ChronoUnit.SECONDS), entry.getKey(), entry.getValue());\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return new WidgetTextDto(LanguageHelper.getText(\"cantGetTitle\"), \"\", new Color(185, 73, 58));\n }\n\n private void getTimingsIfNeeded(TrayIcon trayIcon) throws Exception {\n LocalDate realDate = LocalDate.now();\n if (configurationManager.apiSettingsUpdated || !currentDate.equals(realDate) || timings.isEmpty()){\n currentDate = realDate;\n timings.clear();\n\n PrayerTimesResponse prayerTimes = api.getSalahTimes(currentDate.format(formatter), configurationManager.getSchool(), configurationManager.getMethod(), String.valueOf(configurationManager.getLatitude()), String.valueOf(configurationManager.getLongitude()));\n PrayerTimesResponse tomorrowPrayerTimes = api.getSalahTimes(currentDate.plusDays(1).format(formatter), configurationManager.getSchool(), configurationManager.getMethod(), String.valueOf(configurationManager.getLatitude()), String.valueOf(configurationManager.getLongitude()));\n if (prayerTimes == null || tomorrowPrayerTimes == null){\n throw new RuntimeException();\n }\n\n Timings tomorrowTimings = tomorrowPrayerTimes.getData().getTimings();\n tomorrowFajr = LocalTime.parse(tomorrowTimings.getFajr());\n\n Timings todaysTimings = prayerTimes.getData().getTimings();\n timings.put(title(\"fajrTitle\"), LocalTime.parse(todaysTimings.getFajr()));\n timings.put(title(\"sunriseTitle\"), LocalTime.parse(todaysTimings.getSunrise()));\n timings.put(title(\"dhuhrTitle\"), LocalTime.parse(todaysTimings.getDhuhr()));\n timings.put(title(\"asrTitle\"), LocalTime.parse(todaysTimings.getAsr()));\n timings.put(title(\"maghribTitle\"), LocalTime.parse(todaysTimings.getMaghrib()));\n timings.put(title(\"ishaTitle\"), LocalTime.parse(todaysTimings.getIsha()));\n hijriDate = prayerTimes.getData().getDate().getHijri();\n configurationManager.apiSettingsUpdated = false;\n if (configurationManager.isNotification()) {\n prayerTimeScheduler.checkAndNotifyPrayerTimes(timings, trayIcon);\n }\n }\n }\n\n private String title(String key) {\n return LanguageHelper.getText(key);\n }\n\n private WidgetTextDto getResultText(long remaining, String Salah, LocalTime time) {\n long hours = remaining / 3600;\n long minutes = (remaining % 3600) / 60;\n long seconds = remaining % 60;\n Color color = remaining > 1800 ? Color.WHITE : new Color(185, 73, 58);\n return new WidgetTextDto(String.format(title(\"widgetTextTitle\"), Salah, time), String.format(title(\"remainingTitle\"), hours, minutes, seconds), color);\n }\n}"
}
] | import uz.khoshimjonov.dto.WidgetTextDto;
import uz.khoshimjonov.service.ConfigurationManager;
import uz.khoshimjonov.service.LanguageHelper;
import uz.khoshimjonov.service.SalahTimeService;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | 3,469 | package uz.khoshimjonov.widget;
public class SalahWidget {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final ConfigurationManager configurationManager = ConfigurationManager.getInstance();
private final SalahTimeService salahTimeService = new SalahTimeService();
private FrameDragListener frameDragListener = null;
private SalahTimesWindow salahTimesWindow;
private final TrayIcon trayIcon;
private final SystemTray tray;
private final boolean SET_LOOK_AND_FEEL;
private final int UPDATE_DELAY;
private final int POINT_X;
private final int POINT_Y;
public SalahWidget() {
try {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
throw new UnsupportedOperationException();
}
this.SET_LOOK_AND_FEEL = configurationManager.getLookAndFeelEnabled();
this.UPDATE_DELAY = configurationManager.getUpdateDelay();
this.POINT_X = configurationManager.getPointX();
this.POINT_Y = configurationManager.getPointY();
this.tray = SystemTray.getSystemTray();
BufferedImage trayIconImage = ImageIO.read(Objects.requireNonNull(getClass().getResource("/images/app.png")));
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
this.trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH), LanguageHelper.getText("tooltipTitle"));
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
showSalahTimesWindow(e);
}
}
});
tray.add(trayIcon);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void displayWidget() {
Runnable runnable = () -> {
if (SET_LOOK_AND_FEEL) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
}
final JDialog dialog = new JDialog();
final JLabel timeLabel = new AntiAliasedLabel();
final JLabel remainingLabel = new AntiAliasedLabel();
dialog.setLayout(new FlowLayout(FlowLayout.LEFT));
dialog.requestFocus();
dialog.setMinimumSize(new Dimension(350, 30));
dialog.setFocusableWindowState(false);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setUndecorated(true);
dialog.setBackground(new Color(0, 0, 0, 0));
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.add(timeLabel);
dialog.add(remainingLabel);
dialog.toFront();
scheduler.scheduleAtFixedRate(() -> { | package uz.khoshimjonov.widget;
public class SalahWidget {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final ConfigurationManager configurationManager = ConfigurationManager.getInstance();
private final SalahTimeService salahTimeService = new SalahTimeService();
private FrameDragListener frameDragListener = null;
private SalahTimesWindow salahTimesWindow;
private final TrayIcon trayIcon;
private final SystemTray tray;
private final boolean SET_LOOK_AND_FEEL;
private final int UPDATE_DELAY;
private final int POINT_X;
private final int POINT_Y;
public SalahWidget() {
try {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
throw new UnsupportedOperationException();
}
this.SET_LOOK_AND_FEEL = configurationManager.getLookAndFeelEnabled();
this.UPDATE_DELAY = configurationManager.getUpdateDelay();
this.POINT_X = configurationManager.getPointX();
this.POINT_Y = configurationManager.getPointY();
this.tray = SystemTray.getSystemTray();
BufferedImage trayIconImage = ImageIO.read(Objects.requireNonNull(getClass().getResource("/images/app.png")));
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
this.trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH), LanguageHelper.getText("tooltipTitle"));
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
showSalahTimesWindow(e);
}
}
});
tray.add(trayIcon);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void displayWidget() {
Runnable runnable = () -> {
if (SET_LOOK_AND_FEEL) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
}
final JDialog dialog = new JDialog();
final JLabel timeLabel = new AntiAliasedLabel();
final JLabel remainingLabel = new AntiAliasedLabel();
dialog.setLayout(new FlowLayout(FlowLayout.LEFT));
dialog.requestFocus();
dialog.setMinimumSize(new Dimension(350, 30));
dialog.setFocusableWindowState(false);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setUndecorated(true);
dialog.setBackground(new Color(0, 0, 0, 0));
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.add(timeLabel);
dialog.add(remainingLabel);
dialog.toFront();
scheduler.scheduleAtFixedRate(() -> { | WidgetTextDto widgetText = salahTimeService.getWidgetText(trayIcon); | 0 | 2023-12-07 13:40:16+00:00 | 4k |
Akshar062/MovieReviews | app/src/main/java/com/akshar/moviereviews/ApiUtils/AllMovieApi.java | [
{
"identifier": "AllModel",
"path": "app/src/main/java/com/akshar/moviereviews/Models/AllModel.java",
"snippet": "public class AllModel {\n\n public int page;\n\n @SerializedName(\"results\")\n public List<Result> results;\n\n @SerializedName(\"total_pages\")\n public int totalPages;\n\n @SerializedName(\"total_results\")\n public int totalResults;\n\n public static class Result {\n\n public boolean adult;\n\n @SerializedName(\"backdrop_path\")\n public String backdropPath;\n\n public int id;\n\n // Common fields\n public String title;\n\n @SerializedName(\"original_language\")\n public String originalLanguage;\n\n @SerializedName(\"original_title\")\n public String originalTitle;\n\n public String overview;\n\n @SerializedName(\"poster_path\")\n public String posterPath;\n\n @SerializedName(\"media_type\")\n public String mediaType;\n\n @SerializedName(\"genre_ids\")\n public List<Integer> genreIds;\n\n public double popularity;\n\n @SerializedName(\"release_date\")\n public String releaseDate;\n\n @SerializedName(\"video\")\n public boolean video;\n\n @SerializedName(\"vote_average\")\n public double voteAverage;\n\n @SerializedName(\"vote_count\")\n public int voteCount;\n\n // Movie-specific fields\n public String name; // For TV shows\n\n @SerializedName(\"first_air_date\")\n public String firstAirDate; // For TV shows\n\n @SerializedName(\"origin_country\")\n public List<String> originCountry; // For TV shows\n\n // Person-specific fields\n @SerializedName(\"known_for_department\")\n public String knownForDepartment; // For people\n\n @SerializedName(\"profile_path\")\n public String profilePath; // For people\n\n @SerializedName(\"gender\")\n public int gender; // For people\n\n @SerializedName(\"known_for\")\n public List<KnownFor> knownFor; // For people\n\n public boolean isAdult() {\n return adult;\n }\n\n public String getBackdropPath() {\n return backdropPath;\n }\n\n public int getId() {\n return id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getOriginalLanguage() {\n return originalLanguage;\n }\n\n public String getOriginalTitle() {\n return originalTitle;\n }\n\n public String getOverview() {\n return overview;\n }\n\n public String getPosterPath() {\n return posterPath;\n }\n\n public String getMediaType() {\n return mediaType;\n }\n\n public List<Integer> getGenreIds() {\n return genreIds;\n }\n\n public double getPopularity() {\n return popularity;\n }\n\n public String getReleaseDate() {\n return releaseDate;\n }\n\n public boolean isVideo() {\n return video;\n }\n\n public double getVoteAverage() {\n return voteAverage;\n }\n\n public int getVoteCount() {\n return voteCount;\n }\n\n public String getName() {\n return name;\n }\n\n public String getFirstAirDate() {\n return firstAirDate;\n }\n\n public List<String> getOriginCountry() {\n return originCountry;\n }\n\n public String getKnownForDepartment() {\n return knownForDepartment;\n }\n\n public String getProfilePath() {\n return profilePath;\n }\n\n public int getGender() {\n return gender;\n }\n\n public List<KnownFor> getKnownFor() {\n return knownFor;\n }\n\n public static class KnownFor {\n public boolean adult;\n\n @SerializedName(\"backdrop_path\")\n public String backdropPath;\n\n public int id;\n\n public String title;\n\n public String name;\n\n @SerializedName(\"original_language\")\n public String originalLanguage;\n\n @SerializedName(\"original_title\")\n public String originalTitle;\n\n public String overview;\n\n @SerializedName(\"poster_path\")\n public String posterPath;\n\n @SerializedName(\"media_type\")\n public String mediaType;\n\n @SerializedName(\"genre_ids\")\n public List<Integer> genreIds;\n\n public double popularity;\n\n @SerializedName(\"release_date\")\n public String releaseDate;\n\n @SerializedName(\"video\")\n public boolean video;\n\n @SerializedName(\"vote_average\")\n public double voteAverage;\n\n @SerializedName(\"vote_count\")\n public int voteCount;\n\n public String getName() {\n return name;\n }\n\n public boolean isAdult() {\n return adult;\n }\n\n public String getBackdropPath() {\n return backdropPath;\n }\n\n public int getId() {\n return id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getOriginalLanguage() {\n return originalLanguage;\n }\n\n public String getOriginalTitle() {\n return originalTitle;\n }\n\n public String getOverview() {\n return overview;\n }\n\n public String getPosterPath() {\n return posterPath;\n }\n\n public String getMediaType() {\n return mediaType;\n }\n\n public List<Integer> getGenreIds() {\n return genreIds;\n }\n\n public double getPopularity() {\n return popularity;\n }\n\n public String getReleaseDate() {\n return releaseDate;\n }\n\n public boolean isVideo() {\n return video;\n }\n\n public double getVoteAverage() {\n return voteAverage;\n }\n\n public int getVoteCount() {\n return voteCount;\n }\n }\n\n }\n\n public int getPage() {\n return page;\n }\n\n public List<Result> getResults() {\n return results;\n }\n\n public int getTotalPages() {\n return totalPages;\n }\n\n public int getTotalResults() {\n return totalResults;\n }\n}"
},
{
"identifier": "MovieModel",
"path": "app/src/main/java/com/akshar/moviereviews/Models/MovieModel.java",
"snippet": "public class MovieModel {\n private int page;\n private List<Result> results;\n private int totalResults;\n private int totalPages;\n\n public int getTotalResults() {\n return totalResults;\n }\n\n public void setTotalResults(int totalResults) {\n this.totalResults = totalResults;\n }\n\n public int getTotalPages() {\n return totalPages;\n }\n\n public void setTotalPages(int totalPages) {\n this.totalPages = totalPages;\n }\n public int getPage() {\n return page;\n }\n\n public void setPage(int page) {\n this.page = page;\n }\n\n public List<Result> getResults() {\n return results;\n }\n\n public void setResults(List<Result> results) {\n this.results = results;\n }\n\n public static class Result {\n\n @SerializedName(\"adult\")\n private boolean adult;\n\n @SerializedName(\"backdrop_path\")\n private String backdropPath;\n @SerializedName(\"id\")\n private int id;\n @SerializedName(\"title\")\n private String title;\n\n @SerializedName(\"original_language\")\n private String originalLanguage;\n\n @SerializedName(\"original_title\")\n private String originalTitle;\n\n @SerializedName(\"overview\")\n private String overview;\n\n @SerializedName(\"poster_path\")\n private String posterPath;\n\n @SerializedName(\"media_type\")\n private String mediaType;\n\n @SerializedName(\"genre_ids\")\n private List<Integer> genreIds;\n\n @SerializedName(\"popularity\")\n private double popularity;\n\n @SerializedName(\"release_date\")\n private String releaseDate;\n\n @SerializedName(\"video\")\n private boolean video;\n\n @SerializedName(\"vote_average\")\n private double voteAverage;\n\n @SerializedName(\"vote_count\")\n private int voteCount;\n\n public boolean isAdult() {\n return adult;\n }\n\n public void setAdult(boolean adult) {\n this.adult = adult;\n }\n\n public String getBackdropPath() {\n return backdropPath;\n }\n\n public void setBackdropPath(String backdropPath) {\n this.backdropPath = backdropPath;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getOriginalLanguage() {\n return originalLanguage;\n }\n\n public void setOriginalLanguage(String originalLanguage) {\n this.originalLanguage = originalLanguage;\n }\n\n public String getOriginalTitle() {\n return originalTitle;\n }\n\n public void setOriginalTitle(String originalTitle) {\n this.originalTitle = originalTitle;\n }\n\n public String getOverview() {\n return overview;\n }\n\n public void setOverview(String overview) {\n this.overview = overview;\n }\n\n public String getPosterPath() {\n return posterPath;\n }\n\n public void setPosterPath(String posterPath) {\n this.posterPath = posterPath;\n }\n\n public String getMediaType() {\n return mediaType;\n }\n\n public void setMediaType(String mediaType) {\n this.mediaType = mediaType;\n }\n\n public List<Integer> getGenreIds() {\n return genreIds;\n }\n\n public void setGenreIds(List<Integer> genreIds) {\n this.genreIds = genreIds;\n }\n\n public double getPopularity() {\n return popularity;\n }\n\n public void setPopularity(double popularity) {\n this.popularity = popularity;\n }\n\n public String getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(String releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n public boolean isVideo() {\n return video;\n }\n\n public void setVideo(boolean video) {\n this.video = video;\n }\n\n public double getVoteAverage() {\n return voteAverage;\n }\n\n public void setVoteAverage(double voteAverage) {\n this.voteAverage = voteAverage;\n }\n\n public int getVoteCount() {\n return voteCount;\n }\n\n public void setVoteCount(int voteCount) {\n this.voteCount = voteCount;\n }\n }\n}"
}
] | import com.akshar.moviereviews.Models.AllModel;
import com.akshar.moviereviews.Models.MovieModel;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query; | 2,769 | package com.akshar.moviereviews.ApiUtils;
public interface AllMovieApi {
@GET("trending/all/week") | package com.akshar.moviereviews.ApiUtils;
public interface AllMovieApi {
@GET("trending/all/week") | Call<AllModel> getTrendingAll(@Query("api_key") String apiKey); | 0 | 2023-12-05 10:20:16+00:00 | 4k |
ShardMC/arte | common/src/main/java/io/shardmc/arte/common/pack/manager/PackManager.java | [
{
"identifier": "Arte",
"path": "common/src/main/java/io/shardmc/arte/common/Arte.java",
"snippet": "public interface Arte {\n ArteLogger logger();\n ArteConfig config();\n PackManager getPackManager();\n\n File getDataFolder();\n File getConfigFile();\n\n URL getResourceUrl(String path) throws IOException;\n\n default InputStream getResourceStream(String path) throws IOException {\n return this.getResourceUrl(path).openStream();\n }\n\n default File getResourceFile(String path) throws IOException {\n return new File(this.getResourceUrl(path).getFile());\n }\n}"
},
{
"identifier": "ArteConfig",
"path": "common/src/main/java/io/shardmc/arte/common/config/ArteConfig.java",
"snippet": "public abstract class ArteConfig<T> {\n\n protected final Arte arte;\n protected final Path file;\n\n protected final ArteConfigAdapter<T> serializer;\n\n protected int port;\n protected String address;\n\n protected String prompt;\n protected PackMode mode;\n\n protected boolean useCache;\n protected boolean scramble;\n\n protected Set<String> namespaces;\n protected boolean whitelist;\n\n public ArteConfig(Arte arte, boolean reload) {\n this.arte = arte;\n this.file = arte.getConfigFile().toPath();\n\n this.serializer = this.serializer();\n\n if (reload)\n this.reload();\n }\n\n public ArteConfig(Arte arte) {\n this(arte, true);\n }\n\n protected void read() {\n this.port = this.serializer.read(\"port\");\n this.address = this.serializer.read(\"address\");\n\n this.prompt = this.serializer.read(\"prompt\");\n this.mode = PackMode.valueOf(this.serializer.read(\"mode\"));\n\n this.useCache = this.serializer.read(\"useCache\");\n this.scramble = this.serializer.read(\"scramble\");\n\n this.namespaces = new HashSet<>(this.serializer.readList(\"namespaces\"));\n this.whitelist = this.serializer.read(\"whitelist\");\n }\n\n protected void write() {\n this.serializer.write(\"port\", this.port);\n this.serializer.write(\"address\", this.address);\n\n this.serializer.write(\"prompt\", this.prompt);\n this.serializer.write(\"mode\", this.mode.toString());\n\n this.serializer.write(\"use-cache\", this.useCache);\n this.serializer.write(\"scramble\", this.scramble);\n\n this.serializer.write(\"namespaces\", this.namespaces);\n this.serializer.write(\"whitelist\", this.whitelist);\n }\n\n protected abstract T defaults() throws IOException;\n\n protected abstract T create() throws IOException;\n protected abstract void dump(T r) throws IOException;\n\n protected abstract ArteConfigAdapter<T> serializer();\n\n protected InputStream getResource(Path path) throws IOException {\n return this.arte.getResourceStream(path.getFileName().toString());\n }\n\n protected File getResourceFile(Path path) throws IOException {\n return this.arte.getResourceFile(path.getFileName().toString());\n }\n\n private void saveDefault() throws IOException {\n this.arte.logger().info(\"Config file doesn't exist! Copying from files...\");\n\n Files.createDirectories(this.file.getParent());\n try (InputStream stream = this.getResource(this.file)) {\n Files.copy(stream, this.file);\n }\n }\n\n public void reload() {\n try {\n if (Files.notExists(this.file))\n this.saveDefault();\n\n this.serializer.update(this.create());\n this.serializer.updateDefaults(this.defaults());\n\n this.read();\n } catch (IOException e) {\n this.arte.logger().throwing(e, \"Failed to reload config.\");\n }\n }\n\n public void save() {\n try {\n if (Files.notExists(this.file)) {\n this.saveDefault();\n this.reload();\n }\n\n this.write();\n this.dump(this.serializer.file);\n } catch (IOException e) {\n this.arte.logger().throwing(e, \"Failed to save config.\");\n }\n }\n\n public int getPort() {\n return port;\n }\n\n public String getAddress() {\n return address;\n }\n\n public PackMode getMode() {\n return mode;\n }\n\n public String getPrompt() {\n return prompt;\n }\n\n public boolean shouldUseCache() {\n return useCache;\n }\n\n public boolean shouldScramble() {\n return scramble;\n }\n\n public Set<String> getNamespaces() {\n return namespaces;\n }\n\n public boolean isWhitelist() {\n return whitelist;\n }\n}"
},
{
"identifier": "PackMode",
"path": "common/src/main/java/io/shardmc/arte/common/config/data/PackMode.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic enum PackMode {\n BASIC(BasicPackZipper::new),\n CACHED(CachedPackZipper::new);\n\n private final PackZipperCreator creator;\n\n PackMode(PackZipperCreator creator) {\n this.creator = creator;\n }\n\n public PackZipperCreator creator() {\n return this.creator;\n }\n}"
},
{
"identifier": "PackZipper",
"path": "common/src/main/java/io/shardmc/arte/common/pack/zipper/PackZipper.java",
"snippet": "public abstract class PackZipper {\n\n protected final Path root;\n protected final Path output;\n\n protected final Path assets;\n protected final ArteLogger logger;\n\n protected Collection<BuiltPack> packs = new ArrayList<>();\n\n public PackZipper(ArteLogger logger, Path root, Path output) throws IOException {\n this.root = Files.createDirectories(root);\n this.output = Files.createDirectories(output);\n\n this.assets = Files.createDirectories(this.root.resolve(\"assets\"));\n this.logger = logger;\n }\n\n protected Context createContext() {\n return new Context(this.logger, this.root, this.output, \"pack.mcmeta\", \"pack.png\");\n }\n\n public void zip(FilterList list, boolean scramble, Consumer<BuiltPack> consumer) {\n this.logger.info(\"Pack zipper started re-zipping!\");\n Context context = this.createContext();\n this.zip(context);\n\n this.packs = context.zip(list, scramble, consumer);\n }\n\n public void clean() throws IOException {\n try (Stream<Path> stream = Files.list(this.output)) {\n stream.parallel().forEach(path -> {\n try {\n Files.delete(path);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n }\n\n this.packs.clear();\n }\n\n public Collection<BuiltPack> getPacks() {\n return packs;\n }\n\n protected abstract void zip(Context context);\n\n public static class Context {\n\n protected final ArteLogger logger;\n\n protected final Path root;\n protected final Path output;\n\n protected final List<Namespace> groups = new ArrayList<>();\n protected final List<PackFile> defaults = new ArrayList<>();\n\n public Context(ArteLogger logger, Path root, Path output, String... defaults) {\n this.logger = logger;\n\n this.root = root;\n this.output = output;\n\n for (String path : defaults) {\n this.defaults.add(new BasicPackFile(root.resolve(path)));\n }\n }\n\n public Context addNamespace(String name, Collection<Path> files) {\n this.groups.add(new Namespace(name, files));\n return this;\n }\n\n public Collection<BuiltPack> zip(FilterList list, boolean scramble, Consumer<BuiltPack> consumer) {\n List<BuiltPack> packs = new ArrayList<>();\n ThreadPool pool = new ThreadPool(this.logger);\n\n for (Namespace group : this.groups) {\n pool.add(() -> {\n try {\n Path generated = this.output.resolve(group.name() + \".zip\");\n try (Zip zip = new Zip(this.root, generated, scramble)) {\n group.zip(zip);\n\n for (PackFile file : this.defaults) {\n file.zip(zip);\n }\n }\n\n boolean force = !(list.elements().contains(\n group.name())\n ) && list.whitelist();\n\n BuiltPack pack = new BuiltPack(generated, force);\n\n consumer.accept(pack);\n packs.add(pack);\n } catch (IOException | ExecutionException | InterruptedException e) {\n this.logger.throwing(e, \"Failed to zip pack part: '\" + group + \"'\");\n }\n });\n }\n\n pool.start();\n return packs;\n }\n }\n}"
},
{
"identifier": "PackZipperCreator",
"path": "common/src/main/java/io/shardmc/arte/common/util/lambda/PackZipperCreator.java",
"snippet": "@FunctionalInterface\npublic interface PackZipperCreator {\n PackZipper create(Arte arte, Path root, Path output) throws IOException;\n}"
},
{
"identifier": "WebServer",
"path": "common/src/main/java/io/shardmc/arte/common/web/WebServer.java",
"snippet": "public class WebServer {\n\n private final ArteLogger logger;\n private final String address;\n\n private boolean enabled = false;\n private HttpServer server;\n\n public WebServer(ArteLogger logger, String address) {\n this.logger = logger;\n this.address = address;\n\n this.logger.info(\"Initialized web-server!\");\n }\n\n public WebServer(Arte arte, String address) {\n this(arte.logger(), address);\n }\n\n public WebServer(Arte arte) {\n this(arte, arte.config().getAddress());\n }\n\n public void start(int port) {\n // Server is already enabled stop code\n if (this.enabled)\n return;\n\n try {\n this.server = HttpServer.create(new InetSocketAddress(port), 0);\n\n this.server.setExecutor(null);\n this.server.start();\n this.enabled = true;\n } catch (Exception e) {\n this.stop();\n }\n }\n\n public String getAddress(Hostable hostable) {\n String address = hostable.getName();\n\n if (!address.startsWith(\"/\"))\n address = \"/\" + address;\n\n return \"http://\" + this.address + \":\" + this.server.getAddress().getPort() + address;\n }\n\n public void host(Hostable hostable) throws IOException {\n hostable.host(this);\n }\n\n public void host(Hostable hostable, Path file) throws IOException {\n this.host(file, hostable.getName());\n }\n\n public void host(Path file, String path) throws IOException {\n if (!path.startsWith(\"/\"))\n path = \"/\" + path;\n\n this.logger.info(\"Hosting\", file.toString(), \"at:\", \"'\" + path + \"'\");\n this.server.createContext(path, new FileHandler(file));\n }\n\n public void stop() {\n this.server.stop(0);\n this.enabled = false;\n }\n\n public void restart(int port) {\n if (this.enabled) {\n this.stop();\n }\n\n this.start(port);\n }\n\n static class FileHandler implements HttpHandler {\n\n private final byte[] data;\n\n public FileHandler(byte[] data) {\n this.data = data;\n }\n\n public FileHandler(Path path) throws IOException {\n this(Files.readAllBytes(path));\n }\n\n @Override\n public void handle(HttpExchange t) throws IOException {\n t.sendResponseHeaders(200, this.data.length);\n\n try (OutputStream stream = t.getResponseBody()) {\n stream.write(this.data);\n }\n }\n }\n}"
}
] | import io.shardmc.arte.common.Arte;
import io.shardmc.arte.common.config.ArteConfig;
import io.shardmc.arte.common.config.data.FilterList;
import io.shardmc.arte.common.config.data.PackMode;
import io.shardmc.arte.common.pack.zipper.PackZipper;
import io.shardmc.arte.common.util.lambda.PackZipperCreator;
import io.shardmc.arte.common.web.WebServer;
import java.io.IOException;
import java.nio.file.Path; | 3,021 | package io.shardmc.arte.common.pack.manager;
public class PackManager {
protected final Arte arte;
protected final WebServer server;
protected final Path root;
protected final Path output;
protected PackZipper zipper;
public PackManager(Arte arte) {
this.arte = arte;
this.server = new WebServer(this.arte);
this.root = this.arte.getDataFolder()
.toPath().resolve("resourcepack");
this.output = this.arte.getDataFolder()
.toPath().resolve("generated");
ArteConfig config = this.arte.config();
this.reload(config.shouldUseCache()
? PackMode.CACHED : config.getMode());
}
public void reload() {
this.reload(this.arte.config().getMode());
}
protected void reload(PackMode mode) {
this.reload(mode.creator());
}
| package io.shardmc.arte.common.pack.manager;
public class PackManager {
protected final Arte arte;
protected final WebServer server;
protected final Path root;
protected final Path output;
protected PackZipper zipper;
public PackManager(Arte arte) {
this.arte = arte;
this.server = new WebServer(this.arte);
this.root = this.arte.getDataFolder()
.toPath().resolve("resourcepack");
this.output = this.arte.getDataFolder()
.toPath().resolve("generated");
ArteConfig config = this.arte.config();
this.reload(config.shouldUseCache()
? PackMode.CACHED : config.getMode());
}
public void reload() {
this.reload(this.arte.config().getMode());
}
protected void reload(PackMode mode) {
this.reload(mode.creator());
}
| protected void reload(PackZipperCreator zipper) { | 4 | 2023-12-09 10:58:32+00:00 | 4k |
nurseld/RentACar | pair2/src/main/java/com/tobeto/pair2/services/concretes/CarManager.java | [
{
"identifier": "ModelMapperService",
"path": "pair2/src/main/java/com/tobeto/pair2/core/utilities/mapper/ModelMapperService.java",
"snippet": "public interface ModelMapperService {\n ModelMapper forResponse();\n ModelMapper forRequest();\n\n\n}"
},
{
"identifier": "Car",
"path": "pair2/src/main/java/com/tobeto/pair2/entitites/Car.java",
"snippet": "@Table(name = \"cars\")\n@Entity\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Car {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer id;\n\n @Column(name = \"kilometer\")\n private int kilometer;\n\n @Column(name = \"plate\")\n private String plate;\n\n @Column(name = \"year\")\n private int year;\n\n @Column(name = \"daily_price\")\n private double dailyPrice;\n\n @ManyToOne\n @JoinColumn(name = \"model_id\")\n private Model model;\n\n @ManyToOne\n @JoinColumn(name = \"color_id\")\n private Color color;\n\n @OneToMany(mappedBy = \"car\")\n @JsonIgnore\n private List<Rental> rentals;\n\n}"
},
{
"identifier": "CarRepository",
"path": "pair2/src/main/java/com/tobeto/pair2/repositories/CarRepository.java",
"snippet": "public interface CarRepository extends JpaRepository<Car,Integer> {\n boolean existsCarByPlate(String plate);\n}"
},
{
"identifier": "CarService",
"path": "pair2/src/main/java/com/tobeto/pair2/services/abstracts/CarService.java",
"snippet": "public interface CarService {\n void add(AddCarRequest request);\n void update(UpdateCarRequest request);\n void delete(Integer id);\n List<GetAllCarResponse> getAll();\n GetByIdCarResponse getById(int id);\n boolean existsByCarId(int carId);\n}"
},
{
"identifier": "ColorService",
"path": "pair2/src/main/java/com/tobeto/pair2/services/abstracts/ColorService.java",
"snippet": "public interface ColorService {\n\n void add(AddColorRequest request);\n void update(UpdateColorRequest request);\n void delete(Integer id);\n List<GetAllColorResponse> getAll();\n GetByIdColorResponse getById(int id);\n boolean existsByColorId(int colorId);\n}"
},
{
"identifier": "ModelService",
"path": "pair2/src/main/java/com/tobeto/pair2/services/abstracts/ModelService.java",
"snippet": "public interface ModelService {\n void add(AddModelRequest request);\n void update(UpdateModelRequest request);\n void delete(Integer id);\n List<GetAllModelResponse> getAll();\n GetByIdModelResponse getById(int id);\n boolean existsByModelId(int modelId);\n}"
},
{
"identifier": "AddCarRequest",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/requests/AddCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AddCarRequest {\n\n @Positive(message = \"Kilometer should be a greater than 0.\")\n private int kilometer;\n\n @NotBlank(message = \"Plate number !\")\n @Pattern(regexp = \"^(0[1-9]|[1-7][0-9]|8[01])(([A-Z])(\\\\d{4,5})|([A-Z]{2})(\\\\d{3,4})|([A-Z]{3})(\\\\d{2,3}))$\", message = \" Plate should be a valid Turkish plate format.\")\n private String plate;\n\n public void setPlate(String plate) {\n this.plate = plate != null ? plate.replaceAll(\"\\s\", \"\") : null;\n }\n\n @Min(value = 2005, message = \"Year should be 2005 or greater.\")\n @Max(value = 2024, message = \"Year should be 2024 or less.\")\n private int year;\n\n @Positive(message = \"Daily price should be a greater than 0.\")\n private double dailyPrice;\n\n @Positive(message = \"ModelId should be a greater than 0.\")\n private int modelId;\n\n @Positive(message = \"ColorId should be a greater than 0.\")\n private int colorId;\n\n}"
},
{
"identifier": "UpdateCarRequest",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/requests/UpdateCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UpdateCarRequest {\n\n @Positive(message = \"Doฤru id giriลi yapฤฑnฤฑz\")\n private Integer id;\n\n @Positive(message = \"Kilometer should be a greater than 0.\")\n private int kilometer;\n\n @NotBlank(message = \"The plate cannot be empty!\")\n @Pattern(regexp = \"^(0[1-9]|[1-7][0-9]|8[01])(([A-Z])(\\\\d{4,5})|([A-Z]{2})(\\\\d{3,4})|([A-Z]{3})(\\\\d{2,3}))$\", message = \" Plate should be a valid Turkish plate format.\")\n private String plate;\n\n public void setPlate(String plate) {\n this.plate = plate != null ? plate.replaceAll(\"\\s\", \"\") : null;\n }\n\n @Min(value = 2005, message = \"Year should be 2005 or greater.\")\n @Max(value = 2024, message = \"Year should be 2024 or less.\")\n private int year;\n\n @Positive(message = \"Daily price should be a greater than 0.\")\n private double dailyPrice;\n\n @Positive(message = \"Kilometer should be a greater than 0.\")\n private int modelId;\n\n @Positive(message = \"ColorId should be a greater than 0.\")\n private int colorId;\n}"
},
{
"identifier": "GetAllCarResponse",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/responses/GetAllCarResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetAllCarResponse {\n\n private int kilometer;\n\n private String plate;\n\n private int year;\n\n private double dailyPrice;\n\n private String modelName;\n\n private String colorName;\n\n}"
},
{
"identifier": "GetByIdCarResponse",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/responses/GetByIdCarResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetByIdCarResponse {\n\n private int kilometer;\n\n private String plate;\n\n private int year;\n\n private double dailyPrice;\n\n private String modelName;\n\n private String colorName;\n}"
}
] | import com.tobeto.pair2.core.utilities.mapper.ModelMapperService;
import com.tobeto.pair2.entitites.Car;
import com.tobeto.pair2.repositories.CarRepository;
import com.tobeto.pair2.services.abstracts.CarService;
import com.tobeto.pair2.services.abstracts.ColorService;
import com.tobeto.pair2.services.abstracts.ModelService;
import com.tobeto.pair2.services.dtos.car.requests.AddCarRequest;
import com.tobeto.pair2.services.dtos.car.requests.UpdateCarRequest;
import com.tobeto.pair2.services.dtos.car.responses.GetAllCarResponse;
import com.tobeto.pair2.services.dtos.car.responses.GetByIdCarResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List; | 1,882 | package com.tobeto.pair2.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final ModelService modelService;
private final ColorService colorService;
@Override
public void add(AddCarRequest request) {
if(carRepository.existsCarByPlate(request.getPlate())){
throw new RuntimeException("Another car cannot be added with the same license plate.");
}
if(!modelService.existsByModelId(request.getModelId())) {
throw new RuntimeException("The ModelId must exist in the database.");
}
if(!colorService.existsByColorId(request.getColorId())) {
throw new RuntimeException("The ColorId must exist in the database.");
}
Car car = this.modelMapperService.forRequest().map(request, Car.class);
this.carRepository.save(car);
}
@Override | package com.tobeto.pair2.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final ModelService modelService;
private final ColorService colorService;
@Override
public void add(AddCarRequest request) {
if(carRepository.existsCarByPlate(request.getPlate())){
throw new RuntimeException("Another car cannot be added with the same license plate.");
}
if(!modelService.existsByModelId(request.getModelId())) {
throw new RuntimeException("The ModelId must exist in the database.");
}
if(!colorService.existsByColorId(request.getColorId())) {
throw new RuntimeException("The ColorId must exist in the database.");
}
Car car = this.modelMapperService.forRequest().map(request, Car.class);
this.carRepository.save(car);
}
@Override | public void update(UpdateCarRequest request) { | 7 | 2023-12-11 12:26:27+00:00 | 4k |
fabriciofx/cactoos-pdf | src/main/java/com/github/fabriciofx/cactoos/pdf/image/png/Safe.java | [
{
"identifier": "Indirect",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Indirect.java",
"snippet": "public interface Indirect extends Bytes {\n /**\n * Create an object reference.\n *\n * @return A reference\n */\n Reference reference();\n\n /**\n * Create a dictionary.\n *\n * @return A dictionary\n */\n Dictionary dictionary();\n}"
},
{
"identifier": "Body",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/Body.java",
"snippet": "public interface Body extends Content {\n}"
},
{
"identifier": "Flow",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/Flow.java",
"snippet": "@SuppressWarnings(\"PMD.AvoidUsingShortType\")\npublic final class Flow {\n /**\n * A stream of bytes.\n */\n private final ByteArrayInputStream stream;\n\n /**\n * Ctor.\n *\n * @param bytes An array of bytes\n */\n public Flow(final byte[] bytes) {\n this(new ByteArrayInputStream(bytes));\n }\n\n /**\n * Ctor.\n *\n * @param stream A stream of bytes\n */\n public Flow(final ByteArrayInputStream stream) {\n this.stream = stream;\n }\n\n /**\n * Read length bytes and return a String contains these bytes.\n *\n * @param length Amount of bytes to read\n * @return The String\n * @throws Exception if fails\n */\n public String asString(final int length) throws Exception {\n return new String(readNBytes(this.stream, length));\n }\n\n /**\n * Read length bytes and return an array of bytes.\n *\n * @param length Amount of bytes to read\n * @return An array of bytes\n * @throws Exception if fails\n */\n public byte[] asBytes(final int length) throws Exception {\n return readNBytes(this.stream, length);\n }\n\n /**\n * Read 4 bytes and return an integer that represents these bytes.\n *\n * @return An integer number\n * @throws Exception if fails\n */\n public int asInt() throws Exception {\n final byte[] bytes = this.asBytes(4);\n return ((bytes[0] & 0xFF) << 24)\n | ((bytes[1] & 0xFF) << 16)\n | ((bytes[2] & 0xFF) << 8)\n | (bytes[3] & 0xFF);\n }\n\n /**\n * Read 2 bytes and return a short that represents these bytes.\n *\n * @return A short number\n * @throws Exception if fails\n */\n public short asShort() throws Exception {\n final byte[] bytes = this.asBytes(2);\n return ByteBuffer.wrap(bytes).getShort();\n }\n\n /**\n * Read a unique byte.\n *\n * @return A byte\n * @throws Exception if fails\n */\n public byte asByte() throws Exception {\n return this.asBytes(1)[0];\n }\n\n /**\n * Skip length bytes.\n *\n * @param length Amount of bytes to skip\n * @return Amount of skiped bytes\n * @throws Exception if fails\n */\n public long skip(final int length) throws Exception {\n return this.stream.skip(length);\n }\n\n /**\n * Search for a sequence of bytes.\n *\n * @param marker Bytes to search for\n * @throws Exception if fails\n */\n public void search(final byte[] marker) throws Exception {\n while (true) {\n final byte[] bytes = readNBytes(this.stream, marker.length);\n if (Arrays.equals(bytes, marker)) {\n break;\n }\n }\n }\n\n /**\n * Read n bytes from a ByteArrayInputStream.\n *\n * @param bais A ByteArrayInputStream\n * @param length Amount of bytes to read\n * @return Bytes read\n * @throws Exception if fails\n */\n private static byte[] readNBytes(\n final ByteArrayInputStream bais,\n final int length\n ) throws Exception {\n final byte[] buffer = new byte[length];\n final int read = bais.read(buffer);\n if (read != length) {\n throw new IOException(\n new FormattedText(\n \"Amount of bytes read (%d) is different of specified (%d)\",\n Locale.ENGLISH,\n read,\n length\n ).asString()\n );\n }\n return buffer;\n }\n}"
},
{
"identifier": "Header",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/Header.java",
"snippet": "public interface Header extends Text, Bytes {\n /**\n * Length.\n *\n * @return The length\n * @throws Exception if fails\n */\n int length() throws Exception;\n\n /**\n * Width.\n * @return Image width\n * @throws Exception if fails\n */\n int width() throws Exception;\n\n /**\n * Height.\n *\n * @return Image height\n * @throws Exception if fails\n */\n int height() throws Exception;\n\n /**\n * Bit Depth.\n *\n * @return Amount of image bit depth\n * @throws Exception if fails\n */\n int depth() throws Exception;\n\n /**\n * Color space.\n *\n * @return Color type and space\n * @throws Exception if fails\n */\n Color color() throws Exception;\n\n /**\n * Image compression level.\n *\n * @return Image compression level\n * @throws Exception if fails\n */\n int compression() throws Exception;\n\n /**\n * Image filter type.\n *\n * @return Image filter type\n * @throws Exception if fails\n */\n int filter() throws Exception;\n\n /**\n * Image interlacing.\n *\n * @return Image interlacing\n * @throws Exception if fails\n */\n int interlacing() throws Exception;\n}"
},
{
"identifier": "InvalidFormatException",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/InvalidFormatException.java",
"snippet": "public class InvalidFormatException extends RuntimeException {\n private static final long serialVersionUID = -4456180910126746406L;\n\n /**\n * Ctor.\n */\n public InvalidFormatException() {\n super();\n }\n\n /**\n * Ctor.\n *\n * @param msg Exception message\n */\n public InvalidFormatException(final String msg) {\n super(msg);\n }\n}"
},
{
"identifier": "Palette",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/Palette.java",
"snippet": "public interface Palette extends Content {\n}"
},
{
"identifier": "Raw",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/Raw.java",
"snippet": "public interface Raw {\n /**\n * Header.\n *\n * @return Image header\n * @throws Exception if fails\n */\n Header header() throws Exception;\n\n /**\n * Body.\n *\n * @return Image body\n * @throws Exception if fails\n */\n Body body() throws Exception;\n\n /**\n * Palette.\n *\n * @return Image palette if there is one\n * @throws Exception if fails\n */\n Palette palette() throws Exception;\n}"
}
] | import java.util.Arrays;
import com.github.fabriciofx.cactoos.pdf.Indirect;
import com.github.fabriciofx.cactoos.pdf.image.Body;
import com.github.fabriciofx.cactoos.pdf.image.Flow;
import com.github.fabriciofx.cactoos.pdf.image.Header;
import com.github.fabriciofx.cactoos.pdf.image.InvalidFormatException;
import com.github.fabriciofx.cactoos.pdf.image.Palette;
import com.github.fabriciofx.cactoos.pdf.image.Raw; | 2,303 | /*
* 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.image.png;
/**
* SafePngRaw: Safe decorator for a PNG image raw.
*
* @since 0.0.1
*/
public final class Safe implements Raw {
/**
* PNG file signature.
*/
private static final byte[] SIGNATURE = {
(byte) 137, 'P', 'N', 'G', '\r', '\n', 26, '\n',
};
/**
* Raw origin.
*/
private final PngRaw origin;
/**
* Ctor.
*
* @param raw Image raw
*/
public Safe(final PngRaw raw) {
this.origin = raw;
}
@Override | /*
* 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.image.png;
/**
* SafePngRaw: Safe decorator for a PNG image raw.
*
* @since 0.0.1
*/
public final class Safe implements Raw {
/**
* PNG file signature.
*/
private static final byte[] SIGNATURE = {
(byte) 137, 'P', 'N', 'G', '\r', '\n', 26, '\n',
};
/**
* Raw origin.
*/
private final PngRaw origin;
/**
* Ctor.
*
* @param raw Image raw
*/
public Safe(final PngRaw raw) {
this.origin = raw;
}
@Override | public Header header() throws Exception { | 3 | 2023-12-05 00:07:24+00:00 | 4k |
IzanagiCraft/message-format | src/main/java/com/izanagicraft/messages/translations/GlobalTranslations.java | [
{
"identifier": "StaticMessagePlaceholders",
"path": "src/main/java/com/izanagicraft/messages/placeholders/StaticMessagePlaceholders.java",
"snippet": "public class StaticMessagePlaceholders {\n\n private static MessagePlaceholderHandler placeholderHandler = new MessagePlaceholderHandler();\n\n // instantiation prevention\n private StaticMessagePlaceholders() {\n }\n\n /**\n * Fast format a string with defaultReplacement placeholders.\n *\n * @param format The format string with placeholders\n * @return Formatted string replaced with {@link StaticMessagePlaceholders#getDefaultReplacements()}\n */\n public static String fastFormat(String format) {\n return placeholderHandler.fastFormat(format);\n }\n\n /**\n * Fast format a string with given values for placeholders.\n *\n * @param format The format string with placeholders.\n * @param values Values to replace placeholders.\n * @return Formatted string.\n */\n public static String fastFormat(String format, Map<String, Object> values) {\n return placeholderHandler.fastFormat(format, values);\n }\n\n /**\n * Add or update default replacements for placeholders.\n *\n * @param additionalReplacements The additional replacements to add or update.\n */\n public static void addDefaultReplacements(Map<String, Object> additionalReplacements) {\n placeholderHandler.addDefaultReplacements(additionalReplacements);\n }\n\n /**\n * Get the default replacements for placeholders.\n *\n * @return The default replacements.\n */\n public static Map<String, Object> getDefaultReplacements() {\n return placeholderHandler.getDefaultReplacements();\n }\n\n /**\n * Set the default replacements for placeholders.\n *\n * @param defaultReplacements The default replacements to set.\n */\n public static void setDefaultReplacements(Map<String, Object> defaultReplacements) {\n placeholderHandler.setDefaultReplacements(defaultReplacements);\n }\n\n}"
},
{
"identifier": "WrappedString",
"path": "src/main/java/com/izanagicraft/messages/strings/WrappedString.java",
"snippet": "public class WrappedString {\n\n /**\n * The wrapped String value.\n */\n private String value;\n\n /**\n * Constructs a new WrappedString object with the specified String value.\n *\n * @param value The String value to be wrapped.\n */\n public WrappedString(String value) {\n this.value = value;\n }\n\n /**\n * Creates a new WrappedString object with the specified String value.\n *\n * @param str The String value to be wrapped.\n * @return A new WrappedString object wrapping the given String value.\n */\n public static WrappedString of(String str) {\n return new WrappedString(str);\n }\n\n /**\n * Returns the String representation of this WrappedString.\n *\n * @return The String value of this WrappedString.\n */\n @Override\n public String toString() {\n return this.value;\n }\n\n /**\n * Gets the current String value of this WrappedString.\n *\n * @return The current String value.\n */\n public String getValue() {\n return value;\n }\n\n /**\n * Sets a new String value for this WrappedString.\n *\n * @param value The new String value to be set.\n */\n public void setValue(String value) {\n this.value = value;\n }\n\n}"
}
] | import com.izanagicraft.messages.placeholders.StaticMessagePlaceholders;
import com.izanagicraft.messages.strings.WrappedString;
import java.io.File;
import java.util.Locale;
import java.util.Map;
import java.util.Properties; | 2,794 | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.messages.translations;
/**
* message-format; com.izanagicraft.messages.translations:GlobalTranslations
* <p>
* Utility class for handling translations with placeholders.
* <p>
* Example usage:
* <pre>
* {@code
* GlobalTranslations.init(new File("en_US.properties"), new File("es_ES.properties"));
* String translatedText = GlobalTranslations.translate("greeting", "John");
* }
* </pre>
* <p>
* This class provides static methods to interact with the TranslationHandler,
* which manages translations for different locales with support for placeholders.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
public final class GlobalTranslations {
private static TranslationHandler translationHandler = new TranslationHandler();
// instantiation prevention
private GlobalTranslations() {
}
/**
* Gets the TranslationHandler instance.
*
* @return The TranslationHandler instance.
*/
public static TranslationHandler getTranslationHandler() {
return translationHandler;
}
/**
* Gets the map of translations for different locales.
*
* @return The map of translations with locale codes as keys and Properties objects as values.
*/
public static Map<String, Properties> getTranslations() {
return translationHandler.getTranslations();
}
/**
* Gets the fallback Properties object.
*
* @return The fallback Properties object.
*/
public static Properties getFallback() {
return translationHandler.getFallback();
}
/**
* Gets the default replacements used by the Formatter for placeholder substitution.
*
* @return A map of default replacements with String keys and Object values.
* These replacements are used by the {@link StaticMessagePlaceholders} class during text formatting.
*/
public static Map<String, Object> getDefaultReplacements() {
return translationHandler.getDefaultReplacements();
}
/**
* Load language properties from a file and process them.
*
* @param properties The properties object to load into.
* @param file The file to load properties from.
*/
private static void loadLang(Properties properties, File file) {
translationHandler.loadLang(properties, file);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param files Language properties files to load.
*/
public static void init(File... files) {
translationHandler.init(files);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param defaultReplacements Default replacement map for placeholders.
* @param files Language properties files to load.
*/
public static void init(Map<String, Object> defaultReplacements, File... files) {
translationHandler.init(defaultReplacements, files);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, Object... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, String... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(String key) {
return translationHandler.translate(key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, Object... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, String... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key) {
return translationHandler.translate(locale, key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param langName The language name to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/ | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.messages.translations;
/**
* message-format; com.izanagicraft.messages.translations:GlobalTranslations
* <p>
* Utility class for handling translations with placeholders.
* <p>
* Example usage:
* <pre>
* {@code
* GlobalTranslations.init(new File("en_US.properties"), new File("es_ES.properties"));
* String translatedText = GlobalTranslations.translate("greeting", "John");
* }
* </pre>
* <p>
* This class provides static methods to interact with the TranslationHandler,
* which manages translations for different locales with support for placeholders.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
public final class GlobalTranslations {
private static TranslationHandler translationHandler = new TranslationHandler();
// instantiation prevention
private GlobalTranslations() {
}
/**
* Gets the TranslationHandler instance.
*
* @return The TranslationHandler instance.
*/
public static TranslationHandler getTranslationHandler() {
return translationHandler;
}
/**
* Gets the map of translations for different locales.
*
* @return The map of translations with locale codes as keys and Properties objects as values.
*/
public static Map<String, Properties> getTranslations() {
return translationHandler.getTranslations();
}
/**
* Gets the fallback Properties object.
*
* @return The fallback Properties object.
*/
public static Properties getFallback() {
return translationHandler.getFallback();
}
/**
* Gets the default replacements used by the Formatter for placeholder substitution.
*
* @return A map of default replacements with String keys and Object values.
* These replacements are used by the {@link StaticMessagePlaceholders} class during text formatting.
*/
public static Map<String, Object> getDefaultReplacements() {
return translationHandler.getDefaultReplacements();
}
/**
* Load language properties from a file and process them.
*
* @param properties The properties object to load into.
* @param file The file to load properties from.
*/
private static void loadLang(Properties properties, File file) {
translationHandler.loadLang(properties, file);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param files Language properties files to load.
*/
public static void init(File... files) {
translationHandler.init(files);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param defaultReplacements Default replacement map for placeholders.
* @param files Language properties files to load.
*/
public static void init(Map<String, Object> defaultReplacements, File... files) {
translationHandler.init(defaultReplacements, files);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, Object... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, String... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(String key) {
return translationHandler.translate(key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, Object... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, String... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key) {
return translationHandler.translate(locale, key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param langName The language name to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/ | public static String translate(WrappedString langName, String key, Object... args) { | 1 | 2023-12-13 02:31:22+00:00 | 4k |
ibm-messaging/kafka-connect-xml-converter | src/test/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/XmlTransformationMapTest.java | [
{
"identifier": "ByteGenerators",
"path": "src/test/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/testutils/ByteGenerators.java",
"snippet": "public class ByteGenerators {\n\n public static byte[] getXml(String testCaseId) {\n try {\n return Files.readAllBytes(FileGenerators.getXml(testCaseId).toPath());\n }\n catch (final IOException e) {\n return new byte[0];\n }\n }\n\n public static byte[] getGenericXml(String testCaseId) {\n try {\n return Files.readAllBytes(FileGenerators.getGenericXml(testCaseId).toPath());\n }\n catch (final IOException e) {\n return new byte[0];\n }\n }\n\n\n public static byte[] getJson(String testCaseId) {\n try {\n return Files.readAllBytes(FileGenerators.getJson(testCaseId).toPath());\n }\n catch (final IOException e) {\n return new byte[0];\n }\n }\n\n\n public static byte[] getCombinedJson(String testCaseId) {\n try {\n return Files.readAllBytes(FileGenerators.getCombinedJson(testCaseId).toPath());\n }\n catch (final IOException e) {\n return new byte[0];\n }\n }\n\n}"
},
{
"identifier": "ConfigGenerators",
"path": "src/test/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/testutils/ConfigGenerators.java",
"snippet": "public class ConfigGenerators {\n\n public static XmlPluginsConfig defaultRootNoSchemas() {\n return new XmlPluginsConfig(defaultRootNoSchemasProps());\n }\n\n public static Map<String, String> defaultRootNoSchemasProps() {\n final Map<String, String> props = new HashMap<>();\n props.put(XmlPluginsConfig.TYPE_CONFIG, ConverterType.VALUE.getName());\n props.put(XmlPluginsConfig.SCHEMAS_ENABLE_CONFIG, \"false\");\n return props;\n }\n\n public static Map<String, String> customRootNoSchemasProps(String root) {\n final Map<String, String> props = new HashMap<>();\n props.put(XmlPluginsConfig.TYPE_CONFIG, ConverterType.VALUE.getName());\n props.put(XmlPluginsConfig.SCHEMAS_ENABLE_CONFIG, \"false\");\n props.put(XmlPluginsConfig.XML_ROOT_ELEMENT_NAME_CONFIG, root);\n return props;\n }\n\n public static Map<String, String> flatNoSchemasProps() {\n final Map<String, String> props = new HashMap<>();\n props.put(XmlPluginsConfig.TYPE_CONFIG, ConverterType.VALUE.getName());\n props.put(XmlPluginsConfig.SCHEMAS_ENABLE_CONFIG, \"false\");\n props.put(XmlPluginsConfig.XML_ROOT_FLAT_CONFIG, \"true\");\n return props;\n }\n\n public static Map<String, String> flatSchemasProps(String testCase) {\n final Map<String, String> props = new HashMap<>();\n props.put(XmlPluginsConfig.TYPE_CONFIG, ConverterType.VALUE.getName());\n props.put(XmlPluginsConfig.XML_SCHEMA_EXTERNAL_PATH_CONFIG,\n FileGenerators.getXsd(testCase).getAbsolutePath());\n props.put(XmlPluginsConfig.SCHEMAS_ENABLE_CONFIG, \"true\");\n props.put(XmlPluginsConfig.XML_ROOT_FLAT_CONFIG, \"true\");\n return props;\n }\n\n\n public static XmlPluginsConfig withSchema(String testCase) {\n return new XmlPluginsConfig(withSchemaProps(testCase));\n }\n\n public static Map<String, String> withSchemaProps(String testCase) {\n final Map<String, String> props = new HashMap<>();\n props.put(XmlPluginsConfig.TYPE_CONFIG, ConverterType.VALUE.getName());\n props.put(XmlPluginsConfig.XML_SCHEMA_EXTERNAL_PATH_CONFIG,\n FileGenerators.getXsd(testCase).getAbsolutePath());\n props.put(XmlPluginsConfig.SCHEMAS_ENABLE_CONFIG, \"true\");\n return props;\n }\n\n public static Map<String, String> customRootWithSchemaProps(String testCase, String root) {\n final Map<String, String> props = new HashMap<>();\n props.put(XmlPluginsConfig.TYPE_CONFIG, ConverterType.VALUE.getName());\n props.put(XmlPluginsConfig.XML_SCHEMA_EXTERNAL_PATH_CONFIG,\n FileGenerators.getXsd(testCase).getAbsolutePath());\n props.put(XmlPluginsConfig.SCHEMAS_ENABLE_CONFIG, \"true\");\n props.put(XmlPluginsConfig.XML_ROOT_ELEMENT_NAME_CONFIG, root);\n return props;\n }\n\n}"
},
{
"identifier": "RecordGenerators",
"path": "src/test/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/testutils/RecordGenerators.java",
"snippet": "public class RecordGenerators {\n\n private final static String TOPIC_NAME = \"TOPIC\";\n\n private static SourceRecord createRecord(Schema schema, Object data) {\n return new SourceRecord(Collections.singletonMap(\"partition\", \"1\"),\n Collections.singletonMap(\"timestamp\", \"1\"),\n TOPIC_NAME,\n schema,\n data);\n }\n\n public static SourceRecord struct(String testCaseId) {\n final SchemaAndValue data = StructGenerators.get(testCaseId);\n return createRecord(data.schema(), data.value());\n }\n\n public static SourceRecord map(String testCaseId) {\n final Map<?, ?> data = MapGenerators.get(testCaseId);\n return createRecord(null, data);\n }\n\n public static SourceRecord string(String testCaseId) {\n final String data = new String(ByteGenerators.getXml(testCaseId));\n return createRecord(null, data);\n }\n\n public static SourceRecord bytes(String testCaseId) {\n final byte[] data = ByteGenerators.getXml(testCaseId);\n return createRecord(null, data);\n }\n\n public static SourceRecord nullString() {\n return createRecord(Schema.OPTIONAL_STRING_SCHEMA, null);\n }\n\n public static SourceRecord integer() {\n return createRecord(Schema.INT32_SCHEMA, 123);\n }\n}"
}
] | import com.ibm.eventstreams.kafkaconnect.plugins.xml.testutils.ConfigGenerators;
import com.ibm.eventstreams.kafkaconnect.plugins.xml.testutils.RecordGenerators;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
import java.util.Arrays;
import java.util.Collection;
import org.apache.kafka.connect.source.SourceRecord;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.xmlunit.builder.Input;
import org.xmlunit.builder.Input.Builder;
import com.ibm.eventstreams.kafkaconnect.plugins.xml.testutils.ByteGenerators; | 2,077 | /**
* Copyright 2023 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.eventstreams.kafkaconnect.plugins.xml;
@RunWith(Parameterized.class)
public class XmlTransformationMapTest {
private final XmlTransformation<SourceRecord> transformer = new XmlTransformation<>();
private final String currentTestCase;
private final boolean ambiguousMap;
@Parameterized.Parameters
public static Collection<Object[]> testCases() {
return Arrays.asList(new Object[][] {
{ "000", false },
{ "001", true }, // uses attributes
{ "002", false },
{ "003", false },
{ "004", false },
{ "005", false },
{ "006", true }, // uses attributes
{ "007", false },
{ "008", false },
{ "009", false },
{ "010", true }, // uses maps
{ "011", true }, // uses maps
{ "012", true },
{ "013", false },
{ "014", false },
{ "015", false },
{ "016", false },
{ "017", false },
{ "018", true },
{ "019", true },
{ "020", true },
{ "021", true },
{ "022", true },
{ "023", true },
{ "024", false },
{ "025", true },
{ "026", false },
{ "027", false },
{ "028", true },
{ "029", true },
{ "030", true },
{ "031", true },
{ "032", true },
{ "033", true },
{ "034", true },
{ "035", true },
{ "036", true },
// { "037", true },
{ "038", true },
// { "039", false },
// { "040", true }
{ "043", true },
{ "044", false },
{ "045", false },
{ "046", false },
{ "049", false }
});
}
public XmlTransformationMapTest(String testCase, boolean ambiguousMap) {
this.currentTestCase = testCase;
this.ambiguousMap = ambiguousMap;
}
@After
public void cleanup() {
transformer.close();
}
@Test
public void map() { | /**
* Copyright 2023 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.eventstreams.kafkaconnect.plugins.xml;
@RunWith(Parameterized.class)
public class XmlTransformationMapTest {
private final XmlTransformation<SourceRecord> transformer = new XmlTransformation<>();
private final String currentTestCase;
private final boolean ambiguousMap;
@Parameterized.Parameters
public static Collection<Object[]> testCases() {
return Arrays.asList(new Object[][] {
{ "000", false },
{ "001", true }, // uses attributes
{ "002", false },
{ "003", false },
{ "004", false },
{ "005", false },
{ "006", true }, // uses attributes
{ "007", false },
{ "008", false },
{ "009", false },
{ "010", true }, // uses maps
{ "011", true }, // uses maps
{ "012", true },
{ "013", false },
{ "014", false },
{ "015", false },
{ "016", false },
{ "017", false },
{ "018", true },
{ "019", true },
{ "020", true },
{ "021", true },
{ "022", true },
{ "023", true },
{ "024", false },
{ "025", true },
{ "026", false },
{ "027", false },
{ "028", true },
{ "029", true },
{ "030", true },
{ "031", true },
{ "032", true },
{ "033", true },
{ "034", true },
{ "035", true },
{ "036", true },
// { "037", true },
{ "038", true },
// { "039", false },
// { "040", true }
{ "043", true },
{ "044", false },
{ "045", false },
{ "046", false },
{ "049", false }
});
}
public XmlTransformationMapTest(String testCase, boolean ambiguousMap) {
this.currentTestCase = testCase;
this.ambiguousMap = ambiguousMap;
}
@After
public void cleanup() {
transformer.close();
}
@Test
public void map() { | transformer.configure(ConfigGenerators.defaultRootNoSchemasProps()); | 1 | 2023-12-11 13:56:48+00:00 | 4k |
BeansGalaxy/Beans-Backpacks-2 | forge/src/main/java/com/beansgalaxy/backpacks/network/NetworkPackages.java | [
{
"identifier": "Constants",
"path": "common/src/main/java/com/beansgalaxy/backpacks/Constants.java",
"snippet": "public class Constants {\n\n\tpublic static final String MOD_ID = \"beansbackpacks\";\n\tpublic static final String MOD_NAME = \"Beans' Backpacks\";\n\tpublic static final Logger LOG = LoggerFactory.getLogger(MOD_NAME);\n\n\tpublic static final HashMap<String, Traits> TRAITS_MAP = new HashMap<>();\n\tpublic static HashSet<Item> CHESTPLATE_DISABLED = new HashSet<>();\n\tpublic static HashSet<Item> DISABLES_BACK_SLOT = new HashSet<>();\n\n\tpublic static Item itemFromString(String string) {\n\t\tif (string == null)\n\t\t\treturn Items.AIR;\n\t\tString[] location = string.split(\":\");\n\t\tResourceLocation resourceLocation = new ResourceLocation(location[0], location[1]);\n return BuiltInRegistries.ITEM.get(resourceLocation);\n\t}\n\n\tpublic static void disableFromChestplate(String string) {\n\t\tItem item = itemFromString(string);\n\t\tCHESTPLATE_DISABLED.add(item.asItem());\n\t}\n\n\tpublic static ItemStack getTorsoWearables(Player player, Item item) {\n\t\tItemStack backSlot = BackSlot.get(player).getItem();\n\t\tItemStack chestplate = player.getItemBySlot(EquipmentSlot.CHEST);\n\t\treturn backSlot.is(item) ? backSlot : chestplate;\n\t}\n\n\tpublic static void disablesBackSlot(String string) {\n\t\tItem item = itemFromString(string);\n\t\tDISABLES_BACK_SLOT.add(item.asItem());\n\t}\n\n}"
},
{
"identifier": "ConfigureKeys2C",
"path": "forge/src/main/java/com/beansgalaxy/backpacks/network/client/ConfigureKeys2C.java",
"snippet": "public class ConfigureKeys2C {\n public static void register() {\n NetworkPackages.INSTANCE.messageBuilder(ConfigureKeys2C.class, NetworkDirection.PLAY_TO_CLIENT)\n .encoder(ConfigureKeys2C::encode).decoder(ConfigureKeys2C::new).consumerMainThread(ConfigureKeys2C::handle).add();\n }\n\n final Map<String, CompoundTag> map;\n\n public ConfigureKeys2C(Map<String, CompoundTag> map) {\n this.map = map;\n }\n\n public ConfigureKeys2C(FriendlyByteBuf buf) {\n this(buf.readMap(FriendlyByteBuf::readUtf, FriendlyByteBuf::readNbt));\n }\n\n public void encode(FriendlyByteBuf buf) {\n buf.writeMap(map, FriendlyByteBuf::writeUtf, FriendlyByteBuf::writeNbt);\n }\n\n public void handle(CustomPayloadEvent.Context context) {\n for (String key: map.keySet())\n {\n CompoundTag tag = map.get(key);\n Traits traits = new Traits(tag);\n\n Traits.register(key, traits);\n }\n }\n}"
},
{
"identifier": "SyncBackInventory2C",
"path": "forge/src/main/java/com/beansgalaxy/backpacks/network/client/SyncBackInventory2C.java",
"snippet": "public class SyncBackInventory2C {\n public static void register() {\n NetworkPackages.INSTANCE.messageBuilder(SyncBackInventory2C.class, NetworkDirection.PLAY_TO_CLIENT)\n .encoder(SyncBackInventory2C::encode).decoder(SyncBackInventory2C::new).consumerMainThread(SyncBackInventory2C::handle).add();\n }\n\n final String stacks;\n\n public SyncBackInventory2C(String stacks) {\n this.stacks = stacks;\n }\n\n public SyncBackInventory2C(FriendlyByteBuf buf) {\n this(buf.readUtf());\n }\n\n public void encode(FriendlyByteBuf buf) {\n buf.writeUtf(stacks);\n }\n\n public void handle(CustomPayloadEvent.Context context) {\n SyncBackInventory.receiveAtClient(stacks);\n }\n\n}"
},
{
"identifier": "SyncBackSlot2C",
"path": "forge/src/main/java/com/beansgalaxy/backpacks/network/client/SyncBackSlot2C.java",
"snippet": "public class SyncBackSlot2C {\n public static void register() {\n NetworkPackages.INSTANCE.messageBuilder(SyncBackSlot2C.class, NetworkDirection.PLAY_TO_CLIENT)\n .encoder(SyncBackSlot2C::encode).decoder(SyncBackSlot2C::new).consumerMainThread(SyncBackSlot2C::handle).add();\n }\n\n final UUID uuid;\n final ItemStack stack;\n\n public SyncBackSlot2C(UUID uuid, ItemStack stack) {\n this.uuid = uuid;\n this.stack = stack;\n }\n\n public SyncBackSlot2C(FriendlyByteBuf buf) {\n this(buf.readUUID(), buf.readItem());\n }\n\n public void encode(FriendlyByteBuf buf) {\n buf.writeUUID(uuid);\n buf.writeItem(stack);\n }\n\n public void handle(CustomPayloadEvent.Context context) {\n SyncBackSlot.receiveAtClient(uuid, stack);\n }\n}"
},
{
"identifier": "SyncViewersPacket2C",
"path": "forge/src/main/java/com/beansgalaxy/backpacks/network/client/SyncViewersPacket2C.java",
"snippet": "public class SyncViewersPacket2C {\n public static void register() {\n NetworkPackages.INSTANCE.messageBuilder(SyncViewersPacket2C.class, NetworkDirection.PLAY_TO_CLIENT)\n .encoder(SyncViewersPacket2C::encode).decoder(SyncViewersPacket2C::new).consumerMainThread(SyncViewersPacket2C::handle).add();\n }\n\n int entityId;\n byte viewers;\n\n public SyncViewersPacket2C(int entityId, byte viewers) {\n this.entityId = entityId;\n this.viewers = viewers;\n }\n\n public SyncViewersPacket2C(FriendlyByteBuf byteBuf) {\n this(byteBuf.readInt(), byteBuf.readByte());\n }\n\n public void encode(FriendlyByteBuf byteBuf) {\n byteBuf.writeInt(entityId);\n byteBuf.writeByte(viewers);\n }\n\n public void handle(CustomPayloadEvent.Context context) {\n SyncViewersPacket.receiveAtClient(entityId, viewers);\n }\n}"
},
{
"identifier": "CallBackInventory2S",
"path": "forge/src/main/java/com/beansgalaxy/backpacks/network/packages/CallBackInventory2S.java",
"snippet": "public class CallBackInventory2S {\n public static void register() {\n NetworkPackages.INSTANCE.messageBuilder(CallBackInventory2S.class, NetworkDirection.PLAY_TO_SERVER)\n .encoder(CallBackInventory2S::encode).decoder(CallBackInventory2S::new).consumerMainThread(CallBackInventory2S::handle).add();\n }\n\n final UUID uuid;\n\n public CallBackInventory2S(FriendlyByteBuf buf) {\n this(buf.readUUID());\n }\n\n public CallBackInventory2S(UUID uuid) {\n this.uuid = uuid;\n }\n\n public static void call(Player player) {\n UUID uuid = player.getUUID();\n NetworkPackages.C2S(new CallBackInventory2S(uuid));\n }\n\n public void encode(FriendlyByteBuf buf) {\n buf.writeUUID(uuid);\n }\n\n public void handle(CustomPayloadEvent.Context context) {\n Services.NETWORK.backpackInventory2C(context.getSender());\n }\n}"
},
{
"identifier": "CallBackSlot2S",
"path": "forge/src/main/java/com/beansgalaxy/backpacks/network/packages/CallBackSlot2S.java",
"snippet": "public class CallBackSlot2S {\n public static void register() {\n NetworkPackages.INSTANCE.messageBuilder(CallBackSlot2S.class, NetworkDirection.PLAY_TO_SERVER)\n .encoder(CallBackSlot2S::encode).decoder(CallBackSlot2S::new).consumerMainThread(CallBackSlot2S::handle).add();\n }\n\n final UUID uuid;\n\n public CallBackSlot2S(FriendlyByteBuf buf) {\n this(buf.readUUID());\n }\n\n public CallBackSlot2S(UUID uuid) {\n this.uuid = uuid;\n }\n\n public static void call(Player player) {\n UUID uuid = player.getUUID();\n NetworkPackages.C2S(new CallBackSlot2S(uuid));\n }\n\n public void encode(FriendlyByteBuf buf) {\n buf.writeUUID(uuid);\n }\n\n public void handle(CustomPayloadEvent.Context context) {\n Player otherPlayer = context.getSender().level().getPlayerByUUID(uuid);\n ItemStack stack = BackSlot.get(otherPlayer).getItem();\n NetworkPackages.S2C(new SyncBackSlot2C(uuid, stack), context.getSender());\n }\n}"
},
{
"identifier": "SprintKeyPacket2S",
"path": "fabric/src/main/java/com/beansgalaxy/backpacks/network/packages/SprintKeyPacket2S.java",
"snippet": "public class SprintKeyPacket2S {\n public static void C2S(boolean sprintKeyIsPressed) {\n FriendlyByteBuf buf = PacketByteBufs.create();\n buf.writeBoolean(sprintKeyIsPressed);\n ClientPlayNetworking.send(NetworkPackages.SPRINT_KEY_2S, buf);\n }\n\n public static void receiveAtServer(MinecraftServer server, ServerPlayer serverPlayer, ServerGamePacketListenerImpl handler,\n FriendlyByteBuf buf, PacketSender responseSender) {\n boolean sprintKeyPressed = buf.readBoolean();\n BackSlot.get(serverPlayer).actionKeyPressed = sprintKeyPressed;\n }\n}"
}
] | import com.beansgalaxy.backpacks.Constants;
import com.beansgalaxy.backpacks.network.client.ConfigureKeys2C;
import com.beansgalaxy.backpacks.network.client.SyncBackInventory2C;
import com.beansgalaxy.backpacks.network.client.SyncBackSlot2C;
import com.beansgalaxy.backpacks.network.client.SyncViewersPacket2C;
import com.beansgalaxy.backpacks.network.packages.CallBackInventory2S;
import com.beansgalaxy.backpacks.network.packages.CallBackSlot2S;
import com.beansgalaxy.backpacks.network.packages.SprintKeyPacket2S;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.ChannelBuilder;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.SimpleChannel; | 2,333 | package com.beansgalaxy.backpacks.network;
public class NetworkPackages {
public static SimpleChannel INSTANCE = ChannelBuilder.named(
new ResourceLocation(Constants.MOD_ID, "main"))
.serverAcceptedVersions(((status, version) -> true))
.clientAcceptedVersions(((status, version) -> true))
.networkProtocolVersion(1)
.simpleChannel();
public static void register() { | package com.beansgalaxy.backpacks.network;
public class NetworkPackages {
public static SimpleChannel INSTANCE = ChannelBuilder.named(
new ResourceLocation(Constants.MOD_ID, "main"))
.serverAcceptedVersions(((status, version) -> true))
.clientAcceptedVersions(((status, version) -> true))
.networkProtocolVersion(1)
.simpleChannel();
public static void register() { | SprintKeyPacket2S.register(); | 7 | 2023-12-14 21:55:00+00:00 | 4k |
CADIndie/Scout | src/main/java/pm/c7/scout/ScoutUtil.java | [
{
"identifier": "BaseBagItem",
"path": "src/main/java/pm/c7/scout/item/BaseBagItem.java",
"snippet": "@SuppressWarnings(\"deprecation\")\npublic class BaseBagItem extends TrinketItem {\n private static final String ITEMS_KEY = \"Items\";\n\n private final int slots;\n private final BagType type;\n\n public BaseBagItem(Settings settings, int slots, BagType type) {\n super(settings);\n\n if (type == BagType.SATCHEL && slots > Scout.MAX_SATCHEL_SLOTS) {\n throw new IllegalArgumentException(\"Satchel has too many slots.\");\n }\n if (type == BagType.POUCH && slots > Scout.MAX_POUCH_SLOTS) {\n throw new IllegalArgumentException(\"Pouch has too many slots.\");\n }\n\n this.slots = slots;\n this.type = type;\n }\n\n public int getSlotCount() {\n return this.slots;\n }\n\n public BagType getType() {\n return this.type;\n }\n\n @Override\n public void appendTooltip(ItemStack stack, @Nullable World world, List<Text> tooltip, TooltipContext context) {\n super.appendTooltip(stack, world, tooltip, context);\n tooltip.add(Text.translatable(\"tooltip.scout.slots\", Text.literal(String.valueOf(this.slots)).formatted(Formatting.BLUE)).formatted(Formatting.GRAY));\n }\n\n public Inventory getInventory(ItemStack stack) {\n SimpleInventory inventory = new SimpleInventory(this.slots) {\n @Override\n public void markDirty() {\n stack.getOrCreateNbt().put(ITEMS_KEY, ScoutUtil.inventoryToTag(this));\n super.markDirty();\n }\n };\n\n NbtCompound compound = stack.getOrCreateNbt();\n if (!compound.contains(ITEMS_KEY)) {\n compound.put(ITEMS_KEY, new NbtList());\n }\n\n NbtList items = compound.getList(ITEMS_KEY, 10);\n\n ScoutUtil.inventoryFromTag(items, inventory);\n\n return inventory;\n }\n\n @Override\n public Optional<TooltipData> getTooltipData(ItemStack stack) {\n DefaultedList<ItemStack> stacks = DefaultedList.of();\n Inventory inventory = getInventory(stack);\n\n for (int i = 0; i < slots; i++) {\n stacks.add(inventory.getStack(i));\n }\n\n if (stacks.stream().allMatch(ItemStack::isEmpty)) return Optional.empty();\n\n return Optional.of(new BagTooltipData(stacks, slots));\n }\n\n @Override\n public void onEquip(ItemStack stack, SlotReference slotRef, LivingEntity entity) {\n PlayerEntity player = (PlayerEntity) entity;\n ScoutPlayerScreenHandler handler = (ScoutPlayerScreenHandler) player.playerScreenHandler;\n\n ItemStack satchelStack = ScoutUtil.findBagItem(player, BagType.SATCHEL, false);\n DefaultedList<BagSlot> satchelSlots = handler.scout$getSatchelSlots();\n\n for (int i = 0; i < Scout.MAX_SATCHEL_SLOTS; i++) {\n BagSlot slot = satchelSlots.get(i);\n slot.setInventory(null);\n slot.setEnabled(false);\n }\n if (!satchelStack.isEmpty()) {\n BaseBagItem satchelItem = (BaseBagItem) satchelStack.getItem();\n Inventory satchelInv = satchelItem.getInventory(satchelStack);\n\n for (int i = 0; i < satchelItem.getSlotCount(); i++) {\n BagSlot slot = satchelSlots.get(i);\n slot.setInventory(satchelInv);\n slot.setEnabled(true);\n }\n }\n\n ItemStack leftPouchStack = ScoutUtil.findBagItem(player, BagType.POUCH, false);\n DefaultedList<BagSlot> leftPouchSlots = handler.scout$getLeftPouchSlots();\n\n for (int i = 0; i < Scout.MAX_POUCH_SLOTS; i++) {\n BagSlot slot = leftPouchSlots.get(i);\n slot.setInventory(null);\n slot.setEnabled(false);\n }\n if (!leftPouchStack.isEmpty()) {\n BaseBagItem leftPouchItem = (BaseBagItem) leftPouchStack.getItem();\n Inventory leftPouchInv = leftPouchItem.getInventory(leftPouchStack);\n\n for (int i = 0; i < leftPouchItem.getSlotCount(); i++) {\n BagSlot slot = leftPouchSlots.get(i);\n slot.setInventory(leftPouchInv);\n slot.setEnabled(true);\n }\n }\n\n ItemStack rightPouchStack = ScoutUtil.findBagItem(player, BagType.POUCH, true);\n DefaultedList<BagSlot> rightPouchSlots = handler.scout$getRightPouchSlots();\n\n for (int i = 0; i < Scout.MAX_POUCH_SLOTS; i++) {\n BagSlot slot = rightPouchSlots.get(i);\n slot.setInventory(null);\n slot.setEnabled(false);\n }\n if (!rightPouchStack.isEmpty()) {\n BaseBagItem rightPouchItem = (BaseBagItem) rightPouchStack.getItem();\n Inventory rightPouchInv = rightPouchItem.getInventory(rightPouchStack);\n\n for (int i = 0; i < rightPouchItem.getSlotCount(); i++) {\n BagSlot slot = rightPouchSlots.get(i);\n slot.setInventory(rightPouchInv);\n slot.setEnabled(true);\n }\n }\n\n PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer());\n if (entity instanceof ServerPlayerEntity serverPlayer) {\n ServerPlayNetworking.send(serverPlayer, ScoutNetworking.ENABLE_SLOTS, packet);\n }\n }\n\n @Override\n public void onUnequip(ItemStack stack, SlotReference slotRef, LivingEntity entity) {\n PlayerEntity player = (PlayerEntity) entity;\n ScoutPlayerScreenHandler handler = (ScoutPlayerScreenHandler) player.playerScreenHandler;\n\n ItemStack satchelStack = ScoutUtil.findBagItem(player, BagType.SATCHEL, false);\n DefaultedList<BagSlot> satchelSlots = handler.scout$getSatchelSlots();\n\n for (int i = 0; i < Scout.MAX_SATCHEL_SLOTS; i++) {\n BagSlot slot = satchelSlots.get(i);\n slot.setInventory(null);\n slot.setEnabled(false);\n }\n if (!satchelStack.isEmpty()) {\n BaseBagItem satchelItem = (BaseBagItem) satchelStack.getItem();\n Inventory satchelInv = satchelItem.getInventory(satchelStack);\n\n for (int i = 0; i < satchelItem.getSlotCount(); i++) {\n BagSlot slot = satchelSlots.get(i);\n slot.setInventory(satchelInv);\n slot.setEnabled(true);\n }\n }\n\n ItemStack leftPouchStack = ScoutUtil.findBagItem(player, BagType.POUCH, false);\n DefaultedList<BagSlot> leftPouchSlots = handler.scout$getLeftPouchSlots();\n\n for (int i = 0; i < Scout.MAX_POUCH_SLOTS; i++) {\n BagSlot slot = leftPouchSlots.get(i);\n slot.setInventory(null);\n slot.setEnabled(false);\n }\n if (!leftPouchStack.isEmpty()) {\n BaseBagItem leftPouchItem = (BaseBagItem) leftPouchStack.getItem();\n Inventory leftPouchInv = leftPouchItem.getInventory(leftPouchStack);\n\n for (int i = 0; i < leftPouchItem.getSlotCount(); i++) {\n BagSlot slot = leftPouchSlots.get(i);\n slot.setInventory(leftPouchInv);\n slot.setEnabled(true);\n }\n }\n\n ItemStack rightPouchStack = ScoutUtil.findBagItem(player, BagType.POUCH, true);\n DefaultedList<BagSlot> rightPouchSlots = handler.scout$getRightPouchSlots();\n\n for (int i = 0; i < Scout.MAX_POUCH_SLOTS; i++) {\n BagSlot slot = rightPouchSlots.get(i);\n slot.setInventory(null);\n slot.setEnabled(false);\n }\n if (!rightPouchStack.isEmpty()) {\n BaseBagItem rightPouchItem = (BaseBagItem) rightPouchStack.getItem();\n Inventory rightPouchInv = rightPouchItem.getInventory(rightPouchStack);\n\n for (int i = 0; i < rightPouchItem.getSlotCount(); i++) {\n BagSlot slot = rightPouchSlots.get(i);\n slot.setInventory(rightPouchInv);\n slot.setEnabled(true);\n }\n }\n\n PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer());\n if (entity instanceof ServerPlayerEntity serverPlayer) {\n ServerPlayNetworking.send(serverPlayer, ScoutNetworking.ENABLE_SLOTS, packet);\n }\n }\n\n @Override\n public boolean canEquip(ItemStack stack, SlotReference slot, LivingEntity entity) {\n Item item = stack.getItem();\n\n ItemStack slotStack = slot.inventory().getStack(slot.index());\n Item slotItem = slotStack.getItem();\n\n if (slotItem instanceof BaseBagItem) {\n if (((BaseBagItem) item).getType() == BagType.SATCHEL) {\n if (((BaseBagItem) slotItem).getType() == BagType.SATCHEL) {\n return true;\n } else {\n return ScoutUtil.findBagItem((PlayerEntity) entity, BagType.SATCHEL, false).isEmpty();\n }\n } else if (((BaseBagItem) item).getType() == BagType.POUCH) {\n if (((BaseBagItem) slotItem).getType() == BagType.POUCH) {\n return true;\n } else {\n return ScoutUtil.findBagItem((PlayerEntity) entity, BagType.POUCH, true).isEmpty();\n }\n }\n } else {\n if (((BaseBagItem) item).getType() == BagType.SATCHEL) {\n return ScoutUtil.findBagItem((PlayerEntity) entity, BagType.SATCHEL, false).isEmpty();\n } else if (((BaseBagItem) item).getType() == BagType.POUCH) {\n return ScoutUtil.findBagItem((PlayerEntity) entity, BagType.POUCH, true).isEmpty();\n }\n }\n\n return false;\n }\n\n public enum BagType {\n SATCHEL,\n POUCH\n }\n}"
},
{
"identifier": "BagType",
"path": "src/main/java/pm/c7/scout/item/BaseBagItem.java",
"snippet": "public enum BagType {\n SATCHEL,\n POUCH\n}"
}
] | import java.util.Optional;
import dev.emi.trinkets.api.SlotReference;
import dev.emi.trinkets.api.TrinketComponent;
import dev.emi.trinkets.api.TrinketsApi;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.util.Identifier;
import net.minecraft.util.Pair;
import pm.c7.scout.item.BaseBagItem;
import pm.c7.scout.item.BaseBagItem.BagType; | 2,661 | package pm.c7.scout;
public class ScoutUtil {
public static final Identifier SLOT_TEXTURE = new Identifier("scout", "textures/gui/slots.png");
| package pm.c7.scout;
public class ScoutUtil {
public static final Identifier SLOT_TEXTURE = new Identifier("scout", "textures/gui/slots.png");
| public static ItemStack findBagItem(PlayerEntity player, BaseBagItem.BagType type, boolean right) { | 1 | 2023-12-10 07:43:34+00:00 | 4k |
courage0916/mybatis-gain | src/main/java/com/gain/MybatisGainInterceptor.java | [
{
"identifier": "FillService",
"path": "src/main/java/com/gain/fill/FillService.java",
"snippet": "@Service\npublic class FillService {\n\n private final ListenerSupport listenerSupport;\n\n public FillService() {\n listenerSupport = ListenerSupport.getInstance();\n }\n\n public void fill(Invocation invocation) throws IllegalAccessException {\n\n final Object[] args = invocation.getArgs();\n\n MappedStatement ms = (MappedStatement) args[0];\n\n BoundSql boundSql = ms.getBoundSql(args[1]);\n\n MappedStatement newMs = null;\n\n if (SqlCommandType.INSERT.equals(ms.getSqlCommandType())) {\n\n Object obj = ((DefaultInsertStatementProvider<?>) args[1]).getRow();\n\n listenerSupport.fillObject(ms.getSqlCommandType(), obj);\n BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), listenerSupport.getUpdateSQL(ms.getSqlCommandType(), boundSql.getSql(), obj), listenerSupport.getUpdateParameter(boundSql.getParameterMappings(), ms, obj), boundSql.getParameterObject());\n\n newMs = newMappedStatement(ms, newBoundSql);\n for (ParameterMapping mapping : boundSql.getParameterMappings()) {\n String prop = mapping.getProperty();\n if (boundSql.hasAdditionalParameter(prop)) {\n newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));\n }\n }\n\n args[0] = newMs;\n }\n\n\n\n if (SqlCommandType.UPDATE.equals(ms.getSqlCommandType())) {\n /* Object obj = ((DefaultUpdateStatementProvider) args[1]).getParameters();\n System.out.println(listenerSupport.getUpdateSQL(ms.getSqlCommandType(), boundSql.getSql(), null));\n BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), listenerSupport.getUpdateSQL(ms.getSqlCommandType(), boundSql.getSql(), null), listenerSupport.getUpdateParameter(boundSql.getParameterMappings(), ms, null), boundSql.getParameterObject());\n\n System.out.println(newBoundSql.getSql());\n System.out.println(newBoundSql.getParameterMappings().size());\n newMs = newMappedStatement(ms, newBoundSql);\n for (ParameterMapping mapping : newBoundSql.getParameterMappings()) {\n String prop = mapping.getProperty();\n if (boundSql.hasAdditionalParameter(prop)) {\n newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));\n }\n }\n\n DefaultUpdateStatementProvider.Builder builder1 = new DefaultUpdateStatementProvider.Builder();\n\n Map<String, Object> stringObjectMap = ((DefaultUpdateStatementProvider) args[1]).getParameters();\n stringObjectMap.put(\"p12\",stringObjectMap.get(\"p11\"));\n stringObjectMap.put(\"p11\",new Date());\n builder1.withParameters(stringObjectMap);\n builder1.withUpdateStatement(\n \"update t_power set t_name = #{parameters.p1,jdbcType=VARCHAR}, t_code = #{parameters.p2,jdbcType=VARCHAR}, t_type = #{parameters.p3,jdbcType=VARCHAR}, t_parent_id = #{parameters.p4,jdbcType=BIGINT}, t_position = #{parameters.p5,jdbcType=INTEGER}, t_remark = #{parameters.p6,jdbcType=VARCHAR}, t_url = #{parameters.p7,jdbcType=VARCHAR}, t_icon = #{parameters.p8,jdbcType=VARCHAR}, t_sys_code = #{parameters.p9,jdbcType=VARCHAR}, t_company_code = #{parameters.p10,jdbcType=VARCHAR}, \" +\n \"t_update_time = #{parameters.p11,jdbcType=TIMESTAMP} where t_id = #{parameters.p12,jdbcType=BIGINT}\");\n\n DefaultUpdateStatementProvider builder = builder1.build();\n System.out.println(builder.getUpdateStatement());\n args[1] = builder;*/\n }\n\n\n\n }\n private MappedStatement newMappedStatement(MappedStatement ms, SqlSource sqlSource) {\n\n MappedStatement.Builder builder = new\n MappedStatement.Builder(ms.getConfiguration(), ms.getId(), sqlSource , ms.getSqlCommandType());\n builder.resource(ms.getResource());\n builder.fetchSize(ms.getFetchSize());\n builder.statementType(ms.getStatementType());\n builder.keyGenerator(ms.getKeyGenerator());\n if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {\n builder.keyProperty(ms.getKeyProperties()[0]);\n }\n builder.timeout(ms.getTimeout());\n builder.parameterMap(ms.getParameterMap());\n builder.resultMaps(ms.getResultMaps());\n builder.resultSetType(ms.getResultSetType());\n builder.cache(ms.getCache());\n builder.flushCacheRequired(ms.isFlushCacheRequired());\n builder.useCache(ms.isUseCache());\n\n return builder.build();\n }\n private MappedStatement newMappedStatement(MappedStatement ms, BoundSql newBoundSql) {\n MappedStatement.Builder builder = new\n MappedStatement.Builder(ms.getConfiguration(), ms.getId(), new BoundSqlSource(newBoundSql), ms.getSqlCommandType());\n builder.resource(ms.getResource());\n builder.fetchSize(ms.getFetchSize());\n builder.statementType(ms.getStatementType());\n builder.keyGenerator(ms.getKeyGenerator());\n if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {\n builder.keyProperty(ms.getKeyProperties()[0]);\n }\n builder.timeout(ms.getTimeout());\n builder.parameterMap(ms.getParameterMap());\n builder.resultMaps(ms.getResultMaps());\n builder.resultSetType(ms.getResultSetType());\n builder.cache(ms.getCache());\n builder.flushCacheRequired(ms.isFlushCacheRequired());\n builder.useCache(ms.isUseCache());\n\n return builder.build();\n }\n\n\n class BoundSqlSource implements SqlSource {\n private final BoundSql boundSql;\n\n public BoundSqlSource(BoundSql boundSql) {\n this.boundSql = boundSql;\n }\n\n public BoundSql getBoundSql(Object parameterObject) {\n return boundSql;\n }\n }\n\n}"
},
{
"identifier": "LogService",
"path": "src/main/java/com/gain/log/LogService.java",
"snippet": "@Service\npublic class LogService {\n\n\n public void add(String sqlStr, String objStr) {\n\n // TODO: 2023/7/15 ่ฎฐๅฝ mybatis ๆง่กๆฅๅฟ\n\n }\n}"
},
{
"identifier": "AllowUpdateTables",
"path": "src/main/java/com/gain/safe/AllowUpdateTables.java",
"snippet": "@Component\n@ConfigurationProperties(prefix = \"allow-tables\")\npublic class AllowUpdateTables {\n\n /**\n * ๅฏ็จ\n */\n private boolean enable = false;\n\n /**\n * ๅ
่ฎธๅ
จ่กจๅ ้ค็่กจ\n */\n private List<String> delete;\n\n /**\n * ๅ
่ฎธๅ
จ่กจๆดๆฐ็่กจ\n */\n private List<String> update;\n\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public List<String> getDelete() {\n return delete;\n }\n\n public void setDelete(List<String> delete) {\n this.delete = delete;\n }\n\n public List<String> getUpdate() {\n return update;\n }\n\n public void setUpdate(List<String> update) {\n this.update = update;\n }\n}"
},
{
"identifier": "SafeService",
"path": "src/main/java/com/gain/safe/SafeService.java",
"snippet": "@Service\npublic class SafeService {\n\n private final AllowUpdateTables allowUpdateTables;\n\n public SafeService(AllowUpdateTables allowUpdateTables) {\n this.allowUpdateTables = allowUpdateTables;\n }\n\n public void check(SqlCommandType type, String sql) throws SQLException {\n\n if (!allowUpdateTables.isEnable()) return;\n\n if (SqlCommandType.UPDATE.equals(type) && determine(sql, allowUpdateTables.getUpdate())) return;\n\n if (SqlCommandType.DELETE.equals(type) && determine(sql, allowUpdateTables.getDelete())) return;\n\n if ((SqlCommandType.DELETE.equals(type) || SqlCommandType.UPDATE.equals(type))\n && !sql.toLowerCase().contains(\"where\"))\n throw new SQLException(String.format(\"DELETE OR UPDATE SQL HAVING WHERE CONDITION , ERROR SQL : %S\", sql));\n }\n\n private boolean determine(String str, List<String> list) {\n str = str.toLowerCase();\n for (String item : list) {\n if (str.contains(item.toLowerCase())) {\n return true;\n }\n }\n return false;\n }\n}"
}
] | import com.gain.fill.FillService;
import com.gain.log.LogService;
import com.gain.safe.AllowUpdateTables;
import com.gain.safe.SafeService;
import jakarta.annotation.Resource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.stereotype.Component; | 2,179 | package com.gain;
/**
* Mybatis Gain๏ผๅข็๏ผ ๆฆๆชๅจ
* ไธป่ฆๅฎ็ฐไธไบ้่ฆ้ขๅค็ๅ่ฝ๏ผๅฆๅกซๅ
ๅญๆฎตใๆฐๅข Mybatis Sql ๆฅๅฟ
*/
@Component
@Intercepts({@Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class})})
public class MybatisGainInterceptor implements Interceptor {
@Resource
LogService logService;
@Resource
SafeService safeService;
// ๅ
ณไบ่ฏฅๆไปถ็้
็ฝฎ | package com.gain;
/**
* Mybatis Gain๏ผๅข็๏ผ ๆฆๆชๅจ
* ไธป่ฆๅฎ็ฐไธไบ้่ฆ้ขๅค็ๅ่ฝ๏ผๅฆๅกซๅ
ๅญๆฎตใๆฐๅข Mybatis Sql ๆฅๅฟ
*/
@Component
@Intercepts({@Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class})})
public class MybatisGainInterceptor implements Interceptor {
@Resource
LogService logService;
@Resource
SafeService safeService;
// ๅ
ณไบ่ฏฅๆไปถ็้
็ฝฎ | private final AllowUpdateTables allowUpdateTables; | 2 | 2023-12-11 05:28:00+00:00 | 4k |
Viola-Siemens/Mod-Whitelist | src/main/java/com/hexagram2021/mod_whitelist/server/config/MWServerConfig.java | [
{
"identifier": "ModWhitelist",
"path": "src/main/java/com/hexagram2021/mod_whitelist/ModWhitelist.java",
"snippet": "public class ModWhitelist implements ModInitializer {\n\tpublic static final String MODID = \"mod_whitelist\";\n\tpublic static final String MOD_NAME = \"Mod Whitelist\";\n\tpublic static final String MOD_VERSION = FabricLoader.getInstance().getModContainer(MODID).orElseThrow().getMetadata().getVersion().getFriendlyString();\n\t\n\t@Override\n\tpublic void onInitialize() {\n\t}\n}"
},
{
"identifier": "MWLogger",
"path": "src/main/java/com/hexagram2021/mod_whitelist/common/utils/MWLogger.java",
"snippet": "public class MWLogger {\n\tpublic static final Logger LOGGER = LogUtils.getLogger();\n}"
},
{
"identifier": "MODID",
"path": "src/main/java/com/hexagram2021/mod_whitelist/ModWhitelist.java",
"snippet": "public static final String MODID = \"mod_whitelist\";"
}
] | import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hexagram2021.mod_whitelist.ModWhitelist;
import com.hexagram2021.mod_whitelist.common.utils.MWLogger;
import org.apache.commons.lang3.tuple.Pair;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.hexagram2021.mod_whitelist.ModWhitelist.MODID; | 1,932 | this.name = name;
this.value = value;
configValues.add(this);
}
@Override
public void checkValueRange() throws ConfigValueException {
}
@Override
public void parseAsValue(JsonElement element) {
this.value = element.getAsBoolean();
}
@Override
public String name() {
return this.name;
}
@Override
public Boolean value() {
return this.value;
}
}
public static final File filePath = new File("./config/");
private static final File configFile = new File(filePath + "/" + MODID + "-config.json");
private static final File readmeFile = new File(filePath + "/" + MODID + "-config-readme.md");
//WhiteLists
public static final BoolConfigValue USE_WHITELIST_ONLY = new BoolConfigValue("USE_WHITELIST_ONLY", false);
public static final ModIdListConfigValue CLIENT_MOD_NECESSARY = new ModIdListConfigValue("CLIENT_MOD_NECESSARY", MODID);
public static final ModIdListConfigValue CLIENT_MOD_WHITELIST = new ModIdListConfigValue("CLIENT_MOD_WHITELIST",
"fabric-api",
"fabric-api-base",
"fabric-api-lookup-api-v1",
"fabric-biome-api-v1",
"fabric-block-api-v1",
"fabric-block-view-api-v2",
"fabric-blockrenderlayer-v1",
"fabric-client-tags-api-v1",
"fabric-command-api-v1",
"fabric-command-api-v2",
"fabric-commands-v0",
"fabric-containers-v0",
"fabric-content-registries-v0",
"fabric-convention-tags-v1",
"fabric-crash-report-info-v1",
"fabric-data-generation-api-v1",
"fabric-dimensions-v1",
"fabric-entity-events-v1",
"fabric-events-interaction-v0",
"fabric-events-lifecycle-v0",
"fabric-game-rule-api-v1",
"fabric-item-api-v1",
"fabric-item-group-api-v1",
"fabric-key-binding-api-v1",
"fabric-keybindings-v0",
"fabric-lifecycle-events-v1",
"fabric-loot-api-v2",
"fabric-loot-tables-v1",
"fabric-message-api-v1",
"fabric-mining-level-api-v1",
"fabric-model-loading-api-v1",
"fabric-models-v0",
"fabric-networking-api-v1",
"fabric-networking-v0",
"fabric-object-builder-api-v1",
"fabric-particles-v1",
"fabric-recipe-api-v1",
"fabric-registry-sync-v0",
"fabric-renderer-api-v1",
"fabric-renderer-indigo",
"fabric-renderer-registries-v1",
"fabric-rendering-data-attachment-v1",
"fabric-rendering-fluids-v1",
"fabric-rendering-v0",
"fabric-rendering-v1",
"fabric-resource-conditions-api-v1",
"fabric-resource-loader-v0",
"fabric-screen-api-v1",
"fabric-screen-handler-api-v1",
"fabric-sound-api-v1",
"fabric-transfer-api-v1",
"fabric-transitive-access-wideners-v1",
"fabricloader",
"java", MODID);
public static final ModIdListConfigValue CLIENT_MOD_BLACKLIST = new ModIdListConfigValue("CLIENT_MOD_BLACKLIST", "aristois", "bleachhack", "meteor-client", "wurst");
public static List<Pair<String, MismatchType>> test(List<String> mods) {
List<Pair<String, MismatchType>> ret = Lists.newArrayList();
for(String mod: CLIENT_MOD_NECESSARY.value()) {
if(!mods.contains(mod)) {
ret.add(Pair.of(mod, MismatchType.UNINSTALLED_BUT_SHOULD_INSTALL));
}
}
if(USE_WHITELIST_ONLY.value()) {
for(String mod: mods) {
if(!CLIENT_MOD_WHITELIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
} else {
for(String mod: mods) {
if(CLIENT_MOD_BLACKLIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
}
return ret;
}
static {
lazyInit();
}
private static void lazyInit() {
try {
if (!filePath.exists() && !filePath.mkdir()) { | package com.hexagram2021.mod_whitelist.server.config;
public class MWServerConfig {
public interface IConfigValue<T extends Serializable> {
List<IConfigValue<?>> configValues = Lists.newArrayList();
String name();
T value();
void parseAsValue(JsonElement element);
void checkValueRange() throws ConfigValueException;
}
public static abstract class ListConfigValue<T extends Serializable> implements IConfigValue<ArrayList<T>> {
private final String name;
private final ArrayList<T> value;
@SafeVarargs
public ListConfigValue(String name, T... defaultValues) {
this(name, Arrays.stream(defaultValues).collect(Collectors.toCollection(Lists::newArrayList)));
configValues.add(this);
}
public ListConfigValue(String name, ArrayList<T> value) {
this.name = name;
this.value = value;
}
@Override
public void checkValueRange() throws ConfigValueException {
this.value.forEach(v -> {
if(!this.isValid(v)) {
throw new ConfigValueException(this.createExceptionDescription(v));
}
});
}
@Override
public void parseAsValue(JsonElement element) {
this.value.clear();
element.getAsJsonArray().asList().forEach(e -> this.value.add(this.parseAsElementValue(e)));
}
@Override
public String name() {
return this.name;
}
@Override
public ArrayList<T> value() {
return this.value;
}
protected abstract boolean isValid(T element);
protected abstract String createExceptionDescription(T element);
protected abstract T parseAsElementValue(JsonElement element);
}
public static class ModIdListConfigValue extends ListConfigValue<String> {
public ModIdListConfigValue(String name, String... defaultValues) {
super(name, defaultValues);
}
@SuppressWarnings("unused")
public ModIdListConfigValue(String name, ArrayList<String> value) {
super(name, value);
}
@Override
protected boolean isValid(String element) {
return Pattern.matches("[a-z\\d\\-._]+", element);
}
@Override
protected String createExceptionDescription(String element) {
return "\"%s\" is not a valid modid!".formatted(element);
}
@Override
protected String parseAsElementValue(JsonElement element) {
return element.getAsString();
}
}
public static class BoolConfigValue implements IConfigValue<Boolean> {
private final String name;
private boolean value;
public BoolConfigValue(String name, boolean value) {
this.name = name;
this.value = value;
configValues.add(this);
}
@Override
public void checkValueRange() throws ConfigValueException {
}
@Override
public void parseAsValue(JsonElement element) {
this.value = element.getAsBoolean();
}
@Override
public String name() {
return this.name;
}
@Override
public Boolean value() {
return this.value;
}
}
public static final File filePath = new File("./config/");
private static final File configFile = new File(filePath + "/" + MODID + "-config.json");
private static final File readmeFile = new File(filePath + "/" + MODID + "-config-readme.md");
//WhiteLists
public static final BoolConfigValue USE_WHITELIST_ONLY = new BoolConfigValue("USE_WHITELIST_ONLY", false);
public static final ModIdListConfigValue CLIENT_MOD_NECESSARY = new ModIdListConfigValue("CLIENT_MOD_NECESSARY", MODID);
public static final ModIdListConfigValue CLIENT_MOD_WHITELIST = new ModIdListConfigValue("CLIENT_MOD_WHITELIST",
"fabric-api",
"fabric-api-base",
"fabric-api-lookup-api-v1",
"fabric-biome-api-v1",
"fabric-block-api-v1",
"fabric-block-view-api-v2",
"fabric-blockrenderlayer-v1",
"fabric-client-tags-api-v1",
"fabric-command-api-v1",
"fabric-command-api-v2",
"fabric-commands-v0",
"fabric-containers-v0",
"fabric-content-registries-v0",
"fabric-convention-tags-v1",
"fabric-crash-report-info-v1",
"fabric-data-generation-api-v1",
"fabric-dimensions-v1",
"fabric-entity-events-v1",
"fabric-events-interaction-v0",
"fabric-events-lifecycle-v0",
"fabric-game-rule-api-v1",
"fabric-item-api-v1",
"fabric-item-group-api-v1",
"fabric-key-binding-api-v1",
"fabric-keybindings-v0",
"fabric-lifecycle-events-v1",
"fabric-loot-api-v2",
"fabric-loot-tables-v1",
"fabric-message-api-v1",
"fabric-mining-level-api-v1",
"fabric-model-loading-api-v1",
"fabric-models-v0",
"fabric-networking-api-v1",
"fabric-networking-v0",
"fabric-object-builder-api-v1",
"fabric-particles-v1",
"fabric-recipe-api-v1",
"fabric-registry-sync-v0",
"fabric-renderer-api-v1",
"fabric-renderer-indigo",
"fabric-renderer-registries-v1",
"fabric-rendering-data-attachment-v1",
"fabric-rendering-fluids-v1",
"fabric-rendering-v0",
"fabric-rendering-v1",
"fabric-resource-conditions-api-v1",
"fabric-resource-loader-v0",
"fabric-screen-api-v1",
"fabric-screen-handler-api-v1",
"fabric-sound-api-v1",
"fabric-transfer-api-v1",
"fabric-transitive-access-wideners-v1",
"fabricloader",
"java", MODID);
public static final ModIdListConfigValue CLIENT_MOD_BLACKLIST = new ModIdListConfigValue("CLIENT_MOD_BLACKLIST", "aristois", "bleachhack", "meteor-client", "wurst");
public static List<Pair<String, MismatchType>> test(List<String> mods) {
List<Pair<String, MismatchType>> ret = Lists.newArrayList();
for(String mod: CLIENT_MOD_NECESSARY.value()) {
if(!mods.contains(mod)) {
ret.add(Pair.of(mod, MismatchType.UNINSTALLED_BUT_SHOULD_INSTALL));
}
}
if(USE_WHITELIST_ONLY.value()) {
for(String mod: mods) {
if(!CLIENT_MOD_WHITELIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
} else {
for(String mod: mods) {
if(CLIENT_MOD_BLACKLIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
}
return ret;
}
static {
lazyInit();
}
private static void lazyInit() {
try {
if (!filePath.exists() && !filePath.mkdir()) { | MWLogger.LOGGER.error("Could not mkdir " + filePath); | 1 | 2023-12-06 12:16:52+00:00 | 4k |
sinbad-navigator/erp-crm | system/src/main/java/com/ec/sys/service/ISysMenuService.java | [
{
"identifier": "TreeSelect",
"path": "common/src/main/java/com/ec/common/core/domain/TreeSelect.java",
"snippet": "public class TreeSelect implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * ่็นID\n */\n private Long id;\n\n /**\n * ่็นๅ็งฐ\n */\n private String label;\n\n /**\n * ๅญ่็น\n */\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private List<TreeSelect> children;\n\n public TreeSelect() {\n\n }\n\n public TreeSelect(SysDept dept) {\n this.id = dept.getDeptId();\n this.label = dept.getDeptName();\n this.children = dept.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());\n }\n\n public TreeSelect(SysMenu menu) {\n this.id = menu.getMenuId();\n this.label = menu.getMenuName();\n this.children = menu.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getLabel() {\n return label;\n }\n\n public void setLabel(String label) {\n this.label = label;\n }\n\n public List<TreeSelect> getChildren() {\n return children;\n }\n\n public void setChildren(List<TreeSelect> children) {\n this.children = children;\n }\n}"
},
{
"identifier": "SysMenu",
"path": "common/src/main/java/com/ec/common/core/domain/entity/SysMenu.java",
"snippet": "public class SysMenu extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /**\n * ่ๅID\n */\n private Long menuId;\n\n /**\n * ่ๅๅ็งฐ\n */\n private String menuName;\n\n /**\n * ็ถ่ๅๅ็งฐ\n */\n private String parentName;\n\n /**\n * ็ถ่ๅID\n */\n private Long parentId;\n\n /**\n * ๆพ็คบ้กบๅบ\n */\n private String orderNum;\n\n /**\n * ่ทฏ็ฑๅฐๅ\n */\n private String path;\n\n /**\n * ็ปไปถ่ทฏๅพ\n */\n private String component;\n\n /**\n * ่ทฏ็ฑๅๆฐ\n */\n private String query;\n\n /**\n * ๆฏๅฆไธบๅค้พ๏ผ0ๆฏ 1ๅฆ๏ผ\n */\n private String isFrame;\n\n /**\n * ๆฏๅฆ็ผๅญ๏ผ0็ผๅญ 1ไธ็ผๅญ๏ผ\n */\n private String isCache;\n\n /**\n * ็ฑปๅ๏ผM็ฎๅฝ C่ๅ Fๆ้ฎ๏ผ\n */\n private String menuType;\n\n /**\n * ๆพ็คบ็ถๆ๏ผ0ๆพ็คบ 1้่๏ผ\n */\n private String visible;\n\n /**\n * ่ๅ็ถๆ๏ผ0ๆพ็คบ 1้่๏ผ\n */\n private String status;\n\n /**\n * ๆ้ๅญ็ฌฆไธฒ\n */\n private String perms;\n\n /**\n * ่ๅๅพๆ \n */\n private String icon;\n\n /**\n * ๅญ่ๅ\n */\n private List<SysMenu> children = new ArrayList<SysMenu>();\n\n public Long getMenuId() {\n return menuId;\n }\n\n public void setMenuId(Long menuId) {\n this.menuId = menuId;\n }\n\n @NotBlank(message = \"่ๅๅ็งฐไธ่ฝไธบ็ฉบ\")\n @Size(min = 0, max = 50, message = \"่ๅๅ็งฐ้ฟๅบฆไธ่ฝ่ถ
่ฟ50ไธชๅญ็ฌฆ\")\n public String getMenuName() {\n return menuName;\n }\n\n public void setMenuName(String menuName) {\n this.menuName = menuName;\n }\n\n public String getParentName() {\n return parentName;\n }\n\n public void setParentName(String parentName) {\n this.parentName = parentName;\n }\n\n public Long getParentId() {\n return parentId;\n }\n\n public void setParentId(Long parentId) {\n this.parentId = parentId;\n }\n\n @NotBlank(message = \"ๆพ็คบ้กบๅบไธ่ฝไธบ็ฉบ\")\n public String getOrderNum() {\n return orderNum;\n }\n\n public void setOrderNum(String orderNum) {\n this.orderNum = orderNum;\n }\n\n @Size(min = 0, max = 200, message = \"่ทฏ็ฑๅฐๅไธ่ฝ่ถ
่ฟ200ไธชๅญ็ฌฆ\")\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n @Size(min = 0, max = 200, message = \"็ปไปถ่ทฏๅพไธ่ฝ่ถ
่ฟ255ไธชๅญ็ฌฆ\")\n public String getComponent() {\n return component;\n }\n\n public void setComponent(String component) {\n this.component = component;\n }\n\n public String getQuery() {\n return query;\n }\n\n public void setQuery(String query) {\n this.query = query;\n }\n\n public String getIsFrame() {\n return isFrame;\n }\n\n public void setIsFrame(String isFrame) {\n this.isFrame = isFrame;\n }\n\n public String getIsCache() {\n return isCache;\n }\n\n public void setIsCache(String isCache) {\n this.isCache = isCache;\n }\n\n @NotBlank(message = \"่ๅ็ฑปๅไธ่ฝไธบ็ฉบ\")\n public String getMenuType() {\n return menuType;\n }\n\n public void setMenuType(String menuType) {\n this.menuType = menuType;\n }\n\n public String getVisible() {\n return visible;\n }\n\n public void setVisible(String visible) {\n this.visible = visible;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n @Size(min = 0, max = 100, message = \"ๆ้ๆ ่ฏ้ฟๅบฆไธ่ฝ่ถ
่ฟ100ไธชๅญ็ฌฆ\")\n public String getPerms() {\n return perms;\n }\n\n public void setPerms(String perms) {\n this.perms = perms;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public void setIcon(String icon) {\n this.icon = icon;\n }\n\n public List<SysMenu> getChildren() {\n return children;\n }\n\n public void setChildren(List<SysMenu> children) {\n this.children = children;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)\n .append(\"menuId\", getMenuId())\n .append(\"menuName\", getMenuName())\n .append(\"parentId\", getParentId())\n .append(\"orderNum\", getOrderNum())\n .append(\"path\", getPath())\n .append(\"component\", getComponent())\n .append(\"isFrame\", getIsFrame())\n .append(\"IsCache\", getIsCache())\n .append(\"menuType\", getMenuType())\n .append(\"visible\", getVisible())\n .append(\"status \", getStatus())\n .append(\"perms\", getPerms())\n .append(\"icon\", getIcon())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .toString();\n }\n}"
},
{
"identifier": "RouterVo",
"path": "system/src/main/java/com/ec/sys/domain/vo/RouterVo.java",
"snippet": "@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class RouterVo {\n /**\n * ่ทฏ็ฑๅๅญ\n */\n private String name;\n\n /**\n * ่ทฏ็ฑๅฐๅ\n */\n private String path;\n\n /**\n * ๆฏๅฆ้่่ทฏ็ฑ๏ผๅฝ่ฎพ็ฝฎ true ็ๆถๅ่ฏฅ่ทฏ็ฑไธไผๅไพง่พนๆ ๅบ็ฐ\n */\n private boolean hidden;\n\n /**\n * ้ๅฎๅๅฐๅ๏ผๅฝ่ฎพ็ฝฎ noRedirect ็ๆถๅ่ฏฅ่ทฏ็ฑๅจ้ขๅ
ๅฑๅฏผ่ชไธญไธๅฏ่ขซ็นๅป\n */\n private String redirect;\n\n /**\n * ็ปไปถๅฐๅ\n */\n private String component;\n\n /**\n * ่ทฏ็ฑๅๆฐ๏ผๅฆ {\"id\": 1, \"name\": \"ry\"}\n */\n private String query;\n\n /**\n * ๅฝไฝ ไธไธช่ทฏ็ฑไธ้ข็ children ๅฃฐๆ็่ทฏ็ฑๅคงไบ1ไธชๆถ๏ผ่ชๅจไผๅๆๅตๅฅ็ๆจกๅผ--ๅฆ็ปไปถ้กต้ข\n */\n private Boolean alwaysShow;\n\n /**\n * ๅ
ถไปๅ
็ด \n */\n private MetaVo meta;\n\n /**\n * ๅญ่ทฏ็ฑ\n */\n private List<RouterVo> children;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public boolean getHidden() {\n return hidden;\n }\n\n public void setHidden(boolean hidden) {\n this.hidden = hidden;\n }\n\n public String getRedirect() {\n return redirect;\n }\n\n public void setRedirect(String redirect) {\n this.redirect = redirect;\n }\n\n public String getComponent() {\n return component;\n }\n\n public void setComponent(String component) {\n this.component = component;\n }\n\n public String getQuery() {\n return query;\n }\n\n public void setQuery(String query) {\n this.query = query;\n }\n\n public Boolean getAlwaysShow() {\n return alwaysShow;\n }\n\n public void setAlwaysShow(Boolean alwaysShow) {\n this.alwaysShow = alwaysShow;\n }\n\n public MetaVo getMeta() {\n return meta;\n }\n\n public void setMeta(MetaVo meta) {\n this.meta = meta;\n }\n\n public List<RouterVo> getChildren() {\n return children;\n }\n\n public void setChildren(List<RouterVo> children) {\n this.children = children;\n }\n}"
}
] | import java.util.List;
import java.util.Set;
import com.ec.common.core.domain.TreeSelect;
import com.ec.common.core.domain.entity.SysMenu;
import com.ec.sys.domain.vo.RouterVo; | 3,018 | package com.ec.sys.service;
/**
* ่ๅ ไธๅกๅฑ
*
* @author ec
*/
public interface ISysMenuService {
/**
* ๆ นๆฎ็จๆทๆฅ่ฏข็ณป็ป่ๅๅ่กจ
*
* @param userId ็จๆทID
* @return ่ๅๅ่กจ
*/
public List<SysMenu> selectMenuList(Long userId);
/**
* ๆ นๆฎ็จๆทๆฅ่ฏข็ณป็ป่ๅๅ่กจ
*
* @param menu ่ๅไฟกๆฏ
* @param userId ็จๆทID
* @return ่ๅๅ่กจ
*/
public List<SysMenu> selectMenuList(SysMenu menu, Long userId);
/**
* ๆ นๆฎ็จๆทIDๆฅ่ฏขๆ้
*
* @param userId ็จๆทID
* @return ๆ้ๅ่กจ
*/
public Set<String> selectMenuPermsByUserId(Long userId);
/**
* ๆ นๆฎ็จๆทIDๆฅ่ฏข่ๅๆ ไฟกๆฏ
*
* @param userId ็จๆทID
* @return ่ๅๅ่กจ
*/
public List<SysMenu> selectMenuTreeByUserId(Long userId);
/**
* ๆ นๆฎ่ง่ฒIDๆฅ่ฏข่ๅๆ ไฟกๆฏ
*
* @param roleId ่ง่ฒID
* @return ้ไธญ่ๅๅ่กจ
*/
public List<Long> selectMenuListByRoleId(Long roleId);
/**
* ๆๅปบๅ็ซฏ่ทฏ็ฑๆ้่ฆ็่ๅ
*
* @param menus ่ๅๅ่กจ
* @return ่ทฏ็ฑๅ่กจ
*/ | package com.ec.sys.service;
/**
* ่ๅ ไธๅกๅฑ
*
* @author ec
*/
public interface ISysMenuService {
/**
* ๆ นๆฎ็จๆทๆฅ่ฏข็ณป็ป่ๅๅ่กจ
*
* @param userId ็จๆทID
* @return ่ๅๅ่กจ
*/
public List<SysMenu> selectMenuList(Long userId);
/**
* ๆ นๆฎ็จๆทๆฅ่ฏข็ณป็ป่ๅๅ่กจ
*
* @param menu ่ๅไฟกๆฏ
* @param userId ็จๆทID
* @return ่ๅๅ่กจ
*/
public List<SysMenu> selectMenuList(SysMenu menu, Long userId);
/**
* ๆ นๆฎ็จๆทIDๆฅ่ฏขๆ้
*
* @param userId ็จๆทID
* @return ๆ้ๅ่กจ
*/
public Set<String> selectMenuPermsByUserId(Long userId);
/**
* ๆ นๆฎ็จๆทIDๆฅ่ฏข่ๅๆ ไฟกๆฏ
*
* @param userId ็จๆทID
* @return ่ๅๅ่กจ
*/
public List<SysMenu> selectMenuTreeByUserId(Long userId);
/**
* ๆ นๆฎ่ง่ฒIDๆฅ่ฏข่ๅๆ ไฟกๆฏ
*
* @param roleId ่ง่ฒID
* @return ้ไธญ่ๅๅ่กจ
*/
public List<Long> selectMenuListByRoleId(Long roleId);
/**
* ๆๅปบๅ็ซฏ่ทฏ็ฑๆ้่ฆ็่ๅ
*
* @param menus ่ๅๅ่กจ
* @return ่ทฏ็ฑๅ่กจ
*/ | public List<RouterVo> buildMenus(List<SysMenu> menus); | 2 | 2023-12-07 14:23:12+00:00 | 4k |
SteveKunG/MinecartSpawnerRevived | src/main/java/com/stevekung/msr/mixin/client/MixinMinecartSpawner.java | [
{
"identifier": "MinecartSpawnerRevived",
"path": "src/main/java/com/stevekung/msr/MinecartSpawnerRevived.java",
"snippet": "public class MinecartSpawnerRevived\n{\n public static final String MOD_ID = \"minecart_spawner_revived\";\n public static final Logger LOGGER = LogUtils.getLogger();\n\n /**\n * Use to request SpawnData from the client side. Then sent the SpawnData into the server.\n */\n public static final ResourceLocation REQUEST_SPAWNDATA = new ResourceLocation(MOD_ID, \"request_spawndata\");\n\n /**\n * Use to send SpawnData to the client side to set spawner display.\n */\n public static final ResourceLocation SEND_SPAWNDATA = new ResourceLocation(MOD_ID, \"send_spawndata\");\n\n public static void init()\n {\n LOGGER.info(\"MinecartSpawnerRevived loaded, #PleaseAddSpawnerMinecartItem!\");\n ServerPlayNetworking.registerGlobalReceiver(MinecartSpawnerRevived.REQUEST_SPAWNDATA, MinecartSpawnerRevived::requestSpawnData);\n }\n\n public static void requestSpawnData(MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender)\n {\n var entityId = buf.readVarInt();\n\n // Make sure to run on the server thread because we use level.getRandom() to get SpawnData from the server side. This will prevent \"Accessing LegacyRandomSource from multiple threads\" error.\n server.execute(() ->\n {\n var spawner = (MinecartSpawner)player.level().getEntity(entityId);\n\n if (spawner != null)\n {\n var level = spawner.level();\n sendSpawnDataPacket(player, entityId, spawner.getSpawner().getOrCreateNextSpawnData(level, level.getRandom(), spawner.blockPosition()));\n }\n });\n }\n\n public static void sendSpawnDataPacket(ServerPlayer player, int entityId, SpawnData spawnData)\n {\n // If an entity to spawn is empty, ignore it.\n if (spawnData.entityToSpawn().isEmpty())\n {\n return;\n }\n\n var packetByteBuf = PacketByteBufs.create();\n packetByteBuf.writeInt(entityId);\n var compound = new CompoundTag();\n compound.put(BaseSpawner.SPAWN_DATA_TAG, SpawnData.CODEC.encodeStart(NbtOps.INSTANCE, spawnData).result().orElseThrow(() -> new IllegalStateException(\"Invalid SpawnData\")));\n packetByteBuf.writeNbt(compound);\n ServerPlayNetworking.send(player, MinecartSpawnerRevived.SEND_SPAWNDATA, packetByteBuf);\n }\n}"
},
{
"identifier": "MinecartSpawnerRevivedClient",
"path": "src/main/java/com/stevekung/msr/MinecartSpawnerRevivedClient.java",
"snippet": "public class MinecartSpawnerRevivedClient\n{\n public static void init()\n {\n ClientPlayNetworking.registerGlobalReceiver(MinecartSpawnerRevived.SEND_SPAWNDATA, MinecartSpawnerRevivedClient::setSpawnerDisplay);\n }\n\n public static void sendSpawnDataRequest(int entityId)\n {\n var buff = PacketByteBufs.create();\n buff.writeVarInt(entityId);\n ClientPlayNetworking.send(MinecartSpawnerRevived.REQUEST_SPAWNDATA, buff);\n }\n\n public static void setSpawnerDisplay(Minecraft minecraft, ClientPacketListener listener, FriendlyByteBuf buf, PacketSender responseSender)\n {\n var entityId = buf.readInt();\n var compoundTag = buf.readNbt();\n var level = minecraft.level;\n\n minecraft.execute(() ->\n {\n if (level != null)\n {\n var spawner = (MinecartSpawner)level.getEntity(entityId);\n\n if (spawner == null || compoundTag == null)\n {\n return;\n }\n\n var spawnData = SpawnData.CODEC.parse(NbtOps.INSTANCE, compoundTag.getCompound(BaseSpawner.SPAWN_DATA_TAG)).resultOrPartial(string -> MinecartSpawnerRevived.LOGGER.warn(\"Invalid SpawnData: {}\", string)).orElseGet(SpawnData::new);\n spawner.getSpawner().displayEntity = EntityType.loadEntityRecursive(spawnData.entityToSpawn(), level, Function.identity());\n }\n });\n }\n}"
},
{
"identifier": "SpawnerClientTicker",
"path": "src/main/java/com/stevekung/msr/client/renderer/SpawnerClientTicker.java",
"snippet": "public interface SpawnerClientTicker\n{\n void msr$clientTick(Level level, MinecartSpawner spawner);\n}"
}
] | import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.stevekung.msr.MinecartSpawnerRevived;
import com.stevekung.msr.MinecartSpawnerRevivedClient;
import com.stevekung.msr.client.renderer.SpawnerClientTicker;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.entity.vehicle.MinecartSpawner;
import net.minecraft.world.level.BaseSpawner;
import net.minecraft.world.level.Level; | 1,672 | package com.stevekung.msr.mixin.client;
@Mixin(MinecartSpawner.class)
public abstract class MixinMinecartSpawner extends AbstractMinecart
{
MixinMinecartSpawner()
{
super(null, null);
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>Re-send a request SpawnData packet to the server when modifying spawner minecart data.</p>
*/
@Inject(method = "readAdditionalSaveData", at = @At("TAIL"))
private void msr$resendSpawnDataRequestOnLoad(CompoundTag compound, CallbackInfo info)
{
if (ClientPlayNetworking.canSend(MinecartSpawnerRevived.REQUEST_SPAWNDATA))
{
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>When entity recreated from a packet, send a request SpawnData packet to the server.</p>
*/
@Override
public void recreateFromPacket(ClientboundAddEntityPacket packet)
{
super.recreateFromPacket(packet);
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-66894">MC-66894</a></p>
*
* <p>Fix Spawner Minecart particles position.</p>
*/
@Redirect(method = "method_31554", at = @At(value = "INVOKE", target = "net/minecraft/world/level/BaseSpawner.clientTick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;)V"))
private void msr$createClientTicker(BaseSpawner spawner, Level level, BlockPos pos)
{ | package com.stevekung.msr.mixin.client;
@Mixin(MinecartSpawner.class)
public abstract class MixinMinecartSpawner extends AbstractMinecart
{
MixinMinecartSpawner()
{
super(null, null);
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>Re-send a request SpawnData packet to the server when modifying spawner minecart data.</p>
*/
@Inject(method = "readAdditionalSaveData", at = @At("TAIL"))
private void msr$resendSpawnDataRequestOnLoad(CompoundTag compound, CallbackInfo info)
{
if (ClientPlayNetworking.canSend(MinecartSpawnerRevived.REQUEST_SPAWNDATA))
{
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>When entity recreated from a packet, send a request SpawnData packet to the server.</p>
*/
@Override
public void recreateFromPacket(ClientboundAddEntityPacket packet)
{
super.recreateFromPacket(packet);
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-66894">MC-66894</a></p>
*
* <p>Fix Spawner Minecart particles position.</p>
*/
@Redirect(method = "method_31554", at = @At(value = "INVOKE", target = "net/minecraft/world/level/BaseSpawner.clientTick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;)V"))
private void msr$createClientTicker(BaseSpawner spawner, Level level, BlockPos pos)
{ | ((SpawnerClientTicker)spawner).msr$clientTick(level, MinecartSpawner.class.cast(this)); | 2 | 2023-12-08 06:53:56+00:00 | 4k |
FRC8806/frcBT_2023 | src/main/java/frc/robot/commands/auto/TrackingPath.java | [
{
"identifier": "SwerveConstants",
"path": "src/main/java/frc/robot/constants/SwerveConstants.java",
"snippet": "public class SwerveConstants {\n //The CAN IDs\n //Throttle\n public static final int A_THROTTLE_ID = 5;\n public static final int B_THROTTLE_ID = 2;\n public static final int C_THROTTLE_ID = 7;\n public static final int D_THROTTLE_ID = 1;\n //Rotor\n public static final int A_ROTOR_ID = 11;\n public static final int B_ROTOR_ID = 8;\n public static final int C_ROTOR_ID = 10;\n public static final int D_ROTOR_ID = 4;\n //Encoder\n public static final int A_ENCODER_ID = 0;\n public static final int B_ENCODER_ID = 1;\n public static final int C_ENCODER_ID = 2;\n public static final int D_ENCODER_ID = 3;\n //IMU\n public static final int IMU_ID = 1;\n \n //The module's constants\n public static final double A_ENCODER_OFFSET = 154 * -1;\n public static final double B_ENCODER_OFFSET = -172 * -1;\n public static final double C_ENCODER_OFFSET = -145 * -1;\n public static final double D_ENCODER_OFFSET = 91 * -1;\n public static final Translation2d A_TRANSLATION2D = new Translation2d(-0.25, 0.25);\n public static final Translation2d B_TRANSLATION2D = new Translation2d(-0.25, -0.25);\n public static final Translation2d C_TRANSLATION2D = new Translation2d(0.25, -0.25);\n public static final Translation2d D_TRANSLATION2D = new Translation2d(0.25, 0.25);\n public static final double kWheelDiameterMeters = 4 * 0.0254;\n public static final double kThrottleGearRatio = 6.12;\n public static final double kThrottlePositionConversionFactor = (kWheelDiameterMeters*Math.PI)/(kThrottleGearRatio*2048);\n public static final double kThrottleVelocityConversionFactor = (kWheelDiameterMeters*10*Math.PI)/(kThrottleGearRatio*2048);//*Math.PI\n public static final double kVoltageCompensation = 12.0;\n public static final double kMaxThrottleVelocity = 6380/60/kThrottleGearRatio*kWheelDiameterMeters*Math.PI;\n\n\n //The chassis's constants\n public static final SwerveDriveKinematics SWERVE_KINEMATICS = new SwerveDriveKinematics( A_TRANSLATION2D, B_TRANSLATION2D, C_TRANSLATION2D, D_TRANSLATION2D);\n public static final double kMaxVelocityMetersPerSecond = 4.0;\n public static final double kMaxAccelerationMetersPerSecond = 3.0;\n public static final double kPathingXP = 0.0;\n public static final double kPathingXI = 0.01;//0.0001\n public static final double kPathingXD = 0.0001;//0.001\n public static final double kPathingYP = 0.0;\n public static final double kPathingYI = 0.01;\n public static final double kPathingYD = 0.0001;\n public static final double kPathingTP = 10;\n public static final double kPathingTI = 0.0;\n public static final double kPathingTD = 0.0;\n\n}"
},
{
"identifier": "DriveTrain",
"path": "src/main/java/frc/robot/subsystems/chassis/DriveTrain.java",
"snippet": "public class DriveTrain extends SubsystemBase {\n private Pigeon2 imu = new Pigeon2(SwerveConstants.IMU_ID);\n private SwerveModule moduleA = new SwerveModule(SwerveConstants.A_THROTTLE_ID, SwerveConstants.A_ROTOR_ID, SwerveConstants.A_ENCODER_ID, SwerveConstants.A_ENCODER_OFFSET);\n private SwerveModule moduleB = new SwerveModule(SwerveConstants.B_THROTTLE_ID, SwerveConstants.B_ROTOR_ID, SwerveConstants.B_ENCODER_ID, SwerveConstants.B_ENCODER_OFFSET);\n private SwerveModule moduleC = new SwerveModule(SwerveConstants.C_THROTTLE_ID, SwerveConstants.C_ROTOR_ID, SwerveConstants.C_ENCODER_ID, SwerveConstants.C_ENCODER_OFFSET);\n private SwerveModule moduleD = new SwerveModule(SwerveConstants.D_THROTTLE_ID, SwerveConstants.D_ROTOR_ID, SwerveConstants.D_ENCODER_ID, SwerveConstants.D_ENCODER_OFFSET);\n private SwerveDriveOdometry odometry;\n public DriveTrain() {\n imu.configFactoryDefault();\n odometry = new SwerveDriveOdometry(SwerveConstants.SWERVE_KINEMATICS, getRotation2d(), getModulePositions());\n }\n\n @Override\n public void periodic() {\n odometry.update(getRotation2d(), getModulePositions());\n SmartDashboard.putNumber(\"imu\", getRotation2d().getDegrees());\n SmartDashboard.putNumber(\"ae\", moduleA.getState().angle.getDegrees());\n SmartDashboard.putNumber(\"be\", moduleB.getState().angle.getDegrees());\n SmartDashboard.putNumber(\"ce\", moduleC.getState().angle.getDegrees());\n SmartDashboard.putNumber(\"de\", moduleD.getState().angle.getDegrees());\n SmartDashboard.putNumber(\"speed\", moduleA.getState().speedMetersPerSecond);\n SmartDashboard.putNumber(\"positionA\", moduleA.getPosition().distanceMeters);\n SmartDashboard.putNumber(\"positionB\", moduleB.getPosition().distanceMeters);\n SmartDashboard.putNumber(\"positionC\", moduleC.getPosition().distanceMeters);\n SmartDashboard.putNumber(\"positionD\", moduleD.getPosition().distanceMeters);\n }\n\n public void drive(double xSpeed, double ySpeed, double zSpeed, boolean fieldOriented) {\n SwerveModuleState [] states = fieldOriented ? \n SwerveConstants.SWERVE_KINEMATICS.toSwerveModuleStates(ChassisSpeeds.fromFieldRelativeSpeeds(\n xSpeed * SwerveConstants.kMaxThrottleVelocity, \n ySpeed * SwerveConstants.kMaxThrottleVelocity, \n zSpeed * 15.64 * 0.6, getRotation2d())):\n SwerveConstants.SWERVE_KINEMATICS.toSwerveModuleStates(new ChassisSpeeds(xSpeed, ySpeed, zSpeed));\n SwerveModuleState [] zeroStates = {\n new SwerveModuleState(0, Rotation2d.fromDegrees(135)), \n new SwerveModuleState(0, Rotation2d.fromDegrees(45)), \n new SwerveModuleState(0, Rotation2d.fromDegrees(135)), \n new SwerveModuleState(0, Rotation2d.fromDegrees(45))};\n states = Math.abs(xSpeed) < 0.07 \n \n && Math.abs(ySpeed) <0.07 && Math.abs(zSpeed) < 0.07 ? \n zeroStates : \n states;\n setModuleStates(states);\n }\n\n public SwerveModuleState [] getModuleStates() {\n return new SwerveModuleState [] {\n moduleA.getState(),\n moduleB.getState(),\n moduleC.getState(),\n moduleD.getState()\n };\n }\n\n public SwerveModulePosition [] getModulePositions() {\n return new SwerveModulePosition [] {\n moduleA.getPosition(),\n moduleB.getPosition(),\n moduleC.getPosition(),\n moduleD.getPosition()\n };\n }\n\n public void setModuleStates(SwerveModuleState [] desiredStates) {\n SwerveDriveKinematics.desaturateWheelSpeeds(desiredStates, SwerveConstants.kMaxThrottleVelocity);\n moduleA.setState(desiredStates[0]);\n moduleB.setState(desiredStates[1]);\n moduleC.setState(desiredStates[2]);\n moduleD.setState(desiredStates[3]);\n }\n\n public Pose2d getPose() {\n return odometry.getPoseMeters();\n }\n\n public void resetPose(Pose2d pose) {\n odometry.resetPosition(getRotation2d(), getModulePositions(), pose);\n }\n\n private Rotation2d getRotation2d() {\n return Rotation2d.fromDegrees(imu.getYaw() - 90);\n }\n}"
}
] | import com.pathplanner.lib.PathPlanner;
import com.pathplanner.lib.commands.PPSwerveControllerCommand;
import edu.wpi.first.math.controller.PIDController;
import frc.robot.constants.SwerveConstants;
import frc.robot.subsystems.chassis.DriveTrain; | 2,346 | // ___________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________
// 88 88 88 88 00 00 66
// 88 88 88 88 00 00 66 ________________________
// 88 88 88 88 00 00 66
// 8888888888888888 8888888888888888 00 00 6666666666666666 _____________
// 88 88 88 88 00 00 66 66
// 88 88 88 88 00 00 66 66 _____________________
// 88 88 88 88 00 00 66 66 ________________________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________
// __________________________ __________
package frc.robot.commands.auto;
public class TrackingPath extends PPSwerveControllerCommand{
public TrackingPath(DriveTrain driveTrain,String pathName) {
super( | // ___________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________
// 88 88 88 88 00 00 66
// 88 88 88 88 00 00 66 ________________________
// 88 88 88 88 00 00 66
// 8888888888888888 8888888888888888 00 00 6666666666666666 _____________
// 88 88 88 88 00 00 66 66
// 88 88 88 88 00 00 66 66 _____________________
// 88 88 88 88 00 00 66 66 ________________________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________
// __________________________ __________
package frc.robot.commands.auto;
public class TrackingPath extends PPSwerveControllerCommand{
public TrackingPath(DriveTrain driveTrain,String pathName) {
super( | PathPlanner.loadPath(pathName, SwerveConstants.kMaxVelocityMetersPerSecond, SwerveConstants.kMaxAccelerationMetersPerSecond), | 0 | 2023-12-13 11:38:11+00:00 | 4k |
applepi-2067/2023_Pure_Swerve | src/main/java/frc/robot/subsystems/SteerMotor.java | [
{
"identifier": "Conversions",
"path": "src/main/java/frc/robot/utils/Conversions.java",
"snippet": "public class Conversions {\n public static double RPMToTicksPer100ms(double RPM, double ticksPerRev) {\n return RPM * ticksPerRev / (60.0 * 10.0);\n }\n\n public static double ticksPer100msToRPM(double ticksPer100ms, double ticksPerRev) {\n return ticksPer100ms * (10.0 * 60.0) * (1.0 / ticksPerRev);\n }\n\n\n public static double ticksToMeters(double ticks, double ticksPerRev, double radiusMeters) {\n return ticks * (1.0 / ticksPerRev) * (Math.PI * 2.0 * radiusMeters);\n }\n\n public static double metersToTicks(double meters, double ticksPerRev, double radiusMeters) {\n return meters * (1.0 / (Math.PI * 2.0 * radiusMeters)) * ticksPerRev;\n }\n\n\n public static double metersPerSecondToRPM(double metersPerSecond, double radiusMeters) {\n return metersPerSecond * 60.0 / (radiusMeters * (2.0 * Math.PI));\n }\n\n public static double rpmToMetersPerSecond(double RPM, double radiusMeters) {\n return RPM * (1.0 / 60.0) * (2 * Math.PI) * radiusMeters;\n }\n\n \n public static double degreesToTicks(double degrees, double ticksPerRev) {\n return degrees * (1.0 / 360.0) * ticksPerRev;\n }\n\n public static double ticksToDegrees(double ticks, double ticksPerRev) {\n return ticks * (1.0 / ticksPerRev) * 360.0;\n }\n}"
},
{
"identifier": "Gains",
"path": "src/main/java/frc/robot/utils/Gains.java",
"snippet": "public class Gains {\n public final double kP;\n\tpublic final double kI;\n\tpublic final double kD;\n\tpublic final double kF;\n\tpublic final double kIzone;\n\tpublic final double kPeakOutput;\n\t\n\tpublic Gains(double _kP, double _kF, double _kPeakOutput) {\n\t\tthis(_kP, 0.0, 0.0, _kF, 0.0, _kPeakOutput);\n\t}\n\n\tpublic Gains(\n\t\tdouble _kP, double _kI, double _kD,\n\t\tdouble _kF, double _kIzone, double _kPeakOutput\n\t) {\n\t\tkP = _kP;\n\t\tkI = _kI;\n\t\tkD = _kD;\n\t\tkF = _kF;\n\t\tkIzone = _kIzone;\n\t\tkPeakOutput = _kPeakOutput;\n }\n\n\tpublic void setGains(SparkMaxPIDController pidController, int pidSlot) {\n\t\tpidController.setP(kP, pidSlot);\n pidController.setI(kI, pidSlot);\n pidController.setD(kD, pidSlot);\n pidController.setFF(kF, pidSlot); \n pidController.setIZone(kIzone, pidSlot);\n pidController.setOutputRange(-kPeakOutput, kPeakOutput, pidSlot);\n\t}\n\n\tpublic void setGains(WPI_TalonFX motor, int pidSlot, int pidLoop, int timeoutMS) {\n\t\tmotor.selectProfileSlot(pidSlot, pidLoop);\n\n motor.config_kF(pidSlot, kF, timeoutMS);\n motor.config_kP(pidSlot, kP, timeoutMS);\n motor.config_kI(pidSlot, kI, timeoutMS);\n motor.config_kD(pidSlot, kD, timeoutMS);\n motor.config_IntegralZone(pidSlot, kIzone, timeoutMS);\n\n // Set peak (max) and nominal (min) outputs.\n motor.configNominalOutputForward(0.0, timeoutMS);\n motor.configNominalOutputReverse(0.0, timeoutMS);\n motor.configPeakOutputForward(kPeakOutput, timeoutMS);\n motor.configPeakOutputReverse(-1.0 * kPeakOutput, timeoutMS);\n\t}\n\n\tpublic static void configSmartMotion(\n\t\tSparkMaxPIDController pidController,\n\t\tdouble maxVelocityRPM,\n\t\tdouble minVelocityRPM,\n\t\tdouble maxAccelRPMPerSec,\n\t\tdouble allowedErrorRotations,\n\t\tint pidSlot\n\t) {\n pidController.setSmartMotionMaxVelocity(maxVelocityRPM, pidSlot);\n pidController.setSmartMotionMinOutputVelocity(minVelocityRPM, pidSlot);\n pidController.setSmartMotionMaxAccel(maxAccelRPMPerSec, pidSlot);\n pidController.setSmartMotionAllowedClosedLoopError(allowedErrorRotations, pidSlot);\n }\n\n\tpublic static void configMotionMagic(\n\t\tWPI_TalonFX motor,\n\t\tint cruiseVelocityTicksPer100MS,\n\t\tint maxAccelTicksPer100MS_PerSec,\n\t\tint timeoutMS\n\t) {\n\t\tmotor.configMotionCruiseVelocity(cruiseVelocityTicksPer100MS, timeoutMS);\n\t\tmotor.configMotionAcceleration(maxAccelTicksPer100MS_PerSec, timeoutMS);\n\t}\n}"
}
] | import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.SupplyCurrentLimitConfiguration;
import com.ctre.phoenix.motorcontrol.TalonFXControlMode;
import com.ctre.phoenix.motorcontrol.TalonFXFeedbackDevice;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX;
import com.ctre.phoenix.sensors.CANCoder;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.utils.Conversions;
import frc.robot.utils.Gains; | 1,893 | package frc.robot.subsystems;
public class SteerMotor {
private final WPI_TalonFX m_motor;
private final CANCoder m_canCoder;
// Motor settings.
private static final boolean ENABLE_CURRENT_LIMIT = true;
private static final double CONTINUOUS_CURRENT_LIMIT_AMPS = 55.0;
private static final double TRIGGER_THRESHOLD_LIMIT_AMPS = 60.0;
private static final double TRIGGER_THRESHOLD_TIME_SECONDS = 0.5;
private static final double PERCENT_DEADBAND = 0.001;
// Conversion constants.
private static final double TICKS_PER_REV = 2048.0;
private static final double GEAR_RATIO = 150.0 / 7.0;
// PID.
private static final int K_TIMEOUT_MS = 10;
private static final int K_PID_LOOP = 0;
private static final int K_PID_SLOT = 0;
private static final Gains PID_GAINS = new Gains(0.5, 0.0, 1.0);
private static final int CRUISE_VELOCITY_TICKS_PER_100MS = 20_000;
private static final int MAX_ACCEL_TICKS_PER_100MS_PER_SEC = CRUISE_VELOCITY_TICKS_PER_100MS * 2;
// For debugging.
private int canID;
private double wheelZeroOffsetDegrees;
public SteerMotor(int canID, int canCoderID, double wheelZeroOffsetDegrees, boolean invertMotor) {
this.canID = canID;
this.wheelZeroOffsetDegrees = wheelZeroOffsetDegrees;
// Motor.
m_motor = new WPI_TalonFX(canID);
m_motor.configFactoryDefault();
m_motor.setInverted(invertMotor);
// Coast allows for easier wheel offset tuning.
// Note that brake mode isn't neeeded b/c pid loop runs in background continuously.
m_motor.setNeutralMode(NeutralMode.Coast);
// Limit current going to motor.
SupplyCurrentLimitConfiguration talonCurrentLimit = new SupplyCurrentLimitConfiguration(
ENABLE_CURRENT_LIMIT, CONTINUOUS_CURRENT_LIMIT_AMPS,
TRIGGER_THRESHOLD_LIMIT_AMPS, TRIGGER_THRESHOLD_TIME_SECONDS
);
m_motor.configSupplyCurrentLimit(talonCurrentLimit);
// Seed encoder w/ abs encoder (CAN Coder reading) + wheel zero offset.
m_canCoder = new CANCoder(canCoderID);
| package frc.robot.subsystems;
public class SteerMotor {
private final WPI_TalonFX m_motor;
private final CANCoder m_canCoder;
// Motor settings.
private static final boolean ENABLE_CURRENT_LIMIT = true;
private static final double CONTINUOUS_CURRENT_LIMIT_AMPS = 55.0;
private static final double TRIGGER_THRESHOLD_LIMIT_AMPS = 60.0;
private static final double TRIGGER_THRESHOLD_TIME_SECONDS = 0.5;
private static final double PERCENT_DEADBAND = 0.001;
// Conversion constants.
private static final double TICKS_PER_REV = 2048.0;
private static final double GEAR_RATIO = 150.0 / 7.0;
// PID.
private static final int K_TIMEOUT_MS = 10;
private static final int K_PID_LOOP = 0;
private static final int K_PID_SLOT = 0;
private static final Gains PID_GAINS = new Gains(0.5, 0.0, 1.0);
private static final int CRUISE_VELOCITY_TICKS_PER_100MS = 20_000;
private static final int MAX_ACCEL_TICKS_PER_100MS_PER_SEC = CRUISE_VELOCITY_TICKS_PER_100MS * 2;
// For debugging.
private int canID;
private double wheelZeroOffsetDegrees;
public SteerMotor(int canID, int canCoderID, double wheelZeroOffsetDegrees, boolean invertMotor) {
this.canID = canID;
this.wheelZeroOffsetDegrees = wheelZeroOffsetDegrees;
// Motor.
m_motor = new WPI_TalonFX(canID);
m_motor.configFactoryDefault();
m_motor.setInverted(invertMotor);
// Coast allows for easier wheel offset tuning.
// Note that brake mode isn't neeeded b/c pid loop runs in background continuously.
m_motor.setNeutralMode(NeutralMode.Coast);
// Limit current going to motor.
SupplyCurrentLimitConfiguration talonCurrentLimit = new SupplyCurrentLimitConfiguration(
ENABLE_CURRENT_LIMIT, CONTINUOUS_CURRENT_LIMIT_AMPS,
TRIGGER_THRESHOLD_LIMIT_AMPS, TRIGGER_THRESHOLD_TIME_SECONDS
);
m_motor.configSupplyCurrentLimit(talonCurrentLimit);
// Seed encoder w/ abs encoder (CAN Coder reading) + wheel zero offset.
m_canCoder = new CANCoder(canCoderID);
| double initPositionTicks = Conversions.degreesToTicks( | 0 | 2023-12-13 02:33:42+00:00 | 4k |
ganeshbabugb/NASC-CMS | src/main/java/com/nasc/application/data/components/CreateBloodGroupCrud.java | [
{
"identifier": "BloodGroupEntity",
"path": "src/main/java/com/nasc/application/data/core/BloodGroupEntity.java",
"snippet": "@Entity\n@Data\n@Table(name = \"t_blood_groups\")\npublic class BloodGroupEntity implements BaseEntity {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n\n @Override\n public String toString() {\n return name;\n }\n}"
},
{
"identifier": "BloodGroupService",
"path": "src/main/java/com/nasc/application/services/BloodGroupService.java",
"snippet": "@Service\npublic class BloodGroupService extends BaseServiceClass<BloodGroupEntity> {\n\n private final BloodGroupRepository bloodGroupRepository;\n\n @Autowired\n public BloodGroupService(BloodGroupRepository bloodGroupRepository) {\n this.bloodGroupRepository = bloodGroupRepository;\n }\n\n @Override\n public List<BloodGroupEntity> findAll() {\n return bloodGroupRepository.findAll();\n }\n\n @Override\n public void save(BloodGroupEntity item) {\n bloodGroupRepository.save(item);\n }\n\n @Override\n public void delete(BloodGroupEntity item) {\n bloodGroupRepository.delete(item);\n }\n}"
},
{
"identifier": "GenericDataProvider",
"path": "src/main/java/com/nasc/application/services/dataprovider/GenericDataProvider.java",
"snippet": "public class GenericDataProvider<T extends BaseEntity> extends AbstractBackEndDataProvider<T, CrudFilter> {\n private final Class<T> typeParameterClass;\n private final BaseServiceClass serviceClass;\n private final List<T> DATABASE;\n private Consumer<Long> sizeChangeListener;\n\n public GenericDataProvider(Class<T> typeParameterClass, BaseServiceClass serviceClass) {\n this.typeParameterClass = typeParameterClass;\n this.serviceClass = serviceClass;\n DATABASE = serviceClass.findAll();\n }\n\n public void persist(T item) {\n final Optional<T> existingItem = find(item.getId());\n if (existingItem.isPresent()) {\n int position = DATABASE.indexOf(existingItem.get());\n DATABASE.remove(existingItem.get());\n DATABASE.add(position, item);\n } else {\n DATABASE.add(item);\n }\n serviceClass.save(item);\n }\n\n public void delete(T item) {\n try {\n serviceClass.delete(item);\n DATABASE.removeIf(entity -> entity.getId().equals(item.getId()));\n } catch (Exception e) {\n throw e;\n }\n }\n\n public void setSizeChangeListener(Consumer<Long> listener) {\n sizeChangeListener = listener;\n }\n\n @Override\n protected Stream<T> fetchFromBackEnd(Query<T, CrudFilter> query) {\n int offset = query.getOffset();\n int limit = query.getLimit();\n Stream<T> stream = DATABASE.stream();\n if (query.getFilter().isPresent())\n stream = stream.filter(predicate(query.getFilter().get())).sorted(comparator(query.getFilter().get()));\n return stream.skip(offset).limit(limit);\n }\n\n @Override\n protected int sizeInBackEnd(Query<T, CrudFilter> query) {\n long count = fetchFromBackEnd(query).count();\n if (sizeChangeListener != null)\n sizeChangeListener.accept(count);\n return (int) count;\n }\n\n private Predicate<T> predicate(CrudFilter filter) {\n return filter.getConstraints().entrySet().stream().map(constraint -> (Predicate<T>) obj -> {\n try {\n Object value = valueOf(constraint.getKey(), obj);\n return value != null && value.toString().toLowerCase().contains(constraint.getValue().toLowerCase());\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }).reduce(Predicate::and).orElse(e -> true);\n }\n\n private Comparator<T> comparator(CrudFilter filter) {\n return filter.getSortOrders().entrySet().stream().map(sortClause -> {\n try {\n Comparator<T> comparator = Comparator.comparing(obj -> (Comparable) valueOf(sortClause.getKey(), obj));\n if (sortClause.getValue() == SortDirection.DESCENDING) {\n comparator = comparator.reversed();\n }\n return comparator;\n } catch (Exception ex) {\n return (Comparator<T>) (o1, o2) -> 0;\n }\n }).reduce(Comparator::thenComparing).orElse((o1, o2) -> 0);\n }\n\n private Object valueOf(String fieldName, T obj) {\n try {\n Field field = typeParameterClass.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field.get(obj);\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n private Optional<T> find(Long id) {\n return DATABASE.stream().filter(entity -> entity.getId().equals(id)).findFirst();\n }\n}"
},
{
"identifier": "NotificationUtils",
"path": "src/main/java/com/nasc/application/utils/NotificationUtils.java",
"snippet": "public class NotificationUtils {\n\n // Duration\n private static final int SUCCESS_NOTIFICATION_DURATION = 2000;\n private static final int INFO_NOTIFICATION_DURATION = 3000;\n private static final int ERROR_NOTIFICATION_DURATION = 4000;\n private static final int WARNING_NOTIFICATION_DURATION = 5000;\n\n // Position\n private static final Notification.Position SUCCESS_NOTIFICATION_POSITION = Notification.Position.BOTTOM_END;\n private static final Notification.Position ERROR_NOTIFICATION_POSITION = Notification.Position.TOP_END;\n private static final Notification.Position INFO_NOTIFICATION_POSITION = Notification.Position.TOP_CENTER;\n private static final Notification.Position WARNING_NOTIFICATION_POSITION = Notification.Position.BOTTOM_CENTER;\n\n public static void showSuccessNotification(String message) {\n showNotification(message, SUCCESS_NOTIFICATION_DURATION, SUCCESS_NOTIFICATION_POSITION, VaadinIcon.CHECK_CIRCLE.create());\n }\n\n public static void showInfoNotification(String message) {\n showNotification(message, INFO_NOTIFICATION_DURATION, INFO_NOTIFICATION_POSITION, VaadinIcon.INFO_CIRCLE.create());\n }\n\n public static void showErrorNotification(String message) {\n showNotification(message, ERROR_NOTIFICATION_DURATION, ERROR_NOTIFICATION_POSITION, VaadinIcon.EXCLAMATION_CIRCLE.create());\n }\n\n public static void showWarningNotification(String message) {\n showNotification(message, WARNING_NOTIFICATION_DURATION, WARNING_NOTIFICATION_POSITION, VaadinIcon.WARNING.create());\n }\n\n private static void showNotification(String message, int duration, Notification.Position position, Icon icon) {\n Notification notification = new Notification();\n\n Div messageDiv = new Div(new Text(message));\n messageDiv.getStyle().set(\"font-weight\", \"600\");\n\n Icon closeIcon = VaadinIcon.CLOSE.create();\n closeIcon.addClickListener(event -> notification.close());\n\n HorizontalLayout layout = new HorizontalLayout(icon, messageDiv, closeIcon);\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.setDuration(duration);\n notification.setPosition(position);\n notification.open();\n }\n\n public static void createSubmitSuccess(String message) {\n Notification notification = new Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);\n\n\n Icon icon = VaadinIcon.CHECK_CIRCLE.create();\n\n HorizontalLayout layout = new HorizontalLayout(icon, new Text(message));\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.setDuration(SUCCESS_NOTIFICATION_DURATION);\n notification.setPosition(SUCCESS_NOTIFICATION_POSITION);\n notification.open();\n }\n\n public static void createReportError(String message) {\n Notification notification = new Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_ERROR);\n\n notification.setDuration(ERROR_NOTIFICATION_DURATION);\n notification.setPosition(ERROR_NOTIFICATION_POSITION);\n\n Icon icon = VaadinIcon.WARNING.create();\n\n HorizontalLayout layout = new HorizontalLayout(icon, new Text(message));\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.open();\n }\n\n public static void createUploadSuccess(String message, String fileName) {\n Notification notification = new Notification();\n\n Icon icon = VaadinIcon.CHECK_CIRCLE.create();\n icon.setColor(\"var(--lumo-success-color)\");\n\n Div uploadSuccessful = new Div(new Text(message));\n uploadSuccessful.getStyle()\n .set(\"font-weight\", \"600\")\n .setColor(\"var(--lumo-success-text-color)\");\n\n Span fn = new Span(fileName);\n fn.getStyle()\n .set(\"font-size\", \"var(--lumo-font-size-s)\")\n .set(\"font-weight\", \"600\");\n\n var layout = new HorizontalLayout(icon, uploadSuccessful, new Text(\" \"), fn);\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n\n notification.setDuration(SUCCESS_NOTIFICATION_DURATION);\n notification.setPosition(SUCCESS_NOTIFICATION_POSITION);\n notification.open();\n }\n}"
}
] | import com.flowingcode.vaadin.addons.fontawesome.FontAwesome;
import com.nasc.application.data.core.BloodGroupEntity;
import com.nasc.application.services.BloodGroupService;
import com.nasc.application.services.dataprovider.GenericDataProvider;
import com.nasc.application.utils.NotificationUtils;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.crud.BinderCrudEditor;
import com.vaadin.flow.component.crud.Crud;
import com.vaadin.flow.component.crud.CrudEditor;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.provider.Query;
import com.vaadin.flow.spring.annotation.UIScope;
import com.vaadin.flow.theme.lumo.LumoIcon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import software.xdev.vaadin.grid_exporter.GridExporter;
import software.xdev.vaadin.grid_exporter.column.ColumnConfigurationBuilder; | 2,803 | package com.nasc.application.data.components;
@Component
@UIScope
public class CreateBloodGroupCrud extends VerticalLayout {
private final String EDIT_COLUMN = "vaadin-crud-edit-column";
private final BloodGroupService service;
private final Crud<BloodGroupEntity> crud;
@Autowired
public CreateBloodGroupCrud(BloodGroupService service) {
this.service = service;
crud = new Crud<>(BloodGroupEntity.class, createEditor());
createGrid();
setupDataProvider();
HorizontalLayout horizontalLayout = new HorizontalLayout();
Button exportButton = new Button(
"Export",
FontAwesome.Solid.FILE_EXPORT.create(),
e -> {
int size = crud.getDataProvider().size(new Query<>());
if (size > 0) {
String fileName = "Blood Group";
GridExporter.newWithDefaults(crud.getGrid())
//Removing Edit Column For Export
.withColumnFilter(stateEntityColumn -> !stateEntityColumn.getKey().equals(EDIT_COLUMN))
.withFileName(fileName)
.withColumnConfigurationBuilder(new ColumnConfigurationBuilder())
.open();
}
}
);
exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
horizontalLayout.setWidthFull();
horizontalLayout.setJustifyContentMode(JustifyContentMode.END);
horizontalLayout.setAlignItems(Alignment.CENTER);
horizontalLayout.add(exportButton);
Button newItemBtn = new Button("Create New Blood Group", LumoIcon.PLUS.create());
newItemBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
crud.setNewButton(newItemBtn);
setAlignItems(Alignment.STRETCH);
expand(crud);
setSizeFull();
add(horizontalLayout, crud);
}
private CrudEditor<BloodGroupEntity> createEditor() {
TextField field = new TextField("Blood Group");
FormLayout form = new FormLayout(field);
form.setMaxWidth("480px");
form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1),
new FormLayout.ResponsiveStep("30em", 2));
Binder<BloodGroupEntity> binder = new Binder<>(BloodGroupEntity.class);
binder.forField(field).asRequired().bind(BloodGroupEntity::getName, BloodGroupEntity::setName);
return new BinderCrudEditor<>(binder, form);
}
private void createGrid() {
Grid<BloodGroupEntity> grid = crud.getGrid();
grid.removeColumnByKey("id");
grid.getColumnByKey(EDIT_COLUMN).setHeader("Edit");
grid.getColumnByKey(EDIT_COLUMN).setWidth("100px");
grid.getColumnByKey(EDIT_COLUMN).setResizable(false);
}
private void setupDataProvider() { | package com.nasc.application.data.components;
@Component
@UIScope
public class CreateBloodGroupCrud extends VerticalLayout {
private final String EDIT_COLUMN = "vaadin-crud-edit-column";
private final BloodGroupService service;
private final Crud<BloodGroupEntity> crud;
@Autowired
public CreateBloodGroupCrud(BloodGroupService service) {
this.service = service;
crud = new Crud<>(BloodGroupEntity.class, createEditor());
createGrid();
setupDataProvider();
HorizontalLayout horizontalLayout = new HorizontalLayout();
Button exportButton = new Button(
"Export",
FontAwesome.Solid.FILE_EXPORT.create(),
e -> {
int size = crud.getDataProvider().size(new Query<>());
if (size > 0) {
String fileName = "Blood Group";
GridExporter.newWithDefaults(crud.getGrid())
//Removing Edit Column For Export
.withColumnFilter(stateEntityColumn -> !stateEntityColumn.getKey().equals(EDIT_COLUMN))
.withFileName(fileName)
.withColumnConfigurationBuilder(new ColumnConfigurationBuilder())
.open();
}
}
);
exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
horizontalLayout.setWidthFull();
horizontalLayout.setJustifyContentMode(JustifyContentMode.END);
horizontalLayout.setAlignItems(Alignment.CENTER);
horizontalLayout.add(exportButton);
Button newItemBtn = new Button("Create New Blood Group", LumoIcon.PLUS.create());
newItemBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
crud.setNewButton(newItemBtn);
setAlignItems(Alignment.STRETCH);
expand(crud);
setSizeFull();
add(horizontalLayout, crud);
}
private CrudEditor<BloodGroupEntity> createEditor() {
TextField field = new TextField("Blood Group");
FormLayout form = new FormLayout(field);
form.setMaxWidth("480px");
form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1),
new FormLayout.ResponsiveStep("30em", 2));
Binder<BloodGroupEntity> binder = new Binder<>(BloodGroupEntity.class);
binder.forField(field).asRequired().bind(BloodGroupEntity::getName, BloodGroupEntity::setName);
return new BinderCrudEditor<>(binder, form);
}
private void createGrid() {
Grid<BloodGroupEntity> grid = crud.getGrid();
grid.removeColumnByKey("id");
grid.getColumnByKey(EDIT_COLUMN).setHeader("Edit");
grid.getColumnByKey(EDIT_COLUMN).setWidth("100px");
grid.getColumnByKey(EDIT_COLUMN).setResizable(false);
}
private void setupDataProvider() { | GenericDataProvider<BloodGroupEntity> genericDataProvider = | 2 | 2023-12-10 18:07:28+00:00 | 4k |
Viola-Siemens/StellarForge | src/main/java/com/hexagram2021/stellarforge/common/register/SFBlocks.java | [
{
"identifier": "PillarBlock",
"path": "src/main/java/com/hexagram2021/stellarforge/common/block/PillarBlock.java",
"snippet": "@SuppressWarnings(\"deprecation\")\npublic class PillarBlock extends RotatedPillarBlock {\n\tpublic static final BooleanProperty HEAD = SFBlockStateProperties.HEAD;\n\tpublic static final BooleanProperty HEEL = SFBlockStateProperties.HEEL;\n\n\tpublic PillarBlock(Properties props) {\n\t\tsuper(props);\n\t\tthis.registerDefaultState(this.defaultBlockState().setValue(HEAD, true).setValue(HEEL, true));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n\t\tsuper.createBlockStateDefinition(builder);\n\t\tbuilder.add(HEAD).add(HEEL);\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState blockState, Level level, BlockPos blockPos, BlockState oldBlockState, boolean piston) {\n\t\tfor(Direction direction : Direction.values()) {\n\t\t\tlevel.updateNeighborsAt(blockPos.relative(direction), this);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void neighborChanged(BlockState blockState, Level level, BlockPos blockPos, Block neighbor, BlockPos neighborPos, boolean piston) {\n\t\tDirection.Axis axis = blockState.getValue(AXIS);\n\t\tDirection delta = Direction.fromDelta(blockPos.getX() - neighborPos.getX(), blockPos.getY() - neighborPos.getY(), blockPos.getZ() - neighborPos.getZ());\n\n\t\tif(delta != null && axis.test(delta)) {\n\t\t\tDirection.AxisDirection axisDirection = delta.getAxisDirection();\n\t\t\tBooleanProperty effected = axisDirection.getStep() > 0 ? HEEL : HEAD;\n\t\t\tBlockState neighborState = level.getBlockState(neighborPos);\n\t\t\tboolean flag = neighborState.getBlock() == this && neighborState.hasProperty(AXIS) && neighborState.getValue(AXIS) == axis;\n\t\t\tif(blockState.getValue(effected) == flag) {\n\t\t\t\tlevel.setBlockAndUpdate(blockPos, blockState.setValue(effected, !flag));\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"identifier": "MODID",
"path": "src/main/java/com/hexagram2021/stellarforge/StellarForge.java",
"snippet": "public static final String MODID = \"stellarforge\";"
},
{
"identifier": "getRegistryName",
"path": "src/main/java/com/hexagram2021/stellarforge/common/util/RegistryHelper.java",
"snippet": "static ResourceLocation getRegistryName(Item item) {\n\treturn Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(item));\n}"
}
] | import com.google.common.collect.ImmutableList;
import com.hexagram2021.stellarforge.common.block.PillarBlock;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.SlabType;
import net.minecraft.world.level.material.MapColor;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import org.apache.commons.lang3.tuple.Pair;
import java.util.function.Function;
import java.util.function.Supplier;
import static com.hexagram2021.stellarforge.StellarForge.MODID;
import static com.hexagram2021.stellarforge.common.util.RegistryHelper.getRegistryName; | 2,150 | package com.hexagram2021.stellarforge.common.register;
public final class SFBlocks {
public static final DeferredRegister<Block> REGISTER = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
public static final class Bricks {
public static final DecorBlockEntry MOSSY_BRICKS = new DecorBlockEntry("mossy_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_BRICKS = new DecorBlockEntry("cracked_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_BRICKS = new BlockEntry<>("chiseled_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_NETHER_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_NETHER_BRICKS, SFBlocks::toItem);
private Bricks() {
}
private static void init() {
}
}
public static final class Igneous {
public static final DecorBlockEntry ANDESITE_BRICKS = new DecorBlockEntry("andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_ANDESITE_BRICKS = new DecorBlockEntry("mossy_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_ANDESITE_BRICKS = new BlockEntry<>("chiseled_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_ANDESITE_BRICKS = new DecorBlockEntry("cracked_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry DIORITE_BRICKS = new DecorBlockEntry("diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_DIORITE_BRICKS = new DecorBlockEntry("mossy_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_DIORITE_BRICKS = new BlockEntry<>("chiseled_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DIORITE_BRICKS = new DecorBlockEntry("cracked_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry GRANITE_BRICKS = new DecorBlockEntry("granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_GRANITE_BRICKS = new DecorBlockEntry("mossy_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_GRANITE_BRICKS = new BlockEntry<>("chiseled_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_GRANITE_BRICKS = new DecorBlockEntry("cracked_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
private Igneous() {
}
private static void init() {
}
}
public static final class Stone {
//vanilla
public static final DecorBlockEntry CRACKED_STONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_STONE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry DEEPSLATE = DecorBlockEntry.createFromFull(Blocks.DEEPSLATE, SFBlocks::toItem);
public static final BlockEntry<ButtonBlock> DEEPSLATE_BUTTON = new BlockEntry<>("deepslate_button", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BUTTON), props -> new ButtonBlock(props, SFBlockSetTypes.DEEPSLATE, 20, false), SFBlocks::toItem);
public static final BlockEntry<PressurePlateBlock> DEEPSLATE_PRESSURE_PLATE = new BlockEntry<>("deepslate_pressure_plate", () -> BlockBehaviour.Properties.copy(Blocks.STONE_PRESSURE_PLATE), props -> new PressurePlateBlock(PressurePlateBlock.Sensitivity.MOBS, props, SFBlockSetTypes.DEEPSLATE), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_TILES = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_TILES, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_POLISHED_BLACKSTONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS, SFBlocks::toItem);
//blackstone
public static final DecorBlockEntry COBBLED_BLACKSTONE = new DecorBlockEntry("cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_COBBLED_BLACKSTONE = new DecorBlockEntry("mossy_cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry SMOOTH_BLACKSTONE = new DecorBlockEntry("smooth_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); | package com.hexagram2021.stellarforge.common.register;
public final class SFBlocks {
public static final DeferredRegister<Block> REGISTER = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
public static final class Bricks {
public static final DecorBlockEntry MOSSY_BRICKS = new DecorBlockEntry("mossy_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_BRICKS = new DecorBlockEntry("cracked_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_BRICKS = new BlockEntry<>("chiseled_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_NETHER_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_NETHER_BRICKS, SFBlocks::toItem);
private Bricks() {
}
private static void init() {
}
}
public static final class Igneous {
public static final DecorBlockEntry ANDESITE_BRICKS = new DecorBlockEntry("andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_ANDESITE_BRICKS = new DecorBlockEntry("mossy_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_ANDESITE_BRICKS = new BlockEntry<>("chiseled_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_ANDESITE_BRICKS = new DecorBlockEntry("cracked_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry DIORITE_BRICKS = new DecorBlockEntry("diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_DIORITE_BRICKS = new DecorBlockEntry("mossy_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_DIORITE_BRICKS = new BlockEntry<>("chiseled_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DIORITE_BRICKS = new DecorBlockEntry("cracked_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry GRANITE_BRICKS = new DecorBlockEntry("granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_GRANITE_BRICKS = new DecorBlockEntry("mossy_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_GRANITE_BRICKS = new BlockEntry<>("chiseled_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_GRANITE_BRICKS = new DecorBlockEntry("cracked_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
private Igneous() {
}
private static void init() {
}
}
public static final class Stone {
//vanilla
public static final DecorBlockEntry CRACKED_STONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_STONE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry DEEPSLATE = DecorBlockEntry.createFromFull(Blocks.DEEPSLATE, SFBlocks::toItem);
public static final BlockEntry<ButtonBlock> DEEPSLATE_BUTTON = new BlockEntry<>("deepslate_button", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BUTTON), props -> new ButtonBlock(props, SFBlockSetTypes.DEEPSLATE, 20, false), SFBlocks::toItem);
public static final BlockEntry<PressurePlateBlock> DEEPSLATE_PRESSURE_PLATE = new BlockEntry<>("deepslate_pressure_plate", () -> BlockBehaviour.Properties.copy(Blocks.STONE_PRESSURE_PLATE), props -> new PressurePlateBlock(PressurePlateBlock.Sensitivity.MOBS, props, SFBlockSetTypes.DEEPSLATE), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_TILES = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_TILES, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_POLISHED_BLACKSTONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS, SFBlocks::toItem);
//blackstone
public static final DecorBlockEntry COBBLED_BLACKSTONE = new DecorBlockEntry("cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_COBBLED_BLACKSTONE = new DecorBlockEntry("mossy_cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry SMOOTH_BLACKSTONE = new DecorBlockEntry("smooth_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); | public static final BlockEntry<PillarBlock> POLISHED_BLACKSTONE_PILLAR = new BlockEntry<>("polished_blackstone_pillar", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), PillarBlock::new, SFBlocks::toItem); | 0 | 2023-12-10 07:20:43+00:00 | 4k |
deepcloudlabs/dcl350-2023-dec-04 | hr-core-subdomain/src/com/example/hr/application/business/StandardHrApplication.java | [
{
"identifier": "HrApplication",
"path": "hr-core-subdomain/src/com/example/hr/application/HrApplication.java",
"snippet": "@Port(PortType.DRIVING)\npublic interface HrApplication {\n\tOptional<Employee> getEmployee(TcKimlikNo identity);\n\tEmployee hireEmployee(Employee employee);\n\tEmployee fireEmployee(TcKimlikNo identity);\t\n}"
},
{
"identifier": "EmployeeFiredEvent",
"path": "hr-core-subdomain/src/com/example/hr/application/business/event/EmployeeFiredEvent.java",
"snippet": "@DomainEvent\npublic final class EmployeeFiredEvent extends HrEvent {\n\tprivate final Employee employee;\n\n\tpublic EmployeeFiredEvent(Employee employee) {\n\t\tsuper(employee.getIdentity(), EventType.FIRE_EVENT);\n\t\tthis.employee = employee;\n\t}\n\n\tpublic Employee getEmployee() {\n\t\treturn employee;\n\t}\n\n}"
},
{
"identifier": "EmployeeHiredEvent",
"path": "hr-core-subdomain/src/com/example/hr/application/business/event/EmployeeHiredEvent.java",
"snippet": "@DomainEvent\npublic final class EmployeeHiredEvent extends HrEvent {\n\n\tpublic EmployeeHiredEvent(TcKimlikNo identity) {\n\t\tsuper(identity, EventType.HIRE_EVENT);\n\t}\n\n}"
},
{
"identifier": "HrEvent",
"path": "hr-core-subdomain/src/com/example/hr/application/business/event/HrEvent.java",
"snippet": "sealed public abstract class HrEvent permits EmployeeFiredEvent, EmployeeHiredEvent{\n\tprivate final String eventId = UUID.randomUUID().toString();\n\tprivate final TcKimlikNo identity;\n\tprivate final EventType type;\n\tprivate final ZonedDateTime time = ZonedDateTime.now();\n\n\tpublic HrEvent(TcKimlikNo identity, EventType type) {\n\t\tthis.identity = identity;\n\t\tthis.type = type;\n\t}\n\n\tpublic String getEventId() {\n\t\treturn eventId;\n\t}\n\n\tpublic TcKimlikNo getIdentity() {\n\t\treturn identity;\n\t}\n\n\tpublic EventType getType() {\n\t\treturn type;\n\t}\n\n\tpublic ZonedDateTime getTime() {\n\t\treturn time;\n\t}\n\n}"
},
{
"identifier": "EmployeeNotFoundException",
"path": "hr-core-subdomain/src/com/example/hr/application/business/exception/EmployeeNotFoundException.java",
"snippet": "@SuppressWarnings(\"serial\")\npublic class EmployeeNotFoundException extends RuntimeException {\n\tprivate final TcKimlikNo identity;\n\n\tpublic EmployeeNotFoundException(String message, TcKimlikNo identity) {\n\t\tsuper(message);\n\t\tthis.identity = identity;\n\t}\n\n\tpublic TcKimlikNo getIdentity() {\n\t\treturn identity;\n\t}\n\t\n}"
},
{
"identifier": "ExistingEmployeeException",
"path": "hr-core-subdomain/src/com/example/hr/application/business/exception/ExistingEmployeeException.java",
"snippet": "@SuppressWarnings(\"serial\")\npublic class ExistingEmployeeException extends RuntimeException {\n\tprivate final TcKimlikNo identity;\n\n\tpublic ExistingEmployeeException(String message, TcKimlikNo identity) {\n\t\tsuper(message);\n\t\tthis.identity = identity;\n\t}\n\n\tpublic TcKimlikNo getIdentity() {\n\t\treturn identity;\n\t}\n\t\n}"
},
{
"identifier": "Employee",
"path": "hr-core-subdomain/src/com/example/hr/domain/Employee.java",
"snippet": "@Entity(identity = \"identity\", aggregate=true)\npublic class Employee {\n private final TcKimlikNo identity;\n private FullName fullname;\n private Money salary;\n private Iban iban;\n private Department[] departments;\n private JobStyle jobStyle;\n private final BirthYear birthYear;\n private Photo photo;\n \n\tpublic FullName getFullname() {\n\t\treturn fullname;\n\t}\n\n\tpublic void setFullname(FullName fullname) {\n\t\tthis.fullname = fullname;\n\t}\n\n\tpublic Money getSalary() {\n\t\treturn salary;\n\t}\n\n\tpublic void setSalary(Money salary) {\n\t\tthis.salary = salary;\n\t}\n\n\tpublic Iban getIban() {\n\t\treturn iban;\n\t}\n\n\tpublic void setIban(Iban iban) {\n\t\tthis.iban = iban;\n\t}\n\n\tpublic Department[] getDepartments() {\n\t\treturn departments;\n\t}\n\n\tpublic void setDepartments(Department[] departments) {\n\t\tthis.departments = departments;\n\t}\n\n\tpublic JobStyle getJobStyle() {\n\t\treturn jobStyle;\n\t}\n\n\tpublic void setJobStyle(JobStyle jobStyle) {\n\t\tthis.jobStyle = jobStyle;\n\t}\n\n\tpublic Photo getPhoto() {\n\t\treturn photo;\n\t}\n\n\tpublic void setPhoto(Photo photo) {\n\t\tthis.photo = photo;\n\t}\n\n\tpublic TcKimlikNo getIdentity() {\n\t\treturn identity;\n\t}\n\n\tpublic BirthYear getBirthYear() {\n\t\treturn birthYear;\n\t}\n\n\tprivate Employee(Builder builder) {\n\t\tthis.identity = builder.identity;\n\t\tthis.fullname = builder.fullname;\n\t\tthis.salary = builder.salary;\n\t\tthis.iban = builder.iban;\n\t\tthis.departments = builder.departments;\n\t\tthis.jobStyle = builder.jobStyle;\n\t\tthis.birthYear = builder.birthYear;\n\t\tthis.photo = builder.photo;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(identity);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tEmployee other = (Employee) obj;\n\t\treturn Objects.equals(identity, other.identity);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Employee [identity=\" + identity + \", fullname=\" + fullname + \", salary=\" + salary + \", iban=\" + iban\n\t\t\t\t+ \", departments=\" + Arrays.toString(departments) + \", jobStyle=\" + jobStyle + \", birthYear=\"\n\t\t\t\t+ birthYear + \"]\";\n\t}\n\n\tpublic void increaseSalary(double rate) {\n\t\tvar newSalary = this.salary.multiply(1+rate/100.0);\n\t\t// Validation Rule\n\t\t// Business Rule\n\t\t// Invariants\n\t\t// Constraint\n\t\t// Policy\n\t\tthis.salary = newSalary;\n\t} \n\t\n\tpublic static class Builder {\n\t private TcKimlikNo identity;\n\t private FullName fullname;\n\t private Money salary;\n\t private Iban iban;\n\t private Department[] departments;\n\t private JobStyle jobStyle;\n\t private BirthYear birthYear;\n\t private Photo photo;\n\t \n\t public Builder identity(String value) {\n\t \tthis.identity = TcKimlikNo.valueOf(value);\n\t \treturn this;\n\t }\n\t public Builder fullname(String firstName,String lastName) {\n\t \tthis.fullname = FullName.of(firstName, lastName);\n\t \treturn this;\n\t }\n\t public Builder salary(double value,FiatCurrency currency) {\n\t \tthis.salary = Money.of(value, currency);\n\t \treturn this;\n\t }\n\t public Builder salary(double value) {\n\t \treturn salary(value,FiatCurrency.TL);\n\t }\n\t public Builder iban(String value) {\n\t \tthis.iban = Iban.valueOf(value);\n\t \treturn this;\n\t }\n\t public Builder departments(Department... values) {\n\t \tthis.departments = values;\n\t \treturn this;\n\t }\n\t public Builder departments(String... values) {\n\t \tthis.departments = Arrays.stream(values).map(Department::valueOf).toList().toArray(new Department[0]);\n\t \treturn this;\n\t }\n\t public Builder departments(List<Department> values) {\n\t \tthis.departments = values.toArray(new Department[0]);\n\t \treturn this;\n\t }\n\t public Builder jobStyle(JobStyle value) {\n\t \tthis.jobStyle = value;\n\t \treturn this;\n\t }\n\t public Builder jobStyle(String value) {\n\t \tthis.jobStyle = JobStyle.valueOf(value);\n\t \treturn this;\n\t }\n\t public Builder birthYear(int value) {\n\t \tthis.birthYear = new BirthYear(value);\n\t \treturn this;\n\t }\t \n\t public Builder photo(byte[] values) {\n\t \tthis.photo = Photo.of(values);\n\t \treturn this;\n\t }\t \n\t public Builder photo(String values) {\n\t \tthis.photo = Photo.of(Base64.getDecoder().decode(values));\n\t \treturn this;\n\t }\n\t public Employee build() {\n\t\t\t// Validation Rule\n\t\t\t// Business Rule\n\t\t\t// Invariants\n\t\t\t// Constraint\n\t\t\t// Policy\n\t \treturn new Employee(this);\n\t }\n\t \n\t}\n \n}"
},
{
"identifier": "TcKimlikNo",
"path": "hr-core-subdomain/src/com/example/hr/domain/TcKimlikNo.java",
"snippet": "@ValueObject\npublic final class TcKimlikNo {\n\tprivate final String value;\n\tprivate static final Map<String, TcKimlikNo> CACHE = new ConcurrentHashMap<>();\n\n\tprivate TcKimlikNo(String value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic static TcKimlikNo valueOf(String value) {\n\t\t// validation\n\t\tif (!isValid(value))\n\t\t\tthrow new IllegalArgumentException(\"This is not a valid identity no.\");\n\t\t// caching\n\t\tvar cachedValue = CACHE.get(value);\n\t\tif (Objects.isNull(cachedValue)) {\n\t\t\tcachedValue = new TcKimlikNo(value);\n\t\t\tCACHE.put(value, cachedValue);\n\t\t}\n\t\treturn cachedValue;\n\t}\n\n\tprivate static boolean isValid(String value) {\n\t\tif (value == null)\n\t\t\treturn false;\n\t\tif (!value.matches(\"^\\\\d{11}$\")) { // fail-fast\n\t\t\treturn false;\n\t\t}\n\t\tint[] digits = new int[11];\n\t\tfor (int i = 0; i < digits.length; ++i) {\n\t\t\tdigits[i] = value.charAt(i) - '0';\n\t\t}\n\t\tint x = digits[0];\n\t\tint y = digits[1];\n\t\tfor (int i = 1; i < 5; i++) {\n\t\t\tx += digits[2 * i];\n\t\t}\n\t\tfor (int i = 2; i <= 4; i++) {\n\t\t\ty += digits[2 * i - 1];\n\t\t}\n\t\tint c1 = 7 * x - y;\n\t\tif (c1 % 10 != digits[9]) {\n\t\t\treturn false;\n\t\t}\n\t\tint c2 = 0;\n\t\tfor (int i = 0; i < 10; ++i) {\n\t\t\tc2 += digits[i];\n\t\t}\n\t\tif (c2 % 10 != digits[10]) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(value);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tTcKimlikNo other = (TcKimlikNo) obj;\n\t\treturn Objects.equals(value, other.value);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"TcKimlikNo [value=\" + value + \"]\";\n\t}\n\n}"
},
{
"identifier": "EventPublisher",
"path": "hr-core-subdomain/src/com/example/hr/infrastructure/EventPublisher.java",
"snippet": "@Port(PortType.DRIVEN)\npublic interface EventPublisher<Event> {\n\tpublic void publish(Event event);\n}"
},
{
"identifier": "EmployeeRepository",
"path": "hr-core-subdomain/src/com/example/hr/repository/EmployeeRepository.java",
"snippet": "@Port(PortType.DRIVEN)\npublic interface EmployeeRepository {\n\n\tOptional<Employee> findEmployeeByIdentity(TcKimlikNo identity);\n\n\tboolean existsByIdentity(TcKimlikNo identity);\n\n\tEmployee create(Employee employee);\n\n\tvoid remove(Employee employee);\n\n}"
}
] | import java.util.Optional;
import com.example.ddd.Application;
import com.example.hr.application.HrApplication;
import com.example.hr.application.business.event.EmployeeFiredEvent;
import com.example.hr.application.business.event.EmployeeHiredEvent;
import com.example.hr.application.business.event.HrEvent;
import com.example.hr.application.business.exception.EmployeeNotFoundException;
import com.example.hr.application.business.exception.ExistingEmployeeException;
import com.example.hr.domain.Employee;
import com.example.hr.domain.TcKimlikNo;
import com.example.hr.infrastructure.EventPublisher;
import com.example.hr.repository.EmployeeRepository; | 3,066 | package com.example.hr.application.business;
@Application(port=HrApplication.class)
public class StandardHrApplication implements HrApplication {
private final EmployeeRepository employeeRepository;
private final EventPublisher<HrEvent> eventPublisher;
public StandardHrApplication(EmployeeRepository employeeRepository, EventPublisher<HrEvent> eventPublisher) {
this.employeeRepository = employeeRepository;
this.eventPublisher = eventPublisher;
}
@Override
public Optional<Employee> getEmployee(TcKimlikNo identity) {
return employeeRepository.findEmployeeByIdentity(identity);
}
@Override
public Employee hireEmployee(Employee employee) {
var identity = employee.getIdentity();
if(employeeRepository.existsByIdentity(identity)) | package com.example.hr.application.business;
@Application(port=HrApplication.class)
public class StandardHrApplication implements HrApplication {
private final EmployeeRepository employeeRepository;
private final EventPublisher<HrEvent> eventPublisher;
public StandardHrApplication(EmployeeRepository employeeRepository, EventPublisher<HrEvent> eventPublisher) {
this.employeeRepository = employeeRepository;
this.eventPublisher = eventPublisher;
}
@Override
public Optional<Employee> getEmployee(TcKimlikNo identity) {
return employeeRepository.findEmployeeByIdentity(identity);
}
@Override
public Employee hireEmployee(Employee employee) {
var identity = employee.getIdentity();
if(employeeRepository.existsByIdentity(identity)) | throw new ExistingEmployeeException("Employee already exists",identity); | 5 | 2023-12-05 09:46:09+00:00 | 4k |
nilsgenge/finite-state-machine-visualizer | src/gui/GuiHandler.java | [
{
"identifier": "MouseInputs",
"path": "src/inputs/MouseInputs.java",
"snippet": "public class MouseInputs implements MouseListener {\n\n\tprivate Boolean m1Pressed = false; // left mouse button\n\tprivate Boolean m2Pressed = false; // right mouse button\n\tprivate Boolean m3Pressed = false; // middle mouse button\n\tprivate int mX; // mousepos on entire screen\n\tprivate int mY;\n\tprivate int m1X; // mousepos on last left click\n\tprivate int m1Y;\n\tprivate int m2X; // mousepos on last right click\n\tprivate int m2Y;\n\tprivate int m3X; // mousepos on last middle click\n\tprivate int m3Y;\n\n\tpublic void updateMousePos() {\n\t\tmX = (int) MouseInfo.getPointerInfo().getLocation().getX();\n\t\tmY = (int) MouseInfo.getPointerInfo().getLocation().getY();\n\t}\n\n\t@Override\n\tpublic void mouseClicked(MouseEvent e) {\n\t\t// TODO Auto-generated method stub\n\t}\n\n\t@Override\n\tpublic void mouseEntered(MouseEvent e) {\n\t\t// TODO Auto-generated method stub\n\t}\n\n\t@Override\n\tpublic void mouseExited(MouseEvent e) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void mousePressed(MouseEvent e) {\n\t\tif (SwingUtilities.isLeftMouseButton(e)) {\n\t\t\tm1Pressed = true;\n\t\t\tm1X = e.getX();\n\t\t\tm1Y = e.getY() - 30;\n\t\t}\n\t\tif (SwingUtilities.isRightMouseButton(e)) {\n\t\t\tm2Pressed = true;\n\t\t\tm2X = e.getX();\n\t\t\tm2Y = e.getY() - 30;\n\t\t}\n\t\tif (SwingUtilities.isMiddleMouseButton(e)) {\n\t\t\tm3Pressed = true;\n\t\t\tm3X = e.getX();\n\t\t\tm3Y = e.getY() - 30;\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void mouseReleased(MouseEvent e) {\n\n\t\tif (SwingUtilities.isLeftMouseButton(e)) {\n\t\t\tm1Pressed = false;\n\t\t}\n\t\tif (SwingUtilities.isRightMouseButton(e)) {\n\t\t\tm2Pressed = false;\n\t\t}\n\t\tif (SwingUtilities.isMiddleMouseButton(e)) {\n\t\t\tm3Pressed = false;\n\t\t}\n\t}\n\n\tpublic void resetLeftMousePosition() {\n\t\tthis.m1X = 0;\n\t\tthis.m1Y = 0;\n\t}\n\n\tpublic int getX() {\n\t\treturn mX;\n\t}\n\n\tpublic int getY() {\n\t\treturn mY;\n\t}\n\n\tpublic int getM1X() {\n\t\treturn m1X;\n\t}\n\n\tpublic int getM1Y() {\n\t\treturn m1Y;\n\t}\n\n\tpublic int getM2X() {\n\t\treturn m2X;\n\t}\n\n\tpublic int getM2Y() {\n\t\treturn m2Y;\n\t}\n\n\tpublic int getM3X() {\n\t\treturn m3X;\n\t}\n\n\tpublic int getM3Y() {\n\t\treturn m3Y;\n\t}\n\n\tpublic boolean m1Pressed() {\n\t\treturn m1Pressed;\n\t}\n\n\tpublic boolean m2Pressed() {\n\t\treturn m2Pressed;\n\t}\n\n\tpublic boolean m3Pressed() {\n\t\treturn m3Pressed;\n\t}\n}"
},
{
"identifier": "colortable",
"path": "src/utilz/colortable.java",
"snippet": "public class colortable {\n\n\tprivate static final String HEX_BG_MAIN = \"#fffffe\";\n\tprivate static final String HEX_BG_MENU = \"#eff0f3\";\n\tprivate static final String HEX_STROKE = \"#1f1235\";\n\tprivate static final String HEX_HIGHLIGHT = \"#ff8e3c\";\n\tprivate static final String HEX_TEXT = \"#1f1135\";\n\tprivate static final String HEX_SUBTEXT = \"#1b1325\";\n\n\tpublic static final Color BG_MAIN = new Color(colortable.hexToRGB(HEX_BG_MAIN));\n\tpublic static final Color BG_MENU = new Color(colortable.hexToRGB(HEX_BG_MENU));\n\tpublic static final Color STROKE = new Color(colortable.hexToRGB(HEX_STROKE));\n\tpublic static final Color HIGHLIGHT = new Color(colortable.hexToRGB(HEX_HIGHLIGHT));\n\tpublic static final Color TEXT = new Color(colortable.hexToRGB(HEX_TEXT));\n\tpublic static final Color SUBTEXT = new Color(colortable.hexToRGB(HEX_SUBTEXT));\n\n\tprivate static int hexToRGB(String hex) {\n\t\tlong a = Long.decode(hex) + 4278190080L;\n\t\tint rgbColor = (int) a;\n\t\treturn rgbColor;\n\t}\n}"
},
{
"identifier": "ToolHandler",
"path": "src/workspace/ToolHandler.java",
"snippet": "public class ToolHandler {\n\n\tprotected Main main;\n\tprivate ObjectHandler oh;\n\tprivate MouseInputs m;\n\n\tprivate String currentTool;\n\n\tprivate int leftMouseLastX;\n\tprivate int leftMouseLastY;\n\tprivate int rightMouseLastX;\n\tprivate int rightMouseLastY;\n\n\tpublic ToolHandler(Main main) {\n\t\tthis.main = main;\n\t}\n\n\tpublic void initialize() {\n\t\tthis.m = main.m;\n\t\tthis.oh = main.oh;\n\t\tcurrentTool = tools.EMPTY;\n\t}\n\n\tpublic void updateTool() {\n\t\tcheckDeselect();\n\t\tcheckNewState();\n\t\tcheckNewTransition();\n\t\tcheckNewStartState();\n\t\tcheckNewEndState();\n\t}\n\n\tpublic void addStringToTransition(String s) {\n\t\tif(oh.getSelectedTransition() != null) {\n\t\t\tswitch(s) {\n\t\t\t\tcase(\"DELETE\"):\n\t\t\t\t\tString oldString = oh.getSelectedTransition().getText();\n\t\t\t\t\tif(oldString.length() > 0) {\n\t\t\t\t\t\tString newString = oldString.substring(0, oldString.length() - 1);\n\t\t\t\t\t\toh.getSelectedTransition().setText(newString);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\toh.getSelectedTransition().addString(s);\n\t\t\t\t\tbreak;\n\t\t\t} \t\t\t\n\t\t}\n\t}\n\t\n\tpublic void checkNewStartState() {\n\t\tif (currentTool.equals(tools.START)) {\n\t\t\tif (isNewInput(\"left\", m.getM1X(), m.getM1Y()) && isInWorkspace(m.getM1X(), m.getM1Y())) {\n\t\t\t\toh.setNewStartState();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void checkNewEndState() {\n\t\tif (currentTool.equals(tools.END)) {\n\t\t\tif (isNewInput(\"left\", m.getM1X(), m.getM1Y()) && isInWorkspace(m.getM1X(), m.getM1Y())) {\n\t\t\t\toh.setNewEndState();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void checkNewTransition() {\n\t\tif (currentTool.equals(tools.TRANSITION)) {\n\t\t\tif (isNewInput(\"left\", m.getM1X(), m.getM1Y()) && isInWorkspace(m.getM1X(), m.getM1Y())) {\n\t\t\t\toh.setNewTransition();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkDeselect() {\n\t\tif (isNewInput(\"right\", m.getM2X(), m.getM2Y())) {\n\t\t\tif (m.m2Pressed() && isInWorkspace(m.getM2X(), m.getM2Y())) {\n\t\t\t\tif (currentTool != tools.EMPTY) {\n\t\t\t\t\tthis.setCurrentTool(tools.EMPTY);\n\t\t\t\t}\n\t\t\t\toh.deselectAllStates();\n\t\t\t\trightMouseLastX = m.getM2X();\n\t\t\t\trightMouseLastY = m.getM2Y();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkNewState() {\n\t\tif (currentTool.equals(tools.STATE)) {\n\t\t\tif (isNewInput(\"left\", m.getM1X(), m.getM1Y()) && isInWorkspace(m.getM1X(), m.getM1Y())) {\n\t\t\t\toh.setNewState(m.getM1X(), m.getM1Y());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Boolean isNewInput(String k, int mX, int mY) {\n\t\tswitch (k) {\n\t\tcase (\"left\"): {\n\t\t\tif (mX != leftMouseLastX || mY != leftMouseLastY) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tcase (\"right\"): {\n\t\t\tif (mX != rightMouseLastX || mY != rightMouseLastY) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tcase (\"middle\"): {\n\t\t\treturn false;\n\t\t}\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\n\t}\n\t\n\tpublic boolean isInWorkspace(int x, int y) {\n\t\tif (x >= 350 && y >= 100) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic String getCurrentTool() {\n\t\treturn currentTool;\n\t}\n\n\tpublic void setCurrentTool(String tool) {\n\t\tcurrentTool = tool;\n\t}\n\n}"
}
] | import java.awt.Font;
import java.awt.Graphics2D;
import inputs.MouseInputs;
import main.*;
import utilz.colortable;
import workspace.ToolHandler; | 2,381 | package gui;
public class GuiHandler {
private Main main;
public Toolbar tb;
public Sidebar sb;
private MouseInputs m;
private ToolHandler th;
private int screenWidth;
private int screenHeight;
public GuiHandler(Main main, MouseInputs m, ToolHandler th) {
this.main = main;
this.m = m;
this.th = th;
tb = new Toolbar(this, m, th);
sb = new Sidebar(this);
screenWidth = main.s.getScreenWidth();
screenHeight = main.s.getScreenHeight();
}
public void renderGui(Graphics2D g2) {
sb.render(g2);
tb.render(g2);
g2.setFont(new Font("Monospaced", Font.PLAIN, 12)); | package gui;
public class GuiHandler {
private Main main;
public Toolbar tb;
public Sidebar sb;
private MouseInputs m;
private ToolHandler th;
private int screenWidth;
private int screenHeight;
public GuiHandler(Main main, MouseInputs m, ToolHandler th) {
this.main = main;
this.m = m;
this.th = th;
tb = new Toolbar(this, m, th);
sb = new Sidebar(this);
screenWidth = main.s.getScreenWidth();
screenHeight = main.s.getScreenHeight();
}
public void renderGui(Graphics2D g2) {
sb.render(g2);
tb.render(g2);
g2.setFont(new Font("Monospaced", Font.PLAIN, 12)); | g2.setColor(colortable.TEXT); | 1 | 2023-12-12 20:43:41+00:00 | 4k |
gaetanBloch/jhlite-gateway | src/test/java/com/mycompany/myapp/shared/pagination/infrastructure/secondary/JhipsterSampleApplicationPagesTest.java | [
{
"identifier": "MissingMandatoryValueException",
"path": "src/main/java/com/mycompany/myapp/shared/error/domain/MissingMandatoryValueException.java",
"snippet": "public class MissingMandatoryValueException extends AssertionException {\n\n private MissingMandatoryValueException(String field, String message) {\n super(field, message);\n }\n\n public static MissingMandatoryValueException forBlankValue(String field) {\n return new MissingMandatoryValueException(field, defaultMessage(field, \"blank\"));\n }\n\n public static MissingMandatoryValueException forNullValue(String field) {\n return new MissingMandatoryValueException(field, defaultMessage(field, \"null\"));\n }\n\n public static MissingMandatoryValueException forEmptyValue(String field) {\n return new MissingMandatoryValueException(field, defaultMessage(field, \"empty\"));\n }\n\n private static String defaultMessage(String field, String reason) {\n return new StringBuilder()\n .append(\"The field \\\"\")\n .append(field)\n .append(\"\\\" is mandatory and wasn't set\")\n .append(\" (\")\n .append(reason)\n .append(\")\")\n .toString();\n }\n\n @Override\n public AssertionErrorType type() {\n return AssertionErrorType.MISSING_MANDATORY_VALUE;\n }\n}"
},
{
"identifier": "JhipsterSampleApplicationPage",
"path": "src/main/java/com/mycompany/myapp/shared/pagination/domain/JhipsterSampleApplicationPage.java",
"snippet": "public class JhipsterSampleApplicationPage<T> {\n\n private static final int MINIMAL_PAGE_COUNT = 1;\n \n private final List<T> content;\n private final int currentPage;\n private final int pageSize;\n private final long totalElementsCount;\n\n private JhipsterSampleApplicationPage(JhipsterSampleApplicationPageBuilder<T> builder) {\n content = JhipsterSampleApplicationCollections.immutable(builder.content);\n currentPage = builder.currentPage;\n pageSize = buildPageSize(builder.pageSize);\n totalElementsCount = buildTotalElementsCount(builder.totalElementsCount);\n }\n\n private int buildPageSize(int pageSize) {\n if (pageSize == -1) {\n return content.size();\n }\n\n return pageSize;\n }\n\n private long buildTotalElementsCount(long totalElementsCount) {\n if (totalElementsCount == -1) {\n return content.size();\n }\n\n return totalElementsCount;\n }\n\n public static <T> JhipsterSampleApplicationPage<T> singlePage(List<T> content) {\n return builder(content).build();\n }\n\n public static <T> JhipsterSampleApplicationPageBuilder<T> builder(List<T> content) {\n return new JhipsterSampleApplicationPageBuilder<>(content);\n }\n\n public static <T> JhipsterSampleApplicationPage<T> of(List<T> elements, JhipsterSampleApplicationPageable pagination) {\n Assert.notNull(\"elements\", elements);\n Assert.notNull(\"pagination\", pagination);\n\n List<T> content = elements.subList(\n Math.min(pagination.offset(), elements.size()),\n Math.min(pagination.offset() + pagination.pageSize(), elements.size())\n );\n\n return builder(content).currentPage(pagination.page()).pageSize(pagination.pageSize()).totalElementsCount(elements.size()).build();\n }\n\n public List<T> content() {\n return content;\n }\n\n public int currentPage() {\n return currentPage;\n }\n\n public int pageSize() {\n return pageSize;\n }\n\n public long totalElementsCount() {\n return totalElementsCount;\n }\n\n public int pageCount() {\n if (totalElementsCount > 0) {\n return (int) Math.ceil(totalElementsCount / (float) pageSize);\n }\n\n return MINIMAL_PAGE_COUNT;\n }\n\n public boolean hasPrevious() {\n return currentPage > 0;\n }\n\n public boolean hasNext() {\n return isNotLast();\n }\n\n public boolean isNotLast() {\n return currentPage + 1 < pageCount();\n }\n\n public <R> JhipsterSampleApplicationPage<R> map(Function<T, R> mapper) {\n Assert.notNull(\"mapper\", mapper);\n\n return builder(content().stream().map(mapper).toList())\n .currentPage(currentPage)\n .pageSize(pageSize)\n .totalElementsCount(totalElementsCount)\n .build();\n }\n\n public static class JhipsterSampleApplicationPageBuilder<T> {\n\n private final List<T> content;\n private int currentPage;\n private int pageSize = -1;\n private long totalElementsCount = -1;\n\n private JhipsterSampleApplicationPageBuilder(List<T> content) {\n this.content = content;\n }\n\n public JhipsterSampleApplicationPageBuilder<T> pageSize(int pageSize) {\n this.pageSize = pageSize;\n\n return this;\n }\n\n public JhipsterSampleApplicationPageBuilder<T> currentPage(int currentPage) {\n this.currentPage = currentPage;\n\n return this;\n }\n\n public JhipsterSampleApplicationPageBuilder<T> totalElementsCount(long totalElementsCount) {\n this.totalElementsCount = totalElementsCount;\n\n return this;\n }\n\n public JhipsterSampleApplicationPage<T> build() {\n return new JhipsterSampleApplicationPage<>(this);\n }\n }\n}"
},
{
"identifier": "JhipsterSampleApplicationPageable",
"path": "src/main/java/com/mycompany/myapp/shared/pagination/domain/JhipsterSampleApplicationPageable.java",
"snippet": "public class JhipsterSampleApplicationPageable {\n\n private final int page;\n private final int pageSize;\n private final int offset;\n\n public JhipsterSampleApplicationPageable(int page, int pageSize) {\n Assert.field(\"page\", page).min(0);\n Assert.field(\"pageSize\", pageSize).min(1).max(100);\n\n this.page = page;\n this.pageSize = pageSize;\n offset = page * pageSize;\n }\n\n public int page() {\n return page;\n }\n\n public int pageSize() {\n return pageSize;\n }\n\n public int offset() {\n return offset;\n }\n\n @Override\n @ExcludeFromGeneratedCodeCoverage\n public int hashCode() {\n return new HashCodeBuilder().append(page).append(pageSize).build();\n }\n\n @Override\n @ExcludeFromGeneratedCodeCoverage\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n\n JhipsterSampleApplicationPageable other = (JhipsterSampleApplicationPageable) obj;\n return new EqualsBuilder().append(page, other.page).append(pageSize, other.pageSize).build();\n }\n}"
}
] | import static org.assertj.core.api.Assertions.*;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import com.mycompany.myapp.UnitTest;
import com.mycompany.myapp.shared.error.domain.MissingMandatoryValueException;
import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPage;
import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPageable; | 2,141 | package com.mycompany.myapp.shared.pagination.infrastructure.secondary;
@UnitTest
class JhipsterSampleApplicationPagesTest {
@Test
void shouldNotBuildPageableFromNullJhipsterSampleApplicationPageable() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("pagination");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageable() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination());
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.unsorted());
}
@Test
void shouldNotBuildWithoutSort() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(pagination(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("sort");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageableAndSort() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination(), Sort.by("dummy"));
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.by("dummy"));
}
private JhipsterSampleApplicationPageable pagination() {
return new JhipsterSampleApplicationPageable(2, 15);
}
@Test
void shouldNotConvertFromSpringPageWithoutSpringPage() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null, source -> source))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("springPage");
}
@Test
void shouldNotConvertFromSpringPageWithoutMapper() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(springPage(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("mapper");
}
@Test
void shouldConvertFromSpringPage() { | package com.mycompany.myapp.shared.pagination.infrastructure.secondary;
@UnitTest
class JhipsterSampleApplicationPagesTest {
@Test
void shouldNotBuildPageableFromNullJhipsterSampleApplicationPageable() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("pagination");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageable() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination());
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.unsorted());
}
@Test
void shouldNotBuildWithoutSort() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(pagination(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("sort");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageableAndSort() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination(), Sort.by("dummy"));
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.by("dummy"));
}
private JhipsterSampleApplicationPageable pagination() {
return new JhipsterSampleApplicationPageable(2, 15);
}
@Test
void shouldNotConvertFromSpringPageWithoutSpringPage() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null, source -> source))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("springPage");
}
@Test
void shouldNotConvertFromSpringPageWithoutMapper() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(springPage(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("mapper");
}
@Test
void shouldConvertFromSpringPage() { | JhipsterSampleApplicationPage<String> page = JhipsterSampleApplicationPages.from(springPage(), Function.identity()); | 1 | 2023-12-10 06:39:18+00:00 | 4k |
zerodevstuff/ExploitFixerv2 | src/main/java/dev/_2lstudios/exploitfixer/ExploitFixer.java | [
{
"identifier": "ExploitFixerCommand",
"path": "src/main/java/dev/_2lstudios/exploitfixer/commands/ExploitFixerCommand.java",
"snippet": "public class ExploitFixerCommand implements CommandExecutor {\n\tprivate ExploitFixer exploitFixer;\n\tprivate MessagesModule messagesModule;\n\tprivate NotificationsModule notificationsModule;\n\tprivate ExploitPlayerManager exploitPlayerManager;\n\n\tpublic ExploitFixerCommand(ExploitFixer exploitFixer, ModuleManager moduleManager) {\n\t\tthis.exploitFixer = exploitFixer;\n\t\tthis.messagesModule = moduleManager.getMessagesModule();\n\t\tthis.notificationsModule = moduleManager.getNotificationsModule();\n\t\tthis.exploitPlayerManager = moduleManager.getExploitPlayerManager();\n\t}\n\n\t@Override\n\tpublic boolean onCommand(CommandSender sender, Command command, String label,\n\t\t\tString[] args) {\n\t\tint length = args.length;\n\t\tString lang = null;\n\n\t\tif (sender instanceof Player) {\n\t\t\tlang = exploitPlayerManager.get((Player) sender).getLocale();\n\t\t}\n\n\t\tif (length < 1 || args[0].equalsIgnoreCase(\"help\")) {\n\t\t\tHelpCommand helpCommand = new HelpCommand(messagesModule, lang);\n\n\t\t\thelpCommand.onCommand(sender, command, label, args);\n\t\t} else if (args[0].equalsIgnoreCase(\"reload\")) {\n\t\t\tReloadCommand reloadCommand = new ReloadCommand(exploitFixer, messagesModule, lang);\n\n\t\t\treloadCommand.onCommand(sender, command, label, args);\n\t\t} else if (args[0].equalsIgnoreCase(\"stats\")) {\n\t\t\tStatsCommand statsCommand = new StatsCommand(exploitPlayerManager, messagesModule, lang);\n\n\t\t\tstatsCommand.onCommand(sender, command, label, args);\n\t\t} else if (args[0].equalsIgnoreCase(\"notifications\")) {\n\t\t\tNotificationsCommand notificationsCommand = new NotificationsCommand(notificationsModule,\n\t\t\t\t\tmessagesModule, lang);\n\n\t\t\tnotificationsCommand.onCommand(sender, command, label, args);\n\t\t} else {\n\t\t\tsender.sendMessage(messagesModule.getUnknown(lang));\n\t\t}\n\n\t\treturn true;\n\t}\n}"
},
{
"identifier": "IConfiguration",
"path": "src/main/java/dev/_2lstudios/exploitfixer/configuration/IConfiguration.java",
"snippet": "public interface IConfiguration {\n public IConfiguration getSection(String string);\n\n public Collection<String> getKeys();\n\n public Collection<String> getStringList(String string);\n\n public String getString(String path);\n\n public String getString(String path, String def);\n\n public double getDouble(String path);\n\n public double getDouble(String path, double def);\n\n public long getLong(String path);\n\n public int getInt(String path);\n\n public boolean getBoolean(String path);\n\n public boolean getBoolean(String path, boolean def);\n\n public Object getObject();\n\n public boolean contains(String string);\n}"
},
{
"identifier": "ListenerInitializer",
"path": "src/main/java/dev/_2lstudios/exploitfixer/listener/ListenerInitializer.java",
"snippet": "public class ListenerInitializer {\n\tprivate Plugin plugin;\n\tprivate ModuleManager moduleManager;\n\tprivate boolean registered = false;\n\n\tpublic ListenerInitializer(Plugin plugin, ModuleManager moduleManager) {\n\t\tthis.plugin = plugin;\n\t\tthis.moduleManager = moduleManager;\n\t}\n\n\tpublic void register() {\n\t\tthis.registered = true;\n\n\t\tServer server = plugin.getServer();\n\t\tPluginManager pluginManager = server.getPluginManager();\n\t\tExploitUtil exploitUtil = new ExploitUtil(moduleManager);\n\n\t\tpluginManager.registerEvents(new BlockBreakListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new BlockDispenseListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new BlockPlaceListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new BucketEmptyListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new ChunkUnloadListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new EntityDamageByEntityListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new EntityTeleportListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new InventoryClickListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerInteractEntityListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PacketDecodeListener(exploitUtil, moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PacketReceiveListener(exploitUtil, moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerCommandListener(exploitUtil, moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerInteractListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerLoginListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerMoveListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerQuitListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerShearEntityListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new PlayerTeleportListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new ProjectileLaunchListener(moduleManager), plugin);\n\t\tpluginManager.registerEvents(new StructureGrowListener(moduleManager), plugin);\n\t}\n\n\tpublic void unregister() {\n\t\tthis.registered = false;\n\n\t\tHandlerList.unregisterAll(plugin);\n\t}\n\n\tpublic boolean isRegistered() {\n\t\treturn this.registered;\n\t}\n}"
},
{
"identifier": "ModuleManager",
"path": "src/main/java/dev/_2lstudios/exploitfixer/managers/ModuleManager.java",
"snippet": "public class ModuleManager {\n\tprivate Plugin plugin;\n\tprivate CommandsModule commandsModule;\n\tprivate ConnectionModule connectionModule;\n\tprivate PatcherModule eventsModule;\n\tprivate CreativeItemsFixModule itemsFixModule;\n\tprivate MessagesModule messagesModule;\n\tprivate NotificationsModule notificationsModule;\n\tprivate PacketsModule packetsModule;\n\tprivate ItemAnalysisModule itemAnalysisModule;\n\tprivate ExploitPlayerManager exploitPlayerManager;\n\n\tpublic ModuleManager(ConfigUtil configUtil, Plugin plugin) {\n\t\tthis.plugin = plugin;\n\n\t\tServer server = plugin.getServer();\n\t\tLogger logger = plugin.getLogger();\n\n\t\tthis.commandsModule = new CommandsModule();\n\t\tthis.connectionModule = new ConnectionModule();\n\t\tthis.eventsModule = new PatcherModule();\n\t\tthis.itemsFixModule = new CreativeItemsFixModule(plugin);\n\t\tthis.messagesModule = new MessagesModule(configUtil, logger, plugin.getDescription().getVersion());\n\t\tthis.notificationsModule = new NotificationsModule(server, logger);\n\t\tthis.packetsModule = new PacketsModule();\n\t\tthis.itemAnalysisModule = new ItemAnalysisModule();\n\t\tthis.exploitPlayerManager = new ExploitPlayerManager(plugin, server, this);\n\t}\n\n\tpublic void reload(IConfiguration configYml) {\n\t\ttry {\n\t\t\tFile localeFolder = new File(plugin.getDataFolder() + \"/locales/\");\n\n\t\t\tlocaleFolder.mkdirs();\n\n\t\t\tthis.commandsModule.reload(configYml);\n\t\t\tthis.connectionModule.reload(configYml);\n\t\t\tthis.eventsModule.reload(configYml);\n\t\t\tthis.itemsFixModule.reload(configYml);\n\t\t\tthis.messagesModule.reload(configYml, localeFolder);\n\t\t\tthis.notificationsModule.reload(configYml);\n\t\t\tthis.packetsModule.reload(configYml);\n\t\t\tthis.itemAnalysisModule.reload(configYml);\n\t\t\tthis.exploitPlayerManager.reload();\n\t\t} catch (NullPointerException exception) {\n\t\t\tNullPointerException newException = new NullPointerException(\n\t\t\t\t\t\"Your ExploitFixer configuration is wrong, please reset it or the plugin wont work!\");\n\n\t\t\tnewException.setStackTrace(exception.getStackTrace());\n\n\t\t\tthrow newException;\n\t\t}\n\t}\n\n\tpublic CommandsModule getCommandsModule() {\n\t\treturn commandsModule;\n\t}\n\n\tpublic ConnectionModule getConnectionModule() {\n\t\treturn connectionModule;\n\t}\n\n\tpublic PatcherModule getPatcherModule() {\n\t\treturn eventsModule;\n\t}\n\n\tpublic CreativeItemsFixModule getCreativeItemsFixModule() {\n\t\treturn itemsFixModule;\n\t}\n\n\tpublic MessagesModule getMessagesModule() {\n\t\treturn messagesModule;\n\t}\n\n\tpublic NotificationsModule getNotificationsModule() {\n\t\treturn notificationsModule;\n\t}\n\n\tpublic ExploitPlayerManager getExploitPlayerManager() {\n\t\treturn exploitPlayerManager;\n\t}\n\n\tpublic PacketsModule getPacketsModule() {\n\t\treturn packetsModule;\n\t}\n\n public ItemAnalysisModule getItemAnalysisModule() {\n return itemAnalysisModule;\n }\n}"
},
{
"identifier": "ExploitFixerRepeatingTask",
"path": "src/main/java/dev/_2lstudios/exploitfixer/tasks/ExploitFixerRepeatingTask.java",
"snippet": "public class ExploitFixerRepeatingTask implements Runnable {\n private NotificationsModule notificationsModule;\n int seconds = 0;\n\n public ExploitFixerRepeatingTask(ModuleManager moduleManager) {\n this.notificationsModule = moduleManager.getNotificationsModule();\n }\n\n @Override\n public void run() {\n // Each 10 seconds\n if (seconds % 10 == 9) {\n // Show packets to the console\n notificationsModule.debugPackets();\n }\n\n seconds++;\n }\n}"
},
{
"identifier": "ConfigUtil",
"path": "src/main/java/dev/_2lstudios/exploitfixer/utils/ConfigUtil.java",
"snippet": "public class ConfigUtil {\n\tprivate static String DATA_FOLDER_PLACEHOLDER = \"%datafolder%\";\n\tprivate String dataFolderPath;\n\tprivate Logger logger;\n\tprivate Plugin plugin;\n\tprivate BukkitScheduler scheduler;\n\tprivate ClassLoader classLoader;\n\n\tpublic ConfigUtil(Plugin plugin) {\n\t\tthis.plugin = plugin;\n\t\tthis.scheduler = plugin.getServer().getScheduler();\n\t\tthis.logger = plugin.getLogger();\n\t\tthis.classLoader = plugin.getClass().getClassLoader();\n\t\tthis.dataFolderPath = plugin.getDataFolder().toString();\n\t}\n\n\tprivate void createParentFolder(File file) {\n\t\tFile parentFile = file.getParentFile();\n\n\t\tif (parentFile != null) {\n\t\t\tparentFile.mkdirs();\n\t\t}\n\t}\n\n\tpublic IConfiguration get(String path) {\n\t\tFile file = new File(path.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath));\n\n\t\tif (file.exists()) {\n\t\t\treturn new BukkitConfiguration(YamlConfiguration.loadConfiguration(file));\n\t\t} else {\n\t\t\treturn new BukkitConfiguration(new YamlConfiguration());\n\t\t}\n\t}\n\n\tpublic void create(String rawPath, String resourcePath) {\n\t\tString path = rawPath.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath);\n\n\t\ttry {\n\t\t\tFile configFile = new File(path);\n\n\t\t\tif (!configFile.exists()) {\n\t\t\t\tInputStream inputStream = classLoader.getResourceAsStream(resourcePath);\n\n\t\t\t\tcreateParentFolder(configFile);\n\n\t\t\t\tif (inputStream != null) {\n\t\t\t\t\tFiles.copy(inputStream, configFile.toPath());\n\t\t\t\t} else {\n\t\t\t\t\tconfigFile.createNewFile();\n\t\t\t\t}\n\n\t\t\t\tlogger.info(\"File '\" + path + \"' has been created!\");\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tlogger.info(\"Unable to create '\" + path + \"'!\");\n\t\t}\n\t}\n\n\tpublic void save(IConfiguration configuration, String rawPath) {\n\t\tString path = rawPath.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath);\n\n\t\tscheduler.runTaskAsynchronously(plugin, () -> {\n\t\t\ttry {\n\t\t\t\t((YamlConfiguration) configuration.getObject()).save(path);\n\n\t\t\t\tlogger.info(\"File '\" + path + \"' has been saved!\");\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.info(\"Unable to save '\" + path + \"'!\");\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void delete(String rawPath) {\n\t\tString path = rawPath.replace(DATA_FOLDER_PLACEHOLDER, dataFolderPath);\n\n\t\tscheduler.runTaskAsynchronously(plugin, () -> {\n\t\t\ttry {\n\t\t\t\tFiles.delete(new File(path).toPath());\n\n\t\t\t\tlogger.info(\"File '\" + path + \"' has been removed!\");\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.info(\"Unable to remove '\" + path + \"'!\");\n\t\t\t}\n\t\t});\n\t}\n}"
},
{
"identifier": "PluginDownloader",
"path": "src/main/java/dev/_2lstudios/exploitfixer/utils/PluginDownloader.java",
"snippet": "public class PluginDownloader {\n public File downloadPlugin(String pluginUrl, String pluginsDirectory) throws IOException {\n URL url = new URL(pluginUrl);\n InputStream in = url.openStream();\n String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);\n Path path = Paths.get(pluginsDirectory, fileName);\n\n Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);\n\n return path.toFile();\n }\n\n public void enablePlugin(Plugin plugin) {\n if (plugin != null && !plugin.isEnabled()) {\n plugin.getServer().getPluginManager().enablePlugin(plugin);\n }\n }\n\n public void enablePlugin(String pluginName) {\n enablePlugin(Bukkit.getServer().getPluginManager().getPlugin(\"HamsterAPI\"));\n }\n\n public Plugin loadPlugin(File file, Plugin plugin) throws UnknownDependencyException, InvalidPluginException, InvalidDescriptionException {\n return plugin.getServer().getPluginManager().loadPlugin(file);\n }\n}"
}
] | import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.UnknownDependencyException;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import dev._2lstudios.exploitfixer.commands.ExploitFixerCommand;
import dev._2lstudios.exploitfixer.configuration.IConfiguration;
import dev._2lstudios.exploitfixer.listener.ListenerInitializer;
import dev._2lstudios.exploitfixer.managers.ModuleManager;
import dev._2lstudios.exploitfixer.tasks.ExploitFixerRepeatingTask;
import dev._2lstudios.exploitfixer.utils.ConfigUtil;
import dev._2lstudios.exploitfixer.utils.PluginDownloader; | 3,217 | package dev._2lstudios.exploitfixer;
public class ExploitFixer extends JavaPlugin {
private static ExploitFixer instance;
private ConfigUtil configUtil; | package dev._2lstudios.exploitfixer;
public class ExploitFixer extends JavaPlugin {
private static ExploitFixer instance;
private ConfigUtil configUtil; | private ModuleManager moduleManager; | 3 | 2023-12-13 21:49:27+00:00 | 4k |
12manel123/mcc-tsys-ex2-c4-051223 | Ex02/src/main/java/com/ex02/controller/MensajeController.java | [
{
"identifier": "Mensaje",
"path": "Ex02/src/main/java/com/ex02/dto/Mensaje.java",
"snippet": "@Entity\r\npublic class Mensaje {\r\n\t@Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n private Long id;\r\n private String contenido;\r\n private String nombreUsuarioCreador;\r\n \r\n @ManyToOne\r\n\t@JoinColumn(name = \"partida_id\")\r\n\tprivate Partida partida;\r\n \r\n\tpublic Long getId() {\r\n\t\treturn id;\r\n\t}\r\n\tpublic void setId(Long id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\tpublic String getContenido() {\r\n\t\treturn contenido;\r\n\t}\r\n\tpublic void setContenido(String contenido) {\r\n\t\tthis.contenido = contenido;\r\n\t}\r\n\tpublic String getNombreUsuarioCreador() {\r\n\t\treturn nombreUsuarioCreador;\r\n\t}\r\n\tpublic void setNombreUsuarioCreador(String nombreUsuarioCreador) {\r\n\t\tthis.nombreUsuarioCreador = nombreUsuarioCreador;\r\n\t}\r\n\tpublic Mensaje(Long id, String contenido, String nombreUsuarioCreador) {\r\n\t\tsuper();\r\n\t\tthis.id = id;\r\n\t\tthis.contenido = contenido;\r\n\t\tthis.nombreUsuarioCreador = nombreUsuarioCreador;\r\n\t}\r\n\tpublic Mensaje() {\r\n\t\tsuper();\r\n\t}\r\n\tpublic Partida getPartida() {\r\n\t\treturn partida;\r\n\t}\r\n\tpublic void setPartida(Partida partida) {\r\n\t\tthis.partida = partida;\r\n\t}\r\n\t\r\n \r\n \r\n}\r"
},
{
"identifier": "Partida",
"path": "Ex02/src/main/java/com/ex02/dto/Partida.java",
"snippet": "@Entity\r\npublic class Partida {\r\n @Id\r\n private String nombre;\r\n private String descripcion;\r\n private int jugadores;\r\n private String plataforma;\r\n private Date fechaInicio;\r\n private String videojuego;\r\n \r\n @OneToMany(mappedBy = \"partida\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\r\n @JsonIgnore\r\n private List<Mensaje> mensajes;\r\n \r\n public Partida() {\r\n }\r\n \r\n \r\n\r\n public List<Mensaje> getMensajes() {\r\n\t\treturn mensajes;\r\n\t}\r\n\r\n\r\n\r\n\tpublic void setMensajes(List<Mensaje> mensajes) {\r\n\t\tthis.mensajes = mensajes;\r\n\t}\r\n\r\n\r\n\r\n\tpublic Partida(String nombre, String descripcion, int jugadores, String plataforma, Date fechaInicio, String videojuego) {\r\n this.nombre = nombre;\r\n this.descripcion = descripcion;\r\n this.jugadores = jugadores;\r\n this.plataforma = plataforma;\r\n this.fechaInicio = fechaInicio;\r\n this.videojuego = videojuego;\r\n }\r\n public String getVideojuego() {\r\n return videojuego;\r\n }\r\n\r\n public void setVideojuego(String videojuego) {\r\n this.videojuego = videojuego;\r\n }\r\n public String getNombre() {\r\n return nombre;\r\n }\r\n\r\n public void setNombre(String nombre) {\r\n this.nombre = nombre;\r\n }\r\n\r\n public String getDescripcion() {\r\n return descripcion;\r\n }\r\n\r\n public void setDescripcion(String descripcion) {\r\n this.descripcion = descripcion;\r\n }\r\n\r\n public int getJugadores() {\r\n return jugadores;\r\n }\r\n\r\n public void setJugadores(int jugadores) {\r\n this.jugadores = jugadores;\r\n }\r\n\r\n public String getPlataforma() {\r\n return plataforma;\r\n }\r\n\r\n public void setPlataforma(String plataforma) {\r\n this.plataforma = plataforma;\r\n }\r\n\r\n public Date getFechaInicio() {\r\n return fechaInicio;\r\n }\r\n\r\n public void setFechaInicio(Date fechaInicio) {\r\n this.fechaInicio = fechaInicio;\r\n }\r\n}\r"
},
{
"identifier": "MensajeService",
"path": "Ex02/src/main/java/com/ex02/service/MensajeService.java",
"snippet": "@Service\r\npublic class MensajeService implements IMensajeService {\r\n private final IMensajeDAO mensajeDAO;\r\n\r\n public MensajeService(IMensajeDAO mensajeDAO) {\r\n this.mensajeDAO = mensajeDAO;\r\n }\r\n\r\n public void crearMensaje(Mensaje mensaje) {\r\n mensajeDAO.save(mensaje);\r\n }\r\n\r\n public void eliminarMensaje(Long idMensaje) {\r\n mensajeDAO.deleteById(idMensaje);\r\n }\r\n\r\n public List<Mensaje> verTodosLosMensajes(String nombreSala) {\r\n return mensajeDAO.findAll();\r\n }\r\n public void editarMensaje(Long idMensaje, Mensaje mensajeActualizado) {\r\n Mensaje mensajeExistente = mensajeDAO.findById(idMensaje).orElse(null);\r\n if (mensajeExistente != null) {\r\n mensajeExistente.setContenido(mensajeActualizado.getContenido());\r\n mensajeExistente.setNombreUsuarioCreador(mensajeActualizado.getNombreUsuarioCreador());\r\n mensajeDAO.save(mensajeExistente);\r\n }\r\n }\r\n\r\n}"
},
{
"identifier": "PartidaService",
"path": "Ex02/src/main/java/com/ex02/service/PartidaService.java",
"snippet": "@Service\r\npublic class PartidaService implements IPartidaService {\r\n\r\n private final IPartidaDAO partidaDAO;\r\n\r\n public PartidaService(IPartidaDAO partidaDAO) {\r\n this.partidaDAO = partidaDAO;\r\n }\r\n\r\n @Override\r\n public void crearPartida(Partida partida) {\r\n partidaDAO.save(partida);\r\n }\r\n \r\n public List<Partida> buscarPartidasPorVideojuego(String videojuego) {\r\n return partidaDAO.findByVideojuego(videojuego);\r\n }\r\n\r\n @Override\r\n public void unirseAPartida(String nombrePartida) {\r\n Partida partida = partidaDAO.findById(nombrePartida).orElse(null);\r\n if (partida != null) {\r\n partida.setJugadores(partida.getJugadores()+1);\r\n partidaDAO.save(partida);\r\n }\r\n }\r\n\r\n @Override\r\n public void salirDePartida(String nombrePartida) {\r\n Partida partida = partidaDAO.findById(nombrePartida).orElse(null);\r\n partida.setJugadores(partida.getJugadores()-1);\r\n partidaDAO.save(partida);\r\n \r\n }\r\n \r\n}"
}
] | import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ex02.dto.Mensaje;
import com.ex02.dto.Partida;
import com.ex02.service.MensajeService;
import com.ex02.service.PartidaService;
import jakarta.transaction.Transactional;
| 1,768 | package com.ex02.controller;
@RestController
@RequestMapping("ex2/mensaje")
public class MensajeController {
private final MensajeService mensajeService;
public MensajeController(MensajeService mensajeService) {
this.mensajeService = mensajeService;
}
@PostMapping("/crear")
public ResponseEntity<String> crearMensaje(@RequestBody Mensaje mensaje) {
mensajeService.crearMensaje(mensaje);
return new ResponseEntity<>("Mensaje creado exitosamente", HttpStatus.CREATED);
}
@DeleteMapping("/eliminar/{idMensaje}")
public ResponseEntity<String> eliminarMensaje(@PathVariable Long idMensaje) {
mensajeService.eliminarMensaje(idMensaje);
return ResponseEntity.ok("Mensaje eliminado exitosamente");
}
@GetMapping("/verTodosEnSala/{nombreSala}")
public ResponseEntity<List<Mensaje>> verTodosLosMensajesEnSala(@PathVariable String nombreSala) {
List<Mensaje> mensajes = mensajeService.verTodosLosMensajes(nombreSala);
List<Mensaje> mensajesEnSala = new ArrayList<>();
for (Mensaje mensaje : mensajes) {
| package com.ex02.controller;
@RestController
@RequestMapping("ex2/mensaje")
public class MensajeController {
private final MensajeService mensajeService;
public MensajeController(MensajeService mensajeService) {
this.mensajeService = mensajeService;
}
@PostMapping("/crear")
public ResponseEntity<String> crearMensaje(@RequestBody Mensaje mensaje) {
mensajeService.crearMensaje(mensaje);
return new ResponseEntity<>("Mensaje creado exitosamente", HttpStatus.CREATED);
}
@DeleteMapping("/eliminar/{idMensaje}")
public ResponseEntity<String> eliminarMensaje(@PathVariable Long idMensaje) {
mensajeService.eliminarMensaje(idMensaje);
return ResponseEntity.ok("Mensaje eliminado exitosamente");
}
@GetMapping("/verTodosEnSala/{nombreSala}")
public ResponseEntity<List<Mensaje>> verTodosLosMensajesEnSala(@PathVariable String nombreSala) {
List<Mensaje> mensajes = mensajeService.verTodosLosMensajes(nombreSala);
List<Mensaje> mensajesEnSala = new ArrayList<>();
for (Mensaje mensaje : mensajes) {
| Partida partida = mensaje.getPartida();
| 1 | 2023-12-05 15:39:34+00:00 | 4k |
xIdentified/TavernBard | src/main/java/me/xidentified/tavernbard/managers/SongManager.java | [
{
"identifier": "BardTrait",
"path": "src/main/java/me/xidentified/tavernbard/BardTrait.java",
"snippet": "@TraitName(\"bard\")\npublic class BardTrait extends Trait {\n\n @Persist private boolean isBard = true;\n\n public BardTrait() {\n super(\"bard\");\n }\n\n // Keeping load and save methods as they are\n @Override\n public void load(DataKey key) {\n isBard = key.getBoolean(\"isBard\", true);\n }\n\n @Override\n public void save(DataKey key) {\n key.setBoolean(\"isBard\", isBard);\n }\n\n}"
},
{
"identifier": "MessageUtil",
"path": "src/main/java/me/xidentified/tavernbard/util/MessageUtil.java",
"snippet": "public class MessageUtil {\n private final MiniMessage miniMessage;\n private final FileConfiguration config;\n private final boolean isPaper;\n\n public MessageUtil(FileConfiguration config) {\n this.miniMessage = MiniMessage.miniMessage();\n this.config = config;\n this.isPaper = checkIfPaperServer();\n }\n\n private boolean checkIfPaperServer() {\n try {\n // Attempt to access a Paper-specific class or method\n Class.forName(\"com.destroystokyo.paper.PaperConfig\");\n return true;\n } catch (ClassNotFoundException e) {\n return false;\n }\n }\n\n public boolean isPaper() {\n return this.isPaper;\n }\n\n public Component parse(String message) {\n if (isPaper()) {\n // For Paper, parse using MiniMessage\n return miniMessage.deserialize(message);\n } else {\n // For Spigot, translate color codes and convert to a Component\n String translatedMessage = ChatColor.translateAlternateColorCodes('&', message);\n return Component.text(translatedMessage);\n }\n }\n\n public String getConfigMessage(String path, String defaultValue) {\n return config.getString(path, defaultValue);\n }\n\n // Trying to get messages to work on both Spigot and Paper servers regardless of how you enter color codes\n public String convertToUniversalFormat(String message) {\n Component component;\n\n // First, try parsing as MiniMessage (handles MiniMessage-style tags)\n try {\n component = miniMessage.deserialize(message);\n } catch (Exception e) {\n // If parsing fails, assume it's traditional color codes and convert\n String translatedMessage = ChatColor.translateAlternateColorCodes('&', message);\n component = Component.text(translatedMessage);\n }\n\n // Convert the Component to a universally compatible String format\n String universalString = LegacyComponentSerializer.legacySection().serialize(component);\n return universalString;\n }\n\n}"
}
] | import io.lumine.mythic.bukkit.MythicBukkit;
import io.lumine.mythic.core.mobs.ActiveMob;
import me.xidentified.tavernbard.*;
import me.xidentified.tavernbard.BardTrait;
import me.xidentified.tavernbard.util.MessageUtil;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.title.Title;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap; | 3,153 | Component subtitle = Component.text("Now playing: ", NamedTextColor.YELLOW)
.append(parsedDisplayNameComponent);
Title title = Title.title(mainTitle, subtitle);
nearbyPlayer.showTitle(title);
} else {
// If Spigot, use the universally formatted string directly
nearbyPlayer.sendTitle("", "Now playing: " + universalFormattedString, 10, 70, 20);
}
}
// Set current song
currentSong.put(npcId, new Song(selectedSong.getNamespace(), selectedSong.getName(), selectedSong.getDisplayName(), selectedSong.getArtist(), selectedSong.getDuration(), songStarter.get(npcId).getUniqueId()));
// Update now playing info
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
plugin.debugLog("Sound play attempt completed.");
int taskId = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
Entity bardEntity = plugin.getEntityFromUUID(player.getWorld(), npcId);
if (bardEntity != null) {
Location particleLocation = bardEntity.getLocation().add(0, 2.5, 0);
bardEntity.getWorld().spawnParticle(Particle.NOTE, particleLocation, 1);
} else {
plugin.debugLog("Entity with UUID " + npcId + " is null when trying to spawn particles.");
}
}, 0L, 20L).getTaskId();
long songDurationInTicks = selectedSong.getDuration() * 20L;
currentSongTaskId.put(npcId, taskId);
Bukkit.getScheduler().runTaskLater(plugin, () -> {
plugin.debugLog("Song ended. Attempting to play next song in the queue.");
Bukkit.getScheduler().cancelTask(taskId);
setSongPlaying(npcId, false);
playNextSong(npcId, player);
}, songDurationInTicks);
}
// Stops the current song for nearby players
public void stopCurrentSong(UUID npcId) {
if (isSongPlaying(npcId) && currentSongTaskId.containsKey(npcId) && currentSongTaskId.get(npcId) != -1) {
Bukkit.getScheduler().cancelTask(currentSongTaskId.get(npcId));
setSongPlaying(npcId, false);
UUID bardNpc = bardNpcs.get(npcId);
if (bardNpc != null) {
World world = Bukkit.getServer().getWorlds().get(0);
Entity entity = plugin.getEntityFromUUID(world, bardNpc);
if (entity instanceof Player bardPlayer) {
for (Player nearbyPlayer : bardPlayer.getWorld().getPlayers()) {
if (nearbyPlayer.getLocation().distance(bardPlayer.getLocation()) <= songPlayRadius) {
nearbyPlayer.stopAllSounds();
}
}
}
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
currentSong.remove(npcId);
playNextSong(npcId, songStarter.get(npcId));
songStarter.remove(npcId);
}
}
public void playNextSong(UUID npcId, Player songStarter) {
// Attempt to play next song in queue
Song nextSong = queueManager.getNextSongFromQueue(npcId);
if (nextSong != null && npcId != null) {
playSongForNearbyPlayers(songStarter, npcId, nextSong, false);
}
}
public boolean isSongPlaying(UUID npcId) {
return isSongPlaying.getOrDefault(npcId, false);
}
private void setSongPlaying(UUID npcId, boolean status) {
isSongPlaying.put(npcId, status);
}
public List<Song> getSongs() {
return new ArrayList<>(songs);
}
public Song getSongByName(String actualSongName) {
return songs.stream()
.filter(song -> song.getName().equalsIgnoreCase(actualSongName))
.findFirst()
.orElse(null);
}
public Player getSongStarter(UUID playerId) {
return songStarter.get(playerId);
}
public Song getCurrentSong(UUID npcId) {
return currentSong.get(npcId);
}
public UUID getNearestBard(Player player, double searchRadius) {
double closestDistanceSquared = searchRadius * searchRadius;
UUID closestBard = null;
// Get all entities within the search radius
List<Entity> nearbyEntities = player.getNearbyEntities(searchRadius, searchRadius, searchRadius);
for (Entity entity : nearbyEntities) {
// Check for Citizens NPC
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
NPC npc = CitizensAPI.getNPCRegistry().getNPC(entity); | package me.xidentified.tavernbard.managers;
public class SongManager {
private final TavernBard plugin;
private final QueueManager queueManager;
private final EconomyManager economyManager;
private final ItemCostManager itemCostManager;
private final List<Song> songs;
protected final double songPlayRadius;
private final int defaultSongDuration;
public final Map<UUID, Player> songStarter = new ConcurrentHashMap<>();
private final Map<UUID, Boolean> isSongPlaying = new ConcurrentHashMap<>();
private final Map<UUID, Song> currentSong = new ConcurrentHashMap<>();
private final Map<UUID, Integer> currentSongTaskId = new ConcurrentHashMap<>();
public final Map<UUID, UUID> bardNpcs = new ConcurrentHashMap<>();
public SongManager(TavernBard plugin) {
this.plugin = plugin;
this.queueManager = new QueueManager(this.plugin, this, plugin.getCooldownManager());
this.economyManager = new EconomyManager(this.plugin);
this.songs = loadSongsFromConfig();
this.songPlayRadius = plugin.getConfig().getDouble("song-play-radius", 20.0);
this.defaultSongDuration = plugin.getConfig().getInt("default-song-duration", 180);
this.itemCostManager = new ItemCostManager(
plugin.getConfig().getString("item-cost.item", "GOLD_NUGGET"),
plugin.getConfig().getInt("item-cost.amount", 3),
plugin.getConfig().getBoolean("item-cost.enabled", false),
plugin
);
}
public SongSelectionGUI getSongSelectionGUIForNPC(UUID npcId) {
UUID bardNpc = bardNpcs.get(npcId);
if (bardNpc == null) {
return null;
}
return new SongSelectionGUI(plugin, plugin.getSongManager(), bardNpc);
}
// Reload songs from config
public void reloadSongs() {
plugin.reloadConfig();
songs.clear();
songs.addAll(loadSongsFromConfig());
}
// Load songs from config
private List<Song> loadSongsFromConfig() {
List<Song> loadedSongs = new ArrayList<>();
FileConfiguration config = plugin.getConfig();
if (config.isConfigurationSection("songs")) {
ConfigurationSection songsSection = config.getConfigurationSection("songs");
assert songsSection != null;
for (String key : songsSection.getKeys(false)) {
String namespace = songsSection.getString(key + ".namespace");
String songName = songsSection.getString(key + ".name", key);
String displayName = songsSection.getString(key + ".displayName", songName);
String artist = songsSection.getString(key + ".artist", "Unknown Artist");
int duration = songsSection.getInt(key + ".duration", defaultSongDuration);
loadedSongs.add(new Song(namespace, songName, displayName, artist, duration));
}
} else {
plugin.debugLog("The 'songs' section is missing or misconfigured in config.yml!");
}
return loadedSongs;
}
public void playSongForNearbyPlayers(@NotNull Player player, @NotNull UUID npcId, @NotNull Song selectedSong, boolean chargePlayer) {
MessageUtil messageUtil = this.plugin.getMessageUtil();
CooldownManager cooldownManager = this.plugin.getCooldownManager();
UUID bardNpc = bardNpcs.get(npcId);
Object message = selectedSong.getDisplayName();
if (bardNpc == null) {
plugin.getLogger().severe("Could not retrieve NPC for ID: " + npcId);
return;
}
plugin.debugLog("Attempting to play song: " + message + " for " + songStarter.get(player.getUniqueId()));
// Check if item cost is enabled, return if they can't afford it
if (!cooldownManager.isOnCooldown(player) && chargePlayer && itemCostManager.isEnabled() && !itemCostManager.canAfford(player)) {
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<red>You need " + itemCostManager.getCostAmount() + " " + itemCostManager.formatEnumName(itemCostManager.getCostItem().name()) + "(s) to play a song!"));
return;
}
// Check if economy is enabled
if(!cooldownManager.isOnCooldown(player) && chargePlayer && plugin.getConfig().getBoolean("economy.enabled")) {
double costPerSong = plugin.getConfig().getDouble("economy.cost-per-song");
// Check and charge the player
if(!economyManager.chargePlayer(player, costPerSong)) {
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<red>You need " + costPerSong + " coins to play a song!"));
return;
} else {
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<green>Paid " + costPerSong + " coins to play a song!"));
}
}
if (!cooldownManager.isOnCooldown(player) && chargePlayer && itemCostManager.isEnabled()) {
itemCostManager.deductCost(player);
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<green>Charged " + itemCostManager.getCostAmount() + " " + itemCostManager.formatEnumName(itemCostManager.getCostItem().name()) + "(s) to play a song!"));
}
// If something is already playing, add song to queue
if (isSongPlaying(npcId)) {
queueManager.addSongToQueue(npcId, selectedSong, player);
return;
}
setSongPlaying(npcId, true);
Location bardLocation = Objects.requireNonNull(plugin.getEntityFromUUID(player.getWorld(), bardNpc)).getLocation();
plugin.debugLog("Playing sound reference: " + selectedSong.getSoundReference());
// Play song and show title to players within bard's radius
for (Player nearbyPlayer : bardLocation.getWorld().getPlayers()) {
if (nearbyPlayer.getLocation().distance(bardLocation) <= songPlayRadius) {
nearbyPlayer.playSound(bardLocation, selectedSong.getSoundReference(), 1.0F, 1.0F);
// Convert display name to a universally formatted string
String universalFormattedString = messageUtil.convertToUniversalFormat(selectedSong.getDisplayName());
if (messageUtil.isPaper()) {
// If Paper, parse the string back to a Component for displaying
Component parsedDisplayNameComponent = messageUtil.parse(universalFormattedString);
Component mainTitle = Component.text("");
Component subtitle = Component.text("Now playing: ", NamedTextColor.YELLOW)
.append(parsedDisplayNameComponent);
Title title = Title.title(mainTitle, subtitle);
nearbyPlayer.showTitle(title);
} else {
// If Spigot, use the universally formatted string directly
nearbyPlayer.sendTitle("", "Now playing: " + universalFormattedString, 10, 70, 20);
}
}
// Set current song
currentSong.put(npcId, new Song(selectedSong.getNamespace(), selectedSong.getName(), selectedSong.getDisplayName(), selectedSong.getArtist(), selectedSong.getDuration(), songStarter.get(npcId).getUniqueId()));
// Update now playing info
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
plugin.debugLog("Sound play attempt completed.");
int taskId = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
Entity bardEntity = plugin.getEntityFromUUID(player.getWorld(), npcId);
if (bardEntity != null) {
Location particleLocation = bardEntity.getLocation().add(0, 2.5, 0);
bardEntity.getWorld().spawnParticle(Particle.NOTE, particleLocation, 1);
} else {
plugin.debugLog("Entity with UUID " + npcId + " is null when trying to spawn particles.");
}
}, 0L, 20L).getTaskId();
long songDurationInTicks = selectedSong.getDuration() * 20L;
currentSongTaskId.put(npcId, taskId);
Bukkit.getScheduler().runTaskLater(plugin, () -> {
plugin.debugLog("Song ended. Attempting to play next song in the queue.");
Bukkit.getScheduler().cancelTask(taskId);
setSongPlaying(npcId, false);
playNextSong(npcId, player);
}, songDurationInTicks);
}
// Stops the current song for nearby players
public void stopCurrentSong(UUID npcId) {
if (isSongPlaying(npcId) && currentSongTaskId.containsKey(npcId) && currentSongTaskId.get(npcId) != -1) {
Bukkit.getScheduler().cancelTask(currentSongTaskId.get(npcId));
setSongPlaying(npcId, false);
UUID bardNpc = bardNpcs.get(npcId);
if (bardNpc != null) {
World world = Bukkit.getServer().getWorlds().get(0);
Entity entity = plugin.getEntityFromUUID(world, bardNpc);
if (entity instanceof Player bardPlayer) {
for (Player nearbyPlayer : bardPlayer.getWorld().getPlayers()) {
if (nearbyPlayer.getLocation().distance(bardPlayer.getLocation()) <= songPlayRadius) {
nearbyPlayer.stopAllSounds();
}
}
}
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
currentSong.remove(npcId);
playNextSong(npcId, songStarter.get(npcId));
songStarter.remove(npcId);
}
}
public void playNextSong(UUID npcId, Player songStarter) {
// Attempt to play next song in queue
Song nextSong = queueManager.getNextSongFromQueue(npcId);
if (nextSong != null && npcId != null) {
playSongForNearbyPlayers(songStarter, npcId, nextSong, false);
}
}
public boolean isSongPlaying(UUID npcId) {
return isSongPlaying.getOrDefault(npcId, false);
}
private void setSongPlaying(UUID npcId, boolean status) {
isSongPlaying.put(npcId, status);
}
public List<Song> getSongs() {
return new ArrayList<>(songs);
}
public Song getSongByName(String actualSongName) {
return songs.stream()
.filter(song -> song.getName().equalsIgnoreCase(actualSongName))
.findFirst()
.orElse(null);
}
public Player getSongStarter(UUID playerId) {
return songStarter.get(playerId);
}
public Song getCurrentSong(UUID npcId) {
return currentSong.get(npcId);
}
public UUID getNearestBard(Player player, double searchRadius) {
double closestDistanceSquared = searchRadius * searchRadius;
UUID closestBard = null;
// Get all entities within the search radius
List<Entity> nearbyEntities = player.getNearbyEntities(searchRadius, searchRadius, searchRadius);
for (Entity entity : nearbyEntities) {
// Check for Citizens NPC
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
NPC npc = CitizensAPI.getNPCRegistry().getNPC(entity); | if (!npc.hasTrait(BardTrait.class)) { | 0 | 2023-12-06 06:00:57+00:00 | 4k |
thekocanlhk/TawBrowser-Developed | app/src/main/java/com/thekocanl/tawbrowser/WebActivity.java | [
{
"identifier": "AdBlockerActivity",
"path": "app/src/main/java/com/thekocanl/tawbrowser/AdBlockerActivity.java",
"snippet": "public class AdBlockerActivity {\n\n static Map < String, Boolean > loadedUrls = new HashMap < >();\n\n public static boolean blockAds(WebView view, String url) {\n boolean ad;\n if (!loadedUrls.containsKey(url))\n\t\t{\n ad = AdBlocker.isAd(url);\n loadedUrls.put(url, ad);\n }\n else\n\t\t{\n ad = loadedUrls.get(url);\n }\n return ad;\n }\n\n public static class init {\n Context mContext;\n\n public init(Context mContext)\n\t\t{\n AdBlocker.init(mContext);\n this.mContext = mContext;\n }\n }\n}"
},
{
"identifier": "AdBlocker",
"path": "app/src/main/java/com/thekocanl/tawbrowser/util/AdBlocker.java",
"snippet": "public class AdBlocker {\n private static final String AD_HOSTS_FILE = \"hosts\";\n private static final Set < String > AD_HOSTS = new HashSet < >();\n\n public static void init(final Context mContext) {\n new AsyncTask < Void, Void, Void >() {\n @Override\n protected Void doInBackground(Void...params)\n\t\t\t{\n try\n\t\t\t\t{\n loadFromAssets(mContext);\n }\n catch (IOException e)\n\t\t\t\t{\n //\n }\n return null;\n }\n }.execute();\n }\n\n private static void loadFromAssets(Context mContext) throws IOException {\n InputStream stream = mContext.getAssets().open(AD_HOSTS_FILE);\n InputStreamReader inputStreamReader = new InputStreamReader(stream);\n BufferedReader bufferedReader = new BufferedReader(inputStreamReader);\n String line;\n while ((line = bufferedReader.readLine()) != null) AD_HOSTS.add(line);\n bufferedReader.close();\n inputStreamReader.close();\n stream.close();\n }\n\n public static boolean isAd(String url) {\n try\n\t\t{\n return isAdHost(UrlUtils.getHost(url));\n }\n catch (MalformedURLException e)\n\t\t{\n Log.d(\"\", e.toString());\n return false;\n }\n\n }\n\n private static boolean isAdHost(String host) {\n if (TextUtils.isEmpty(host))\n\t\t{\n return false;\n }\n int index = host.indexOf(\".\");\n return index >= 0 && (AD_HOSTS.contains(host) || index + 1 < host.length() && isAdHost(host.substring(index + 1)));\n }\n\n public static WebResourceResponse createEmptyResource()\n\t{\n return new WebResourceResponse(\"text/plain\", \"utf-8\", new ByteArrayInputStream(\"\".getBytes()));\n }\n\n}"
}
] | import com.thekocanl.tawbrowser.AdBlockerActivity;
import com.thekocanl.tawbrowser.util.AdBlocker;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.widget.*;
import android.graphics.*;
import android.webkit.SslErrorHandler;
import android.net.http.SslError;
import android.view.ViewTreeObserver;
import android.support.v7.app.AlertDialog;
import android.content.DialogInterface;
import android.print.PrintManager;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.view.View.*;
import java.lang.reflect.Method;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.os.Handler;
import android.os.Looper;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.webkit.GeolocationPermissions;
import android.webkit.WebResourceResponse;
import android.net.http.SslCertificate;
import java.util.Date;
import android.content.pm.ActivityInfo;
import android.speech.RecognizerIntent;
import android.content.ActivityNotFoundException;
import java.util.ArrayList;
import android.text.TextUtils;
import android.content.*; | 2,922 | }
else {
//
}
break;
}
}
});
// bazฤฑ eylemler yapmak iรงin hayฤฑr dรผฤmesini ayarlayฤฑn
builder.setNegativeButton("Hayฤฑr", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
}
});
// bazฤฑ eylemler yapmak iรงin evet dรผฤmesini ayarlayฤฑn
builder.setPositiveButton("Evet", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
// uyarฤฑ iletiลim kutusunu gรถster
AlertDialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
}
/**
* Web Site Sertifika Bilgisi
*/
private void certificateControl() {
SslCertificate certificate = webView.getCertificate();
if (certificate == null) {
//
initView();
webCertificate.setImageResource(R.drawable.unreliable_certificate);
cuhideshowControl();
initView();
}
else
{
//
initView();
webCertificate.setImageResource(R.drawable.reliable_certificate);
cuhideshowControl();
initView();
}
}
/**
* Web Site S CUHideShowControl
*/
private void cuhideshowControl() {
String cuUrl = getResources().getString(R.string.home_url);
if (webView.getUrl() != null && !webView.getUrl().equals(cuUrl))
{
initView();
webIcon.setVisibility(View.GONE);
webCertificate.setVisibility(View.VISIBLE);
initView();
}
else
{
initView();
webCertificate.setVisibility(View.GONE);
webIcon.setVisibility(View.VISIBLE);
initView();
}
}
/**
* Light Theme
*/
private void lightTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#cccccc"));
getWindow().setNavigationBarColor(Color.parseColor("#cccccc"));
}
/**
* Dark Theme
*/
private void darkTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#0f0f0f"));
getWindow().setNavigationBarColor(Color.parseColor("#0f0f0f"));
}
/**
* Main Menu Printer
*/
private void createWebPrintJob(WebView webView) {
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
String jobName = getString(R.string.app_name) + " Print Test";
printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
}
/**
* Yeniden Yazmak WebViewClient
*/
private class TawWebViewClient extends WebViewClient {
// Ad Blocker
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (adblockeronoff == 1) { | package com.thekocanl.tawbrowser;
public class WebActivity extends AppCompatActivity implements View.OnClickListener {
private WebView webView;
private ProgressBar progressBar;
private EditText textUrl, findBox;
private TextView homePageSearch, urltitle, urlfull;
private ImageView webIcon, webCertificate, goBack, goForward, navSet, goHome, speakGo, btnStart, btnSearchEngine, textUrlClean, textUrlEdit, floatButton, homePageSpeakGo, imageLabeldownload, imageLabelhistory, imageLabelsavedpage, imageLabeladdpage, imageLabelshare, imageLabeldarktheme, imageLabeladblocker, imageLabelfindpage, imageLabeldesktopsite, imageLabeltextsize, imageLabelzoomin, imageLabelprint, imageLabelsecurity, imageLabelsettings, imageLabeltranslation, imageLabelotorotate, imageLabelfullscreen, imageLabelwidefullscreen, imageLabelswiperefresh, imageLabelnojavascript, imageLabelnopicture, imageLabelcleandata, imageLabelsafebrowser, imageLabelexitapp;
private SwipeRefreshLayout swipeRefreshLayout;
// Tam Ekran Kullanฤฑmฤฑ
private LinearLayout toplinearLayout, sublinearLayout, layoutSearch, layoutSearchUrlInfo;
// Search
private ImageButton closeButton, nextButton, backButton;
// Ayarlar
private FrameLayout navsetLayout, homePageLayout;
private long exitTime = 0;
// Tam Ekran Kullanฤฑmฤฑ
private int floatbutton = 0;
// Main Menu Fullscreen
private int floatbuttonhideshow = 0;
// Main Menu Wide Fullscreen
private int widefullscreen = 0;
// Main Menu Wide Fullscreen On Off
private int widefullscreen_on_off = 0;
// Main Menu Dark Theme
private int darktheme = 0;
// Main Menu Swipe Refresh
private int swiperefresh = 0;
// Main Menu No Javascript
private int nojavascript = 0;
// Main Menu No Picture
private int nopicture = 0;
// Main Menu Desktop Site
private int desktopsite = 0;
// Main Menu Oto Rotate
private int otorotate = 0;
// Ayarlar
private int navset = 0;
// Ad Blocker
private int adblocker = 0;
// Ad Blocker On Off
private int adblockeronoff = 0;
// Search
private int findpage = 0;
// Clean Data
private int gt = 1;
private int agt = 1;
private int wot = 0;
private int uot = 0;
private int fvt = 1;
private int wct = 1;
private boolean bol0 = true;
private boolean bol1 = true;
private boolean bol2 = false;
private boolean bol3 = false;
private boolean bol4 = true;
private boolean bol5 = true;
//Search Engine
private boolean sebol0 = true;
private boolean sebol1 = false;
private boolean sebol2 = false;
private boolean sebol3 = false;
private boolean sebol4 = false;
private boolean sebol5 = false;
private boolean sebol6 = false;
private boolean sebol7 = false;
private String searchengineurlinput = "https://www.google.com/search?q=";
// Arama รubuฤu Gรถster Gizle
private float startY;
private int autohidesearchbar = 0;
private int homepagesearch = 0;
private int homepagespeakgo = 0;
private Context mContext;
private InputMethodManager manager;
private static final int RESULT_SPEECH = 1;
private static final String HTTP = "http://";
private static final String HTTPS = "https://";
private static final int PRESS_BACK_EXIT_GAP = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Alt Dรผฤmenin Yukarฤฑ Hareket Etmesini Engelle
getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
setContentView(R.layout.activity_web);
mContext = WebActivity.this;
manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
// Ad Blocker
new AdBlockerActivity.init(this);
// Baฤlama Kontrolleri
initView();
// Web Gรถrรผnรผmรผnรผ Baลlat
initWeb();
// Swipe Refresh
swipeRefresh();
// Arama รubuฤu Gรถster Gizle
autohideSearchBar();
}
/**
* Baฤlama Kontrolleri
*/
private void initView() {
webView = findViewById(R.id.webView);
progressBar = findViewById(R.id.progressBar);
textUrl = findViewById(R.id.textUrl);
webIcon = findViewById(R.id.webIcon);
webCertificate = findViewById(R.id.webCertificate);
btnStart = findViewById(R.id.btnStart);
goBack = findViewById(R.id.goBack);
goForward = findViewById(R.id.goForward);
navSet = findViewById(R.id.navSet);
goHome = findViewById(R.id.goHome);
// Main Menu Baฤlama Kontrolleri
imageLabeldownload = findViewById(R.id.imageLabeldownload);
imageLabelhistory = findViewById(R.id.imageLabelhistory);
imageLabelsavedpage = findViewById(R.id.imageLabelsavedpage);
imageLabeladdpage = findViewById(R.id.imageLabeladdpage);
imageLabelshare = findViewById(R.id.imageLabelshare);
imageLabeldarktheme = findViewById(R.id.imageLabeldarktheme);
imageLabeladblocker = findViewById(R.id.imageLabeladblocker);
imageLabelfindpage = findViewById(R.id.imageLabelfindpage);
imageLabeldesktopsite = findViewById(R.id.imageLabeldesktopsite);
imageLabeltextsize = findViewById(R.id.imageLabeltextsize);
imageLabelzoomin = findViewById(R.id.imageLabelzoomin);
imageLabelprint = findViewById(R.id.imageLabelprint);
imageLabelsecurity = findViewById(R.id.imageLabelsecurity);
imageLabelsettings = findViewById(R.id.imageLabelsettings);
imageLabeltranslation = findViewById(R.id.imageLabeltranslation);
imageLabelotorotate = findViewById(R.id.imageLabelotorotate);
imageLabelfullscreen = findViewById(R.id.imageLabelfullscreen);
imageLabelwidefullscreen = findViewById(R.id.imageLabelwidefullscreen);
imageLabelswiperefresh = findViewById(R.id.imageLabelswiperefresh);
imageLabelnojavascript = findViewById(R.id.imageLabelnojavascript);
imageLabelnopicture = findViewById(R.id.imageLabelnopicture);
imageLabelcleandata = findViewById(R.id.imageLabelcleandata);
imageLabelsafebrowser = findViewById(R.id.imageLabelsafebrowser);
imageLabelexitapp = findViewById(R.id.imageLabelexitapp);
//Tam Ekran Kullanฤฑmฤฑ
toplinearLayout = findViewById(R.id.toplinearLayout);
sublinearLayout = findViewById(R.id.sublinearLayout);
// Search
findBox = findViewById(R.id.findBox);
nextButton = findViewById(R.id.nextButton);
backButton = findViewById(R.id.backButton);
closeButton = findViewById(R.id.closeButton);
layoutSearch = findViewById(R.id.layoutSearch);
// Layout Search Url Info
layoutSearchUrlInfo = findViewById(R.id.layoutSearchUrlInfo);
urltitle = findViewById(R.id.urltitle);
urlfull = findViewById(R.id.urlfull);
// Search Engine
btnSearchEngine = findViewById(R.id.btnSearchEngine);
// Speak Go
speakGo = findViewById(R.id.speakGo);
// Ayarlar
navsetLayout = findViewById(R.id.navsetLayout);
// Anasayfa Layout
homePageLayout = findViewById(R.id.homePageLayout);
homePageSearch = findViewById(R.id.homePageSearch);
homePageSpeakGo = findViewById(R.id.homePageSpeakGo);
// Adresi Silme
textUrlClean = findViewById(R.id.textUrlClean);
// Adresi Dรผzenleme
textUrlEdit = findViewById(R.id.textUrlEdit);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeColors(Color.BLACK,Color.BLACK,Color.BLACK);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (swiperefresh == 1) {
webView.reload();
swipeRefreshLayout.setRefreshing(false);
}
else if (swiperefresh == 0) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
// Web Site Sertifika Bilgisi
webCertificate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = "URL: " + webView.getUrl() + "\n";
s += "Baลlฤฑk: " + webView.getTitle() + "\n\n";
SslCertificate certificate = webView.getCertificate();
s += certificate == null ? "Gรผvenli deฤil" : "Sertifika: Gรผvenli\n" + certificateToStr(certificate);
AlertDialog.Builder certificateDialog = new AlertDialog.Builder(WebActivity.this)
.setTitle("Sertifika bilgisi")
.setMessage(s)
.setPositiveButton("Kapat", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
//
}
});
certificateDialog.show();
}
});
// SwipeRefreshLayout sayfa รผstรผnde yenileme ayarฤฑ
webView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (swiperefresh == 1) {
if (webView.getScrollY()==0) {
swipeRefreshLayout.setEnabled(true);
}else {
swipeRefreshLayout.setEnabled(false);
}
}
}
});
// Anasayfa Arama odaklanma
homePageSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
if(homepagesearch == 0) {
textUrl.requestFocus();
//InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//inputMethodManager.showSoftInput(textUrl, InputMethodManager.SHOW_IMPLICIT);
showKeyboard(textUrl);
navsetLayout.setVisibility(View.GONE);
navset = 0;
//
// Gรถsterme Animasyonu
toplinearLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
//
// Gรถsterme Sรผresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.VISIBLE);
}
}, 1);
//
}
}
});
// Anasayfa Speak Go
homePageSpeakGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
if(homepagespeakgo == 0) {
speakGo();
navsetLayout.setVisibility(View.GONE);
navset = 0;
//
// Gรถsterme Animasyonu
toplinearLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
//
// Gรถsterme Sรผresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.VISIBLE);
}
}, 1);
//
}
}
});
// Speak Go
speakGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
speakGo();
//
}
});
// Adresi Silme
textUrlClean.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textUrl.setText(webView.getUrl());
textUrl.setSelection(textUrl.getText().length());
textUrl.getText().clear();
}
});
// Adresi Silme
textUrlEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textUrl.setText(webView.getUrl());
textUrl.setSelection(textUrl.getText().length());
}
});
//Tam Ekran Kullanฤฑmฤฑ
floatButton = findViewById(R.id.floatButton);
// Tam Ekran Dรผฤmesi Kullanฤฑmฤฑ
floatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if (floatbutton == 0)
{
initView();
toplinearLayout.setVisibility(View.GONE);
Toast.makeText(mContext, "Tam Ekran aรงฤฑldฤฑ รงฤฑkmak iรงin tekrar basฤฑn", Toast.LENGTH_SHORT).show();
floatButton.setImageResource(R.drawable.icfullscreenexit24dp);
sublinearLayout.setVisibility(View.GONE);
autohidesearchbar = 1;
floatbutton = 1;
initView();
}
else if (floatbutton == 1)
{
initView();
toplinearLayout.setVisibility(View.VISIBLE);
toplinearLayout.setAlpha(1.0f);
Toast.makeText(mContext, "Tam Ekrandan รงฤฑkฤฑldฤฑ aรงmak iรงin tekrar basฤฑn", Toast.LENGTH_SHORT).show();
floatButton.setImageResource(R.drawable.icfullscreen24dp);
sublinearLayout.setVisibility(View.VISIBLE);
autohidesearchbar = 0;
floatbutton = 0;
initView();
}
if (findpage == 1)
{
initView();
toplinearLayout.setVisibility(View.GONE);
layoutSearch.setVisibility(View.VISIBLE);
autohidesearchbar = 1;
initView();
}
}
});
// Baฤlama Dรผฤmesi Tฤฑklama Olayฤฑ
btnStart.setOnClickListener(this);
goBack.setOnClickListener(this);
goForward.setOnClickListener(this);
navSet.setOnClickListener(this);
goHome.setOnClickListener(this);
// Main Menu Baฤlama Kontrolleri
imageLabeldownload.setOnClickListener(this);
imageLabelhistory.setOnClickListener(this);
imageLabelsavedpage.setOnClickListener(this);
imageLabeladdpage.setOnClickListener(this);
imageLabelshare.setOnClickListener(this);
imageLabeldarktheme.setOnClickListener(this);
imageLabeladblocker.setOnClickListener(this);
imageLabelfindpage.setOnClickListener(this);
imageLabeldesktopsite.setOnClickListener(this);
imageLabeltextsize.setOnClickListener(this);
imageLabelzoomin.setOnClickListener(this);
imageLabelprint.setOnClickListener(this);
imageLabelsecurity.setOnClickListener(this);
imageLabelsettings.setOnClickListener(this);
imageLabeltranslation.setOnClickListener(this);
imageLabelotorotate.setOnClickListener(this);
imageLabelfullscreen.setOnClickListener(this);
imageLabelwidefullscreen.setOnClickListener(this);
imageLabelswiperefresh.setOnClickListener(this);
imageLabelnojavascript.setOnClickListener(this);
imageLabelnopicture.setOnClickListener(this);
imageLabelcleandata.setOnClickListener(this);
imageLabelsafebrowser.setOnClickListener(this);
imageLabelexitapp.setOnClickListener(this);
// Search
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
closeButton.setOnClickListener(this);
//Search Engine
btnSearchEngine.setOnClickListener(this);
// Adresi Silme
textUrlClean.setVisibility(View.GONE);
// Adresi Dรผzenleme
textUrlEdit.setVisibility(View.GONE);
// Speak Go
speakGo.setVisibility(View.GONE);
// Adres Giriล Alanฤฑ Odaฤฤฑ Alฤฑr Ve Kaybeder
textUrl.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
// Geรงerli URL Baฤlantฤฑsฤฑnฤฑ Gรถster TODO:Arama Terimlerini Gรถsteren Arama Sayfasฤฑ
textUrl.setText(webView.getUrl());
// Sonunda ฤฐmleรง
textUrl.setSelection(textUrl.getText().length());
// Adresi Silme
textUrl.getText().clear();
// ฤฐnternet Simgesini Gรถster
webIcon.setImageResource(R.drawable.internet);
// Atlama dรผฤmelerini gรถster
btnStart.setImageResource(R.drawable.go);
// Adresi Silme
textUrlClean.setVisibility(View.VISIBLE);
// Adresi Dรผzenleme
textUrlEdit.setVisibility(View.VISIBLE);
// Web Site Sertifika Bilgisi
webCertificate.setVisibility(View.GONE);
webIcon.setVisibility(View.VISIBLE);
// Speak Go
speakGo.setVisibility(View.VISIBLE);
// Layout Search Url Info
urltitle.setText(webView.getTitle());
urltitle.setEms(14);
urlfull.setText(webView.getUrl());
urlfull.setEms(18);
layoutSearchUrlInfo.setVisibility(View.VISIBLE);
}
else {
// Web Sitesi Adฤฑnฤฑ Gรถster
textUrl.setText(webView.getTitle());
// Favicon'u Gรถster
webIcon.setImageBitmap(webView.getFavicon());
// Yenile Dรผฤmesini Gรถster
btnStart.setImageResource(R.drawable.refresh);
// Adresi Silme
textUrlClean.setVisibility(View.INVISIBLE);
// Adresi Dรผzenleme
textUrlEdit.setVisibility(View.INVISIBLE);
// Web Site S CUHideShowControl
cuhideshowControl();
// Speak Go
speakGo.setVisibility(View.GONE);
// Layout Search Url Info
layoutSearchUrlInfo.setVisibility(View.GONE);
// Gรถrรผnรผmรผ Tekrar Baลlat
initView();
}
}
});
// Search
findBox.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (((findpage == 1)) && ((event.getAction() == KeyEvent.ACTION_DOWN)) && ((keyCode == KeyEvent.KEYCODE_ENTER)))
{
webView.findAllAsync(findBox.getText().toString());
try
{
for (Method m : WebView.class.getDeclaredMethods())
{
if (m.getName().equals("setFindIsUp"))
{
m.setAccessible(true);
m.invoke(webView, true);
break;
}
}
}
catch (Exception ignored)
{
}
finally
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View vv = getCurrentFocus();
if (vv != null)
{
inputManager.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
return false;
}
});
// Monitรถr Klavyesi Aramaya Gir
textUrl.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
// Arama Yap
btnStart.callOnClick();
textUrl.clearFocus();
}
return false;
}
});
}
/**
* Web'i Baลlat
*/
@SuppressLint("SetJavaScriptEnabled")
private void initWeb() {
// Yeniden Yazmak WebViewClient
webView.setWebViewClient(new TawWebViewClient());
// Yeniden Yazmak WebChromeClient
webView.setWebChromeClient(new TawWebChromeClient());
WebSettings settings = webView.getSettings();
// JS ฤฐลlevini Etkinleลtir
settings.setJavaScriptEnabled(true);
// Tarayฤฑcฤฑyฤฑ Kullanฤฑcฤฑ Aracฤฑsฤฑ Olarak Ayarla
settings.setUserAgentString(settings.getUserAgentString() + " TawBrowser/" + getVerName(mContext));
// Resmi Web Gรถrรผnรผmรผne Sฤฑฤdฤฑrmak ฤฐรงin Yeniden Boyutlandฤฑrฤฑn
settings.setUseWideViewPort(true);
// Ekranฤฑn Boyutuna Yakฤฑnlaลtฤฑrฤฑn
settings.setLoadWithOverviewMode(true);
// รlรงeklendirmeyi Destekler, Varsayฤฑlanlar true'dur. Aลaฤฤฑdakilerin รncรผlรผdรผr.
settings.setSupportZoom(true);
// Yerleลik Yakฤฑnlaลtฤฑrma Kontrollerini Ayarlar. false'yse, WebView Yakฤฑnlaลtฤฑrฤฑlamaz
settings.setBuiltInZoomControls(true);
// Yerel Yakฤฑnlaลtฤฑrma Denetimlerini Gizle
settings.setDisplayZoomControls(false);
// รoklu Pencereleri Destekleme
settings.setSupportMultipleWindows(true);
// WebView Background Color
webView.setBackgroundColor(Color.WHITE);
// รnbellek
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
// Dosya Eriลimini Ayarla
settings.setAllowFileAccess(true);
// JS Aracฤฑlฤฑฤฤฑyla Yeni Pencerelerin Aรงฤฑlmasฤฑnฤฑ Destekleyin
settings.setJavaScriptCanOpenWindowsAutomatically(true);
// Resimlerin Otomatik Yรผklenmesini Destekleyin
settings.setLoadsImagesAutomatically(true);
// Varsayฤฑlan Kodlama Biรงimini Ayarlayฤฑn
settings.setDefaultTextEncodingName("utf-8");
// Yerel Depolama
settings.setDomStorageEnabled(true);
settings.setPluginState(WebSettings.PluginState.ON);
// Geolocation Path
settings.setGeolocationEnabled(true);
settings.setGeolocationDatabasePath(String.valueOf(mContext.getFilesDir().getAbsolutePath()) + "/location");
// AppCache Path
settings.setAppCacheEnabled(true);
settings.setAppCachePath(String.valueOf(mContext.getFilesDir().getAbsolutePath()) + "/cache");
// Database Path
settings.setDatabaseEnabled(true);
settings.setDatabasePath(String.valueOf(mContext.getFilesDir().getAbsolutePath()) + "/databases");
// WebView Metin Boyutu
settings.setTextZoom(100);
// Kaynak Karฤฑลฤฑmฤฑ Modu
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
// Ana Sayfayฤฑ Yรผkle
SharedPreferences sp = getSharedPreferences("PREFS", MODE_PRIVATE);
SharedPreferences.Editor spe = sp.edit();
//
if (sp.getInt("HOMEPAGEURLCHANGE", 0) == 1) {
//
webView.loadUrl(""+sp.getString("HOMEPAGEURL", ""));
}
else {
//
webView.loadUrl(getResources().getString(R.string.home_url));
}
}
/**
* Swipe Refresh
*/
private void swipeRefresh() {
swipeRefreshLayout.setEnabled(false);
}
/**
* WebView Back Forward Control
*/
private void goBackForwardControl() {
//
goBack.setColorFilter(Color.parseColor("#c8c8c8"));
goForward.setColorFilter(Color.parseColor("#c8c8c8"));
//
if(webView.canGoBack()) {
//
goBack.setColorFilter(Color.parseColor("#4d4d4d"));
}
//
if(webView.canGoForward()) {
//
goForward.setColorFilter(Color.parseColor("#4d4d4d"));
}
//
}
/**
* WebView Share Url Control
*/
private void webviewShareUrlControl() {
//
imageLabelshare.setColorFilter(Color.parseColor("#c8c8c8"));
imageLabelprint.setColorFilter(Color.parseColor("#c8c8c8"));
imageLabeltranslation.setColorFilter(Color.parseColor("#c8c8c8"));
//
String cuUrl = getResources().getString(R.string.home_url);
if(webView.getUrl() != null && !webView.getUrl().equals(cuUrl)) {
//
imageLabelshare.setColorFilter(Color.parseColor("#000000"));
imageLabelprint.setColorFilter(Color.parseColor("#000000"));
imageLabeltranslation.setColorFilter(Color.parseColor("#000000"));
}
//
}
/**
* Speak Go
*/
private void speakGo() {
//
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Konuลmadan Niyet Kullanarak Deฤeri Alฤฑn
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "tr-TR");
try {
startActivityForResult(intent, RESULT_SPEECH);
// Metni Boล Olarak Ayarla
textUrl.setText("");
}
catch (ActivityNotFoundException a) {
// Cihaz Desteklenmiyorsa Bir Tost Gรถster
Toast.makeText(getApplicationContext(), "รzgรผnรผm cihazฤฑnฤฑz Speech to Text'i desteklemiyor", Toast.LENGTH_SHORT)
.show();
}
//
}
/**
* Hide Keyboard
*/
private void hideKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* Show Keyboard
*/
private void showKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
/**
* Anasayfa Kontrol - Show Hide
*/
private void homePageControl() {
String cuUrl = getResources().getString(R.string.home_url);
if (webView.getUrl() != null && !webView.getUrl().equals(cuUrl))
{
initView();
// Gizleme Sรผresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
// Gizleme Animasyonu
homePageLayout.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
}
}, 500);
//
homepagesearch = 1;
homepagespeakgo = 1;
initView();
}
else
{
initView();
// Gรถsterme Sรผresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
// Gรถsterme Animasyonu
homePageLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
webView.setVisibility(View.GONE);
}
}, 1);
//
Handler handler2 = new Handler(Looper.getMainLooper());
handler2.postDelayed(new Runnable() {
public void run() {
webView.setVisibility(View.VISIBLE);
}
}, 500);
//
homepagesearch = 0;
homepagespeakgo = 0;
initView();
}
}
/**
* Arama รubuฤu Gรถster Gizle
*/
private void autohideSearchBar() {
this.webView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// NavSetLayout Touch Hide
navsetLayout.setVisibility(View.GONE);
navset = 0;
// Hide Keyboard
hideKeyboard(textUrl);
//
// Aรงฤฑk = Kapalฤฑ
if (WebActivity.this.autohidesearchbar == 1) {
return false;
}
//
// 1
if (event.getAction() == 0) {
WebActivity.this.startY = event.getY();
}
//
// 2
if (event.getAction() == 2 || Math.abs(WebActivity.this.startY - event.getY()) <= ((float) (new ViewConfiguration().getScaledTouchSlop() * 5))) {
return false;
}
//
// Gรถster
if (WebActivity.this.startY < event.getY()) {
// Gรถsterme Animasyonu
toplinearLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
//
// Gรถsterme Sรผresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.VISIBLE);
}
}, 1);
//
return false;
}
//
// Gizle
// Gizleme Animasyonu
toplinearLayout.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
//
// Gizleme Sรผresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.GONE);
}
}, 1);
//
return false;
//
}
});
}
/**
* Search Engine
*/
private void searchEngineChange() {
//
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Arama motoru seรงin");
String[] items = {"Google", "Bing", "Yandex", "DuckDuckGo", "Startpage", "Yahoo", "Ask", "Wow"};
boolean[] checkedItems = {sebol0, sebol1, sebol2, sebol3, sebol4, sebol5, sebol6, sebol7};
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
switch (which) {
//
case 0:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_google);
sebol0 = true;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://www.google.com/search?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol0 = true;
dialog.cancel();
initView();
}
break;
//
case 1:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_bing);
sebol0 = false;
sebol1 = true;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://www.bing.com/search?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol1 = true;
dialog.cancel();
initView();
}
break;
//
case 2:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_yandex);
sebol0 = false;
sebol1 = false;
sebol2 = true;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://yandex.com/search/touch/?text=";
dialog.cancel();
initView();
} else {
//
initView();
sebol2 = true;
dialog.cancel();
initView();
}
break;
//
case 3:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_duckduckgo);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = true;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://duckduckgo.com/?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol3 = true;
dialog.cancel();
initView();
}
break;
//
case 4:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_startpage);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = true;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://www.startpage.com/do/search?query=";
dialog.cancel();
initView();
} else {
//
initView();
sebol4 = true;
dialog.cancel();
initView();
}
break;
//
case 5:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_yahoo);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = true;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://search.yahoo.com/search?p=";
dialog.cancel();
initView();
} else {
//
initView();
sebol5 = true;
dialog.cancel();
initView();
}
break;
//
case 6:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_ask);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = true;
sebol7 = false;
searchengineurlinput = "https://www.ask.com/web?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol6 = true;
dialog.cancel();
initView();
}
break;
case 7:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_wow);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = true;
searchengineurlinput = "https://www.wow.com/search?p=";
dialog.cancel();
initView();
} else {
//
initView();
sebol7 = true;
dialog.cancel();
initView();
}
break;
}
}
});
builder.setNeutralButton("Varsayฤฑlan", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int which) {
initView();
btnSearchEngine.setImageResource(R.drawable.se_google);
sebol0 = true;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
Toast.makeText(WebActivity.this, "Varsayฤฑlan arama motoru seรงildi", Toast.LENGTH_SHORT)
.show();
initView();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Clean Data D
*/
private void cleanAllData() {
//
AlertDialog.Builder alertDialog = new AlertDialog.Builder(WebActivity.this);
alertDialog.setTitle("");
String[] items = {"Geรงmiลi temizle", "Arama geรงmiลini temizle", "Web รถnbelleฤini temizle", "Uygulama รถnbelleฤini temizle", "Form verilerini temizle ", "Web รงerezlerini temizle"};
boolean[] checkedItems = {bol0, bol1, bol2, bol3, bol4, bol5};
alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
switch (which) {
case 0:
if(isChecked) {
gt = 1;
bol0 = true;
}
else {
gt = 0;
bol0 = false;
}
break;
case 1:
if(isChecked) {
agt = 1;
bol1 = true;
}
else {
agt = 0;
bol1 = false;
}
break;
case 2:
if(isChecked) {
wot = 1;
bol2 = true;
}
else {
wot = 0;
bol2 = false;
}
break;
case 3:
if(isChecked) {
uot = 1;
bol3 = true;
}
else {
uot = 0;
bol3 =false;
}
break;
case 4:
if(isChecked) {
fvt = 1;
bol4 = true;
}
else {
fvt = 0;
bol4 = false;
}
break;
case 5:
if(isChecked) {
wct = 1;
bol5 = true;
}
else {
wct = 0;
bol5 = false;
}
break;
}
}
});
alertDialog.setNeutralButton("Varsayฤฑlan", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
initView();
cleanAllDataDefault();
Toast.makeText(WebActivity.this, "Varsayฤฑlan ayarlara sฤฑfฤฑrlandฤฑ", Toast.LENGTH_SHORT).show();
cleanAllData();
initView();
}
});
alertDialog.setNegativeButton("ฤฐptal", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(WebActivity.this, "ฤฐptal edildi", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
if(gt == 1 || agt == 1 || wot == 1 || uot == 1 || fvt == 1 || wct ==1) {
//
// Geรงmiลi temizle
if(gt == 1) {
//
webView.clearHistory();
}
else if(gt == 0) {
//
}
//
// Arama geรงmiลini temizle
if(agt == 1) {
//
webView.clearMatches();
}
else if(agt == 0) {
//
}
//
// Web รถnbelleฤini temizle
if(wot == 1) {
//
}
else if (wot == 0) {
//
}
//
// Uygulama รถnbelleฤini temizle
if(uot == 1) {
//
}
else if(uot == 0) {
//
}
//
// Form verilerini temizle
if(fvt == 1) {
//
webView.clearFormData();
}
else if(fvt == 0) {
//
}
//
// Web รงerezlerini temizle
if(wct == 1) {
//
webView.clearHistory();
webView.clearFormData();
webView.clearCache(true);
}
else if(wct == 0) {
//
}
//
if (gt == 1 || agt == 1 || wot == 1 || uot == 1 || fvt == 1 || wct ==1) {
if (gt == 1 && agt == 1 && wot == 1 && uot == 1 && fvt == 1 && wct ==1) {
Toast.makeText(WebActivity.this, "Tรผmรผ temizleniyor...", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(WebActivity.this, "Seรงilenler temizleniyor...", Toast.LENGTH_SHORT).show();
}
Toast.makeText(WebActivity.this, "Temizlendi", Toast.LENGTH_SHORT).show();
}
}
else if(gt == 0 && agt == 0 && wot == 0 && uot == 0 && fvt == 0 && wct == 0) {
initView();
cleanAllData();
Toast.makeText(WebActivity.this, "Hฤฑรงbir รถฤe seรงilmedi tekrar seรงim yapฤฑn ve tamam tuลuna basฤฑn veya รงฤฑkmak iรงin iptal tuลuna basฤฑnฤฑz", Toast.LENGTH_SHORT).show();
initView();
}
}
});
AlertDialog alert = alertDialog.create();
alert.setCanceledOnTouchOutside(false);
alert.show();
//
}
/**
* Clean Data D Reset Value
*/
private void cleanAllDataReset() {
gt = 0;
agt = 0;
wot = 0;
uot = 0;
fvt = 0;
wct = 0;
bol0 = false;
bol1 = false;
bol2 = false;
bol3 = false;
bol4 = false;
bol5 = false;
}
/**
* Clean Data D Default Value
*/
private void cleanAllDataDefault() {
gt = 1;
agt = 1;
wot = 0;
uot = 0;
fvt = 1;
wct = 1;
bol0 = true;
bol1 = true;
bol2 = false;
bol3 = false;
bol4 = true;
bol5 = true;
}
/**
* Exit App
*/
private void confirmExitApp() {
// uyarฤฑ iletiลim kutusu
AlertDialog.Builder builder = new AlertDialog.Builder(WebActivity.this);
builder.setIcon(R.drawable.splash);
builder.setTitle("TawBrowser'dan รงฤฑkฤฑล yapmak istediฤinize emin misiniz?");
//
String[] items = {"Web รถnbelleฤini temizle", "Geรงmiลi temizle", "Her seferinde bana sor"};
boolean[] checkedItems = {false, false, true};
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
switch (which) {
//
case 0:
if(isChecked) {
//
}
else {
//
}
break;
//
case 1:
if(isChecked) {
//
webView.clearHistory();
}
else {
//
}
break;
//
case 2:
if(isChecked) {
//
}
else {
//
}
break;
}
}
});
// bazฤฑ eylemler yapmak iรงin hayฤฑr dรผฤmesini ayarlayฤฑn
builder.setNegativeButton("Hayฤฑr", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
}
});
// bazฤฑ eylemler yapmak iรงin evet dรผฤmesini ayarlayฤฑn
builder.setPositiveButton("Evet", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
// uyarฤฑ iletiลim kutusunu gรถster
AlertDialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
}
/**
* Web Site Sertifika Bilgisi
*/
private void certificateControl() {
SslCertificate certificate = webView.getCertificate();
if (certificate == null) {
//
initView();
webCertificate.setImageResource(R.drawable.unreliable_certificate);
cuhideshowControl();
initView();
}
else
{
//
initView();
webCertificate.setImageResource(R.drawable.reliable_certificate);
cuhideshowControl();
initView();
}
}
/**
* Web Site S CUHideShowControl
*/
private void cuhideshowControl() {
String cuUrl = getResources().getString(R.string.home_url);
if (webView.getUrl() != null && !webView.getUrl().equals(cuUrl))
{
initView();
webIcon.setVisibility(View.GONE);
webCertificate.setVisibility(View.VISIBLE);
initView();
}
else
{
initView();
webCertificate.setVisibility(View.GONE);
webIcon.setVisibility(View.VISIBLE);
initView();
}
}
/**
* Light Theme
*/
private void lightTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#cccccc"));
getWindow().setNavigationBarColor(Color.parseColor("#cccccc"));
}
/**
* Dark Theme
*/
private void darkTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#0f0f0f"));
getWindow().setNavigationBarColor(Color.parseColor("#0f0f0f"));
}
/**
* Main Menu Printer
*/
private void createWebPrintJob(WebView webView) {
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
String jobName = getString(R.string.app_name) + " Print Test";
printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
}
/**
* Yeniden Yazmak WebViewClient
*/
private class TawWebViewClient extends WebViewClient {
// Ad Blocker
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (adblockeronoff == 1) { | return AdBlockerActivity.blockAds(view, url) ? AdBlocker.createEmptyResource() : super.shouldInterceptRequest(view, url); | 1 | 2023-12-09 12:57:19+00:00 | 4k |
connect-ankit/contact-directory | contact-app/src/test/java/com/inn/assignment/PersonControllerTest.java | [
{
"identifier": "AppRunner",
"path": "contact-app/src/main/java/com/inn/assignment/task2/appconfiguration/AppRunner.java",
"snippet": "@SpringBootApplication\n@ComponentScan(basePackages = { \"com.inn\" })\n@EnableAutoConfiguration\n@EnableAspectJAutoProxy\n@EnableFeignClients(basePackages = { \"com.inn\" })\n@EnableJpaRepositories(basePackages = \"com.inn\")\n@EntityScan(\"com.inn\")\npublic class AppRunner {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(AppRunner.class, args);\n\n\t}\n\n}"
},
{
"identifier": "IPersonController",
"path": "contact-api/src/main/java/com/inn/assignment/task2/controller/IPersonController.java",
"snippet": "@Validated\n@CrossOrigin(origins = \"*\")\n\n@Tag(name = \"IPersonController\", description = \"Endpoint for managing contact directory data\")\npublic interface IPersonController {\n\t@Operation(summary = \"Add a new person details in directory \", description = \"Add a new person details in directory and return created Object in response\")\n\t@PostMapping(\"/create\")\n\tPerson create(@Valid @RequestBody Person model);\n\n\t@Operation(summary = \"update a existing person details in directory\", description = \"update a existing details and return updated data in response\")\n\t@PostMapping(\"/update\")\n\tPerson update(@Valid @RequestBody Person model);\n\n\t@Operation(summary = \"Find all person records\", description = \"Retrieve all the person records.\")\n\t@GetMapping(\"/findAll\")\n\tpublic List<Person> findAll();\n\n\t@Operation(summary = \"Delete a existing person details from directory\", description = \"Delete a existing details in directory and return success\")\n\t@DeleteMapping(\"/delete/{id}\")\n\tString delete(@PathVariable Integer id);\n\n\t@Operation(summary = \"Search person record from person directory\", description = \"Perform an advanced version of the search for person records based on the provided query and limits.\")\n\t@PostMapping(path = \"/search\")\n\tList<Person> search(\n\t\t\[email protected](content = @Content(schema = @Schema(implementation = String.class)), required = false) @Parameter(description = \"Search query\") String query,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Upper limit for search\") Integer ulimit,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Lower limit for search\") Integer llimit,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Field to order results by\") String orderBy,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Type of ordering (ascending/descending\") String orderType);\n\n\t@Hidden\n\t@Operation(summary = \"Get count of searched contact records\", description = \"Retrieve the count of contact records based on the advanced search query.\")\n\t@PostMapping(path = \"getCount\")\n\tLong getCount(\n\t\t\[email protected](content = @Content(schema = @Schema(implementation = String.class)), required = false) @Parameter(description = \"Search query\") String query);\n}"
},
{
"identifier": "Constant",
"path": "contact-api/src/main/java/com/inn/assignment/task2/core/Constant.java",
"snippet": "public class Constant {\n\tpublic static final String EMPTY_OBJECT_STR = \"{}\";\n\t@UtilityClass\n\tpublic static final class ResponseKey {\n\t\tpublic static final String DATA = \"data\";\n\t\tpublic static final String STATUS = \"status\";\n\t\tpublic static final String STATUS_INFO = \"statusInfo\";\n\t\tpublic static final String STATUS_CODE = \"statusCode\";\n\t\tpublic static final String COUNT = \"count\";\n\t\tpublic static final String MESSAGE = \"message\";\n\t\tpublic static final String MEDIA_TYPE = \"mediaType\";\n\t\tpublic static final String ERROR = \"error\";\n\t\tpublic static final String HTTP_STATUS_CODE = \"http.status_code\";\n\n\t}\n\t\n\t@UtilityClass\n\tpublic static final class ResponseStatus {\n\t\tpublic static final String SUCCESS = \"SUCCESS\";\n\t\tpublic static final String INTERNAL_SERVER_ERROR = \"INTERNAL_SERVER_ERROR\";\n\t\tpublic static final String NOT_IMPLEMENTED_SERVER_ERROR = \"NOT_IMPLEMENTED_SERVER_ERROR\";\n\t\tpublic static final String NO_CONTENT = \"NO_CONTENT\";\n\t\tpublic static final String INVALID_PATH_SEQUENCE = \"INVALID_PATH_SEQUENCE\";\n\t\tpublic static final String FILE_NOT_FOUND = \"FILE_NOT_FOUND\";\n\t\tpublic static final String NOT_CREATE_DIRECTORY = \"NOT_CREATE_DIRECTORY\";\n\t\tpublic static final String FAILED = \"FAILED\";\n\t\tpublic static final String SERVICE_UNAVAILABLE = \"SERVICE_UNAVAILABLE\";\n\t\tpublic static final String NOT_FOUND = \"NOT_FOUND\";\n\t\tpublic static final String SUCCESS_JSON = \"{\\\"status\\\":\\\"success\\\"}\";\n\t\tpublic static final String FAILURE_JSON = \"{\\\"status\\\":\\\"failure\\\"}\";\n\t}\n\t\n\t\n\t@UtilityClass\n\tpublic static final class FIQL {\n\t\tpublic static final String CONSTRAINT = \"CONSTRAINT\";\n\t\tpublic static final String TYPE = \"type\";\n\t\tpublic static final String SELECTOR = \"selector\";\n\t\tpublic static final String COMPARISON = \"comparison\";\n\t\tpublic static final String WILDCARD = \"WILDCARD\";\n\t\tpublic static final String ARGUMENT = \"argument\";\n\t\tpublic static final String INCLUDE = \"INCLUDE\";\n\t\tpublic static final String NOT_INCLUDE = \"NOT_INCLUDE\";\n\t\tpublic static final String COMBINATION = \"COMBINATION\";\n\t\tpublic static final String AND = \"AND\";\n\t\tpublic static final String OPERATOR = \"operator\";\n\t\tpublic static final String LHS = \"lhs\";\n\t\tpublic static final String RHS = \"rhs\";\n\t\tpublic static final String OR = \"OR\";\n\t\tpublic static final String OPERATOR_IS_INCORRECT = \"Operator is incorrect\";\n\t\tpublic static final String FIQL_TYPE_IS_INCORRECT = \"Fiql type is incorrect\";\n\t}\n}"
},
{
"identifier": "Contact",
"path": "contact-api/src/main/java/com/inn/assignment/task2/model/Contact.java",
"snippet": "@Entity\n@Data\n@Valid\n@AllArgsConstructor\n@NoArgsConstructor\n@Table(name = \"CONTACT\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n@JsonIgnoreProperties({ \"hibernateLazyInitializer\", \"handler\" })\npublic class Contact {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n\t\n\t@NotEmpty(message = \"Email Address is required\")\n\t@Email(message = \"Invalid email format\")\n\tprivate String emailAddress;\n\n\t@NotEmpty(message = \"Phone Number is required\")\n\t@Size(min = 10, max = 10, message = \"Phone Number should be of 10 digits only\")\n\t@Pattern(regexp = \"^[0-9]+$\", message = \"Phone Number should contain only digits\")\n\tprivate String phoneNumber;\n\n}"
},
{
"identifier": "Person",
"path": "contact-api/src/main/java/com/inn/assignment/task2/model/Person.java",
"snippet": "@Entity\n@Data\n@Valid\n@AllArgsConstructor\n@NoArgsConstructor\n@Table(name = \"PERSON\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n@JsonIgnoreProperties({ \"hibernateLazyInitializer\", \"handler\" })\npublic class Person {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n \n\t@NotEmpty(message = \"Name is required\")\n\t@Pattern(regexp = \"^[a-zA-Z ]+$\", message = \"Name cannot have numbers or special characters\")\n\tprivate String name;\n\n\t@Valid\n\t@OneToOne(targetEntity = Contact.class, fetch = jakarta.persistence.FetchType.EAGER, cascade = CascadeType.ALL)\n\tprivate Contact contact;\n\n}"
}
] | import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.inn.assignment.task2.appconfiguration.AppRunner;
import com.inn.assignment.task2.controller.IPersonController;
import com.inn.assignment.task2.core.Constant;
import com.inn.assignment.task2.model.Contact;
import com.inn.assignment.task2.model.Person; | 1,841 | package com.inn.assignment;
@SpringBootTest(classes = AppRunner.class)
@ExtendWith(SpringExtension.class)
class PersonControllerTest {
@MockBean | package com.inn.assignment;
@SpringBootTest(classes = AppRunner.class)
@ExtendWith(SpringExtension.class)
class PersonControllerTest {
@MockBean | private IPersonController personController; | 1 | 2023-12-14 20:15:48+00:00 | 4k |
Crydsch/the-one | src/movement/DefaultMovementEngine.java | [
{
"identifier": "ConnectivityGrid",
"path": "src/interfaces/ConnectivityGrid.java",
"snippet": "public class ConnectivityGrid extends ConnectivityOptimizer {\n\n\t/**\n\t * Cell based optimization cell size multiplier -setting id ({@value}).\n\t * Used in {@link World#OPTIMIZATION_SETTINGS_NS} name space.\n\t * Single ConnectivityCell's size is the biggest radio range times this.\n\t * Larger values save memory and decrease startup time but may result in\n\t * slower simulation.\n\t * Default value is {@link #DEF_CON_CELL_SIZE_MULT}.\n\t * Smallest accepted value is 1.\n\t */\n\tpublic static final String CELL_SIZE_MULT_S = \"cellSizeMult\";\n\t/** default value for cell size multiplier ({@value}) */\n\tpublic static final int DEF_CON_CELL_SIZE_MULT = 5;\n\n\tprivate GridCell[][] cells;\n\tprivate List<NetworkInterface> interfaces;\n\tprivate HashMap<NetworkInterface, GridCell> ginterfaces;\n\tprivate int cellSize;\n\tprivate int rows;\n\tprivate int cols;\n\tprivate int worldSizeX;\n\tprivate int worldSizeY;\n\tprivate int cellSizeMultiplier;\n\n\t/**\n\t * Creates a new ConnectivityGrid\n\t * @param interfaces The interfaces to be managed by this grid\n\t */\n\tpublic ConnectivityGrid(List<NetworkInterface> interfaces) {\n\t\tSettings s = new Settings(MovementModel.MOVEMENT_MODEL_NS);\n\t\tint [] worldSize = s.getCsvInts(MovementModel.WORLD_SIZE,2);\n\t\tworldSizeX = worldSize[0];\n\t\tworldSizeY = worldSize[1];\n\n\t\ts.setNameSpace(World.OPTIMIZATION_SETTINGS_NS);\n\t\tif (s.contains(CELL_SIZE_MULT_S)) {\n\t\t\tcellSizeMultiplier = s.getInt(CELL_SIZE_MULT_S);\n\t\t}\n\t\telse {\n\t\t\tcellSizeMultiplier = DEF_CON_CELL_SIZE_MULT;\n\t\t}\n\t\tif (cellSizeMultiplier < 1) {\n\t\t\tthrow new SettingsError(\"Too small value (\" + cellSizeMultiplier +\n\t\t\t\t\t\") for \" + World.OPTIMIZATION_SETTINGS_NS +\n\t\t\t\t\t\".\" + CELL_SIZE_MULT_S);\n\t\t}\n\n\t\tdouble maxRange = Double.MIN_VALUE;\n\t\tfor (NetworkInterface ni : interfaces) {\n\t\t\tmaxRange = Math.max(maxRange, ni.getTransmitRange());\n\t\t}\n\n\t\tthis.interfaces = interfaces;\n\t\tthis.cellSize = (int)Math.ceil(maxRange * cellSizeMultiplier);\n\t\tthis.rows = worldSizeY/cellSize + 1;\n\t\tthis.cols = worldSizeX/cellSize + 1;\n\t\t// leave empty cells on both sides to make neighbor search easier\n\t\tthis.cells = new GridCell[rows+2][cols+2];\n\n\t\tfor (int i=0; i<rows+2; i++) {\n\t\t\tfor (int j=0; j<cols+2; j++) {\n\t\t\t\tthis.cells[i][j] = new GridCell();\n\t\t\t}\n\t\t}\n\t\tthis.ginterfaces = new HashMap<>();\n\t}\n\n\t/**\n\t * Detects interfaces which are in range/no longer in range of each other\n\t * Issues LinkUp/LinkDown events to the corresponding interfaces\n\t */\n\t@Override\n\tpublic void detectConnectivity() {\n\t\t// Update all interface positions\n\t\tfor (NetworkInterface ni : interfaces) {\n\t\t\tupdateLocation(ni);\n\t\t}\n\n\t\t// Detect link events\n\t\tfor (NetworkInterface ni : interfaces) {\n\t\t\t// Issue LinkDown Events\n\t\t\tList<Connection> connections = ni.getConnections();\n\t\t\tfor (int i = 0; i < connections.size(); ) {\n\t\t\t\tConnection con = connections.get(i);\n\t\t\t\tNetworkInterface other = con.getOtherInterface(ni);\n\n\t\t\t\t// all connections should be up at this stage\n\t\t\t\tassert con.isUp() : \"Connection \" + con + \" was down!\";\n\n\t\t\t\tif (!areWithinRange(ni, other)) {\n\t\t\t\t\tni.linkDown(other);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Issue LinkUp Events\n\t\t\tfor (NetworkInterface i : getInterfacesInRange(ni)) {\n\t\t\t\tif (ni != i && !ni.isConnected(i)) {\n\t\t\t\t\tni.linkUp(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks and updates (if necessary) interface's position in the grid\n\t * @param ni The interface to update\n\t */\n\tprivate void updateLocation(NetworkInterface ni) {\n\t\tGridCell oldCell = ginterfaces.get(ni);\n\t\tGridCell newCell = cellFromCoord(ni.getLocation());\n\n\t\tif (oldCell == null) { // This interface is new\n\t\t\tnewCell.addInterface(ni);\n\t\t\tginterfaces.put(ni, newCell);\n\t\t} else if (newCell != oldCell) {\n\t\t\toldCell.moveInterface(ni, newCell);\n\t\t\tginterfaces.put(ni,newCell);\n\t\t}\n\t}\n\n\t/**\n\t * Finds all neighboring cells and the cell itself based on the coordinates\n\t * @param c The coordinates\n\t * @return Array of neighboring cells\n\t */\n\tprivate GridCell[] getNeighborCellsByCoord(Coord c) {\n\t\t// +1 due empty cells on both sides of the matrix\n\t\tint row = (int)(c.getY()/cellSize) + 1;\n\t\tint col = (int)(c.getX()/cellSize) + 1;\n\t\treturn getNeighborCells(row,col);\n\t}\n\n\t/**\n\t * Returns an array of Cells that contains the neighbors of a certain\n\t * cell and the cell itself.\n\t * @param row Row index of the cell\n\t * @param col Column index of the cell\n\t * @return Array of neighboring Cells\n\t */\n\tprivate GridCell[] getNeighborCells(int row, int col) {\n\t\treturn new GridCell[] {\n\t\t\tcells[row-1][col-1],cells[row-1][col],cells[row-1][col+1],//1st row\n\t\t\tcells[row][col-1],cells[row][col],cells[row][col+1],//2nd row\n\t\t\tcells[row+1][col-1],cells[row+1][col],cells[row+1][col+1]//3rd row\n\t\t};\n\t}\n\n\t/**\n\t * Get the cell having the specific coordinates\n\t * @param c Coordinates\n\t * @return The cell\n\t */\n\tprivate GridCell cellFromCoord(Coord c) {\n\t\t// +1 due empty cells on both sides of the matrix\n\t\tint row = (int)(c.getY()/cellSize) + 1;\n\t\tint col = (int)(c.getX()/cellSize) + 1;\n\n\t\tassert row > 0 && row <= rows && col > 0 && col <= cols : \"Location \" +\n\t\tc + \" is out of world's bounds\";\n\n\t\treturn this.cells[row][col];\n\t}\n\n\t/**\n\t * Returns all interfaces that are in range (i.e., in neighboring grid cells)\n\t * and use the same technology and channel as the given interface\n\t * @param ni The interface whose neighboring interfaces are returned\n\t * @return Set of in range interfaces\n\t */\n\tprivate Collection<NetworkInterface> getInterfacesInRange(NetworkInterface ni) {\n\t\tupdateLocation(ni);\n\n\t\tList<NetworkInterface> niList = new ArrayList<>();\n\t\tGridCell loc = ginterfaces.get(ni);\n\n\t\tif (loc != null) {\n\t\t\tGridCell[] neighbors = getNeighborCellsByCoord(ni.getLocation());\n for (GridCell neighbor : neighbors) {\n\t\t\t\tfor (NetworkInterface nni : neighbor.getInterfaces()) {\n\t\t\t\t\tif (areWithinRange(ni, nni)) {\n\t\t\t\t\t\tniList.add(nni);\n\t\t\t\t\t}\n\t\t\t\t}\n }\n\t\t}\n\n\t\treturn niList;\n\t}\n\n\t/**\n\t * Returns a string representation of the ConnectivityCells object\n\t * @return a string representation of the ConnectivityCells object\n\t */\n\tpublic String toString() {\n\t\treturn getClass().getSimpleName() + \" of size \" +\n\t\t\tthis.cols + \"x\" + this.rows + \", cell size=\" + this.cellSize;\n\t}\n\n\t/**\n\t * A single cell in the cell grid. Contains the interfaces that are\n\t * currently in that part of the grid.\n\t */\n\tpublic class GridCell {\n\t\t// how large array is initially chosen\n\t\tprivate static final int EXPECTED_INTERFACE_COUNT = 5;\n\t\tprivate ArrayList<NetworkInterface> interfaces;\n\n\t\tprivate GridCell() {\n\t\t\tthis.interfaces = new ArrayList<NetworkInterface>(\n\t\t\t\t\tEXPECTED_INTERFACE_COUNT);\n\t\t}\n\n\t\t/**\n\t\t * Returns a list of of interfaces in this cell\n\t\t * @return a list of of interfaces in this cell\n\t\t */\n\t\tpublic ArrayList<NetworkInterface> getInterfaces() {\n\t\t\treturn this.interfaces;\n\t\t}\n\n\t\t/**\n\t\t * Adds an interface to this cell\n\t\t * @param ni The interface to add\n\t\t */\n\t\tpublic void addInterface(NetworkInterface ni) {\n\t\t\tthis.interfaces.add(ni);\n\t\t}\n\n\t\t/**\n\t\t * Removes an interface from this cell\n\t\t * @param ni The interface to remove\n\t\t */\n\t\tpublic void removeInterface(NetworkInterface ni) {\n\t\t\tthis.interfaces.remove(ni);\n\t\t}\n\n\t\t/**\n\t\t * Moves a interface in a Cell to another Cell\n\t\t * @param ni The interface to move\n\t\t * @param to The cell where the interface should be moved to\n\t\t */\n\t\tpublic void moveInterface(NetworkInterface ni, GridCell to) {\n\t\t\tto.addInterface(ni);\n\t\t\tboolean removeOk = this.interfaces.remove(ni);\n\t\t\tassert removeOk : \"interface \" + ni +\n\t\t\t\t\" not found from cell with \" + interfaces.toString();\n\t\t}\n\n\t\t/**\n\t\t * Returns a string representation of the cell\n\t\t * @return a string representation of the cell\n\t\t */\n\t\tpublic String toString() {\n\t\t\treturn getClass().getSimpleName() + \" with \" +\n\t\t\t\tthis.interfaces.size() + \" interfaces :\" + this.interfaces;\n\t\t}\n\t}\n\n}"
},
{
"identifier": "ConnectivityOptimizer",
"path": "src/interfaces/ConnectivityOptimizer.java",
"snippet": "abstract public class ConnectivityOptimizer {\n\t/**\n\t * Returns true if both interfaces are within radio range of each other.\n\t * @param a The first interface\n\t * @param b The second interface\n\t * @return True if the interfaces are within range, false if not\n\t */\n\tpublic boolean areWithinRange(NetworkInterface a, NetworkInterface b) {\n\t\tdouble range = Math.min(a.getTransmitRange(), b.getTransmitRange());\n\t\treturn a.getLocation().distanceSquared(b.getLocation()) <= range * range;\n\t}\n\n\t/**\n\t * Detects interfaces which are in range/no longer in range of each other\n\t * Issues LinkUp/LinkDown events to the corresponding interfaces\n\t */\n\tabstract public void detectConnectivity();\n}"
}
] | import core.*;
import interfaces.ConnectivityGrid;
import interfaces.ConnectivityOptimizer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.*; | 2,906 | package movement;
/**
* Provides a default implementation to move hosts in the world according to their MovementModel
*/
public class DefaultMovementEngine extends MovementEngine {
/** movement engines -setting id ({@value})*/
public static final String NAME = "DefaultMovementEngine";
private final Coord ORIGIN = new Coord(0.0, 0.0);
/**
* Creates a new MovementEngine based on a Settings object's settings.
* @param settings The Settings object where the settings are read from
*/
public DefaultMovementEngine(Settings settings) {
super(settings);
}
/**
* Initializes the movement engine
* @param hosts to be moved
*/
@Override
public void init(List<DTNHost> hosts, int worldSizeX, int worldSizeY) {
super.init(hosts, worldSizeX, worldSizeY);
// Initialize optimizer
Map<String, List<NetworkInterface>> interface_map = new HashMap<>();
for (DTNHost host : hosts) {
for (NetworkInterface ni : host.getInterfaces()) {
if (ni.getTransmitRange() > 0) {
interface_map.computeIfAbsent(ni.getInterfaceType(), k -> new ArrayList<>()).add(ni);
}
}
}
for (List<NetworkInterface> interfaces : interface_map.values()) { | package movement;
/**
* Provides a default implementation to move hosts in the world according to their MovementModel
*/
public class DefaultMovementEngine extends MovementEngine {
/** movement engines -setting id ({@value})*/
public static final String NAME = "DefaultMovementEngine";
private final Coord ORIGIN = new Coord(0.0, 0.0);
/**
* Creates a new MovementEngine based on a Settings object's settings.
* @param settings The Settings object where the settings are read from
*/
public DefaultMovementEngine(Settings settings) {
super(settings);
}
/**
* Initializes the movement engine
* @param hosts to be moved
*/
@Override
public void init(List<DTNHost> hosts, int worldSizeX, int worldSizeY) {
super.init(hosts, worldSizeX, worldSizeY);
// Initialize optimizer
Map<String, List<NetworkInterface>> interface_map = new HashMap<>();
for (DTNHost host : hosts) {
for (NetworkInterface ni : host.getInterfaces()) {
if (ni.getTransmitRange() > 0) {
interface_map.computeIfAbsent(ni.getInterfaceType(), k -> new ArrayList<>()).add(ni);
}
}
}
for (List<NetworkInterface> interfaces : interface_map.values()) { | optimizer.add(new ConnectivityGrid(interfaces)); | 0 | 2023-12-10 15:51:41+00:00 | 4k |
BarriBarri20/flink-tuto | docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/ClickEventCount.java | [
{
"identifier": "BackpressureMap",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/functions/BackpressureMap.java",
"snippet": "public class BackpressureMap implements MapFunction<ClickEvent, ClickEvent> {\n\n\tprivate boolean causeBackpressure() {\n\t\treturn ((LocalTime.now().getMinute() % 2) == 0);\n\t}\n\n\t@Override\n\tpublic ClickEvent map(ClickEvent event) throws Exception {\n\t\tif (causeBackpressure()) {\n\t\t\tThread.sleep(100);\n\t\t}\n\n\t\treturn event;\n\t}\n\n}"
},
{
"identifier": "ClickEventStatisticsCollector",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/functions/ClickEventStatisticsCollector.java",
"snippet": "public class ClickEventStatisticsCollector\n\t\textends ProcessWindowFunction<Long, ClickEventStatistics, String, TimeWindow> {\n\n\t@Override\n\tpublic void process(\n\t\t\tfinal String page,\n\t\t\tfinal Context context,\n\t\t\tfinal Iterable<Long> elements,\n\t\t\tfinal Collector<ClickEventStatistics> out) throws Exception {\n\n\t\tLong count = elements.iterator().next();\n\n\t\tout.collect(new ClickEventStatistics(new Date(context.window().getStart()), new Date(context.window().getEnd()), page, count));\n\t}\n}"
},
{
"identifier": "CountingAggregator",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/functions/CountingAggregator.java",
"snippet": "public class CountingAggregator implements AggregateFunction<ClickEvent, Long, Long> {\n\t@Override\n\tpublic Long createAccumulator() {\n\t\treturn 0L;\n\t}\n\n\t@Override\n\tpublic Long add(final ClickEvent value, final Long accumulator) {\n\t\treturn accumulator + 1;\n\t}\n\n\t@Override\n\tpublic Long getResult(final Long accumulator) {\n\t\treturn accumulator;\n\t}\n\n\t@Override\n\tpublic Long merge(final Long a, final Long b) {\n\t\treturn a + b;\n\t}\n}"
},
{
"identifier": "ClickEvent",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/records/ClickEvent.java",
"snippet": "public class ClickEvent {\n\n\t//using java.util.Date for better readability\n\t@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"dd-MM-yyyy hh:mm:ss:SSS\")\n\tprivate Date timestamp;\n\tprivate String page;\n\n\tpublic ClickEvent() {\n\t}\n\n\tpublic ClickEvent(final Date timestamp, final String page) {\n\t\tthis.timestamp = timestamp;\n\t\tthis.page = page;\n\t}\n\n\tpublic Date getTimestamp() {\n\t\treturn timestamp;\n\t}\n\n\tpublic void setTimestamp(final Date timestamp) {\n\t\tthis.timestamp = timestamp;\n\t}\n\n\tpublic String getPage() {\n\t\treturn page;\n\t}\n\n\tpublic void setPage(final String page) {\n\t\tthis.page = page;\n\t}\n\n\t@Override\n\tpublic boolean equals(final Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal ClickEvent that = (ClickEvent) o;\n\t\treturn Objects.equals(timestamp, that.timestamp) && Objects.equals(page, that.page);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(timestamp, page);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tfinal StringBuilder sb = new StringBuilder(\"ClickEvent{\");\n\t\tsb.append(\"timestamp=\").append(timestamp);\n\t\tsb.append(\", page='\").append(page).append('\\'');\n\t\tsb.append('}');\n\t\treturn sb.toString();\n\t}\n}"
},
{
"identifier": "ClickEventDeserializationSchema",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/records/ClickEventDeserializationSchema.java",
"snippet": "public class ClickEventDeserializationSchema implements DeserializationSchema<ClickEvent> {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\t@Override\n\tpublic ClickEvent deserialize(byte[] message) throws IOException {\n\t\treturn objectMapper.readValue(message, ClickEvent.class);\n\t}\n\n\t@Override\n\tpublic boolean isEndOfStream(ClickEvent nextElement) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic TypeInformation<ClickEvent> getProducedType() {\n\t\treturn TypeInformation.of(ClickEvent.class);\n\t}\n}"
},
{
"identifier": "ClickEventStatistics",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/records/ClickEventStatistics.java",
"snippet": "public class ClickEventStatistics {\n\n\t//using java.util.Date for better readability\n\t@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"dd-MM-yyyy hh:mm:ss:SSS\")\n\tprivate Date windowStart;\n\t//using java.util.Date for better readability\n\t@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"dd-MM-yyyy hh:mm:ss:SSS\")\n\tprivate Date windowEnd;\n\tprivate String page;\n\tprivate long count;\n\n\tpublic ClickEventStatistics() {\n\t}\n\n\tpublic ClickEventStatistics(\n\t\t\tfinal Date windowStart,\n\t\t\tfinal Date windowEnd,\n\t\t\tfinal String page,\n\t\t\tfinal long count) {\n\t\tthis.windowStart = windowStart;\n\t\tthis.windowEnd = windowEnd;\n\t\tthis.page = page;\n\t\tthis.count = count;\n\t}\n\n\tpublic Date getWindowStart() {\n\t\treturn windowStart;\n\t}\n\n\tpublic void setWindowStart(final Date windowStart) {\n\t\tthis.windowStart = windowStart;\n\t}\n\n\tpublic Date getWindowEnd() {\n\t\treturn windowEnd;\n\t}\n\n\tpublic void setWindowEnd(final Date windowEnd) {\n\t\tthis.windowEnd = windowEnd;\n\t}\n\n\tpublic String getPage() {\n\t\treturn page;\n\t}\n\n\tpublic void setPage(final String page) {\n\t\tthis.page = page;\n\t}\n\n\tpublic long getCount() {\n\t\treturn count;\n\t}\n\n\tpublic void setCount(final long count) {\n\t\tthis.count = count;\n\t}\n\n\t@Override\n\tpublic boolean equals(final Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal ClickEventStatistics that = (ClickEventStatistics) o;\n\t\treturn count == that.count &&\n\t\t\t\tObjects.equals(windowStart, that.windowStart) &&\n\t\t\t\tObjects.equals(windowEnd, that.windowEnd) &&\n\t\t\t\tObjects.equals(page, that.page);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(windowStart, windowEnd, page, count);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tfinal StringBuilder sb = new StringBuilder(\"ClickEventStatistics{\");\n\t\tsb.append(\"windowStart=\").append(windowStart);\n\t\tsb.append(\", windowEnd=\").append(windowEnd);\n\t\tsb.append(\", page='\").append(page).append('\\'');\n\t\tsb.append(\", count=\").append(count);\n\t\tsb.append('}');\n\t\treturn sb.toString();\n\t}\n}"
},
{
"identifier": "ClickEventStatisticsSerializationSchema",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/records/ClickEventStatisticsSerializationSchema.java",
"snippet": "public class ClickEventStatisticsSerializationSchema implements SerializationSchema<ClickEventStatistics> {\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\t@Override\n\tpublic byte[] serialize(ClickEventStatistics event) {\n\t\ttry {\n\t\t\t//if topic is null, default topic will be used\n\t\t\treturn objectMapper.writeValueAsBytes(event);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new IllegalArgumentException(\"Could not serialize record: \" + event, e);\n\t\t}\n\t}\n}"
}
] | import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.playgrounds.ops.clickcount.functions.BackpressureMap;
import org.apache.flink.playgrounds.ops.clickcount.functions.ClickEventStatisticsCollector;
import org.apache.flink.playgrounds.ops.clickcount.functions.CountingAggregator;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEvent;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEventDeserializationSchema;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEventStatistics;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEventStatisticsSerializationSchema;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit; | 3,093 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.playgrounds.ops.clickcount;
/**
* A simple streaming job reading {@link ClickEvent}s from Kafka, counting events per 15 seconds and
* writing the resulting {@link ClickEventStatistics} back to Kafka.
*
* <p> It can be run with or without checkpointing and with event time or processing time semantics.
* </p>
*
* <p>The Job can be configured via the command line:</p>
* * "--checkpointing": enables checkpointing
* * "--event-time": use an event time window assigner
* * "--backpressure": insert an operator that causes periodic backpressure
* * "--input-topic": the name of the Kafka Topic to consume {@link ClickEvent}s from
* * "--output-topic": the name of the Kafka Topic to produce {@link ClickEventStatistics} to
* * "--bootstrap.servers": comma-separated list of Kafka brokers
*
*/
public class ClickEventCount {
public static final String CHECKPOINTING_OPTION = "checkpointing";
public static final String EVENT_TIME_OPTION = "event-time";
public static final String BACKPRESSURE_OPTION = "backpressure";
public static final String OPERATOR_CHAINING_OPTION = "chaining";
public static final Time WINDOW_SIZE = Time.of(15, TimeUnit.SECONDS);
public static void main(String[] args) throws Exception {
final ParameterTool params = ParameterTool.fromArgs(args);
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
configureEnvironment(params, env);
boolean inflictBackpressure = params.has(BACKPRESSURE_OPTION);
String inputTopic = params.get("input-topic", "input");
String outputTopic = params.get("output-topic", "output");
String brokers = params.get("bootstrap.servers", "localhost:9092");
Properties kafkaProps = new Properties();
kafkaProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
kafkaProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "click-event-count");
KafkaSource<ClickEvent> source = KafkaSource.<ClickEvent>builder()
.setTopics(inputTopic)
.setValueOnlyDeserializer(new ClickEventDeserializationSchema())
.setProperties(kafkaProps)
.build();
WatermarkStrategy<ClickEvent> watermarkStrategy = WatermarkStrategy
.<ClickEvent>forBoundedOutOfOrderness(Duration.ofMillis(200))
.withIdleness(Duration.ofSeconds(5))
.withTimestampAssigner((clickEvent, l) -> clickEvent.getTimestamp().getTime());
DataStream<ClickEvent> clicks = env.fromSource(source, watermarkStrategy, "ClickEvent Source");
if (inflictBackpressure) {
// Force a network shuffle so that the backpressure will affect the buffer pools
clicks = clicks
.keyBy(ClickEvent::getPage)
.map(new BackpressureMap())
.name("Backpressure");
}
WindowAssigner<Object, TimeWindow> assigner = params.has(EVENT_TIME_OPTION) ?
TumblingEventTimeWindows.of(WINDOW_SIZE) :
TumblingProcessingTimeWindows.of(WINDOW_SIZE);
DataStream<ClickEventStatistics> statistics = clicks
.keyBy(ClickEvent::getPage)
.window(assigner) | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.playgrounds.ops.clickcount;
/**
* A simple streaming job reading {@link ClickEvent}s from Kafka, counting events per 15 seconds and
* writing the resulting {@link ClickEventStatistics} back to Kafka.
*
* <p> It can be run with or without checkpointing and with event time or processing time semantics.
* </p>
*
* <p>The Job can be configured via the command line:</p>
* * "--checkpointing": enables checkpointing
* * "--event-time": use an event time window assigner
* * "--backpressure": insert an operator that causes periodic backpressure
* * "--input-topic": the name of the Kafka Topic to consume {@link ClickEvent}s from
* * "--output-topic": the name of the Kafka Topic to produce {@link ClickEventStatistics} to
* * "--bootstrap.servers": comma-separated list of Kafka brokers
*
*/
public class ClickEventCount {
public static final String CHECKPOINTING_OPTION = "checkpointing";
public static final String EVENT_TIME_OPTION = "event-time";
public static final String BACKPRESSURE_OPTION = "backpressure";
public static final String OPERATOR_CHAINING_OPTION = "chaining";
public static final Time WINDOW_SIZE = Time.of(15, TimeUnit.SECONDS);
public static void main(String[] args) throws Exception {
final ParameterTool params = ParameterTool.fromArgs(args);
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
configureEnvironment(params, env);
boolean inflictBackpressure = params.has(BACKPRESSURE_OPTION);
String inputTopic = params.get("input-topic", "input");
String outputTopic = params.get("output-topic", "output");
String brokers = params.get("bootstrap.servers", "localhost:9092");
Properties kafkaProps = new Properties();
kafkaProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
kafkaProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "click-event-count");
KafkaSource<ClickEvent> source = KafkaSource.<ClickEvent>builder()
.setTopics(inputTopic)
.setValueOnlyDeserializer(new ClickEventDeserializationSchema())
.setProperties(kafkaProps)
.build();
WatermarkStrategy<ClickEvent> watermarkStrategy = WatermarkStrategy
.<ClickEvent>forBoundedOutOfOrderness(Duration.ofMillis(200))
.withIdleness(Duration.ofSeconds(5))
.withTimestampAssigner((clickEvent, l) -> clickEvent.getTimestamp().getTime());
DataStream<ClickEvent> clicks = env.fromSource(source, watermarkStrategy, "ClickEvent Source");
if (inflictBackpressure) {
// Force a network shuffle so that the backpressure will affect the buffer pools
clicks = clicks
.keyBy(ClickEvent::getPage)
.map(new BackpressureMap())
.name("Backpressure");
}
WindowAssigner<Object, TimeWindow> assigner = params.has(EVENT_TIME_OPTION) ?
TumblingEventTimeWindows.of(WINDOW_SIZE) :
TumblingProcessingTimeWindows.of(WINDOW_SIZE);
DataStream<ClickEventStatistics> statistics = clicks
.keyBy(ClickEvent::getPage)
.window(assigner) | .aggregate(new CountingAggregator(), | 2 | 2023-12-10 14:25:58+00:00 | 4k |
bggRGjQaUbCoE/c001apk | app/src/main/java/com/example/c001apk/view/vertical/VerticalTabLayout.java | [
{
"identifier": "TabAdapter",
"path": "app/src/main/java/com/example/c001apk/view/vertical/adapter/TabAdapter.java",
"snippet": "public interface TabAdapter {\n int getCount();\n\n TabView.TabBadge getBadge(int position);\n\n TabView.TabIcon getIcon(int position);\n\n TabView.TabTitle getTitle(int position);\n\n int getBackground(int position);\n}"
},
{
"identifier": "QTabView",
"path": "app/src/main/java/com/example/c001apk/view/vertical/widget/QTabView.java",
"snippet": "public class QTabView extends TabView {\n private final Context mContext;\n private TextView mTitle;\n private Badge mBadgeView;\n private TabIcon mTabIcon;\n private TabTitle mTabTitle;\n private TabBadge mTabBadge;\n private boolean mChecked;\n private final Drawable mDefaultBackground;\n\n\n public QTabView(Context context) {\n super(context);\n mContext = context;\n mTabIcon = new TabIcon.Builder().build();\n mTabTitle = new TabTitle.Builder().build();\n mTabBadge = new TabBadge.Builder().build();\n initView();\n int[] attrs;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n attrs = new int[]{android.R.attr.selectableItemBackgroundBorderless};\n } else {\n attrs = new int[]{android.R.attr.selectableItemBackground};\n }\n TypedArray a = mContext.getTheme().obtainStyledAttributes(attrs);\n mDefaultBackground = a.getDrawable(0);\n a.recycle();\n setDefaultBackground();\n }\n\n private void initView() {\n setMinimumHeight(DisplayUtil.dp2px(mContext, 25));\n if (mTitle == null) {\n mTitle = new TextView(mContext);\n LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);\n params.gravity = Gravity.CENTER;\n mTitle.setLayoutParams(params);\n this.addView(mTitle);\n }\n initTitleView();\n initIconView();\n initBadge();\n }\n\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n public void setPaddingRelative(@Px int start, @Px int top, @Px int end, @Px int bottom) {\n mTitle.setPaddingRelative(start, top, end, bottom);\n }\n\n @Override\n public void setPadding(@Px int left, @Px int top, @Px int right, @Px int bottom) {\n mTitle.setPadding(left, top, right, bottom);\n }\n\n private void initBadge() {\n mBadgeView = TabBadgeView.bindTab(this);\n if (mTabBadge.getBackgroundColor() != 0xFFE84E40) {\n mBadgeView.setBadgeBackgroundColor(mTabBadge.getBackgroundColor());\n }\n if (mTabBadge.getBadgeTextColor() != 0xFFFFFFFF) {\n mBadgeView.setBadgeTextColor(mTabBadge.getBadgeTextColor());\n }\n if (mTabBadge.getStrokeColor() != Color.TRANSPARENT || mTabBadge.getStrokeWidth() != 0) {\n mBadgeView.stroke(mTabBadge.getStrokeColor(), mTabBadge.getStrokeWidth(), true);\n }\n if (mTabBadge.getDrawableBackground() != null || mTabBadge.isDrawableBackgroundClip()) {\n mBadgeView.setBadgeBackground(mTabBadge.getDrawableBackground(), mTabBadge.isDrawableBackgroundClip());\n }\n if (mTabBadge.getBadgeTextSize() != 11) {\n mBadgeView.setBadgeTextSize(mTabBadge.getBadgeTextSize(), true);\n }\n if (mTabBadge.getBadgePadding() != 5) {\n mBadgeView.setBadgePadding(mTabBadge.getBadgePadding(), true);\n }\n if (mTabBadge.getBadgeNumber() != 0) {\n mBadgeView.setBadgeNumber(mTabBadge.getBadgeNumber());\n }\n if (mTabBadge.getBadgeText() != null) {\n mBadgeView.setBadgeText(mTabBadge.getBadgeText());\n }\n if (mTabBadge.getBadgeGravity() != (Gravity.END | Gravity.TOP)) {\n mBadgeView.setBadgeGravity(mTabBadge.getBadgeGravity());\n }\n if (mTabBadge.getGravityOffsetX() != 5 || mTabBadge.getGravityOffsetY() != 5) {\n mBadgeView.setGravityOffset(mTabBadge.getGravityOffsetX(), mTabBadge.getGravityOffsetY(), true);\n }\n if (mTabBadge.isExactMode()) {\n mBadgeView.setExactMode(mTabBadge.isExactMode());\n }\n if (!mTabBadge.isShowShadow()) {\n mBadgeView.setShowShadow(mTabBadge.isShowShadow());\n }\n if (mTabBadge.getOnDragStateChangedListener() != null) {\n mBadgeView.setOnDragStateChangedListener(mTabBadge.getOnDragStateChangedListener());\n }\n }\n\n private void initTitleView() {\n mTitle.setTextColor(isChecked() ? mTabTitle.getColorSelected() : mTabTitle.getColorNormal());\n mTitle.setTextSize(mTabTitle.getTitleTextSize());\n mTitle.setText(mTabTitle.getContent());\n mTitle.setGravity(Gravity.CENTER);\n mTitle.setEllipsize(TextUtils.TruncateAt.END);\n refreshDrawablePadding();\n }\n\n private void initIconView() {\n int iconResid = mChecked ? mTabIcon.getSelectedIcon() : mTabIcon.getNormalIcon();\n Drawable drawable = null;\n if (iconResid != 0) {\n drawable = mContext.getResources().getDrawable(iconResid);\n int r = mTabIcon.getIconWidth() != -1 ? mTabIcon.getIconWidth() : drawable.getIntrinsicWidth();\n int b = mTabIcon.getIconHeight() != -1 ? mTabIcon.getIconHeight() : drawable.getIntrinsicHeight();\n drawable.setBounds(0, 0, r, b);\n }\n switch (mTabIcon.getIconGravity()) {\n case Gravity.START:\n mTitle.setCompoundDrawables(drawable, null, null, null);\n break;\n case Gravity.TOP:\n mTitle.setCompoundDrawables(null, drawable, null, null);\n break;\n case Gravity.END:\n mTitle.setCompoundDrawables(null, null, drawable, null);\n break;\n case Gravity.BOTTOM:\n mTitle.setCompoundDrawables(null, null, null, drawable);\n break;\n }\n refreshDrawablePadding();\n }\n\n private void refreshDrawablePadding() {\n int iconResid = mChecked ? mTabIcon.getSelectedIcon() : mTabIcon.getNormalIcon();\n if (iconResid != 0) {\n if (!TextUtils.isEmpty(mTabTitle.getContent()) && mTitle.getCompoundDrawablePadding() != mTabIcon.getMargin()) {\n mTitle.setCompoundDrawablePadding(mTabIcon.getMargin());\n } else if (TextUtils.isEmpty(mTabTitle.getContent())) {\n mTitle.setCompoundDrawablePadding(0);\n }\n } else {\n mTitle.setCompoundDrawablePadding(0);\n }\n }\n\n @Override\n public QTabView setBadge(TabBadge badge) {\n if (badge != null) {\n mTabBadge = badge;\n }\n initBadge();\n return this;\n }\n\n @Override\n public QTabView setIcon(TabIcon icon) {\n if (icon != null) {\n mTabIcon = icon;\n }\n initIconView();\n return this;\n }\n\n @Override\n public QTabView setTitle(TabTitle title) {\n if (title != null) {\n mTabTitle = title;\n }\n initTitleView();\n return this;\n }\n\n /**\n * @param resId The Drawable res to use as the background, if less than 0 will to remove the\n * background\n */\n @Override\n public QTabView setBackground(int resId) {\n if (resId == 0) {\n setDefaultBackground();\n } else if (resId <= 0) {\n setBackground(null);\n } else {\n super.setBackgroundResource(resId);\n }\n return this;\n }\n\n @Override\n public TabBadge getBadge() {\n return mTabBadge;\n }\n\n @Override\n public TabIcon getIcon() {\n return mTabIcon;\n }\n\n @Override\n public TabTitle getTitle() {\n return mTabTitle;\n }\n\n @Override\n @Deprecated\n public ImageView getIconView() {\n return null;\n }\n\n @Override\n public TextView getTitleView() {\n return mTitle;\n }\n\n @Override\n public Badge getBadgeView() {\n return mBadgeView;\n }\n\n @Override\n public void setBackground(Drawable background) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {\n super.setBackground(background);\n } else {\n super.setBackgroundDrawable(background);\n }\n }\n\n @Override\n public void setBackgroundResource(int resid) {\n setBackground(resid);\n }\n\n private void setDefaultBackground() {\n if (getBackground() != mDefaultBackground) {\n setBackground(mDefaultBackground);\n }\n }\n\n @Override\n public void setChecked(boolean checked) {\n mChecked = checked;\n setSelected(checked);\n refreshDrawableState();\n mTitle.setTextColor(checked ? mTabTitle.getColorSelected() : mTabTitle.getColorNormal());\n initIconView();\n }\n\n @Override\n public boolean isChecked() {\n return mChecked;\n }\n\n @Override\n public void toggle() {\n setChecked(!mChecked);\n }\n}"
},
{
"identifier": "TabView",
"path": "app/src/main/java/com/example/c001apk/view/vertical/widget/TabView.java",
"snippet": "public abstract class TabView extends FrameLayout implements Checkable, ITabView {\n\n public TabView(Context context) {\n super(context);\n }\n\n @Override\n public TabView getTabView() {\n return this;\n }\n\n @Deprecated\n public abstract ImageView getIconView();\n\n public abstract TextView getTitleView();\n\n public abstract Badge getBadgeView();\n}"
}
] | import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_IDLE;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.c001apk.R;
import com.example.c001apk.view.vertical.adapter.TabAdapter;
import com.example.c001apk.view.vertical.util.DisplayUtil;
import com.example.c001apk.view.vertical.util.TabFragmentManager;
import com.example.c001apk.view.vertical.widget.QTabView;
import com.example.c001apk.view.vertical.widget.TabView;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List; | 2,698 | package com.example.c001apk.view.vertical;
/**
* @author chqiu
* Email:[email protected]
*/
public class VerticalTabLayout extends ScrollView {
private final Context mContext;
private TabStrip mTabStrip;
private int mColorIndicator; | package com.example.c001apk.view.vertical;
/**
* @author chqiu
* Email:[email protected]
*/
public class VerticalTabLayout extends ScrollView {
private final Context mContext;
private TabStrip mTabStrip;
private int mColorIndicator; | private TabView mSelectedTab; | 2 | 2023-12-18 15:02:49+00:00 | 4k |
rcaneppele/simple-openai-client | src/test/java/br/com/rcaneppele/openai/endpoints/chatcompletion/request/stream/ChatCompletionStreamRequestSenderTest.java | [
{
"identifier": "OpenAIModel",
"path": "src/main/java/br/com/rcaneppele/openai/common/OpenAIModel.java",
"snippet": "public enum OpenAIModel {\n\n GPT_3_5_TURBO_1106(\"gpt-3.5-turbo-1106\"),\n GPT_3_5_TURBO(\"gpt-3.5-turbo\"),\n GPT_3_5_TURBO_16k(\"gpt-3.5-turbo-16k\"),\n GPT_3_5_TURBO_INSTRUCT(\"gpt-3.5-turbo-instruct\"),\n GPT_4_1106_PREVIEW(\"gpt-4-1106-preview\"),\n GPT_4(\"gpt-4\"),\n GPT_4_32K(\"gpt-4-32k\"),\n GPT_4_0613(\"gpt-4-0613\"),\n GPT_4_32k_0613(\"gpt-4-32k-0613\");\n\n private final String name;\n\n OpenAIModel(String name) {\n this.name = name;\n }\n\n @JsonValue\n public String getName() {\n return name;\n }\n\n @JsonCreator\n public static OpenAIModel fromString(String value) {\n return Arrays.stream(OpenAIModel.values())\n .filter(model -> model.getName().equalsIgnoreCase(value))\n .findFirst()\n .orElseThrow(() -> new IllegalArgumentException(\"Unknown OpenAIModel enum constant: \" + value));\n }\n\n}"
},
{
"identifier": "JsonConverter",
"path": "src/main/java/br/com/rcaneppele/openai/common/json/JsonConverter.java",
"snippet": "public class JsonConverter<T> {\n\n private final ObjectMapper mapper;\n private final Class<T> targetType;\n\n public JsonConverter(Class<T> targetType) {\n this.mapper = new ObjectMapperCreator().create();\n this.targetType = targetType;\n }\n\n public String convertRequestToJson(T request) {\n try {\n return this.mapper.writeValueAsString(request);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Error during serialization to json\", e);\n }\n }\n\n public T convertJsonToResponse(String json) {\n try {\n return this.mapper.readValue(json, targetType);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Error during deserialization of json to response\", e);\n }\n }\n\n}"
},
{
"identifier": "HttpMethod",
"path": "src/main/java/br/com/rcaneppele/openai/common/request/HttpMethod.java",
"snippet": "public enum HttpMethod {\n\n GET,\n POST,\n DELETE;\n\n}"
},
{
"identifier": "BaseRequestSenderTest",
"path": "src/test/java/br/com/rcaneppele/openai/endpoints/BaseRequestSenderTest.java",
"snippet": "public abstract class BaseRequestSenderTest {\n\n protected static final Duration TIMEOUT = Duration.ofSeconds(2);\n protected static final String API_KEY = \"fake-api-key\";\n private static final MediaType MEDIA_TYPE = MediaType.parse(\"application/json; charset=utf-8\");\n private static final String AUTH_HEADER_VALUE = \"Bearer \" +API_KEY;\n private static final String ASSISTANT_HEADER_VALUE = \"assistants=v1\";\n private static final String TEST_BASE_URL = \"/test/\";\n\n protected MockWebServer server;\n protected String url;\n\n @BeforeEach\n void baseSetUp() throws IOException {\n this.server = new MockWebServer();\n this.server.start();\n this.url = this.server.url(TEST_BASE_URL).url().toString();\n this.server.enqueue(new MockResponse()\n .setResponseCode(200)\n .setBody(mockJsonResponse()));\n }\n\n @AfterEach\n void baseTearDown() throws IOException {\n server.shutdown();\n }\n\n public void executeRequestAssertions(String expectedRequestBody, int expectedRequestCount, HttpMethod expectedHttpMethod, boolean assertAssistantHeader) {\n try {\n var request = server.takeRequest();\n assertEquals(expectedRequestCount, server.getRequestCount());\n assertEquals(expectedHttpMethod.toString(), request.getMethod());\n assertEquals(TEST_BASE_URL + expectedURI(), request.getPath());\n assertEquals(MEDIA_TYPE.toString(), request.getHeader(\"Content-Type\"));\n assertEquals(expectedRequestBody, request.getBody().readUtf8());\n assertEquals(AUTH_HEADER_VALUE, request.getHeader(\"Authorization\"));\n if (assertAssistantHeader) {\n assertEquals(ASSISTANT_HEADER_VALUE, request.getHeader(\"OpenAI-Beta\"));\n }\n } catch (Exception e) {\n throw new RuntimeException(\"Exception on executeRequestAssertions method call!\", e);\n }\n }\n\n public void executeResponseAssertions(Object expectedResponse, Object actualResponse) {\n assertNotNull(expectedResponse);\n assertNotNull(actualResponse);\n assertEquals(expectedResponse, actualResponse);\n }\n\n protected abstract String expectedURI();\n protected abstract String mockJsonResponse();\n protected abstract void shouldSendRequest();\n\n}"
},
{
"identifier": "ChatCompletionRequestBuilder",
"path": "src/main/java/br/com/rcaneppele/openai/endpoints/chatcompletion/request/ChatCompletionRequestBuilder.java",
"snippet": "public class ChatCompletionRequestBuilder {\n\n private OpenAIModel model;\n private Integer n = 1;\n private Integer maxTokens = 256;\n private Double frequencyPenalty = 0.0;\n private Double presencePenalty = 0.0;\n private Double temperature = 1.0;\n private Double topP = 1.0;\n private String[] stop;\n private List<String> userMessages = new ArrayList<>();\n private List<String> systemMessages = new ArrayList<>();\n private Boolean logprobs = false;\n private Integer topLogprobs;\n private String user;\n private Integer seed;\n private Map<Integer, Integer> logitBias;\n\n public ChatCompletionRequestBuilder model(OpenAIModel model) {\n if (model == null) {\n throw new IllegalArgumentException(\"Model cannot be null!\");\n }\n this.model = model;\n return this;\n }\n\n public ChatCompletionRequestBuilder n(Integer n) {\n if (n == null || n < 1) {\n throw new IllegalArgumentException(\"Parameter n must be greater than or equal to 1!\");\n }\n this.n = n;\n return this;\n }\n\n public ChatCompletionRequestBuilder maxTokens(Integer maxTokens) {\n if (maxTokens == null || maxTokens < 1) {\n throw new IllegalArgumentException(\"Parameter maxTokens must be greater than or equal to 1!\");\n }\n this.maxTokens = maxTokens;\n return this;\n }\n\n public ChatCompletionRequestBuilder frequencyPenalty(Double frequencyPenalty) {\n if (frequencyPenalty == null || frequencyPenalty < -2.0 || frequencyPenalty > 2.0) {\n throw new IllegalArgumentException(\"Parameter frequencyPenalty must be between -2.0 and 2.0!\");\n }\n this.frequencyPenalty = frequencyPenalty;\n return this;\n }\n\n public ChatCompletionRequestBuilder presencePenalty(Double presencePenalty) {\n if (presencePenalty == null || presencePenalty < -2.0 || presencePenalty > 2.0) {\n throw new IllegalArgumentException(\"Parameter presencePenalty must be between -2.0 and 2.0!\");\n }\n this.presencePenalty = presencePenalty;\n return this;\n }\n\n public ChatCompletionRequestBuilder temperature(Double temperature) {\n if (temperature == null || temperature < 0 || temperature > 2.0) {\n throw new IllegalArgumentException(\"Parameter temperature must be between 0 and 2.0!\");\n }\n this.temperature = temperature;\n return this;\n }\n\n public ChatCompletionRequestBuilder topP(Double topP) {\n if (topP == null || topP < 0 || topP > 1.0) {\n throw new IllegalArgumentException(\"Parameter topP must be between 0 and 1.0!\");\n }\n this.topP = topP;\n return this;\n }\n\n public ChatCompletionRequestBuilder stop(String... stop) {\n if (stop == null || stop.length > 4) {\n throw new IllegalArgumentException(\"Parameter stop must be up to 4 sequences!\");\n }\n this.stop = stop;\n return this;\n }\n\n public ChatCompletionRequestBuilder userMessage(String userMessage) {\n this.userMessages.add(userMessage);\n return this;\n }\n\n public ChatCompletionRequestBuilder systemMessage(String systemMessage) {\n this.systemMessages.add(systemMessage);\n return this;\n }\n\n public ChatCompletionRequestBuilder logprobs() {\n this.logprobs = true;\n return this;\n }\n\n public ChatCompletionRequestBuilder topLogprobs(Integer topLogprobs) {\n if (topLogprobs == null || topLogprobs < 0 || topLogprobs > 5) {\n throw new IllegalArgumentException(\"Parameter topLogprobs must be between 0 and 5!\");\n }\n this.topLogprobs = topLogprobs;\n // To use the 'topLogprobs' parameter, 'logprobs' must be set to 'true'\n this.logprobs = true;\n return this;\n }\n\n public ChatCompletionRequestBuilder user(String user) {\n this.user = user;\n return this;\n }\n\n public ChatCompletionRequestBuilder seed(Integer seed) {\n this.seed = seed;\n return this;\n }\n\n public ChatCompletionRequestBuilder logitBias(Map<Integer, Integer> logitBias) {\n var valuesValid = logitBias.values().stream().allMatch(value -> value >= -100 && value <= 100);\n if (!valuesValid) {\n throw new IllegalArgumentException(\"Values of logitBias parameter must be between -100 and 100!\");\n }\n this.logitBias = logitBias;\n return this;\n }\n\n public ChatCompletionRequest build() {\n validateRequiredFields();\n\n return new ChatCompletionRequest(\n this.model,\n this.n,\n this.maxTokens,\n this.frequencyPenalty,\n this.presencePenalty,\n this.temperature,\n this.topP,\n this.stop,\n createOpenAIMessages(),\n this.logprobs,\n this.topLogprobs,\n this.user,\n this.seed,\n this.logitBias,\n false\n );\n }\n\n private void validateRequiredFields() {\n validateModel();\n validateMessages();\n }\n\n private void validateModel() {\n if (this.model == null) {\n throw new IllegalArgumentException(\"Model is required!\");\n }\n }\n\n private void validateMessages() {\n var isUserMessageProvided = isUserMessageProvided();\n var isSystemMessageProvided = isSystemMessageProvided();\n\n if (!isUserMessageProvided && !isSystemMessageProvided) {\n throw new IllegalArgumentException(\"At least 1 message is required!\");\n }\n }\n\n private boolean isUserMessageProvided() {\n return !this.userMessages.isEmpty();\n }\n\n private boolean isSystemMessageProvided() {\n return !this.systemMessages.isEmpty();\n }\n\n private List<ChatMessage> createOpenAIMessages() {\n var messages = new ArrayList<ChatMessage>();\n\n if (isUserMessageProvided()) {\n this.userMessages.forEach(message -> {\n messages.add(new ChatMessage(\"user\", message));\n });\n }\n\n if (isSystemMessageProvided()) {\n this.systemMessages.forEach(message -> {\n messages.add(new ChatMessage(\"system\", message));\n });\n }\n\n return messages;\n }\n\n}"
}
] | import br.com.rcaneppele.openai.common.OpenAIModel;
import br.com.rcaneppele.openai.common.json.JsonConverter;
import br.com.rcaneppele.openai.common.request.HttpMethod;
import br.com.rcaneppele.openai.endpoints.BaseRequestSenderTest;
import br.com.rcaneppele.openai.endpoints.chatcompletion.request.ChatCompletionRequest;
import br.com.rcaneppele.openai.endpoints.chatcompletion.request.ChatCompletionRequestBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull; | 3,108 | package br.com.rcaneppele.openai.endpoints.chatcompletion.request.stream;
class ChatCompletionStreamRequestSenderTest extends BaseRequestSenderTest {
private ChatCompletionStreamRequestSender sender;
private JsonConverter<ChatCompletionRequest> jsonConverter;
private ChatCompletionRequestBuilder builder;
@Override
protected String expectedURI() {
return "chat/completions";
}
@Override
protected String mockJsonResponse() {
return "data: {}";
}
@BeforeEach
void setUp() {
this.sender = new ChatCompletionStreamRequestSender(url, TIMEOUT, API_KEY);
this.jsonConverter = new JsonConverter<>(ChatCompletionRequest.class);
this.builder = new ChatCompletionRequestBuilder();
}
@Test
public void shouldSendRequest() {
var request = builder
.model(OpenAIModel.GPT_4_1106_PREVIEW)
.userMessage("the user message")
.build();
var testObserver = sender.sendStreamRequest(request).test();
testObserver.assertNoErrors();
testObserver.assertNotComplete();
assertNotNull(testObserver.values());
var expectedRequestBody = jsonConverter.convertRequestToJson(request); | package br.com.rcaneppele.openai.endpoints.chatcompletion.request.stream;
class ChatCompletionStreamRequestSenderTest extends BaseRequestSenderTest {
private ChatCompletionStreamRequestSender sender;
private JsonConverter<ChatCompletionRequest> jsonConverter;
private ChatCompletionRequestBuilder builder;
@Override
protected String expectedURI() {
return "chat/completions";
}
@Override
protected String mockJsonResponse() {
return "data: {}";
}
@BeforeEach
void setUp() {
this.sender = new ChatCompletionStreamRequestSender(url, TIMEOUT, API_KEY);
this.jsonConverter = new JsonConverter<>(ChatCompletionRequest.class);
this.builder = new ChatCompletionRequestBuilder();
}
@Test
public void shouldSendRequest() {
var request = builder
.model(OpenAIModel.GPT_4_1106_PREVIEW)
.userMessage("the user message")
.build();
var testObserver = sender.sendStreamRequest(request).test();
testObserver.assertNoErrors();
testObserver.assertNotComplete();
assertNotNull(testObserver.values());
var expectedRequestBody = jsonConverter.convertRequestToJson(request); | executeRequestAssertions(expectedRequestBody, 1, HttpMethod.POST, false); | 2 | 2023-12-21 19:17:56+00:00 | 4k |
373675032/smart-medicine | src/main/java/world/xuewei/service/FeedbackService.java | [
{
"identifier": "FeedbackDao",
"path": "src/main/java/world/xuewei/dao/FeedbackDao.java",
"snippet": "@Repository\npublic interface FeedbackDao extends BaseMapper<Feedback> {\n\n}"
},
{
"identifier": "Feedback",
"path": "src/main/java/world/xuewei/entity/Feedback.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@TableName(\"feedback\")\npublic class Feedback {\n\n /**\n * ไธป้ฎID\n */\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n /**\n * ๅ้ฆ็จๆท\n */\n private String name;\n\n /**\n * ้ฎ็ฎฑ\n */\n private String email;\n\n /**\n * ๅ้ฆๆ ้ข\n */\n private String title;\n\n /**\n * ๅ้ฆๅ
ๅฎน\n */\n private String content;\n\n /**\n * ๅๅปบๆถ้ด\n */\n private Date createTime;\n\n /**\n * ๆดๆฐๆถ้ด\n */\n private Date updateTime;\n\n}"
},
{
"identifier": "Assert",
"path": "src/main/java/world/xuewei/utils/Assert.java",
"snippet": "public class Assert {\n\n public static boolean isEmpty(CharSequence s) {\n if (s == null || s.length() == 0) {\n return true;\n }\n for (int i = 0; i < s.length(); ++i) {\n if (' ' != s.charAt(i)) {\n return false;\n }\n }\n return true;\n }\n\n public static boolean isEmpty(Collection<?> obj) {\n return obj == null || obj.isEmpty();\n }\n\n public static boolean isEmpty(Map<?, ?> obj) {\n return obj == null || obj.isEmpty();\n }\n\n public static boolean isEmpty(Object[] obj) {\n return obj == null || obj.length == 0;\n }\n\n public static boolean isEmpty(Object obj) {\n return obj == null;\n }\n\n public static boolean isEmpty(List<?> obj) {\n return obj == null || obj.size() == 0;\n }\n\n public static boolean notEmpty(CharSequence s) {\n return !isEmpty(s);\n }\n\n public static boolean notEmpty(Collection<?> obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(Map<?, ?> obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(Object[] obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(Object obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(List<?> obj) {\n return !isEmpty(obj);\n }\n\n public static void assertNotEmpty(CharSequence s, String name) {\n if (isEmpty(s)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Collection<?> obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Map<?, ?> obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Object[] obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Object obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(List<?> obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n private static String throwException(String name) {\n throw new RuntimeException(\"REQUEST_PARAM_IS_NULL ่ฏทๆฑๅๆฐ<\" + name + \">ไธบ็ฉบ\");\n }\n\n}"
},
{
"identifier": "BeanUtil",
"path": "src/main/java/world/xuewei/utils/BeanUtil.java",
"snippet": "public class BeanUtil {\n\n private static Map<String, BeanCopier> beanCopierMap = new HashMap();\n\n\n public static <T> T copy(Object src, Class<T> clazz)\n throws InstantiationException, IllegalAccessException {\n if ((null == src) || (null == clazz)) return null;\n Object des = clazz.newInstance();\n copy(src, des);\n return (T) des;\n }\n\n\n public static void copy(Object src, Object des) {\n if ((null == src) || (null == des)) return;\n String key = generateKey(src.getClass(), des.getClass());\n BeanCopier copier = (BeanCopier) beanCopierMap.get(key);\n if (null == copier) {\n copier = BeanCopier.create(src.getClass(), des.getClass(), false);\n beanCopierMap.put(key, copier);\n }\n copier.copy(src, des, null);\n }\n\n\n public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz)\n throws InstantiationException, IllegalAccessException {\n if ((null == map) || (null == clazz)) return null;\n T bean = clazz.newInstance();\n map2Bean(map, bean);\n return bean;\n }\n\n\n public static <T> void map2Bean(Map<String, Object> map, T bean) {\n if ((null == map) || (null == bean)) return;\n BeanMap beanMap = BeanMap.create(bean);\n beanMap.putAll(map);\n }\n\n\n public static Map<String, Object> bean2Map(Object bean) {\n if (null == bean) return null;\n return copy(BeanMap.create(bean));\n }\n\n\n public static <T> List<Map<String, Object>> mapList(List<T> beanList) {\n if ((null == beanList) || (beanList.size() < 1)) return null;\n List<Map<String, Object>> mapList = new ArrayList();\n int i = 0;\n for (int size = beanList.size(); i < size; i++) {\n mapList.add(bean2Map(beanList.get(i)));\n }\n return mapList;\n }\n\n public static <K, V> Map<K, V> copy(Map<K, V> src) {\n if (null == src) return null;\n Map<K, V> des = new HashMap();\n des.putAll(src);\n\n\n return des;\n }\n\n\n public static void apply(Object des, Object... srcs) {\n if ((null == des) || (null == srcs) || (srcs.length < 1)) return;\n BeanMap desBeanMap = BeanMap.create(des);\n Set<?> keys = desBeanMap.keySet();\n BeanMap srcBeanMap = null;\n for (Object src : srcs) {\n if (null != src) {\n srcBeanMap = BeanMap.create(src);\n for (Object key : keys) {\n Object value = srcBeanMap.get(key);\n if ((null != value) && (null == desBeanMap.get(key))) {\n desBeanMap.put(des, key, value);\n }\n }\n }\n }\n }\n\n\n public static void apply(Object des, List<Map<String, Object>> srcList) {\n Map<String, Object> src;\n if ((null == des) || (null == srcList) || (srcList.isEmpty())) return;\n BeanMap desBeanMap = BeanMap.create(des);\n Set<?> keys = desBeanMap.keySet();\n for (Iterator localIterator1 = srcList.iterator(); localIterator1.hasNext(); ) {\n src = (Map) localIterator1.next();\n if ((null != src) && (!src.isEmpty())) {\n for (Object key : keys) {\n Object value = src.get(key);\n if (null != value) {\n desBeanMap.put(des, key, value);\n }\n }\n }\n }\n }\n\n private static String generateKey(Class<?> src, Class<?> des) {\n return src.getName() + des.getName();\n }\n\n /**\n * bean ่ฝฌ String\n */\n public static <T> String beanToString(T value) {\n if (value == null) {\n return null;\n }\n Class<?> clazz = value.getClass();\n if (clazz == int.class || clazz == Integer.class) {\n return \"\" + value;\n } else if (clazz == String.class) {\n return (String) value;\n } else if (clazz == long.class || clazz == Long.class) {\n return \"\" + value;\n } else {\n return JSON.toJSONString(value);\n }\n }\n\n\n /**\n * string ่ฝฌ bean\n */\n public static <T> T stringToBean(String str, Class<T> clazz) {\n if (str == null || str.length() <= 0 || clazz == null) {\n return null;\n }\n if (clazz == int.class || clazz == Integer.class) {\n return (T) Integer.valueOf(str);\n } else if (clazz == String.class) {\n return (T) str;\n } else if (clazz == long.class || clazz == Long.class) {\n return (T) Long.valueOf(str);\n } else {\n return JSON.toJavaObject(JSON.parseObject(str), clazz);\n }\n }\n\n\n}"
},
{
"identifier": "VariableNameUtils",
"path": "src/main/java/world/xuewei/utils/VariableNameUtils.java",
"snippet": "public class VariableNameUtils {\n\n private static Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n private static Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n\n /**\n * ไธๅ็บฟ่ฝฌ้ฉผๅณฐ\n */\n public static String lineToHump(String str) {\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n /**\n * ้ฉผๅณฐ่ฝฌไธๅ็บฟ\n */\n public static String humpToLine(String str) {\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n}"
}
] | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import world.xuewei.dao.FeedbackDao;
import world.xuewei.entity.Feedback;
import world.xuewei.utils.Assert;
import world.xuewei.utils.BeanUtil;
import world.xuewei.utils.VariableNameUtils;
import java.io.Serializable;
import java.util.List;
import java.util.Map; | 2,632 | package world.xuewei.service;
/**
* ๅ้ฆๆๅก็ฑป
*
* @author XUEW
*/
@Service
public class FeedbackService extends BaseService<Feedback> {
@Autowired
protected FeedbackDao userDao;
@Override
public List<Feedback> query(Feedback o) {
QueryWrapper<Feedback> wrapper = new QueryWrapper();
if (Assert.notEmpty(o)) { | package world.xuewei.service;
/**
* ๅ้ฆๆๅก็ฑป
*
* @author XUEW
*/
@Service
public class FeedbackService extends BaseService<Feedback> {
@Autowired
protected FeedbackDao userDao;
@Override
public List<Feedback> query(Feedback o) {
QueryWrapper<Feedback> wrapper = new QueryWrapper();
if (Assert.notEmpty(o)) { | Map<String, Object> bean2Map = BeanUtil.bean2Map(o); | 3 | 2023-12-16 11:16:11+00:00 | 4k |
C0urante/joplin | src/main/java/io/github/c0urante/joplin/HueEntertainmentClient.java | [
{
"identifier": "DtlsClient",
"path": "src/main/java/io/github/c0urante/joplin/internal/DtlsClient.java",
"snippet": "public class DtlsClient implements AutoCloseable {\n\n private final DTLSTransport transport;\n\n public DtlsClient(String hostnameOrIpAddress, int port, TlsPSKIdentity pskIdentity) throws IOException {\n BouncyCastleClient bouncyCastleClient = new BouncyCastleClient(pskIdentity);\n\n InetAddress address = InetAddress.getByName(hostnameOrIpAddress);\n DatagramSocket socket = new DatagramSocket();\n // Extremely conservative. From the docs:\n // \"After 10 seconds of no activity the connection is closed automatically\"\n socket.setSoTimeout(30_000);\n socket.connect(address, port);\n\n int mtu = 1500;\n DatagramTransport transport = new UDPTransport(socket, mtu);\n\n DTLSClientProtocol protocol = new DTLSClientProtocol();\n\n this.transport = protocol.connect(bouncyCastleClient, transport);\n }\n\n public void send(byte[] message) throws IOException {\n transport.send(message, 0, message.length);\n }\n\n @Override\n public void close() throws IOException {\n transport.close();\n }\n\n private static class BouncyCastleClient extends PSKTlsClient {\n\n public BouncyCastleClient(TlsPSKIdentity pskIdentity) {\n super(new BcTlsCrypto(), pskIdentity);\n }\n\n @Override\n protected ProtocolVersion[] getSupportedVersions() {\n return ProtocolVersion.DTLSv12.only();\n }\n\n @Override\n protected int[] getSupportedCipherSuites() {\n return TlsUtils.getSupportedCipherSuites(\n getCrypto(),\n new int[]{CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256}\n );\n }\n }\n\n}"
},
{
"identifier": "InsecureSslContextFactory",
"path": "src/main/java/io/github/c0urante/joplin/internal/InsecureSslContextFactory.java",
"snippet": "public class InsecureSslContextFactory {\n\n public static SSLContext context() {\n TrustManager trustManager = new InsecureTrustManager();\n\n SSLContext result;\n try {\n result = SSLContext.getInstance(\"TLS\");\n } catch (NoSuchAlgorithmException e) {\n throw new HttpsException(\"Failed to create SSL context\", e);\n }\n\n try {\n result.init(\n null,\n new TrustManager[]{trustManager},\n new SecureRandom()\n );\n } catch (KeyManagementException e) {\n throw new HttpsException(\"Failed to initialize SSL context\", e);\n }\n\n return result;\n }\n\n private static class InsecureTrustManager extends X509ExtendedTrustManager {\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {\n }\n\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {\n }\n }\n\n}"
},
{
"identifier": "Serialization",
"path": "src/main/java/io/github/c0urante/joplin/internal/Serialization.java",
"snippet": "public final class Serialization {\n\n public static byte[] serializeStreamCommand(\n byte colorSpace,\n byte[] entertainmentArea,\n Light[] lights\n ) {\n ByteBuffer result = ByteBuffer.allocate(52 + 7 * lights.length);\n\n // Protocol name\n result.put(\"HueStream\".getBytes(StandardCharsets.UTF_8));\n\n // Streaming API version (1 byte major, 1 byte minor)\n result.put((byte) 0x02);\n result.put((byte) 0x00);\n\n // Sequence number (1 byte, currently unused)\n result.put((byte) 0x00);\n\n // Reserved (2 bytes, all zeros should be sent)\n result.put((byte) 0x00);\n result.put((byte) 0x00);\n\n // Color space\n result.put(colorSpace);\n\n // Reserved (1 byte, all zeros should be sent)\n result.put((byte) 0x00);\n\n // Entertainment area ID\n result.put(entertainmentArea);\n\n // Lights (channel + color)\n for (Light light : lights) {\n light.serializeTo(result);\n }\n\n return result.array();\n }\n\n}"
},
{
"identifier": "Validation",
"path": "src/main/java/io/github/c0urante/joplin/internal/Validation.java",
"snippet": "public class Validation {\n\n public static byte[] entertainmentArea(\n String entertainmentArea\n ) {\n byte[] result = entertainmentArea.getBytes(\n StandardCharsets.UTF_8\n );\n\n if (result.length != 36)\n throw new IllegalArgumentException(\n \"Invalid value \" + entertainmentArea\n + \" for entertainment area ID; \"\n + \"must be exactly 36 bytes long\"\n );\n\n return result;\n }\n\n public static void red(int red) {\n validateColor(red, \"red\");\n }\n\n public static void green(int green) {\n validateColor(green, \"green\");\n }\n\n public static void blue(int blue) {\n validateColor(blue, \"blue\");\n }\n\n private static void validateColor(int value, String color) {\n if (value > 0xFFFF)\n throw new IllegalArgumentException(\n \"Invalid value \" + value\n + \" for color \" + color\n + \"; must be between 0 and 65535, inclusive\"\n );\n }\n\n public static byte colorSpace(int colorSpace) {\n if (colorSpace < 0 || colorSpace > 255)\n throw new IllegalArgumentException(\n \"Invalid value \" + colorSpace\n + \" for color space; \"\n + \"must be between 0 and 255, inclusive\"\n );\n\n return (byte) colorSpace;\n }\n\n}"
}
] | import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.c0urante.joplin.internal.DtlsClient;
import io.github.c0urante.joplin.internal.InsecureSslContextFactory;
import io.github.c0urante.joplin.internal.Serialization;
import io.github.c0urante.joplin.internal.Validation;
import org.bouncycastle.tls.BasicTlsPSKIdentity;
import org.bouncycastle.tls.TlsPSKIdentity;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.IntStream; | 2,060 | /*
* Copyright ยฉ 2023 Chris Egerton ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.c0urante.joplin;
/**
* A synchronous client for the
* <a href="https://developers.meethue.com/develop/hue-entertainment/hue-entertainment-api/">
* Philips Hue Entertainment API</a>.
* <p>
* This client can prepare a stream for initialization
*/
public class HueEntertainmentClient implements AutoCloseable {
private static final Duration REST_CONNECT_TIMEOUT = Duration.ofSeconds(5);
private static final int TRIES = 3;
private final TlsPSKIdentity pskIdentity;
private final String host;
private final int port;
private final String username;
private final byte colorSpace;
private final byte[] entertainmentArea;
private final URI baseUri;
private final HttpClient httpClient;
private Thread httpThread; | /*
* Copyright ยฉ 2023 Chris Egerton ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.c0urante.joplin;
/**
* A synchronous client for the
* <a href="https://developers.meethue.com/develop/hue-entertainment/hue-entertainment-api/">
* Philips Hue Entertainment API</a>.
* <p>
* This client can prepare a stream for initialization
*/
public class HueEntertainmentClient implements AutoCloseable {
private static final Duration REST_CONNECT_TIMEOUT = Duration.ofSeconds(5);
private static final int TRIES = 3;
private final TlsPSKIdentity pskIdentity;
private final String host;
private final int port;
private final String username;
private final byte colorSpace;
private final byte[] entertainmentArea;
private final URI baseUri;
private final HttpClient httpClient;
private Thread httpThread; | private DtlsClient dtlsClient = null; | 0 | 2023-12-21 19:01:36+00:00 | 4k |
simasch/vaadin-jooq-template | src/main/java/ch/martinelli/vj/ui/views/user/UserView.java | [
{
"identifier": "Role",
"path": "src/main/java/ch/martinelli/vj/domain/user/Role.java",
"snippet": "public class Role {\n\n public static final String USER = \"USER\";\n public static final String ADMIN = \"ADMIN\";\n\n private Role() {\n }\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/ch/martinelli/vj/domain/user/UserService.java",
"snippet": "@Transactional(readOnly = true)\n@Service\npublic class UserService {\n\n private final DSLContext ctx;\n\n public UserService(DSLContext ctx) {\n this.ctx = ctx;\n }\n\n public Optional<UserRecord> findUserByUsername(String username) {\n return ctx.selectFrom(USER)\n .where(USER.USERNAME.eq(username))\n .fetchOptional();\n }\n\n public Optional<UserWithRoles> findUserWithRolesByUsername(String username) {\n return ctx.select(USER,\n multiset(select(USER_ROLE.ROLE)\n .from(USER_ROLE)\n .where(USER_ROLE.USERNAME.eq(USER.USERNAME))\n ).convertFrom(r -> r.map(Record1::value1)))\n .from(USER)\n .where(USER.USERNAME.eq(username))\n .fetchOptional(mapping(UserWithRoles::new));\n }\n\n public List<UserRoleRecord> findRolesByUsername(String username) {\n return ctx.selectFrom(USER_ROLE)\n .where(USER_ROLE.USERNAME.eq(username))\n .fetch();\n }\n\n public List<UserWithRoles> findAllUserWithRoles(int offset, int limit, List<OrderField<?>> orderFields) {\n return ctx.select(USER,\n multiset(select(USER_ROLE.ROLE)\n .from(USER_ROLE)\n .where(USER_ROLE.USERNAME.eq(USER.USERNAME))\n ).convertFrom(r -> r.map(Record1::value1)))\n .from(USER)\n .orderBy(orderFields)\n .offset(offset)\n .limit(limit)\n .fetch(mapping(UserWithRoles::new));\n }\n\n @Transactional\n public void save(UserWithRoles userWithRoles) {\n var user = userWithRoles.getUser();\n ctx.attach(user);\n user.store();\n\n // First delete all assigned roles\n ctx.deleteFrom(USER_ROLE)\n .where(USER_ROLE.USERNAME.eq(user.getUsername()))\n .execute();\n\n // Then add all roles\n for (var role : userWithRoles.getRoles()) {\n var userRole = new UserRoleRecord(user.getUsername(), role);\n ctx.attach(userRole);\n userRole.store();\n }\n }\n\n @Transactional\n public void deleteByUsername(String username) {\n ctx.deleteFrom(USER_ROLE)\n .where(USER_ROLE.USERNAME.eq(username))\n .execute();\n ctx.deleteFrom(USER)\n .where(USER.USERNAME.eq(username))\n .execute();\n }\n}"
},
{
"identifier": "UserWithRoles",
"path": "src/main/java/ch/martinelli/vj/domain/user/UserWithRoles.java",
"snippet": "public class UserWithRoles {\n private final UserRecord user;\n private Set<String> roles;\n\n public UserWithRoles() {\n this.user = new UserRecord();\n this.roles = new HashSet<>();\n }\n\n public UserWithRoles(UserRecord user, List<String> roles) {\n this.user = user;\n this.roles = new HashSet<>(roles);\n }\n\n public UserRecord getUser() {\n return user;\n }\n\n public Set<String> getRoles() {\n return roles;\n }\n\n public void setRoles(Set<String> roles) {\n this.roles = roles;\n }\n}"
},
{
"identifier": "Notifier",
"path": "src/main/java/ch/martinelli/vj/ui/components/Notifier.java",
"snippet": "public class Notifier extends Notification {\n\n public static final int DURATION = 3000;\n\n public static void info(String message) {\n showNotification(message);\n }\n\n public static void success(String message) {\n var notification = showNotification(message);\n notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);\n }\n\n public static void warn(String message) {\n var notification = showNotification(message);\n notification.addThemeVariants(NotificationVariant.LUMO_WARNING);\n }\n\n public static void error(String message) {\n var text = new NativeLabel(message);\n var close = new Button(\"OK\");\n\n var content = new HorizontalLayout(text, close);\n content.addClassName(LumoUtility.AlignItems.CENTER);\n\n var notification = new Notification(content);\n notification.addThemeVariants(NotificationVariant.LUMO_ERROR);\n notification.setPosition(Position.TOP_END);\n\n close.addClickListener(buttonClickEvent -> notification.close());\n notification.open();\n close.focus();\n }\n\n private static Notification showNotification(String message) {\n return show(message, DURATION, Position.TOP_END);\n }\n\n}"
},
{
"identifier": "MainLayout",
"path": "src/main/java/ch/martinelli/vj/ui/layout/MainLayout.java",
"snippet": "public class MainLayout extends AppLayout {\n\n private final transient AuthenticatedUser authenticatedUser;\n private final AccessAnnotationChecker accessChecker;\n\n private H2 viewTitle;\n\n public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {\n this.authenticatedUser = authenticatedUser;\n this.accessChecker = accessChecker;\n\n setPrimarySection(Section.DRAWER);\n addDrawerContent();\n addHeaderContent();\n }\n\n private void addHeaderContent() {\n var toggle = new DrawerToggle();\n toggle.setAriaLabel(\"Menu toggle\");\n\n viewTitle = new H2();\n viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);\n\n addToNavbar(true, toggle, viewTitle);\n }\n\n private void addDrawerContent() {\n var appName = new H1(\"Vaadin jOOQ Template\");\n appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);\n\n var header = new Header(appName);\n\n var scroller = new Scroller(createNavigation());\n\n addToDrawer(header, scroller, createFooter());\n }\n\n private SideNav createNavigation() {\n var nav = new SideNav();\n\n if (accessChecker.hasAccess(HelloWorldView.class)) {\n nav.addItem(new SideNavItem(getTranslation(\"Hello World\"), HelloWorldView.class, VaadinIcon.GLOBE.create()));\n\n }\n if (accessChecker.hasAccess(PersonView.class)) {\n nav.addItem(new SideNavItem(getTranslation(\"Persons\"), PersonView.class, VaadinIcon.ARCHIVES.create()));\n }\n if (accessChecker.hasAccess(UserView.class)) {\n nav.addItem(new SideNavItem(getTranslation(\"Users\"), UserView.class, VaadinIcon.USER.create()));\n }\n\n return nav;\n }\n\n private Footer createFooter() {\n var layout = new Footer();\n\n var optionalUserRecord = authenticatedUser.get();\n if (optionalUserRecord.isPresent()) {\n var user = optionalUserRecord.get();\n\n var avatar = new Avatar(\"%s %s\".formatted(user.getFirstName(), user.getLastName()));\n var resource = new StreamResource(\"profile-pic\", () -> new ByteArrayInputStream(user.getPicture()));\n avatar.setImageResource(resource);\n avatar.setThemeName(\"xsmall\");\n avatar.getElement().setAttribute(\"tabindex\", \"-1\");\n\n var userMenu = new MenuBar();\n userMenu.setThemeName(\"tertiary-inline contrast\");\n\n var userName = userMenu.addItem(\"\");\n\n var div = new Div();\n div.add(avatar);\n div.add(\"%s %s\".formatted(user.getFirstName(), user.getLastName()));\n div.add(LumoIcon.DROPDOWN.create());\n div.addClassNames(LumoUtility.Display.FLEX, LumoUtility.AlignItems.CENTER, LumoUtility.Gap.SMALL);\n userName.add(div);\n userName.getSubMenu().addItem(getTranslation(\"Sign out\"), e -> authenticatedUser.logout());\n\n layout.add(userMenu);\n } else {\n var loginLink = new Anchor(\"login\", getTranslation(\"Sign in\"));\n layout.add(loginLink);\n }\n\n return layout;\n }\n\n @Override\n protected void afterNavigation() {\n super.afterNavigation();\n viewTitle.setText(getCurrentPageTitle());\n }\n\n private String getCurrentPageTitle() {\n var title = getContent().getClass().getAnnotation(PageTitle.class);\n return title == null ? \"\" : title.value();\n }\n}"
}
] | import ch.martinelli.vj.domain.user.Role;
import ch.martinelli.vj.domain.user.UserService;
import ch.martinelli.vj.domain.user.UserWithRoles;
import ch.martinelli.vj.ui.components.Notifier;
import ch.martinelli.vj.ui.layout.MainLayout;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.MultiSelectComboBox;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridSortOrder;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.*;
import io.seventytwo.vaadinjooq.util.VaadinJooqUtil;
import jakarta.annotation.security.RolesAllowed;
import org.jooq.exception.DataAccessException;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Set;
import static ch.martinelli.vj.db.tables.User.USER; | 2,285 | package ch.martinelli.vj.ui.views.user;
@RolesAllowed(Role.ADMIN)
@PageTitle("Users") | package ch.martinelli.vj.ui.views.user;
@RolesAllowed(Role.ADMIN)
@PageTitle("Users") | @Route(value = "users", layout = MainLayout.class) | 4 | 2023-12-20 13:08:17+00:00 | 4k |
373675032/academic-report | src/main/java/world/xuewei/service/DepartmentService.java | [
{
"identifier": "Leader",
"path": "src/main/java/world/xuewei/constant/Leader.java",
"snippet": "public class Leader {\n public static final Integer YES = 1;\n public static final Integer NO = 0;\n}"
},
{
"identifier": "DepartmentMapper",
"path": "src/main/java/world/xuewei/dao/DepartmentMapper.java",
"snippet": "@Mapper\npublic interface DepartmentMapper {\n\n /**\n * ๆทปๅ Department\n */\n int insert(Department department);\n\n /**\n * ๅ ้คDepartment\n */\n int deleteById(Integer id);\n\n /**\n * ๆฅ่ฏขๅๆกๆฐๆฎ\n */\n Department getById(Integer id);\n\n /**\n * ๆฅ่ฏขๅๆกๆฐๆฎ\n */\n Department getByNo(String no);\n\n /**\n * ๆฅ่ฏขๅ
จ้จๆฐๆฎ\n * ๅ้กตไฝฟ็จMyBatis็ๆไปถๅฎ็ฐ\n */\n List<Department> listDepartments();\n\n /**\n * ๅฎไฝไฝไธบ็ญ้ๆกไปถๆฅ่ฏขๆฐๆฎ\n */\n List<Department> listDepartments(Department department);\n\n /**\n * ๅฎไฝไฝไธบ็ญ้ๆกไปถ่ทๅ็ปๆๆฐ้\n */\n int countDepartments(Department department);\n\n /**\n * ไฟฎๆนDepartment, ๆ นๆฎ department ็ไธป้ฎไฟฎๆนๆฐๆฎ\n */\n int update(Department department);\n\n}"
},
{
"identifier": "College",
"path": "src/main/java/world/xuewei/entity/College.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class College implements Serializable {\n\n private static final long serialVersionUID = 370311530547536003L;\n\n /**\n * ๅญฆ้ขID\n */\n private Integer id;\n\n /**\n * ๅญฆ้ขๅ็งฐ\n */\n private String name;\n\n /**\n * ้ข้ฟIDใๅฏนๅบ่ๅทฅ่กจใ\n */\n private Integer leaderId;\n\n /**\n * ้ข้ฟ\n */\n private Teacher leader;\n}"
},
{
"identifier": "Department",
"path": "src/main/java/world/xuewei/entity/Department.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Department implements Serializable {\n\n private static final long serialVersionUID = 719806364595412025L;\n\n /**\n * ไธป้ฎID\n */\n private Integer id;\n\n /**\n * ้จ้จ็ผๅท\n */\n private String no;\n\n /**\n * ้จ้จๅ็งฐ\n */\n private String name;\n\n /**\n * ้จ้จ้จ้ฟID\n */\n private Integer leaderId;\n\n /**\n * ๅญฆ้ขID\n */\n private Integer collegeId;\n\n /**\n * ็ปๅฝๅฏ็ \n */\n private String password;\n\n /**\n * ๅคดๅ\n */\n private String img = Photo.department;\n\n /**\n * ้จ้ฟ\n */\n private Teacher leader;\n\n /**\n * ๅญฆ้ข\n */\n private College college;\n\n}"
},
{
"identifier": "Teacher",
"path": "src/main/java/world/xuewei/entity/Teacher.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@ExcelTarget(\"Teacher\")\npublic class Teacher implements Serializable {\n\n private static final long serialVersionUID = 459028036953009293L;\n\n /**\n * ไธป้ฎID\n */\n private Integer id;\n\n /**\n * ่ๅทฅๅท\n */\n @Excel(name = \"ๅทฅๅท\", width = 20)\n private String no;\n\n /**\n * ๅงๅ\n */\n @Excel(name = \"ๅงๅ\")\n private String name;\n\n /**\n * ็ปๅฝๅฏ็ \n */\n private String password;\n\n /**\n * ๆงๅซ\n */\n @Excel(name = \"ๆงๅซ\")\n private String sex;\n\n /**\n * ๆๆบๅท็ \n */\n @Excel(name = \"ๆๆบๅท็ \", width = 20)\n private String phone;\n\n /**\n * ๅบ็ๅนดๆ\n */\n @Excel(name = \"ๅบ็ๆฅๆ\", format = \"yyyyๅนดMMๆddๆฅ\", width = 20)\n private Date birthday;\n\n /**\n * ๅบ็ๆฅๆๅญ็ฌฆไธฒ\n */\n private String birthdayStr;\n\n /**\n * ่็งฐใๅฉๆใ่ฎฒๅธใๅฏๆๆใๆๆใ\n */\n @Excel(name = \"่็งฐ\")\n private String position;\n\n /**\n * ๆฏๅฆๆฏ้ข้ฟใ1ๆฏใใ0ๅฆใ\n */\n private Integer isCollegeLeader;\n\n /**\n * ๅญฆ้ขID\n */\n private Integer collegeId;\n\n /**\n * ้ข็ณป\n */\n @Excel(name = \"้ข็ณป\", width = 30)\n private String collegeName;\n\n /**\n * ้ข็ณป\n */\n private College college;\n\n /**\n * ๆฏๅฆๆฏ้จ้จ้จ้ฟใ1ๆฏใใ0ๅฆใ\n */\n private Integer isDepartmentLeader;\n\n /**\n * ๆๅฑ้จ้จID\n */\n private String departmentId;\n\n /**\n * ๅคดๅ\n */\n private String img = Photo.teacher;\n\n}"
}
] | import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import world.xuewei.constant.Leader;
import world.xuewei.dao.DepartmentMapper;
import world.xuewei.entity.College;
import world.xuewei.entity.Department;
import world.xuewei.entity.Teacher;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 2,510 | package world.xuewei.service;
/**
* ้จ้จๆๅก
*
* <p>
* ==========================================================================
* ้้่ฏดๆ๏ผๆฌ้กน็ฎๅ
่ดนๅผๆบ๏ผๅๅไฝ่
ไธบ๏ผ่ไผๅๅญฆ๏ผไธฅ็ฆ็ง่ชๅบๅฎใ
* ==========================================================================
* B็ซ่ดฆๅท๏ผ่ไผๅๅญฆ
* ๅพฎไฟกๅ
ฌไผๅท๏ผ่ไผๅๅญฆ
* ไฝ่
ๅๅฎข๏ผhttp://xuewei.world
* ==========================================================================
* ้้็ปญ็ปญๆปไผๆถๅฐ็ฒไธ็ๆ้๏ผๆปไผๆไบไบบไธบไบ่ตๅๅฉ็ๅๅๆ็ๅผๆบ้กน็ฎใ
* ไธไนๆ็ฒไธๆๅๅบ็ฐ้ฑไป่ฟๅป๏ผ้ฃ่พนๅชๆไปฃ็ ๅ็ปไปๅฐฑ่ท่ทฏ็๏ผๆๅ่ฟๆฏๆ นๆฎ็บฟ็ดขๆพๅฐๆใใ
* ๅธๆๅไฝๆๅๆฆไบฎๆ
ง็ผ๏ผ่ฐจ้ฒไธๅฝๅ้ช๏ผ
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Slf4j
@Service
public class DepartmentService {
@Resource
private DepartmentMapper departmentMapper;
@Resource
private CollegeService collegeService;
@Resource
private TeacherService teacherService;
public boolean insert(Department department) {
return departmentMapper.insert(department) == 1;
}
public boolean deleteById(Integer id) {
return departmentMapper.deleteById(id) == 1;
}
public Department getById(Integer id) {
return departmentMapper.getById(id);
}
public Department getByNo(String no) {
return departmentMapper.getByNo(no);
}
public List<Department> listDepartments() {
return departmentMapper.listDepartments();
}
public List<Department> listDepartments(Department department) {
return departmentMapper.listDepartments(department);
}
public int countDepartments(Department department) {
return departmentMapper.countDepartments(department);
}
public boolean update(Department department) {
return departmentMapper.update(department) == 1;
}
/**
* ๅ้กตๆฅ่ฏข้จ้จ
*/
public Map<String, Object> pageAllDepartments(Integer page, Integer rows, String searchField, String searchString) {
Map<String, Object> map = new HashMap<>();
List<Department> departments = new ArrayList<>();
if (StrUtil.isNotEmpty(searchString)) {
// ๆ็ดข
Department search = null;
if ("no".equals(searchField)) {
search = Department.builder().no(searchString).build();
}
if ("name".equals(searchField)) {
search = Department.builder().name(searchString).build();
}
if ("college.name".equals(searchField)) {
College college = College.builder().name(searchString).build();
List<College> colleges = collegeService.listColleges(college);
if (colleges.size() > 0) {
search = Department.builder().collegeId(colleges.get(0).getId()).build();
} else {
search = Department.builder().collegeId(-1).build();
}
}
departments = listDepartments(search);
} else {
// ๅ้กตๆฅ่ฏข
PageHelper.startPage(page, rows);
departments = listDepartments();
}
PageInfo<Department> pageInfo = new PageInfo<>(departments);
// ๅฐๆฅ่ฏข็ปๆๆพๅ
ฅmap
map.put("rows", dealDepartment(departments));
// ๆป้กตๆฐ
map.put("total", pageInfo.getPages());
// ๆปๆกๆฐ
map.put("records", pageInfo.getTotal());
return map;
}
/**
* ๅค็ๅฎๅ้จ้จๅฏน่ฑก
*/
private List<Department> dealDepartment(List<Department> list) {
list.forEach(department -> {
// ่ฎพ็ฝฎๅญฆ้ข
Integer collegeId = department.getCollegeId();
College college = collegeService.getById(collegeId);
// ่ฎพ็ฝฎ้จ้ฟ
Integer leaderId = department.getLeaderId();
Teacher teacher = teacherService.getById(leaderId);
department.setCollege(college);
department.setLeader(teacher);
});
return list;
}
/**
* ็ผ่พ้จ้จ
*/
public void editDepartment(Department department, String action) {
if ("edit".equals(action)) {
// ็ผ่พ
update(department);
// ่ทๅๅๆฅ้จ้จ็ไฟกๆฏ
Department target = getById(department.getId());
// ่ทๅ็ผ่พ้จ้จ็้ขๅฏผ
Teacher teacher = teacherService.getByNo(department.getLeader().getNo());
if (ObjectUtil.isNotEmpty(teacher)) {
if (target.getLeaderId().intValue() != teacher.getId()) {
// ๆดๆข้ขๅฏผ
Integer oldLeaderId = target.getLeaderId(); | package world.xuewei.service;
/**
* ้จ้จๆๅก
*
* <p>
* ==========================================================================
* ้้่ฏดๆ๏ผๆฌ้กน็ฎๅ
่ดนๅผๆบ๏ผๅๅไฝ่
ไธบ๏ผ่ไผๅๅญฆ๏ผไธฅ็ฆ็ง่ชๅบๅฎใ
* ==========================================================================
* B็ซ่ดฆๅท๏ผ่ไผๅๅญฆ
* ๅพฎไฟกๅ
ฌไผๅท๏ผ่ไผๅๅญฆ
* ไฝ่
ๅๅฎข๏ผhttp://xuewei.world
* ==========================================================================
* ้้็ปญ็ปญๆปไผๆถๅฐ็ฒไธ็ๆ้๏ผๆปไผๆไบไบบไธบไบ่ตๅๅฉ็ๅๅๆ็ๅผๆบ้กน็ฎใ
* ไธไนๆ็ฒไธๆๅๅบ็ฐ้ฑไป่ฟๅป๏ผ้ฃ่พนๅชๆไปฃ็ ๅ็ปไปๅฐฑ่ท่ทฏ็๏ผๆๅ่ฟๆฏๆ นๆฎ็บฟ็ดขๆพๅฐๆใใ
* ๅธๆๅไฝๆๅๆฆไบฎๆ
ง็ผ๏ผ่ฐจ้ฒไธๅฝๅ้ช๏ผ
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Slf4j
@Service
public class DepartmentService {
@Resource
private DepartmentMapper departmentMapper;
@Resource
private CollegeService collegeService;
@Resource
private TeacherService teacherService;
public boolean insert(Department department) {
return departmentMapper.insert(department) == 1;
}
public boolean deleteById(Integer id) {
return departmentMapper.deleteById(id) == 1;
}
public Department getById(Integer id) {
return departmentMapper.getById(id);
}
public Department getByNo(String no) {
return departmentMapper.getByNo(no);
}
public List<Department> listDepartments() {
return departmentMapper.listDepartments();
}
public List<Department> listDepartments(Department department) {
return departmentMapper.listDepartments(department);
}
public int countDepartments(Department department) {
return departmentMapper.countDepartments(department);
}
public boolean update(Department department) {
return departmentMapper.update(department) == 1;
}
/**
* ๅ้กตๆฅ่ฏข้จ้จ
*/
public Map<String, Object> pageAllDepartments(Integer page, Integer rows, String searchField, String searchString) {
Map<String, Object> map = new HashMap<>();
List<Department> departments = new ArrayList<>();
if (StrUtil.isNotEmpty(searchString)) {
// ๆ็ดข
Department search = null;
if ("no".equals(searchField)) {
search = Department.builder().no(searchString).build();
}
if ("name".equals(searchField)) {
search = Department.builder().name(searchString).build();
}
if ("college.name".equals(searchField)) {
College college = College.builder().name(searchString).build();
List<College> colleges = collegeService.listColleges(college);
if (colleges.size() > 0) {
search = Department.builder().collegeId(colleges.get(0).getId()).build();
} else {
search = Department.builder().collegeId(-1).build();
}
}
departments = listDepartments(search);
} else {
// ๅ้กตๆฅ่ฏข
PageHelper.startPage(page, rows);
departments = listDepartments();
}
PageInfo<Department> pageInfo = new PageInfo<>(departments);
// ๅฐๆฅ่ฏข็ปๆๆพๅ
ฅmap
map.put("rows", dealDepartment(departments));
// ๆป้กตๆฐ
map.put("total", pageInfo.getPages());
// ๆปๆกๆฐ
map.put("records", pageInfo.getTotal());
return map;
}
/**
* ๅค็ๅฎๅ้จ้จๅฏน่ฑก
*/
private List<Department> dealDepartment(List<Department> list) {
list.forEach(department -> {
// ่ฎพ็ฝฎๅญฆ้ข
Integer collegeId = department.getCollegeId();
College college = collegeService.getById(collegeId);
// ่ฎพ็ฝฎ้จ้ฟ
Integer leaderId = department.getLeaderId();
Teacher teacher = teacherService.getById(leaderId);
department.setCollege(college);
department.setLeader(teacher);
});
return list;
}
/**
* ็ผ่พ้จ้จ
*/
public void editDepartment(Department department, String action) {
if ("edit".equals(action)) {
// ็ผ่พ
update(department);
// ่ทๅๅๆฅ้จ้จ็ไฟกๆฏ
Department target = getById(department.getId());
// ่ทๅ็ผ่พ้จ้จ็้ขๅฏผ
Teacher teacher = teacherService.getByNo(department.getLeader().getNo());
if (ObjectUtil.isNotEmpty(teacher)) {
if (target.getLeaderId().intValue() != teacher.getId()) {
// ๆดๆข้ขๅฏผ
Integer oldLeaderId = target.getLeaderId(); | Teacher oldLeader = Teacher.builder().id(oldLeaderId).isDepartmentLeader(Leader.NO).build(); | 0 | 2023-12-21 06:59:12+00:00 | 4k |
misode/packtest | src/main/java/io/github/misode/packtest/mixin/GameTestInfoMixin.java | [
{
"identifier": "ChatListener",
"path": "src/main/java/io/github/misode/packtest/ChatListener.java",
"snippet": "public class ChatListener {\n\n private static final List<ChatListener> listeners = new ArrayList<>();\n\n public static void broadcast(ServerPlayer player, Component chatMessage) {\n Message message = new Message(player.getName().getString(), chatMessage.getString());\n ChatListener.listeners.forEach(l -> l.messages.add(message));\n }\n\n public ChatListener() {\n ChatListener.listeners.add(this);\n }\n\n public final List<Message> messages = new ArrayList<>();\n\n public void stop() {\n ChatListener.listeners.remove(this);\n }\n\n public List<String> filter(Predicate<Message> predicate) {\n return this.messages.stream()\n .filter(predicate)\n .map(m -> m.content)\n .toList();\n }\n\n public void reset() {\n this.messages.clear();\n }\n\n public record Message(String player, String content) {}\n}"
},
{
"identifier": "PackTestInfo",
"path": "src/main/java/io/github/misode/packtest/PackTestInfo.java",
"snippet": "public interface PackTestInfo {\n long packtest$getTick();\n void packtest$setChatListener(ChatListener listener);\n ChatListener packtest$getChatListener();\n}"
},
{
"identifier": "Dummy",
"path": "src/main/java/io/github/misode/packtest/dummy/Dummy.java",
"snippet": "public class Dummy extends ServerPlayer {\n public Vec3 originalSpawn;\n\n public static Dummy createRandom(MinecraftServer server, ResourceKey<Level> dimensionId, Vec3 pos) {\n RandomSource random = server.overworld().getRandom();\n int tries = 0;\n while (tries++ < 10) {\n String playerName = \"Dummy\" + random.nextInt(100, 1000);\n if (server.getPlayerList().getPlayerByName(playerName) == null) {\n return create(playerName, server, dimensionId, pos);\n }\n }\n throw new IllegalStateException(\"Failed to spawn dummy with a random name\");\n }\n\n public static Dummy create(String username, MinecraftServer server, ResourceKey<Level> dimensionId, Vec3 pos) {\n ServerLevel level = server.getLevel(dimensionId);\n GameProfileCache.setUsesAuthentication(false);\n GameProfile profile;\n try {\n var profileCache = server.getProfileCache();\n profile = profileCache == null ? null : profileCache.get(username).orElse(null);\n }\n finally {\n GameProfileCache.setUsesAuthentication(server.isDedicatedServer() && server.usesAuthentication());\n }\n if (profile == null) {\n profile = new GameProfile(UUIDUtil.createOfflinePlayerUUID(username), username);\n }\n Vec3 originalSpawn = Vec3.atBottomCenterOf(BlockPos.containing(pos));\n Dummy dummy = new Dummy(server, level, profile, ClientInformation.createDefault(), originalSpawn);\n server.getPlayerList().placeNewPlayer(\n new DummyClientConnection(PacketFlow.SERVERBOUND),\n dummy,\n new CommonListenerCookie(profile, 0, dummy.clientInformation()));\n dummy.teleportTo(level, originalSpawn.x, originalSpawn.y, originalSpawn.z, 0, 0);\n dummy.setHealth(20);\n dummy.unsetRemoved();\n dummy.gameMode.changeGameModeForPlayer(GameType.SURVIVAL);\n server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(dummy, (byte) (dummy.yHeadRot * 256 / 360)), dimensionId);\n server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(dummy), dimensionId);\n dummy.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, (byte) 0x7f);\n return dummy;\n }\n\n public Dummy(MinecraftServer server, ServerLevel level, GameProfile profile, ClientInformation cli, Vec3 originalSpawn) {\n super(server, level, profile, cli);\n this.originalSpawn = originalSpawn;\n }\n\n public String getUsername() {\n return this.getGameProfile().getName();\n }\n\n public void leave(Component reason) {\n server.getPlayerList().remove(this);\n this.connection.onDisconnect(reason);\n }\n\n public void respawn() {\n server.getPlayerList().respawn(this, false);\n }\n\n @Override\n public void tick() {\n if (Objects.requireNonNull(this.getServer()).getTickCount() % 10 == 0) {\n this.connection.resetPosition();\n this.serverLevel().getChunkSource().move(this);\n }\n try {\n super.tick();\n this.doTick();\n } catch (NullPointerException ignored) {}\n }\n\n @Override\n public void die(DamageSource cause) {\n super.die(cause);\n if (this.serverLevel().getGameRules().getBoolean(GameRules.RULE_DO_IMMEDIATE_RESPAWN)) {\n this.server.tell(new TickTask(this.server.getTickCount(),\n () -> this.connection.handleClientCommand(new ServerboundClientCommandPacket(ServerboundClientCommandPacket.Action.PERFORM_RESPAWN))\n ));\n }\n }\n\n @Override\n public void onEquipItem(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack) {\n if (!isUsingItem()) super.onEquipItem(slot, previous, stack);\n }\n\n @Override\n public @NotNull String getIpAddress() {\n return \"127.0.0.1\";\n }\n}"
}
] | import com.llamalad7.mixinextras.sugar.Local;
import io.github.misode.packtest.ChatListener;
import io.github.misode.packtest.PackTestInfo;
import io.github.misode.packtest.dummy.Dummy;
import net.minecraft.gametest.framework.GameTestInfo;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.phys.AABB;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 1,702 | package io.github.misode.packtest.mixin;
/**
* Adds chat listener field and accessors. Removes the listener when finishing.
* Prevents crash when test has already started.
* Clears dummies after succeeding.
*/
@Mixin(GameTestInfo.class)
public abstract class GameTestInfoMixin implements PackTestInfo {
@Shadow
public abstract ServerLevel getLevel();
@Shadow private long tickCount;
@Unique
private ChatListener chatListener;
@Override
public long packtest$getTick() {
return this.tickCount;
}
@Override
public void packtest$setChatListener(ChatListener chatListener) {
this.chatListener = chatListener;
}
@Override
public ChatListener packtest$getChatListener() {
return this.chatListener;
}
@Inject(method = "startTest", cancellable = true, at = @At(value = "INVOKE", target = "Ljava/lang/IllegalStateException;<init>(Ljava/lang/String;)V"))
private void startTest(CallbackInfo ci) {
ci.cancel();
}
@Inject(method = "finish", at = @At("HEAD"))
private void finish(CallbackInfo ci) {
this.chatListener.stop();
}
@Inject(method = "succeed", at = @At(value = "INVOKE", target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", shift = At.Shift.AFTER))
private void succeed(CallbackInfo ci, @Local(ordinal = 0) AABB aabb) { | package io.github.misode.packtest.mixin;
/**
* Adds chat listener field and accessors. Removes the listener when finishing.
* Prevents crash when test has already started.
* Clears dummies after succeeding.
*/
@Mixin(GameTestInfo.class)
public abstract class GameTestInfoMixin implements PackTestInfo {
@Shadow
public abstract ServerLevel getLevel();
@Shadow private long tickCount;
@Unique
private ChatListener chatListener;
@Override
public long packtest$getTick() {
return this.tickCount;
}
@Override
public void packtest$setChatListener(ChatListener chatListener) {
this.chatListener = chatListener;
}
@Override
public ChatListener packtest$getChatListener() {
return this.chatListener;
}
@Inject(method = "startTest", cancellable = true, at = @At(value = "INVOKE", target = "Ljava/lang/IllegalStateException;<init>(Ljava/lang/String;)V"))
private void startTest(CallbackInfo ci) {
ci.cancel();
}
@Inject(method = "finish", at = @At("HEAD"))
private void finish(CallbackInfo ci) {
this.chatListener.stop();
}
@Inject(method = "succeed", at = @At(value = "INVOKE", target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", shift = At.Shift.AFTER))
private void succeed(CallbackInfo ci, @Local(ordinal = 0) AABB aabb) { | this.getLevel().getEntitiesOfClass(Dummy.class, aabb.inflate(1)) | 2 | 2023-12-15 10:08:54+00:00 | 4k |
John200410/rusherhack-spotify | src/main/java/me/john200410/spotify/http/SpotifyAPI.java | [
{
"identifier": "Config",
"path": "src/main/java/me/john200410/spotify/Config.java",
"snippet": "public class Config {\n\t\n\tpublic String appId = \"\";\n\tpublic String appSecret = \"\";\n\tpublic String refresh_token = \"\";\n\t\n}"
},
{
"identifier": "SpotifyPlugin",
"path": "src/main/java/me/john200410/spotify/SpotifyPlugin.java",
"snippet": "public class SpotifyPlugin extends Plugin {\n\t\n\tpublic static final File CONFIG_FILE = RusherHackAPI.getConfigPath().resolve(\"spotify.json\").toFile();\n\tpublic static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();\n\t\n\tprivate Config config = new Config();\n\tprivate HttpServer httpServer;\n\tprivate SpotifyAPI api;\n\t\n\t@Override\n\tpublic void onLoad() {\n\t\t\n\t\t//try load config\n\t\tif(CONFIG_FILE.exists()) {\n\t\t\ttry {\n\t\t\t\tthis.config = GSON.fromJson(IOUtils.toString(CONFIG_FILE.toURI(), StandardCharsets.UTF_8), Config.class);\n\t\t\t} catch(IOException e) {\n\t\t\t\tthis.logger.warn(\"Failed to load config\");\n\t\t\t}\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tthis.httpServer = this.setupServer();\n\t\t\tthis.httpServer.start();\n\t\t\tthis.api = new SpotifyAPI(this);\n\t\t\tthis.api.appID = this.config.appId;\n\t\t\tthis.api.appSecret = this.config.appSecret;\n\t\t\tthis.api.refreshToken = this.config.refresh_token;\n\t\t\t\n\t\t\tif(!this.api.appID.isEmpty() && !this.api.appSecret.isEmpty() && !this.api.refreshToken.isEmpty()) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.api.authorizationRefreshToken();\n\t\t\t\t} catch(Throwable t) {\n\t\t\t\t\tt.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//hud element\n\t\t\tRusherHackAPI.getHudManager().registerFeature(new SpotifyHudElement(this));\n\t\t} catch(IOException e) {\n\t\t\t//throw exception so plugin doesnt load\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\t\n\t\t//TODO: maybe window in the future?\n\t}\n\t\n\t@Override\n\tpublic void onUnload() {\n\t\tif(this.httpServer != null) {\n\t\t\tthis.httpServer.stop(0);\n\t\t}\n\t\t\n\t\tthis.saveConfig();\n\t}\n\t\n\t@Override\n\tpublic String getName() {\n\t\treturn \"Spotify\";\n\t}\n\t\n\t@Override\n\tpublic String getVersion() {\n\t\treturn \"1.1.1\";\n\t}\n\t\n\t@Override\n\tpublic String getDescription() {\n\t\treturn \"Spotify integration for rusherhack\";\n\t}\n\t\n\t@Override\n\tpublic String[] getAuthors() {\n\t\treturn new String[]{\"John200410\", \"DarkerInk\"};\n\t}\n\t\n\tpublic SpotifyAPI getAPI() {\n\t\treturn this.api;\n\t}\n\t\n\tprivate HttpServer setupServer() throws IOException {\n\t\tfinal HttpServer server = HttpServer.create(new InetSocketAddress(\"0.0.0.0\", 4000), 0);\n\t\t\n\t\tserver.createContext(\"/\", (req) -> {\n\t\t\tfinal URI uri = req.getRequestURI();\n\t\t\t\n\t\t\tbyte[] response = new byte[0];\n\t\t\t\n\t\t\tfinal Map<String, String> queryParams = getQueryParameters(uri.getQuery());\n\t\t\t\n\t\t\tif(uri.getPath().equals(\"/callback\")) {\n\t\t\t\tfinal String code = queryParams.get(\"code\");\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tvar res = this.api.authorizationCodeGrant(code);\n\t\t\t\t\t\n\t\t\t\t\tif(res) {\n\t\t\t\t\t\tthis.logger.info(\"Successfully got access token\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.logger.error(\"Failed to get access token\");\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t} catch(InterruptedException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t\tthis.logger.error(\"Failed to get access token\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttry(InputStream is = SpotifyPlugin.class.getResourceAsStream(\"/site/success.html\")) {\n\t\t\t\t\tObjects.requireNonNull(is, \"Couldn't find login.html\");\n\t\t\t\t\tresponse = IOUtils.toByteArray(is);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"text/html\");\n\t\t\t} else if(uri.getPath().equals(\"/\")) {\n\t\t\t\t\n\t\t\t\ttry(InputStream is = SpotifyPlugin.class.getResourceAsStream(\"/site/login.html\")) {\n\t\t\t\t\tObjects.requireNonNull(is, \"Couldn't find login.html\");\n\t\t\t\t\tresponse = IOUtils.toByteArray(is);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"text/html\");\n\t\t\t} else if(uri.getPath().equals(\"/setup\")) {\n\t\t\t\tfinal String appId = queryParams.get(\"appId\");\n\t\t\t\tfinal String appSecret = queryParams.get(\"appSecret\");\n\t\t\t\t\n\t\t\t\tString oauthUrl = this.api.setAppID(appId).setAppSecret(appSecret).setRedirectURI(\"http://localhost:4000/callback\").generateOAuthUrl();\n\t\t\t\t\n\t\t\t\tresponse = (\"{\\\"url\\\": \\\"\" + oauthUrl + \"\\\"}\").getBytes();\n\t\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"application/json\");\n\t\t\t}\n\t\t\t\n\t\t\treq.getResponseHeaders().add(\"Content-Type\", \"text/html\");\n\t\t\treq.sendResponseHeaders(200, response.length);\n\t\t\treq.getResponseBody().write(response);\n\t\t\treq.getResponseBody().close();\n\t\t});\n\t\t\n\t\treturn server;\n\t}\n\t\n\tprivate Map<String, String> getQueryParameters(String query) {\n\t\tMap<String, String> queryParams = new HashMap<>();\n\t\t\n\t\tif(query != null) {\n\t\t\tString[] pairs = query.split(\"&\");\n\t\t\t\n\t\t\tfor(String pair : pairs) {\n\t\t\t\tString[] keyValue = pair.split(\"=\");\n\t\t\t\tif(keyValue.length == 2) {\n\t\t\t\t\tString key = keyValue[0];\n\t\t\t\t\tString value = keyValue[1];\n\t\t\t\t\tqueryParams.put(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn queryParams;\n\t}\n\t\n\tpublic Config getConfig() {\n\t\treturn this.config;\n\t}\n\t\n\tpublic void saveConfig() {\n\t\ttry(FileWriter writer = new FileWriter(CONFIG_FILE)) {\n\t\t\tGSON.toJson(this.config, writer);\n\t\t} catch(IOException e) {\n\t\t\tthis.logger.error(\"Failed to save config\");\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "CodeGrant",
"path": "src/main/java/me/john200410/spotify/http/responses/CodeGrant.java",
"snippet": "public class CodeGrant {\n public String access_token;\n public int expires_in;\n public String refresh_token;\n public String scope;\n public String token_type;\n}"
},
{
"identifier": "PlaybackState",
"path": "src/main/java/me/john200410/spotify/http/responses/PlaybackState.java",
"snippet": "public class PlaybackState {\n\n\tpublic Device device;\n\tpublic String repeat_state;\n\tpublic boolean shuffle_state;\n\tpublic Context context;\n\tpublic long timestamp;\n\tpublic int progress_ms;\n\tpublic boolean is_playing;\n\tpublic Item item;\n\tpublic String currently_playing_type;\n\tpublic Actions actions;\n\n\tpublic static class Device {\n\t\tpublic String id;\n\t\tpublic boolean is_active;\n\t\tpublic boolean is_private_session;\n\t\tpublic boolean is_restricted;\n\t\tpublic String name;\n\t\tpublic String type;\n\t\tpublic int volume_percent;\n\t\tpublic boolean supports_volume;\n\t}\n\n\tpublic static class Context {\n\t\tpublic String type;\n\t\tpublic String href;\n\t\tpublic ExternalUrls external_urls;\n\t\tpublic String uri;\n\n\t\tpublic static class ExternalUrls {\n\t\t\tpublic String spotify;\n\t\t}\n\t}\n\n\tpublic static class Item {\n\t\tpublic Album album;\n\t\tpublic Artist[] artists;\n\t\tpublic String[] available_markets;\n\t\tpublic int disc_number;\n\t\tpublic long duration_ms;\n\t\tpublic boolean explicit;\n\t\tpublic ExternalIds external_ids;\n\t\tpublic ExternalUrls external_urls;\n\t\tpublic String href;\n\t\tpublic String id;\n\t\tpublic String name;\n\t\tpublic int popularity;\n\t\tpublic String preview_url;\n\t\tpublic int track_number;\n\t\tpublic String type;\n\t\tpublic String uri;\n\t\tpublic boolean is_local;\n\n\t\tpublic static class Album {\n\t\t\tpublic String album_type;\n\t\t\tpublic int total_tracks;\n\t\t\tpublic String[] available_markets;\n\t\t\tpublic ExternalUrls external_urls;\n\t\t\tpublic String href;\n\t\t\tpublic String id;\n\t\t\tpublic Image[] images;\n\t\t\tpublic String name;\n\t\t\tpublic String release_date;\n\t\t\tpublic String release_date_precision;\n\t\t\tpublic String type;\n\t\t\tpublic String uri;\n\t\t\tpublic Artist[] artists;\n\n\t\t\tpublic static class Image {\n\t\t\t\tpublic String url;\n\t\t\t\tpublic int height;\n\t\t\t\tpublic int width;\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Artist {\n\t\t\tpublic ExternalUrls external_urls;\n\t\t\tpublic String href;\n\t\t\tpublic String id;\n\t\t\tpublic String name;\n\t\t\tpublic String type;\n\t\t\tpublic String uri;\n\t\t}\n\n\t\tpublic static class ExternalIds {\n\t\t\tpublic String isrc;\n\t\t}\n\n\t\tpublic static class ExternalUrls {\n\t\t\tpublic String spotify;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn this.id.hashCode();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\treturn obj instanceof Item item && item.id != null && item.id.equals(this.id);\n\t\t}\n\t}\n\n\tpublic static class Actions {\n\t\tpublic boolean interrupting_playback;\n\t\tpublic boolean pausing;\n\t\tpublic boolean resuming;\n\t\tpublic boolean seeking;\n\t\tpublic boolean skipping_next;\n\t\tpublic boolean skipping_prev;\n\t\tpublic boolean toggling_repeat_context;\n\t\tpublic boolean toggling_repeat_track;\n\t\tpublic boolean toggling_shuffle;\n\t\tpublic boolean transferring_playback;\n\t}\n}"
},
{
"identifier": "User",
"path": "src/main/java/me/john200410/spotify/http/responses/User.java",
"snippet": "public class User {\n\n public String country;\n public String display_name;\n public String email;\n public ExplicitContent explicit_content;\n public ExternalUrls external_urls;\n public Followers followers;\n public String href;\n public String id;\n public Image[] images;\n public String product;\n public String type;\n public String uri;\n\n public static class ExplicitContent {\n public boolean filter_enabled;\n public boolean filter_locked;\n }\n\n public static class ExternalUrls {\n public String spotify;\n }\n\n public static class Followers {\n public String href;\n public int total;\n }\n\n public static class Image {\n public String url;\n public int height;\n public int width;\n }\n}"
}
] | import com.google.gson.JsonSyntaxException;
import me.john200410.spotify.Config;
import me.john200410.spotify.SpotifyPlugin;
import me.john200410.spotify.http.responses.CodeGrant;
import me.john200410.spotify.http.responses.PlaybackState;
import me.john200410.spotify.http.responses.Response;
import me.john200410.spotify.http.responses.User;
import net.minecraft.Util;
import org.rusherhack.client.api.RusherHackAPI;
import org.rusherhack.core.notification.NotificationType;
import org.rusherhack.core.utils.MathUtils;
import org.rusherhack.core.utils.Timer;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors; | 2,692 | package me.john200410.spotify.http;
public class SpotifyAPI {
/**
* Constants
*/
public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
private static final String API_URL = "https://api.spotify.com";
private static final String AUTH_URL = "https://accounts.spotify.com";
/**
* Variables
*/
private final SpotifyPlugin plugin;
private boolean isConnected = false;
private boolean playbackAvailable = false; | package me.john200410.spotify.http;
public class SpotifyAPI {
/**
* Constants
*/
public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
private static final String API_URL = "https://api.spotify.com";
private static final String AUTH_URL = "https://accounts.spotify.com";
/**
* Variables
*/
private final SpotifyPlugin plugin;
private boolean isConnected = false;
private boolean playbackAvailable = false; | private PlaybackState currentStatus; | 3 | 2023-12-19 17:59:37+00:00 | 4k |
SciBorgs/Crescendo-2024 | src/main/java/org/sciborgs1155/robot/Robot.java | [
{
"identifier": "CommandRobot",
"path": "src/main/java/org/sciborgs1155/lib/CommandRobot.java",
"snippet": "public class CommandRobot extends TimedRobot {\n\n protected CommandRobot(double period) {\n super(period);\n }\n\n @Override\n public void robotPeriodic() {\n CommandScheduler.getInstance().run();\n }\n\n @Override\n public void simulationPeriodic() {}\n\n @Override\n public void disabledPeriodic() {}\n\n @Override\n public void autonomousPeriodic() {}\n\n @Override\n public void teleopPeriodic() {}\n\n @Override\n public void testPeriodic() {}\n\n @Override\n public void testInit() {\n CommandScheduler.getInstance().cancelAll();\n }\n\n public Trigger robot() {\n return new Trigger(() -> true);\n }\n\n public Trigger autonomous() {\n return new Trigger(DriverStation::isAutonomous);\n }\n\n public Trigger teleop() {\n return new Trigger(DriverStation::isTeleop);\n }\n\n public Trigger test() {\n return new Trigger(DriverStation::isTest);\n }\n\n public Trigger simulation() {\n return new Trigger(TimedRobot::isSimulation);\n }\n}"
},
{
"identifier": "Fallible",
"path": "src/main/java/org/sciborgs1155/lib/Fallible.java",
"snippet": "@FunctionalInterface\npublic interface Fallible extends Sendable {\n\n /** An individual fault, containing necessary information. */\n public static record Fault(String description, FaultType type, double timestamp) {\n public Fault(String description, FaultType type) {\n this(description, type, Timer.getFPGATimestamp());\n }\n }\n\n /**\n * The type of fault, used for detecting whether the fallible is in a failure state and displaying\n * to NetworkTables.\n */\n public static enum FaultType {\n INFO,\n WARNING,\n ERROR,\n }\n\n public static double DEFAULT_DEBOUNCE_TIME = 0.1;\n\n /**\n * Returns a list of all current faults.\n *\n * @return A list of all current faults.\n */\n public List<Fault> getFaults();\n\n /**\n * Returns whether the fallible is failing.\n *\n * @return Whether or not a fault with status {@code FaultType.ERROR} is present in {@link\n * #getFaults()}.\n */\n public default boolean isFailing() {\n for (Fault fault : getFaults()) {\n if (fault.type() == FaultType.ERROR) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Returns a trigger for when the fallible is failing.\n *\n * @return A trigger based on {@link #isFailing()}.\n */\n public default Trigger getTrigger() {\n return new Trigger(this::isFailing);\n }\n\n /**\n * Schedules a specified command when the fallible is failing.\n *\n * @param command The command to schedule.\n * @see #getTrigger()\n */\n public default void onFailing(Command command) {\n getTrigger().debounce(DEFAULT_DEBOUNCE_TIME).onTrue(command);\n }\n\n /**\n * Creates a list of a single fault from necessary information or empty list based on the provided\n * condition.\n *\n * @param description The fault's text.\n * @param type The type of fault.\n * @param condition The condition that defines failure.\n * @return Either a list of one fault or an empty list.\n */\n public default List<Fault> from(String description, FaultType type, boolean condition) {\n return condition ? List.of(new Fault(description, type)) : List.of();\n }\n\n /**\n * WIP: Returns hardware faults from a {@link CANSparkMax}.\n *\n * @param sparkMax The SparkMax.\n * @return A list of faults containing all reported REVLib errors and faults.\n */\n public default List<Fault> from(CANSparkMax sparkMax) {\n List<Fault> faults = new ArrayList<>();\n REVLibError err = sparkMax.getLastError();\n int id = sparkMax.getDeviceId();\n if (err != REVLibError.kOk) {\n faults.add(\n new Fault(String.format(\"SparkMax [%d]: Error: %s\", id, err.name()), FaultType.ERROR));\n }\n for (FaultID fault : FaultID.values()) {\n if (sparkMax.getFault(fault)) {\n faults.add(\n new Fault(\n String.format(\"SparkMax [%d]: Fault: %s\", id, fault.name()), FaultType.WARNING));\n }\n }\n return faults;\n }\n\n /**\n * Returns hardware faults from a {@link DutyCycleEncoder}.\n *\n * @param encoder The DutyCycleEncoder.\n * @return A list that is either empty or contains a fault for the encoder being disconnected.\n */\n public default List<Fault> from(DutyCycleEncoder encoder) {\n return from(\n String.format(\"DutyCycleEncoder [%d]: Disconnected\", encoder.getSourceChannel()),\n FaultType.ERROR,\n !encoder.isConnected());\n }\n\n /**\n * Merges several lists of hardware faults into one.\n *\n * <p>This makes building for {@link #getFaults()} much more ergonomic.\n *\n * @param faults A variable number of lists of faults.\n * @return A single list of faults.\n */\n @SafeVarargs\n public static List<Fault> from(List<Fault>... faults) {\n // calculate length to be allocated\n int len = 0;\n for (List<Fault> f : faults) {\n len += f.size();\n }\n\n List<Fault> allFaults = new ArrayList<>(len);\n\n for (List<Fault> f : faults) {\n allFaults.addAll(f);\n }\n\n return allFaults;\n }\n\n /**\n * Returns an array of descriptions of all faults that match the specified type.\n *\n * @param type The type to filter for.\n * @return An array of description strings.\n */\n public default String[] getStrings(FaultType type) {\n return getFaults().stream()\n .filter(a -> a.type() == type)\n .map(Fault::description)\n .toArray(String[]::new);\n }\n\n @Override\n public default void initSendable(SendableBuilder builder) {\n builder.setSmartDashboardType(\"Alerts\");\n builder.addStringArrayProperty(\"errors\", () -> getStrings(FaultType.ERROR), null);\n builder.addStringArrayProperty(\"warnings\", () -> getStrings(FaultType.WARNING), null);\n builder.addStringArrayProperty(\"infos\", () -> getStrings(FaultType.INFO), null);\n }\n}"
},
{
"identifier": "SparkUtils",
"path": "src/main/java/org/sciborgs1155/lib/SparkUtils.java",
"snippet": "public class SparkUtils {\n\n private static final ArrayList<CANSparkMax> sparks = new ArrayList<>();\n\n /**\n * Creates a brushless CANSparkMax and restores it to factory defaults.\n *\n * <p>All Spark Max should be created using this method so they can all be stored in a static\n * list.\n *\n * @param id The CAN ID of the Spark Max.\n * @return A CANSparkMax instance.\n * @see #safeBurnFlash()\n */\n public static CANSparkMax create(int id) {\n CANSparkMax spark = new CANSparkMax(id, MotorType.kBrushless);\n spark.restoreFactoryDefaults();\n sparks.add(spark);\n return spark;\n }\n\n /**\n * Burn all motor configs to flash at the same time, accounting for CAN bus delay. Use once after\n * fully configuring motors.\n */\n public static void safeBurnFlash() {\n Timer.delay(0.2);\n for (CANSparkMax spark : sparks) {\n spark.burnFlash();\n Timer.delay(0.025);\n }\n Timer.delay(0.2);\n }\n\n /**\n * Disables a list of frames for a specific motor.\n *\n * <p>For a list of specific frames and what they do, read {@href\n * https://docs.revrobotics.com/sparkmax/operating-modes/control-interfaces}.\n *\n * <p>Typically, we want to disable as many frames as possible to keep CAN bus usage low.\n * Typically, for all \"follower\" motor controllers where you do not need to access any data, you\n * should disable frames 1-6.\n *\n * @param spark\n * @param frames\n */\n public static void disableFrames(CANSparkMax spark, int... frames) {\n for (int frame : frames) {\n spark.setPeriodicFramePeriod(PeriodicFrame.fromId(frame), 65535);\n }\n }\n\n /**\n * Sets the position and velocity conversion factors of a {@link RelativeEncoder} based on the\n * supplied {@link Measure}.\n *\n * <p>The default units of a neo integrated encoder are rotations and minutes. This method\n * automatically converts a supplied ratio into the appropriate units.\n *\n * <pre>\n * encoder = driveMotor.getEncoder();\n * // Configure the encoder to return distance with a gearing of 3/2 and wheel circumference of 2 inches\n * setConversion(encoder, Rotations.of(3).divide(2).times(Inches.of(2)).per(Rotations));\n * </pre>\n *\n * @param encoder The encoder to configure.\n * @param conversion The ratio of rotations to a desired unit as an angle measure.\n */\n public static <U extends Unit<U>> void setConversion(\n RelativeEncoder encoder, Measure<Per<U, Angle>> conversion) {\n var numerator = conversion.unit().numerator();\n encoder.setPositionConversionFactor(conversion.in(numerator.per(Rotations)));\n encoder.setVelocityConversionFactor(\n conversion.per(Seconds.one()).in(numerator.per(Rotations).per(Minute)));\n }\n\n /**\n * Sets the position and velocity conversion factors of a {@link AbsoluteEncoder} based on the\n * supplied {@link Measure}.\n *\n * <p>The default units of a neo integrated encoder are rotations and minutes. This method\n * automatically converts a supplied ratio into the appropriate units.\n *\n * <pre>\n * encoder = driveMotor.getEncoder();\n * // Configure the encoder to return distance with a gearing of 3/2 and wheel circumference of 2 inches\n * setConversion(encoder, Rotations.of(3).divide(2).times(Inches.of(2)).per(Rotations));\n * </pre>\n *\n * @param encoder The encoder to configure.\n * @param conversion The ratio of rotations to a desired unit as an angle measure.\n */\n public static <U extends Unit<U>> void setConversion(\n AbsoluteEncoder encoder, Measure<Per<U, Angle>> conversion) {\n var numerator = conversion.unit().numerator();\n encoder.setPositionConversionFactor(conversion.in(numerator.per(Rotations)));\n encoder.setVelocityConversionFactor(\n conversion.per(Seconds.one()).in(numerator.per(Rotations).per(Minute)));\n }\n\n /**\n * Enables and sets the minimum and maximum bounds for input wrapping on an onboard Spark Max PID\n * controller.\n *\n * @param controller The onboard PID controller object.\n * @param min The minimum position input.\n * @param max The maximum position input.\n */\n public static void enableContinuousPIDInput(\n SparkMaxPIDController controller, double min, double max) {\n controller.setPositionPIDWrappingEnabled(true);\n controller.setPositionPIDWrappingMinInput(min);\n controller.setPositionPIDWrappingMaxInput(max);\n }\n}"
},
{
"identifier": "OI",
"path": "src/main/java/org/sciborgs1155/robot/Ports.java",
"snippet": "public static final class OI {\n public static final int OPERATOR = 0;\n public static final int DRIVER = 1;\n}"
},
{
"identifier": "Autos",
"path": "src/main/java/org/sciborgs1155/robot/commands/Autos.java",
"snippet": "public final class Autos implements Sendable {\n\n private final SendableChooser<Supplier<Command>> chooser = new SendableChooser<>();\n\n public Command get() {\n return chooser.getSelected().get();\n }\n\n @Override\n public void initSendable(SendableBuilder builder) {\n chooser.initSendable(builder);\n }\n}"
}
] | import edu.wpi.first.wpilibj.DataLogManager;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj2.command.ProxyCommand;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import java.util.List;
import monologue.Logged;
import monologue.Monologue;
import monologue.Monologue.LogBoth;
import org.sciborgs1155.lib.CommandRobot;
import org.sciborgs1155.lib.Fallible;
import org.sciborgs1155.lib.SparkUtils;
import org.sciborgs1155.robot.Ports.OI;
import org.sciborgs1155.robot.commands.Autos; | 3,300 | package org.sciborgs1155.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class Robot extends CommandRobot implements Logged, Fallible {
// INPUT DEVICES
private final CommandXboxController operator = new CommandXboxController(OI.OPERATOR);
private final CommandXboxController driver = new CommandXboxController(OI.DRIVER);
// SUBSYSTEMS
// COMMANDS | package org.sciborgs1155.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class Robot extends CommandRobot implements Logged, Fallible {
// INPUT DEVICES
private final CommandXboxController operator = new CommandXboxController(OI.OPERATOR);
private final CommandXboxController driver = new CommandXboxController(OI.DRIVER);
// SUBSYSTEMS
// COMMANDS | @LogBoth Autos autos = new Autos(); | 4 | 2023-12-19 00:56:38+00:00 | 4k |
Swofty-Developments/HypixelSkyBlock | generic/src/main/java/net/swofty/types/generic/item/set/impl/ArmorSet.java | [
{
"identifier": "ArmorSetRegistry",
"path": "generic/src/main/java/net/swofty/types/generic/item/set/ArmorSetRegistry.java",
"snippet": "@Getter\npublic enum ArmorSetRegistry {\n LEAFLET(LeafletSet.class, ItemType.LEAFLET_SANDALS, ItemType.LEAFLET_PANTS, ItemType.LEAFLET_TUNIC, ItemType.LEAFLET_HAT),\n ;\n\n private final Class<? extends ArmorSet> clazz;\n private final ItemType boots;\n private final ItemType leggings;\n private final ItemType chestplate;\n private final ItemType helmet;\n\n ArmorSetRegistry(Class<? extends ArmorSet> clazz, ItemType boots, ItemType legging,\n ItemType chestplate, ItemType helmet) {\n this.clazz = clazz;\n this.boots = boots;\n this.leggings = legging;\n this.chestplate = chestplate;\n this.helmet = helmet;\n }\n\n public static ArmorSetRegistry getArmorSet(Class<? extends ArmorSet> clazz) {\n for (ArmorSetRegistry armorSetRegistry : values()) {\n if (armorSetRegistry.getClazz() == clazz) {\n return armorSetRegistry;\n }\n }\n return null;\n }\n\n public static ArmorSetRegistry getArmorSet(ItemType item) {\n for (ArmorSetRegistry armorSetRegistry : values()) {\n if (armorSetRegistry.getBoots() == item\n || armorSetRegistry.getLeggings() == item\n || armorSetRegistry.getChestplate() == item\n || armorSetRegistry.getHelmet() == item) {\n return armorSetRegistry;\n }\n }\n return null;\n }\n\n public static ArmorSetRegistry getArmorSet(ItemType boots, ItemType leggings, ItemType chestplate, ItemType helmet) {\n for (ArmorSetRegistry armorSetRegistry : values()) {\n if (armorSetRegistry.getBoots() == boots\n && armorSetRegistry.getLeggings() == leggings\n && armorSetRegistry.getChestplate() == chestplate\n && armorSetRegistry.getHelmet() == helmet) {\n return armorSetRegistry;\n }\n }\n return null;\n }\n}"
},
{
"identifier": "SkyBlockPlayer",
"path": "generic/src/main/java/net/swofty/types/generic/user/SkyBlockPlayer.java",
"snippet": "public class SkyBlockPlayer extends Player {\n\n @Getter\n private float mana = 100;\n public float health = 100;\n public long joined;\n @Setter\n @Getter\n public boolean bypassBuild = false;\n\n @Getter\n private StatisticDisplayReplacement manaDisplayReplacement = null;\n @Getter\n private StatisticDisplayReplacement defenseDisplayReplacement = null;\n @Getter\n private StatisticDisplayReplacement coinsDisplayReplacement = null;\n @Getter\n private PlayerAbilityHandler abilityHandler = new PlayerAbilityHandler();\n @Getter\n private SkyBlockIsland skyBlockIsland;\n\n public SkyBlockPlayer(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) {\n super(uuid, username, playerConnection);\n\n joined = System.currentTimeMillis();\n }\n\n public void setSkyBlockIsland(SkyBlockIsland island) {\n this.skyBlockIsland = island;\n }\n\n public DataHandler getDataHandler() {\n return DataHandler.getUser(this.uuid);\n }\n\n public PlayerStatistics getStatistics() {\n return new PlayerStatistics(this);\n }\n\n public AntiCheatHandler getAntiCheatHandler() {\n return new AntiCheatHandler(this);\n }\n\n public LogHandler getLogHandler() {\n return new LogHandler(this);\n }\n\n public UserProfiles getProfiles() {\n return UserProfiles.get(this.getUuid());\n }\n\n public MissionData getMissionData() {\n MissionData data = getDataHandler().get(DataHandler.Data.MISSION_DATA, DatapointMissionData.class).getValue();\n data.setSkyBlockPlayer(this);\n return data;\n }\n\n public String getFullDisplayName() {\n return getDataHandler().get(DataHandler.Data.RANK, DatapointRank.class).getValue().getPrefix() + this.getUsername();\n }\n\n public PlayerShopData getShoppingData() {\n return getDataHandler().get(DataHandler.Data.SHOPPING_DATA, DatapointShopData.class).getValue();\n }\n\n public DatapointCollection.PlayerCollection getCollection() {\n return getDataHandler().get(DataHandler.Data.COLLECTION, DatapointCollection.class).getValue();\n }\n\n public boolean isOnIsland() {\n return getInstance() != null && getInstance() != SkyBlockConst.getInstanceContainer();\n }\n\n public boolean hasTalisman(Talisman talisman) {\n return getTalismans().stream().anyMatch(talisman1 -> talisman1.getClass() == talisman.getClass());\n }\n\n public List<Talisman> getTalismans() {\n return Stream.of(getAllPlayerItems())\n .filter(item -> item.getGenericInstance() instanceof Talisman)\n .map(item -> (Talisman) item.getGenericInstance()).collect(Collectors.toList());\n }\n\n public SkyBlockItem[] getAllPlayerItems() {\n return Stream.of(getInventory().getItemStacks())\n .map(SkyBlockItem::new)\n .filter(item -> item.getGenericInstance() instanceof CustomSkyBlockItem)\n .toArray(SkyBlockItem[]::new);\n }\n\n public boolean isCoop() {\n return getDataHandler().get(DataHandler.Data.IS_COOP, DatapointBoolean.class).getValue();\n }\n\n public ArmorSetRegistry getArmorSet() {\n ItemType helmet = new SkyBlockItem(getInventory().getHelmet()).getAttributeHandler().getItemTypeAsType();\n ItemType chestplate = new SkyBlockItem(getInventory().getChestplate()).getAttributeHandler().getItemTypeAsType();\n ItemType leggings = new SkyBlockItem(getInventory().getLeggings()).getAttributeHandler().getItemTypeAsType();\n ItemType boots = new SkyBlockItem(getInventory().getBoots()).getAttributeHandler().getItemTypeAsType();\n\n if (helmet == null || chestplate == null || leggings == null || boots == null) return null;\n\n return ArmorSetRegistry.getArmorSet(boots, leggings, chestplate, helmet);\n }\n\n public boolean isWearingItem(SkyBlockItem item) {\n SkyBlockItem[] armor = getArmor();\n\n for (SkyBlockItem armorItem : armor) {\n if (armorItem == null) continue;\n if (armorItem.getAttributeHandler().getItemTypeAsType() == item.getAttributeHandler().getItemTypeAsType()) {\n return true;\n }\n }\n\n return false;\n }\n\n public SkyBlockItem[] getArmor() {\n return new SkyBlockItem[]{\n new SkyBlockItem(getInventory().getHelmet()),\n new SkyBlockItem(getInventory().getChestplate()),\n new SkyBlockItem(getInventory().getLeggings()),\n new SkyBlockItem(getInventory().getBoots())\n };\n }\n\n public ProxyPlayer asProxyPlayer() {\n return new ProxyPlayer(this);\n }\n\n public void setDisplayReplacement(StatisticDisplayReplacement replacement, StatisticDisplayReplacement.DisplayType type) {\n switch (type) {\n case MANA:\n this.manaDisplayReplacement = replacement;\n break;\n case DEFENSE:\n this.defenseDisplayReplacement = replacement;\n break;\n case COINS:\n this.coinsDisplayReplacement = replacement;\n break;\n }\n\n int hashCode = replacement.hashCode();\n\n MinecraftServer.getSchedulerManager().scheduleTask(() -> {\n StatisticDisplayReplacement scheduledReplacement = switch (type) {\n case MANA -> this.manaDisplayReplacement;\n case DEFENSE -> this.defenseDisplayReplacement;\n case COINS -> this.coinsDisplayReplacement;\n };\n if (hashCode == scheduledReplacement.hashCode()) {\n switch (type) {\n case MANA -> this.manaDisplayReplacement = null;\n case DEFENSE -> this.defenseDisplayReplacement = null;\n case COINS -> this.coinsDisplayReplacement = null;\n }\n }\n }, TaskSchedule.tick(replacement.getTicksToLast()), TaskSchedule.stop());\n }\n\n public SkyBlockItem updateItem(PlayerItemOrigin origin, Consumer<SkyBlockItem> update) {\n ItemStack toUpdate = origin.getStack(this);\n if (toUpdate == null) return null;\n\n SkyBlockItem item = new SkyBlockItem(toUpdate);\n update.accept(item);\n\n origin.setStack(this, PlayerItemUpdater.playerUpdate(this, item.getItemStack()).build());\n return item;\n }\n\n public SkyBlockRegion getRegion() {\n if (isOnIsland()) {\n return SkyBlockRegion.getIslandRegion();\n }\n\n return SkyBlockRegion.getRegionOfPosition(this.getPosition());\n }\n\n public void setMana(float mana) {\n this.mana = mana;\n }\n\n public void addAndUpdateItem(SkyBlockItem item) {\n ItemStack toAdd = PlayerItemUpdater.playerUpdate(this, item.getItemStack()).build();\n this.getInventory().addItemStack(toAdd);\n }\n\n public void addAndUpdateItem(ItemStack item) {\n addAndUpdateItem(new SkyBlockItem(item));\n }\n\n public float getMaxMana() {\n return (float) (100 + getStatistics().allStatistics().get(ItemStatistic.INTELLIGENCE));\n }\n\n public int getMiningSpeed() {\n return this.getStatistics().allStatistics().get(ItemStatistic.MINING_SPEED);\n }\n\n public void sendTo(ServerType type) {\n sendTo(type, false);\n }\n\n public void sendTo(ServerType type, boolean force) {\n ProxyPlayer player = asProxyPlayer();\n\n if (type == SkyBlockConst.getTypeLoader().getType() && !force) {\n this.teleport(SkyBlockConst.getTypeLoader().getLoaderValues().spawnPosition());\n return;\n }\n\n player.transferTo(type);\n }\n\n public double getTimeToMine(SkyBlockItem item, Block b) {\n MineableBlock block = MineableBlock.get(b);\n if (block == null) return -1;\n if (!item.getAttributeHandler().isMiningTool()) return -1;\n if (getRegion() == null) return -1;\n\n if (block.getMiningPowerRequirement() > item.getAttributeHandler().getBreakingPower()) return -1;\n if (block.getStrength() > 0) {\n double time = (block.getStrength() * 30) / (Math.max(getMiningSpeed(), 1));\n ValueUpdateEvent event = new MiningValueUpdateEvent(\n this,\n time,\n item);\n\n SkyBlockValueEvent.callValueUpdateEvent(event);\n time = (double) event.getValue();\n\n double softcap = ((double) 20 / 3) * block.getStrength();\n if (time < 1)\n return 1;\n\n return Math.min(time, softcap);\n }\n\n return 0;\n }\n\n public float getDefense() {\n float defence = 0;\n\n PlayerStatistics statistics = this.getStatistics();\n defence += statistics.allStatistics().get(ItemStatistic.DEFENSE);\n\n return defence;\n }\n\n public void playSuccessSound() {\n playSound(Sound.sound(Key.key(\"block.note_block.pling\"), Sound.Source.PLAYER, 1.0f, 2.0f));\n }\n\n @Override\n public void kill() {\n setHealth(getMaxHealth());\n sendTo(SkyBlockConst.getTypeLoader().getType());\n\n DeathMessageCreator creator = new DeathMessageCreator(lastDamageSource);\n\n sendMessage(\"ยงcโ ยง7You \" + creator.createPersonal());\n\n DatapointDouble coins = getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class);\n coins.setValue(coins.getValue() / 2);\n\n playSound(Sound.sound(Key.key(\"block.anvil.fall\"), Sound.Source.PLAYER, 1.0f, 2.0f));\n\n sendMessage(\"ยงcYou died and lost \" + StringUtility.commaify(coins.getValue()) + \" coins!\");\n\n if (!SkyBlockConst.getTypeLoader().getLoaderValues().announceDeathMessages()) return;\n\n SkyBlockGenericLoader.getLoadedPlayers().forEach(player -> {\n if (player.getUuid().equals(getUuid())) return;\n if (player.getInstance() != getInstance()) return;\n\n player.sendMessage(\"ยงcโ ยง7\" + getFullDisplayName() + \" ยง7\" + creator.createOther());\n });\n }\n\n @Override\n public float getMaxHealth() {\n PlayerStatistics statistics = this.getStatistics();\n return statistics.allStatistics().get(ItemStatistic.HEALTH);\n }\n\n @Override\n public float getHealth() {\n return this.health;\n }\n\n @Override\n public void setHealth(float health) {\n if ((System.currentTimeMillis() - joined) < 3000)\n return;\n if (health < 0) {\n kill();\n return;\n }\n this.health = health;\n this.sendPacket(new UpdateHealthPacket((health / getMaxHealth()) * 20, 20, 20));\n }\n\n @Override\n public void sendMessage(@NotNull String message) {\n super.sendMessage(message.replace(\"&\", \"ยง\"));\n }\n\n @Override\n public void closeInventory() {\n Inventory tempInv = this.getOpenInventory();\n super.closeInventory();\n if (SkyBlockInventoryGUI.GUI_MAP.containsKey(this.getUuid())) {\n SkyBlockInventoryGUI gui = SkyBlockInventoryGUI.GUI_MAP.get(this.getUuid());\n\n if (gui == null) return;\n\n gui.onClose(new InventoryCloseEvent(tempInv, this), SkyBlockInventoryGUI.CloseReason.SERVER_EXITED);\n SkyBlockInventoryGUI.GUI_MAP.remove(this.getUuid());\n }\n }\n\n public static String getDisplayName(UUID uuid) {\n if (SkyBlockGenericLoader.getLoadedPlayers().stream().anyMatch(player -> player.getUuid().equals(uuid))) {\n return SkyBlockGenericLoader.getLoadedPlayers().stream().filter(player -> player.getUuid().equals(uuid)).findFirst().get().getFullDisplayName();\n } else {\n UserProfiles profiles = new UserDatabase(uuid).getProfiles();\n UUID selected = profiles.getProfiles().get(0);\n\n if (selected == null) {\n return \"ยง7Unknown\";\n } else {\n DataHandler handler = DataHandler.fromDocument(new ProfilesDatabase(selected.toString()).getDocument());\n return handler.get(DataHandler.Data.RANK, DatapointRank.class).getValue().getPrefix() +\n handler.get(DataHandler.Data.IGN, DatapointString.class).getValue();\n }\n }\n }\n}"
}
] | import net.swofty.types.generic.SkyBlockGenericLoader;
import net.swofty.types.generic.item.set.ArmorSetRegistry;
import net.swofty.types.generic.user.SkyBlockPlayer;
import java.util.ArrayList;
import java.util.List; | 3,583 | package net.swofty.types.generic.item.set.impl;
public interface ArmorSet {
String getName();
String getDescription();
default boolean isWearingSet(SkyBlockPlayer player) { | package net.swofty.types.generic.item.set.impl;
public interface ArmorSet {
String getName();
String getDescription();
default boolean isWearingSet(SkyBlockPlayer player) { | return player.getArmorSet() != null && player.getArmorSet().equals(ArmorSetRegistry.getArmorSet(this.getClass())); | 0 | 2023-12-14 09:51:15+00:00 | 4k |
refutix/refutix | refutix-server/src/main/java/org/refutix/refutix/server/controller/TableController.java | [
{
"identifier": "TableDTO",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/dto/TableDTO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TableDTO {\n\n private Integer catalogId;\n\n private String catalogName;\n\n private String databaseName;\n\n private String name;\n\n private String description;\n\n private List<TableColumn> tableColumns;\n\n private List<String> partitionKey;\n\n private Map<String, String> tableOptions;\n}"
},
{
"identifier": "AlterTableRequest",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/model/AlterTableRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AlterTableRequest {\n\n private TableColumn oldColumn;\n\n private TableColumn newColumn;\n}"
},
{
"identifier": "R",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/result/R.java",
"snippet": "@Data\npublic class R<T> {\n /** result code. */\n private final int code;\n /** result msg. */\n private final String msg;\n /** result data. */\n private final T data;\n\n public R(\n @JsonProperty(\"code\") int code,\n @JsonProperty(\"msg\") String msg,\n @JsonProperty(\"data\") T data) {\n this.code = code;\n this.msg = msg;\n this.data = data;\n }\n\n public static <T> R<T> of(T data, int code, String msg) {\n return new R<>(code, msg, data);\n }\n\n public static <T> R<T> of(T data, int code, Status status) {\n return new R<>(code, status.getMsg(), data);\n }\n\n public static <T> R<T> succeed() {\n return of(null, Status.SUCCESS.getCode(), MessageUtils.getMsg(Status.SUCCESS.getMsg()));\n }\n\n public static <T> R<T> succeed(T data) {\n return of(data, Status.SUCCESS.getCode(), MessageUtils.getMsg(Status.SUCCESS.getMsg()));\n }\n\n public static <T> R<T> failed() {\n return of(null, Status.FAILED.getCode(), Status.FAILED.getMsg());\n }\n\n public static <T> R<T> failed(Status status) {\n return of(null, status.getCode(), MessageUtils.getMsg(status.getMsg()));\n }\n\n public static <T> R<T> failed(Status status, Object... args) {\n return of(null, status.getCode(), MessageUtils.getMsg(status.getMsg(), args));\n }\n\n public static <T> R<T> failed(T data) {\n return of(data, Status.FAILED.getCode(), MessageUtils.getMsg(Status.FAILED.getMsg()));\n }\n}"
},
{
"identifier": "Status",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/result/enums/Status.java",
"snippet": "public enum Status {\n /** response data msg. */\n SUCCESS(200, \"successfully\"),\n FAILED(400, \"failed\"),\n UNAUTHORIZED(401, \"unauthorized\"),\n FORBIDDEN(403, \"forbidden\"),\n METHOD_NOT_ALLOWED(405, \"method.not.allowed\"),\n\n // TODO\n UNKNOWN_ERROR(500, \"unknown.error\"),\n INTERNAL_SERVER_ERROR_ARGS(501, \"internal.server.error\"),\n\n REQUEST_PARAMS_NOT_VALID_ERROR(4001, \"invalid.request.parameter\"),\n REQUEST_PARAMS_ERROR(4002, \"request.parameter.error\"),\n\n USER_NOT_EXIST(10001, \"user.not.exist\"),\n USER_PASSWORD_ERROR(10002, \"user.password.error\"),\n USER_DISABLED_ERROR(10003, \"user.is.disabled\"),\n USER_NOT_BING_TENANT(10004, \"user.not.bing.tenant\"),\n /** ------------role-----------------. */\n ROLE_IN_USED(10101, \"role.in.used\"),\n ROLE_NAME_IS_EXIST(10102, \"role.name.exist\"),\n ROLE_KEY_IS_EXIST(10103, \"role.key.exist\"),\n /** ------------menu-----------------. */\n MENU_IN_USED(10201, \"menu.in.used\"),\n MENU_NAME_IS_EXIST(10202, \"menu.name.exist\"),\n MENU_PATH_INVALID(10203, \"menu.path.invalid\"),\n\n /** ------------catalog-----------------. */\n CATALOG_NAME_IS_EXIST(10301, \"catalog.name.exist\"),\n CATALOG_CREATE_ERROR(10302, \"catalog.create.error\"),\n CATALOG_REMOVE_ERROR(10303, \"catalog.remove.error\"),\n CATALOG_NOT_EXIST(10304, \"catalog.not.exists\"),\n\n /** ------------database-----------------. */\n DATABASE_NAME_IS_EXIST(10401, \"database.name.exist\"),\n DATABASE_CREATE_ERROR(10402, \"database.create.error\"),\n DATABASE_DROP_ERROR(10403, \"database.drop.error\"),\n\n /** ------------table-----------------. */\n TABLE_NAME_IS_EXIST(10501, \"table.name.exist\"),\n TABLE_CREATE_ERROR(10502, \"table.create.error\"),\n TABLE_ADD_COLUMN_ERROR(10503, \"table.add.column.error\"),\n TABLE_ADD_OPTION_ERROR(10504, \"table.add.option.error\"),\n TABLE_REMOVE_OPTION_ERROR(10505, \"table.remove.option.error\"),\n TABLE_DROP_COLUMN_ERROR(10506, \"table.drop.column.error\"),\n TABLE_AlTER_COLUMN_ERROR(10507, \"table.alter.column.error\"),\n TABLE_DROP_ERROR(10510, \"table.drop.error\"),\n TABLE_RENAME_ERROR(10510, \"table.rename.error\");\n\n private final int code;\n private final String msg;\n\n Status(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n public int getCode() {\n return this.code;\n }\n\n public String getMsg() {\n return this.msg;\n }\n}"
},
{
"identifier": "TableVO",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/vo/TableVO.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TableVO {\n\n private Integer catalogId;\n\n private String catalogName;\n\n private String databaseName;\n\n private String name;\n}"
},
{
"identifier": "TableService",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/service/TableService.java",
"snippet": "public interface TableService {\n\n /**\n * Creates a table in the database given ${@link TableDTO}.\n *\n * @param tableDTO The TableDTO object containing information about the table.\n * @return R<Void/> indicating the success or failure of the operation.\n */\n R<Void> createTable(TableDTO tableDTO);\n\n /**\n * Adds a column to the table.\n *\n * @param tableDTO The information of the table, including the catalog name, database name,\n * table name, and table columns.\n * @return A response indicating the success or failure of the operation.\n */\n R<Void> addColumn(TableDTO tableDTO);\n\n /**\n * Drops a column from a table.\n *\n * @param catalogName The name of the catalog.\n * @param databaseName The name of the database.\n * @param tableName The name of the table.\n * @param columnName The name of the column to be dropped.\n * @return The result indicating the success or failure of the operation.\n */\n R<Void> dropColumn(\n String catalogName, String databaseName, String tableName, String columnName);\n\n /**\n * Alters a table.\n *\n * @param catalogName The name of the catalog.\n * @param databaseName The name of the database.\n * @param tableName The name of the table.\n * @param alterTableRequest The param of the alter table request.\n * @return A response indicating the success or failure of the operation.\n */\n R<Void> alterTable(\n String catalogName,\n String databaseName,\n String tableName,\n AlterTableRequest alterTableRequest);\n\n /**\n * Adds options to a table.\n *\n * @param tableDTO An object containing table information.\n * @return If the options are successfully added, returns a successful result object. If an\n * exception occurs, returns a result object with an error status.\n */\n R<Void> addOption(TableDTO tableDTO);\n\n /**\n * Removes an option from a table.\n *\n * @param catalogName The name of the catalog.\n * @param databaseName The name of the database.\n * @param tableName The name of the table.\n * @param key The key of the option to be removed.\n * @return Returns a {@link R} object indicating the success or failure of the operation. If the\n * option is successfully removed, the result will be a successful response with no data. If\n * an error occurs during the operation, the result will be a failed response with an error\n * code. Possible error codes: {@link Status#TABLE_REMOVE_OPTION_ERROR}.\n */\n R<Void> removeOption(String catalogName, String databaseName, String tableName, String key);\n\n /**\n * Drops a table from the specified database in the given catalog.\n *\n * @param catalogName The name of the catalog from which the table will be dropped.\n * @param databaseName The name of the database from which the table will be dropped.\n * @param tableName The name of the table to be dropped.\n * @return A Response object indicating the success or failure of the operation. If the\n * operation is successful, the response will be R.succeed(). If the operation fails, the\n * response will be R.failed() with Status.TABLE_DROP_ERROR.\n * @throws RuntimeException If there is an error during the operation, a RuntimeException is\n * thrown with the error message.\n */\n R<Void> dropTable(String catalogName, String databaseName, String tableName);\n\n /**\n * Renames a table in the specified database of the given catalog.\n *\n * @param catalogName The name of the catalog where the table resides.\n * @param databaseName The name of the database where the table resides.\n * @param fromTableName The current name of the table to be renamed.\n * @param toTableName The new name for the table.\n * @return A Response object indicating the success or failure of the operation. If the\n * operation is successful, the response will be R.succeed(). If the operation fails, the\n * response will be R.failed() with Status.TABLE_RENAME_ERROR.\n * @throws RuntimeException If there is an error during the operation, a RuntimeException is\n * thrown with the error message.\n */\n R<Void> renameTable(\n String catalogName, String databaseName, String fromTableName, String toTableName);\n\n /**\n * Lists tables given {@link TableDTO} condition.\n *\n * @return Response object containing a list of {@link TableVO} representing the tables.\n */\n List<TableVO> listTables(TableDTO tableDTO);\n}"
}
] | import lombok.extern.slf4j.Slf4j;
import org.refutix.refutix.server.data.dto.TableDTO;
import org.refutix.refutix.server.data.model.AlterTableRequest;
import org.refutix.refutix.server.data.result.R;
import org.refutix.refutix.server.data.result.enums.Status;
import org.refutix.refutix.server.data.vo.TableVO;
import org.refutix.refutix.server.service.TableService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors; | 3,425 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.refutix.refutix.server.controller;
/** Table api controller. */
@Slf4j
@RestController
@RequestMapping("/api/table")
public class TableController {
private final TableService tableService;
public TableController(TableService tableService) {
this.tableService = tableService;
}
/**
* Creates a table in the database based on the provided TableInfo.
*
* @param tableDTO The TableDTO object containing information about the table.
* @return R<Void/> indicating the success or failure of the operation.
*/
@PostMapping("/create")
public R<Void> createTable(@RequestBody TableDTO tableDTO) {
return tableService.createTable(tableDTO);
}
/**
* Adds a column to the table.
*
* @param tableDTO The information of the table, including the catalog name, database name,
* table name, and table columns.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/column/add")
public R<Void> addColumn(@RequestBody TableDTO tableDTO) {
return tableService.addColumn(tableDTO);
}
/**
* Drops a column from a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param columnName The name of the column to be dropped.
* @return The result indicating the success or failure of the operation.
*/
@DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}")
public R<Void> dropColumn(
@PathVariable String catalogName,
@PathVariable String databaseName,
@PathVariable String tableName,
@PathVariable String columnName) {
return tableService.dropColumn(catalogName, databaseName, tableName, columnName);
}
/**
* Modify a column in a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param alterTableRequest The param of the alter table request.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/alter")
public R<Void> alterTable(
@RequestParam String catalogName,
@RequestParam String databaseName,
@RequestParam String tableName, | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.refutix.refutix.server.controller;
/** Table api controller. */
@Slf4j
@RestController
@RequestMapping("/api/table")
public class TableController {
private final TableService tableService;
public TableController(TableService tableService) {
this.tableService = tableService;
}
/**
* Creates a table in the database based on the provided TableInfo.
*
* @param tableDTO The TableDTO object containing information about the table.
* @return R<Void/> indicating the success or failure of the operation.
*/
@PostMapping("/create")
public R<Void> createTable(@RequestBody TableDTO tableDTO) {
return tableService.createTable(tableDTO);
}
/**
* Adds a column to the table.
*
* @param tableDTO The information of the table, including the catalog name, database name,
* table name, and table columns.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/column/add")
public R<Void> addColumn(@RequestBody TableDTO tableDTO) {
return tableService.addColumn(tableDTO);
}
/**
* Drops a column from a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param columnName The name of the column to be dropped.
* @return The result indicating the success or failure of the operation.
*/
@DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}")
public R<Void> dropColumn(
@PathVariable String catalogName,
@PathVariable String databaseName,
@PathVariable String tableName,
@PathVariable String columnName) {
return tableService.dropColumn(catalogName, databaseName, tableName, columnName);
}
/**
* Modify a column in a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param alterTableRequest The param of the alter table request.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/alter")
public R<Void> alterTable(
@RequestParam String catalogName,
@RequestParam String databaseName,
@RequestParam String tableName, | @RequestBody AlterTableRequest alterTableRequest) { | 1 | 2023-12-21 03:39:07+00:00 | 4k |
Tianscar/uxgl | desktop/src/main/java/unrefined/runtime/DesktopConsole.java | [
{
"identifier": "ConsoleSignal",
"path": "desktop/src/main/java/unrefined/desktop/ConsoleSignal.java",
"snippet": "public final class ConsoleSignal {\n\n private ConsoleSignal() {\n throw new NotInstantiableError(ConsoleSignal.class);\n }\n\n private static final Set<Handler> CONSOLE_SIGNAL_HANDLERS = new ConcurrentHashSet<>();\n\n private static final SignalHandler NATIVE_HANDLER = sig -> {\n synchronized (CONSOLE_SIGNAL_HANDLERS) {\n for (Handler handler : CONSOLE_SIGNAL_HANDLERS) {\n handler.handle(\"SIG\" + sig.getName(), sig.getNumber());\n }\n }\n };\n\n public static void addConsoleSignalHandler(Handler handler) {\n CONSOLE_SIGNAL_HANDLERS.add(handler);\n }\n\n public static void removeConsoleSignalHandler(Handler handler) {\n CONSOLE_SIGNAL_HANDLERS.remove(handler);\n }\n\n public static void clearConsoleSignalHandlers() {\n CONSOLE_SIGNAL_HANDLERS.clear();\n }\n\n private static final Map<String, Signal> SIGNALS = new HashMap<>();\n\n private static void handle0(String signal, SignalHandler handler) throws SignalNotFoundException, AlreadyUsedException {\n Objects.requireNonNull(signal);\n signal = signal.toUpperCase(Locale.ENGLISH);\n if (signal.startsWith(\"SIG\")) signal = signal.substring(3);\n synchronized (SIGNALS) {\n if (!SIGNALS.containsKey(signal)) {\n final Signal sig;\n try {\n sig = new Signal(signal);\n }\n catch (IllegalArgumentException e) {\n if (!signal.startsWith(\"SIG\")) signal = \"SIG\" + signal;\n throw new SignalNotFoundException(signal);\n }\n SIGNALS.put(signal, sig);\n try {\n Signal.handle(sig, handler);\n }\n catch (IllegalArgumentException e) {\n if (!signal.startsWith(\"SIG\")) signal = \"SIG\" + signal;\n throw new AlreadyUsedException(\"Signal already used by VM or OS: \" + signal + \" (\" + sig.getNumber() + \")\");\n }\n }\n }\n }\n\n public static void handle(String signal) throws AlreadyUsedException, SignalNotFoundException {\n handle0(signal, NATIVE_HANDLER);\n }\n\n public static void reset(String signal) throws AlreadyUsedException, SignalNotFoundException {\n handle0(signal, SignalHandler.SIG_DFL);\n }\n\n public static void ignore(String signal) throws AlreadyUsedException, SignalNotFoundException {\n handle0(signal, SignalHandler.SIG_IGN);\n }\n\n public static void raise(String signal) throws UnhandledSignalException {\n Objects.requireNonNull(signal);\n signal = signal.toUpperCase(Locale.ENGLISH);\n if (signal.startsWith(\"SIG\")) signal = signal.substring(3);\n synchronized (SIGNALS) {\n Signal sig = SIGNALS.get(signal);\n if (sig == null) {\n if (!signal.startsWith(\"SIG\")) signal = \"SIG\" + signal;\n throw new UnhandledSignalException(signal);\n }\n else {\n try {\n Signal.raise(sig);\n }\n catch (IllegalArgumentException e) {\n if (!signal.startsWith(\"SIG\")) signal = \"SIG\" + signal;\n throw new UnhandledSignalException(signal);\n }\n }\n }\n }\n\n public interface Handler {\n void handle(String signal, int identifier);\n }\n\n}"
},
{
"identifier": "AlreadyUsedException",
"path": "base/src/main/java/unrefined/io/AlreadyUsedException.java",
"snippet": "public class AlreadyUsedException extends IOException {\n\n private static final long serialVersionUID = 9126243530325685788L;\n\n public AlreadyUsedException() {\n super(\"Already used\");\n }\n\n public AlreadyUsedException(String message) {\n super(message);\n }\n\n public AlreadyUsedException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public AlreadyUsedException(Throwable cause) {\n super(cause);\n }\n \n}"
},
{
"identifier": "Console",
"path": "base/src/main/java/unrefined/io/console/Console.java",
"snippet": "public abstract class Console {\n\n private static volatile Console INSTANCE;\n private static final Object INSTANCE_LOCK = new Object();\n public static Console getInstance() {\n if (INSTANCE == null) synchronized (INSTANCE_LOCK) {\n if (INSTANCE == null) INSTANCE = Environment.global().get(\"unrefined.runtime.console\", Console.class);\n }\n return INSTANCE;\n }\n\n private final Signal<EventSlot<SignalEvent>> onSignal = Signal.ofSlot();\n public Signal<EventSlot<SignalEvent>> onSignal() {\n return onSignal;\n }\n\n public abstract void handle(String signal) throws AlreadyUsedException, SignalNotFoundException;\n public abstract void ignore(String signal) throws AlreadyUsedException, SignalNotFoundException;\n public abstract void reset(String signal) throws AlreadyUsedException, SignalNotFoundException;\n public abstract void raise(String signal) throws UnhandledSignalException;\n\n public InputStream stdin() {\n return System.in;\n }\n\n private static final ConsoleStream stdout = new ConsoleStream(FileDescriptor.out);\n\n public ConsoleStream stdout() {\n return stdout;\n }\n\n private static final ConsoleStream stderr = new ConsoleStream(FileDescriptor.err);\n\n public ConsoleStream stderr() {\n return stderr;\n }\n\n public static class SignalEvent extends Event<Console> {\n private final String signal;\n private final int identifier;\n public SignalEvent(Console source, String signal, int identifier) {\n super(source);\n this.signal = Objects.requireNonNull(signal);\n this.identifier = identifier;\n }\n public String getSignal() {\n return signal;\n }\n public int getIdentifier() {\n return identifier;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n\n SignalEvent that = (SignalEvent) o;\n\n if (identifier != that.identifier) return false;\n return signal.equals(that.signal);\n }\n\n @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + signal.hashCode();\n result = 31 * result + identifier;\n return result;\n }\n\n @Override\n public String toString() {\n return getClass().getName()\n + '{' +\n \"signal='\" + signal + '\\'' +\n \", identifier=\" + identifier +\n '}';\n }\n\n }\n\n}"
},
{
"identifier": "SignalNotFoundException",
"path": "base/src/main/java/unrefined/io/console/SignalNotFoundException.java",
"snippet": "public class SignalNotFoundException extends IOException {\n\n private static final long serialVersionUID = 1940230514032183183L;\n\n public SignalNotFoundException(String signal) {\n super(signal);\n }\n \n}"
},
{
"identifier": "UnhandledSignalException",
"path": "base/src/main/java/unrefined/io/console/UnhandledSignalException.java",
"snippet": "public class UnhandledSignalException extends IOException {\n\n private static final long serialVersionUID = 6590459242474420065L;\n\n public UnhandledSignalException(String signal) {\n super(signal);\n }\n \n}"
}
] | import unrefined.desktop.ConsoleSignal;
import unrefined.io.AlreadyUsedException;
import unrefined.io.console.Console;
import unrefined.io.console.SignalNotFoundException;
import unrefined.io.console.UnhandledSignalException; | 1,723 | package unrefined.runtime;
public class DesktopConsole extends Console {
public DesktopConsole() { | package unrefined.runtime;
public class DesktopConsole extends Console {
public DesktopConsole() { | ConsoleSignal.addConsoleSignalHandler((signal, identifier) -> | 0 | 2023-12-15 19:03:31+00:00 | 4k |
jlokitha/layered-architecture-jlokitha | src/main/java/lk/jl/layeredarchitecture/controller/PlaceOrderFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/lk/jl/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private static BOFactory boFactory;\n\n private BOFactory() {\n\n }\n\n public static BOFactory getBoFactory() {\n return (boFactory == null) ? boFactory = new BOFactory() : boFactory;\n }\n\n public enum BOType {\n CUSTOMER,ITEM,PLACE_ORDER,MAIN\n }\n\n public SuperBO getBO(BOType boType) {\n switch (boType) {\n case CUSTOMER:\n return new CustomerBOImpl();\n case ITEM:\n return new ItemBOImpl();\n case PLACE_ORDER:\n return new PlaceOrderBOImpl();\n case MAIN:\n return new MainBOImpl();\n default:\n return null;\n }\n }\n}"
},
{
"identifier": "PlaceOrderBO",
"path": "src/main/java/lk/jl/layeredarchitecture/bo/custom/PlaceOrderBO.java",
"snippet": "public interface PlaceOrderBO extends SuperBO {\n boolean saveOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException;\n ItemDTO searchItem(String newItemCode) throws SQLException, ClassNotFoundException;\n CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException;\n boolean isExistsItem(String id) throws SQLException, ClassNotFoundException;\n boolean isExistsCustomer(String id) throws SQLException, ClassNotFoundException;\n String generateNewOrderId() throws SQLException, ClassNotFoundException;\n ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException;\n ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/lk/jl/layeredarchitecture/dto/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/lk/jl/layeredarchitecture/dto/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private int qtyOnHand;\n private BigDecimal unitPrice;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, int qtyOnHand, BigDecimal unitPrice) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "OrderDetailDTO",
"path": "src/main/java/lk/jl/layeredarchitecture/dto/OrderDetailDTO.java",
"snippet": "public class OrderDetailDTO implements Serializable {\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public OrderDetailDTO() {\n }\n\n public OrderDetailDTO(String itemCode, int qty, BigDecimal unitPrice) {\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailDTO{\" +\n \"itemCode='\" + itemCode + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n '}';\n }\n}"
},
{
"identifier": "OrderDetailTM",
"path": "src/main/java/lk/jl/layeredarchitecture/view/tdm/OrderDetailTM.java",
"snippet": "public class OrderDetailTM{\n private String code;\n private String description;\n private int qty;\n private BigDecimal unitPrice;\n private BigDecimal total;\n\n public OrderDetailTM() {\n }\n\n public OrderDetailTM(String code, String description, int qty, BigDecimal unitPrice, BigDecimal total) {\n this.code = code;\n this.description = description;\n this.qty = qty;\n this.unitPrice = unitPrice;\n this.total = total;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public BigDecimal getTotal() {\n return total;\n }\n\n public void setTotal(BigDecimal total) {\n this.total = total;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n \", total=\" + total +\n '}';\n }\n}"
}
] | import lk.jl.layeredarchitecture.bo.BOFactory;
import lk.jl.layeredarchitecture.bo.custom.PlaceOrderBO;
import lk.jl.layeredarchitecture.dto.CustomerDTO;
import lk.jl.layeredarchitecture.dto.ItemDTO;
import lk.jl.layeredarchitecture.dto.OrderDetailDTO;
import lk.jl.layeredarchitecture.view.tdm.OrderDetailTM;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 2,099 | package lk.jl.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId; | package lk.jl.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId; | PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBoFactory().getBO( BOFactory.BOType.PLACE_ORDER ); | 1 | 2023-12-16 04:21:58+00:00 | 4k |
lemonguge/autogen4j | src/test/java/cn/homj/autogen4j/GroupChatManagerTest.java | [
{
"identifier": "Client",
"path": "src/main/java/cn/homj/autogen4j/support/Client.java",
"snippet": "public class Client {\n /**\n * application/json\n */\n private static final MediaType APPLICATION_JSON = MediaType.parse(\"application/json\");\n /**\n * OpenAI API\n */\n private static final String OPEN_AI_URL = \"https://api.openai.com/v1\";\n /**\n * Create chat completion\n */\n private static final String COMPLETION_URL = OPEN_AI_URL + \"/chat/completions\";\n /**\n * DashScope API\n */\n private static final String DASH_SCOPE_URL = \"https://dashscope.aliyuncs.com/api/v1/services\";\n /**\n * ้ไนๅ้ฎ\n */\n private static final String QIAN_WEN_URL = DASH_SCOPE_URL + \"/aigc/text-generation/generation\";\n /**\n * ้็จๆๆฌๅ้\n */\n private static final String EMBEDDING_URL = DASH_SCOPE_URL + \"/embeddings/text-embedding/text-embedding\";\n /**\n * Http Client\n */\n @Getter\n private final OkHttpClient client;\n @Setter\n @Getter\n private String qianWenUrl = QIAN_WEN_URL;\n @Setter\n @Getter\n private String embeddingUrl = EMBEDDING_URL;\n @Setter\n @Getter\n private String completionUrl = COMPLETION_URL;\n\n public Client() {\n this(new OkHttpClient.Builder().readTimeout(15, TimeUnit.SECONDS).build());\n }\n\n public Client(OkHttpClient client) {\n this.client = client;\n }\n\n private static void put(Map<String, Object> map, String key, Object value) {\n if (value == null) {\n return;\n }\n if (value instanceof Map) {\n if (!((Map<?, ?>)value).isEmpty()) {\n map.put(key, value);\n }\n } else if (value instanceof Collection) {\n if (!((Collection<?>)value).isEmpty()) {\n map.put(key, value);\n }\n } else {\n map.put(key, value);\n }\n }\n\n private static Request postRequest(GenerationRequest request, Builder builder) {\n Map<String, Object> input = new HashMap<>();\n put(input, \"messages\", request.getMessages());\n\n Map<String, Object> parameters = new HashMap<>();\n put(parameters, \"incremental_output\", request.getIncrementalOutput());\n put(parameters, \"enable_search\", request.getEnableSearch());\n put(parameters, \"result_format\", request.getResultFormat());\n put(parameters, \"temperature\", request.getTemperature());\n put(parameters, \"top_p\", request.getTopP());\n put(parameters, \"top_k\", request.getTopK());\n put(parameters, \"seed\", request.getSeed());\n put(parameters, \"stop\", request.getStop());\n\n Map<String, Object> data = new HashMap<>();\n put(data, \"model\", request.getModel());\n put(data, \"input\", input);\n put(data, \"parameters\", parameters);\n return builder.post(RequestBody.create(JSON.toJSONString(data), APPLICATION_JSON)).build();\n }\n\n /**\n * ๆตๅผ่พๅบ\n *\n * @param apiKey\n * @param request\n * @param listener\n */\n public void stream(String apiKey, GenerationRequest request, EventSourceListener listener) {\n Builder builder = new Builder().url(qianWenUrl)\n .addHeader(\"Accept\", \"text/event-stream\")\n .addHeader(\"Content-Type\", \"application/json\")\n .addHeader(\"Authorization\", \"Bearer \" + apiKey);\n EventSources.createFactory(client)\n .newEventSource(postRequest(request, builder), listener);\n }\n\n /**\n * ๆง่ก่ฏทๆฑ\n *\n * @param apiKey\n * @param request\n * @return\n */\n public GenerationResponse generate(String apiKey, GenerationRequest request) {\n Request.Builder builder = new Builder().url(qianWenUrl)\n .addHeader(\"Accept\", \"application/json\")\n .addHeader(\"Content-Type\", \"application/json\")\n .addHeader(\"Authorization\", \"Bearer \" + apiKey);\n return execute(postRequest(request, builder), GenerationResponse.class);\n }\n\n /**\n * ๆง่ก่ฏทๆฑ\n *\n * @param apiKey\n * @param request\n * @return\n */\n public EmbeddingResponse embed(String apiKey, EmbeddingRequest request) {\n Map<String, Object> data = new HashMap<>();\n data.put(\"model\", request.getModel());\n data.put(\"input\", singletonMap(\"texts\", request.getTexts()));\n data.put(\"parameters\", singletonMap(\"text_type\", request.getTextType()));\n Request r = new Builder().url(embeddingUrl)\n .addHeader(\"Accept\", \"application/json\")\n .addHeader(\"Content-Type\", \"application/json\")\n .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .post(RequestBody.create(JSON.toJSONString(data), APPLICATION_JSON)).build();\n return execute(r, EmbeddingResponse.class);\n }\n\n private <T extends ErrorResponse> T execute(Request request, Class<T> clazz) {\n try (Response response = client.newCall(request).execute()) {\n if (response.code() == 200) {\n ResponseBody body = response.body();\n if (body == null) {\n return clazz.newInstance();\n }\n return JSON.parseObject(body.string(), clazz);\n }\n ResponseBody body = response.body();\n if (body == null) {\n T unknown = clazz.newInstance();\n unknown.setErrorCode(\"Unknown\");\n return unknown;\n }\n String s = response.header(\"Content-Type\");\n if (s != null && s.toLowerCase().contains(\"application/json\")) {\n return JSON.parseObject(body.string(), clazz);\n }\n T unknown = clazz.newInstance();\n unknown.setErrorCode(\"Unknown\");\n unknown.setErrorMessage(body.string());\n return unknown;\n } catch (Exception e) {\n throw new RuntimeException(\"Call request error\", e);\n }\n }\n\n /**\n * ๆตๅผ่พๅบ\n *\n * @param apiKey\n * @param request\n * @param listener\n */\n public void stream(String apiKey, CompletionRequest request, EventSourceListener listener) {\n request.setStream(true);\n Request r = new Builder().url(completionUrl)\n .addHeader(\"Accept\", \"text/event-stream\")\n .addHeader(\"Content-Type\", \"application/json\")\n .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .post(RequestBody.create(JSON.toJSONString(request), APPLICATION_JSON)).build();\n EventSources.createFactory(client).newEventSource(r, listener);\n }\n\n /**\n * ๆง่ก่ฏทๆฑ\n *\n * @param apiKey\n * @param request\n * @return\n */\n public CompletionResponse complete(String apiKey, CompletionRequest request) {\n request.setStream(false);\n Request r = new Builder().url(completionUrl)\n .addHeader(\"Accept\", \"application/json\")\n .addHeader(\"Content-Type\", \"application/json\")\n .addHeader(\"Authorization\", \"Bearer \" + apiKey)\n .post(RequestBody.create(JSON.toJSONString(request), APPLICATION_JSON)).build();\n try (Response response = client.newCall(r).execute()) {\n ResponseBody body = response.body();\n if (body == null) {\n return null;\n }\n return JSON.parseObject(body.string(), CompletionResponse.class);\n } catch (Exception e) {\n throw new RuntimeException(\"Call request error\", e);\n }\n }\n}"
},
{
"identifier": "qianWenApiKey",
"path": "src/test/java/cn/homj/autogen4j/Definition.java",
"snippet": "public static String qianWenApiKey;"
}
] | import cn.homj.autogen4j.support.Client;
import static cn.homj.autogen4j.Definition.qianWenApiKey; | 2,110 | package cn.homj.autogen4j;
/**
* @author jiehong.jh
* @date 2023/12/1
*/
public class GroupChatManagerTest {
public static void main(String[] args) {
Client client = new Client();
UserProxyAgent user = new UserProxyAgent("Hom J.");
QianWenAgent taylor = new QianWenAgent("Taylor");
QianWenAgent jarvis = new QianWenAgent("Jarvis");
GroupChat groupChat = new GroupChat()
.addAgent(user, "ๆญฃๅจๅฏปๆฑๅธฎๅฉ็็จๆท")
.addAgent(taylor, "ๆธฉๆ็็ฅๅฟๅงๅง๏ผๅฝไฝ ้ๅฐ้ฎ้ขๆถ๏ผๆปๆฏไผ็ปไบ้ผๅฑๅๆฏๆใ")
.addAgent(jarvis, "ๆ
ๆธธ่พพไบบ๏ผๅฏไปฅๆไพ็ฎ็ๅฐๅปบ่ฎฎใ่ก็จ่งๅใ");
GroupChatManager manager = taylor.newManager("manager").groupChat(groupChat);
taylor
.client(client)
.model("qwen-plus") | package cn.homj.autogen4j;
/**
* @author jiehong.jh
* @date 2023/12/1
*/
public class GroupChatManagerTest {
public static void main(String[] args) {
Client client = new Client();
UserProxyAgent user = new UserProxyAgent("Hom J.");
QianWenAgent taylor = new QianWenAgent("Taylor");
QianWenAgent jarvis = new QianWenAgent("Jarvis");
GroupChat groupChat = new GroupChat()
.addAgent(user, "ๆญฃๅจๅฏปๆฑๅธฎๅฉ็็จๆท")
.addAgent(taylor, "ๆธฉๆ็็ฅๅฟๅงๅง๏ผๅฝไฝ ้ๅฐ้ฎ้ขๆถ๏ผๆปๆฏไผ็ปไบ้ผๅฑๅๆฏๆใ")
.addAgent(jarvis, "ๆ
ๆธธ่พพไบบ๏ผๅฏไปฅๆไพ็ฎ็ๅฐๅปบ่ฎฎใ่ก็จ่งๅใ");
GroupChatManager manager = taylor.newManager("manager").groupChat(groupChat);
taylor
.client(client)
.model("qwen-plus") | .apiKey(qianWenApiKey) | 1 | 2023-12-15 01:43:11+00:00 | 4k |
wenbochang888/min-read-book | house/src/main/java/com/tianya/controller/MybatisPlusController.java | [
{
"identifier": "UserMapper",
"path": "house/src/main/java/com/tianya/dao3/UserMapper.java",
"snippet": "@Repository(\"userMapper\")\npublic interface UserMapper extends BaseMapper<User> {\n\n}"
},
{
"identifier": "TElement",
"path": "house/src/main/java/com/tianya/entity/TElement.java",
"snippet": "public class TElement implements Serializable {\n /**\n * Database Column Remarks:\n * ่ฆ็ด ่ชๅขไธป้ฎ\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column t_element.F_element_id\n *\n * @mbg.generated\n */\n @TableId\n private Long fElementId;\n\n /**\n * Database Column Remarks:\n * ่ฆ็ด ๅ็งฐ\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column t_element.F_element_name\n *\n * @mbg.generated\n */\n private String fElementName;\n\n /**\n * Database Column Remarks:\n * ๅ่ฝ็ถๆ 1.enabled 2.disabled\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column t_element.F_element_status\n *\n * @mbg.generated\n */\n private Byte fElementStatus;\n\n /**\n * Database Column Remarks:\n * ่ฎฐๅฝๅๅปบๆถ้ด\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column t_element.F_create_time\n *\n * @mbg.generated\n */\n private Date fCreateTime;\n\n /**\n * Database Column Remarks:\n * ๆๅไฟฎๆนๆถ้ด\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column t_element.F_modify_time\n *\n * @mbg.generated\n */\n private Date fModifyTime;\n\n /**\n * Database Column Remarks:\n * ๆฉๅฑๅญๆฎต\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column t_element.F_extension\n *\n * @mbg.generated\n */\n private String fExtension;\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column t_element.F_element_id\n *\n * @return the value of t_element.F_element_id\n *\n * @mbg.generated\n */\n public Long getfElementId() {\n return fElementId;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column t_element.F_element_id\n *\n * @param fElementId the value for t_element.F_element_id\n *\n * @mbg.generated\n */\n public void setfElementId(Long fElementId) {\n this.fElementId = fElementId;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column t_element.F_element_name\n *\n * @return the value of t_element.F_element_name\n *\n * @mbg.generated\n */\n public String getfElementName() {\n return fElementName;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column t_element.F_element_name\n *\n * @param fElementName the value for t_element.F_element_name\n *\n * @mbg.generated\n */\n public void setfElementName(String fElementName) {\n this.fElementName = fElementName == null ? null : fElementName.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column t_element.F_element_status\n *\n * @return the value of t_element.F_element_status\n *\n * @mbg.generated\n */\n public Byte getfElementStatus() {\n return fElementStatus;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column t_element.F_element_status\n *\n * @param fElementStatus the value for t_element.F_element_status\n *\n * @mbg.generated\n */\n public void setfElementStatus(Byte fElementStatus) {\n this.fElementStatus = fElementStatus;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column t_element.F_create_time\n *\n * @return the value of t_element.F_create_time\n *\n * @mbg.generated\n */\n public Date getfCreateTime() {\n return fCreateTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column t_element.F_create_time\n *\n * @param fCreateTime the value for t_element.F_create_time\n *\n * @mbg.generated\n */\n public void setfCreateTime(Date fCreateTime) {\n this.fCreateTime = fCreateTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column t_element.F_modify_time\n *\n * @return the value of t_element.F_modify_time\n *\n * @mbg.generated\n */\n public Date getfModifyTime() {\n return fModifyTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column t_element.F_modify_time\n *\n * @param fModifyTime the value for t_element.F_modify_time\n *\n * @mbg.generated\n */\n public void setfModifyTime(Date fModifyTime) {\n this.fModifyTime = fModifyTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column t_element.F_extension\n *\n * @return the value of t_element.F_extension\n *\n * @mbg.generated\n */\n public String getfExtension() {\n return fExtension;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column t_element.F_extension\n *\n * @param fExtension the value for t_element.F_extension\n *\n * @mbg.generated\n */\n public void setfExtension(String fExtension) {\n this.fExtension = fExtension == null ? null : fExtension.trim();\n }\n}"
},
{
"identifier": "User",
"path": "house/src/main/java/com/tianya/entity/User.java",
"snippet": "@TableName(\"user\")\n@AllArgsConstructor\n@NoArgsConstructor\n@Data\npublic class User {\n\tprivate Long id;\n\tprivate String name;\n\tprivate Integer age;\n\tprivate String email;\n\n\tpublic User(Long id, String name) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n}"
},
{
"identifier": "TelementService",
"path": "house/src/main/java/com/tianya/service/TelementService.java",
"snippet": "@Service\n@Slf4j\npublic class TelementService extends ServiceImpl<TElementMapper, TElement> {\n\n}"
}
] | import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.tianya.dao3.UserMapper;
import com.tianya.entity.TElement;
import com.tianya.entity.User;
import com.tianya.service.TelementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; | 2,161 | package com.tianya.controller;
/**
* @author changwenbo
* @date 2022/6/14 11:17
*/
@RestController
@Slf4j
public class MybatisPlusController {
@Autowired
private UserMapper userMapper;
@Autowired
private TelementService service;
@RequestMapping("/test/mybatis/test")
public String test() {
TElement element = new TElement();
element.setfElementName("111");
log.info("element = {}", JSON.toJSONString(element));
boolean save = service.save(element);
log.info("save = {}, element = {}", save, JSON.toJSONString(element));
return "ok";
}
@RequestMapping("/test/mybatis/page")
public String testPublish0(String str, int page, int current) {
List<Integer> list = Lists.newArrayList(1, 2,3 ,4,5 ,6);
List<Integer> remove = Lists.newArrayList(2, 5);
System.out.println(list);
list.removeIf(remove::contains);
System.out.println(list);
return "ok";
}
@RequestMapping("/test/mybatis/select/one")
public String testPublish1() {
| package com.tianya.controller;
/**
* @author changwenbo
* @date 2022/6/14 11:17
*/
@RestController
@Slf4j
public class MybatisPlusController {
@Autowired
private UserMapper userMapper;
@Autowired
private TelementService service;
@RequestMapping("/test/mybatis/test")
public String test() {
TElement element = new TElement();
element.setfElementName("111");
log.info("element = {}", JSON.toJSONString(element));
boolean save = service.save(element);
log.info("save = {}, element = {}", save, JSON.toJSONString(element));
return "ok";
}
@RequestMapping("/test/mybatis/page")
public String testPublish0(String str, int page, int current) {
List<Integer> list = Lists.newArrayList(1, 2,3 ,4,5 ,6);
List<Integer> remove = Lists.newArrayList(2, 5);
System.out.println(list);
list.removeIf(remove::contains);
System.out.println(list);
return "ok";
}
@RequestMapping("/test/mybatis/select/one")
public String testPublish1() {
| LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class); | 2 | 2023-12-18 13:31:20+00:00 | 4k |
Valerde/vadb | va-collection/src/main/java/com/sovava/vacollection/valist/VaArrayList.java | [
{
"identifier": "VaPredicate",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/function/VaPredicate.java",
"snippet": "@FunctionalInterface\npublic interface VaPredicate<T> {\n /**\n * description: ๅคๆญ่พๅ
ฅ็ๅๆฐtๆฏๅฆๆปก่ถณๆญ่จ\n *\n * @Author sovava\n * @Date 12/18/23 6:02 PM\n * @param: t - [T]\n * @return boolean\n */\n boolean test(T t);\n}"
},
{
"identifier": "VaUnaryOperator",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/function/VaUnaryOperator.java",
"snippet": "public interface VaUnaryOperator<T> extends VaFunction<T, T> {\n}"
},
{
"identifier": "VaArrays",
"path": "va-collection/src/main/java/com/sovava/vacollection/collections/VaArrays.java",
"snippet": "public class VaArrays {\n\n /**\n * description: ้่ฟๆนๆณ็งๆๆๅถ้ป่ฎคๆ้ ๅจ๏ผ็กฎไฟ็ฑปไธๅฏๅฎไพๅ\n *\n * @Author sovava\n * @Date 12/19/23 5:52 PM\n */\n private VaArrays() {\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T[] copyOf(T[] original, int newLen) {\n return (T[])copyOf(original,newLen,original.getClass());\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T, O> T[] copyOf(O[] original, int newLen, Class<? extends T[]> newType) {\n T[] copy;\n if ((Object)newType == (Object)Object[].class) {// ๅฆๆๅๆฌข่ฝฌๆข็็ฑปๅๆฏObject[].class,ๅฐฑ็ดๆฅๅๅปบ๏ผไธ้่ฆๅๅฐ\n copy = (T[]) new Object[newLen]; //ไปฃ็ ่ฟ่กๅฐ่ฟ้ไธๅฎๆฏObject็ฑปๅ,ๅชไธ่ฟไธๅผบ่ฝฌ็ฑปๅ่ฟไธๅป็ผ่ฏ\n } else {\n //้่ฟๅๅฐๅๅปบๆฐๆฐ็ป\n copy = (T[]) Array.newInstance(newType.getComponentType(), newLen);\n }\n //็ณป็ปๅบๅฑๅฎ็ฐ็ๆฐ็ปๆท่ด\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n // ไปฅไธๅบๆฌๆฐๆฎ็ฑปๅ็ๆท่ดๅไธบๅๅฐๅๅฐๅผ้\n public static short[] copyOf(short[] original, int newLen) {\n short[] copy = new short[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n public static int[] copyOf(int[] original, int newLen) {\n int[] copy = new int[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n public static long[] copyOf(long[] original, int newLen) {\n long[] copy = new long[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n public static char[] copyOf(char[] original, int newLen) {\n char[] copy = new char[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n public static float[] copyOf(float[] original, int newLen) {\n float[] copy = new float[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n public static double[] copyOf(double[] original, int newLen) {\n double[] copy = new double[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n\n public static boolean[] copyOf(boolean[] original, int newLen) {\n boolean[] copy = new boolean[newLen];\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLen));\n return copy;\n }\n //-----------------------------copyOf end , sort start ---------------------------------------------\n\n}"
}
] | import com.sovava.vacollection.api.*;
import com.sovava.vacollection.api.function.VaPredicate;
import com.sovava.vacollection.api.function.VaUnaryOperator;
import com.sovava.vacollection.collections.VaArrays;
import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer; | 2,991 | }
@Override
public int indexOf(Object o) {
if (null == o) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Object[] toVaArray() {
return VaArrays.copyOf(elementData, size);
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toVaArray(T[] ts) {
if (ts.length < size) {
return (T[]) VaArrays.copyOf(ts, size, ts.getClass());
}
System.arraycopy(elementData, 0, ts, 0, size);
if (ts.length > size) {
ts[size] = null;
}
return ts;
}
@Override
public int lastIndexOf(Object o) {
if (null == o) {
for (int i = size - 1; i > 0; i--) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i > 0; i--) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
protected Object clone() throws CloneNotSupportedException {
VaArrayList<?> clone = (VaArrayList<?>) super.clone();
clone.elementData = VaArrays.copyOf(this.elementData, size);
return clone;
}
@Override
public boolean removeAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
private boolean batchRemove(VaCollection<?> c, boolean exit) {
Object[] dataTmp = this.elementData;
int toIdx, newSize = 0;
boolean modified = false;
for (toIdx = 0; toIdx < size; toIdx++) {
if (c.contains(dataTmp[toIdx]) == exit) {
dataTmp[newSize++] = dataTmp[toIdx];
}
}
if (newSize != size) {
for (int i = newSize; i < size; i++) {
dataTmp[i] = null;
}
size = newSize;
modified = true;
}
return modified;
}
@Override
public boolean retainAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
@Override
public void replaceAll(VaUnaryOperator<E> operator) {
Objects.requireNonNull(operator);
int size = this.size;
for (int i = 0; i < size; i++) {
elementData[i] = operator.apply(elementData(i));
}
}
@Override
public void forEach(VaConsumer<? super E> action) {
Objects.requireNonNull(action);
int size = this.size;
for (int i = 0; i < size; i++) {
action.accept(elementData(i));
}
}
@Override | package com.sovava.vacollection.valist;
/**
* Description: ็ฑไบๅ็ปญไธไผๅฐๆญค็ฑป็จไบ็บฟ็จไธๅฎๅ
จๅบๆฏ๏ผๅ ๆญคๆไธๅฏน็ฑปไธญ็ๆนๆณๅๅฟซ้ๅคฑ่ดฅไธๅฏน็บฟ็จๅฎๅ
จ็ไธไบๅบๆฌๆชๆฝ
*
* @author: ykn
* @date: 2023ๅนด12ๆ25ๆฅ 8:32 PM
**/
public class VaArrayList<E> extends VaAbstractList<E> implements VaList<E>, RandomAccess, Cloneable, Serializable {
private static final long serialVersionUID = 5716796482536510252L;
/**
* ้ป่ฎคๅคงๅฐ๏ผ 10
*/
private static final int DEFAULT_CAPACITY = 10;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* ็จไบ็ฉบๅฎไพ็ๅ
ฑไบซๆฐ็ปๅฎไพ
*/
private static final Object[] EMPTY_ELEMENT_DATA = {};
/**
* ็จไบ้ป่ฎคๅคงๅฐ็็ฉบๅฎไพ
*/
private static final Object[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {};
Object[] elementData;
private int size;
public VaArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENT_DATA;
} else {
throw new IllegalArgumentException("ไธๅ็็ๅฎน้๏ผ" + initialCapacity);
}
}
public VaArrayList() {
this.elementData = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA;
}
public VaArrayList(VaCollection<? extends E> c) {
elementData = c.toVaArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class) {
elementData = VaArrays.copyOf(elementData, size, Object[].class);
}
} else {
this.elementData = EMPTY_ELEMENT_DATA;
}
}
@SuppressWarnings("unchecked")
E elementData(int idx) {
return (E) elementData[idx];
}
public int size() {
return size;
}
public E set(int idx, E e) {
rangeCheck(idx);
E oldV = elementData(idx);
elementData[idx] = e;
return oldV;
}
@Override
public E get(int idx) {
rangeCheck(idx);
return elementData(idx);
}
@Override
public boolean add(E e) {
ensureCapInternal(size + 1);
elementData[size++] = e;
return true;
}
@Override
public void add(int idx, E e) {
rangeCheck(idx);
ensureCapInternal(size + 1);
System.arraycopy(elementData, idx, elementData, idx + 1, size - idx);
elementData[idx] = e;
size++;
}
@Override
public E remove(int idx) {
rangeCheck(idx);
E oldV = elementData(idx);
int numMoved = size - idx - 1;
if (numMoved > 0) {
System.arraycopy(elementData, idx + 1, elementData, idx, numMoved);
}
elementData[size--] = null;
return oldV;
}
@Override
public boolean remove(Object o) {
if (null == o) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
fastRemove(i);
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
fastRemove(i);
return true;
}
}
}
return false;
}
private void fastRemove(int idx) {
int numMoved = size - idx - 1;
if (numMoved > 0) {
System.arraycopy(elementData, idx + 1, elementData, idx, numMoved);
}
elementData[--size] = null;
}
public void clear() {
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
public boolean addAll(VaCollection<? extends E> c) {
return addAll(size, c);
}
public boolean addAll(int index, VaCollection<? extends E> c) {
rangeCheckForAdd(index);
Object[] cs = c.toVaArray();
int csSize = c.size();
if (csSize == 0) return false;
ensureCapInternal(size + csSize);
int numMoved = size - index;
if (numMoved > 0) {
System.arraycopy(elementData, index, elementData, index + csSize, numMoved);
}
System.arraycopy(cs, 0, elementData, index, csSize);
size += csSize;
return true;
}
protected void removeRange(int fromIndex, int toIndex) {
System.arraycopy(elementData, toIndex, elementData, fromIndex, toIndex - fromIndex);
int newSize = size - (toIndex - fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
public void ensureCapInternal(int minCap) {
ensureLegalCap(calcCap(elementData, minCap));
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int indexOf(Object o) {
if (null == o) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Object[] toVaArray() {
return VaArrays.copyOf(elementData, size);
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toVaArray(T[] ts) {
if (ts.length < size) {
return (T[]) VaArrays.copyOf(ts, size, ts.getClass());
}
System.arraycopy(elementData, 0, ts, 0, size);
if (ts.length > size) {
ts[size] = null;
}
return ts;
}
@Override
public int lastIndexOf(Object o) {
if (null == o) {
for (int i = size - 1; i > 0; i--) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i > 0; i--) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
protected Object clone() throws CloneNotSupportedException {
VaArrayList<?> clone = (VaArrayList<?>) super.clone();
clone.elementData = VaArrays.copyOf(this.elementData, size);
return clone;
}
@Override
public boolean removeAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
private boolean batchRemove(VaCollection<?> c, boolean exit) {
Object[] dataTmp = this.elementData;
int toIdx, newSize = 0;
boolean modified = false;
for (toIdx = 0; toIdx < size; toIdx++) {
if (c.contains(dataTmp[toIdx]) == exit) {
dataTmp[newSize++] = dataTmp[toIdx];
}
}
if (newSize != size) {
for (int i = newSize; i < size; i++) {
dataTmp[i] = null;
}
size = newSize;
modified = true;
}
return modified;
}
@Override
public boolean retainAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
@Override
public void replaceAll(VaUnaryOperator<E> operator) {
Objects.requireNonNull(operator);
int size = this.size;
for (int i = 0; i < size; i++) {
elementData[i] = operator.apply(elementData(i));
}
}
@Override
public void forEach(VaConsumer<? super E> action) {
Objects.requireNonNull(action);
int size = this.size;
for (int i = 0; i < size; i++) {
action.accept(elementData(i));
}
}
@Override | public boolean removeIf(VaPredicate<? super E> filter) { | 0 | 2023-12-17 13:29:10+00:00 | 4k |
alexeytereshchenko/CodeGuardian | plugin/src/main/java/io/github/alexeytereshchenko/guardian/GuardianPlugin.java | [
{
"identifier": "ErrorProneExtension",
"path": "plugin/src/main/java/io/github/alexeytereshchenko/guardian/extention/ErrorProneExtension.java",
"snippet": "public class ErrorProneExtension {\n private boolean enable = true;\n private String dependency = \"com.google.errorprone:error_prone_core:2.23.0\";\n private String dependencyJavac = \"com.google.errorprone:javac:9+181-r4173-1\";\n\n private Set<String> bugPatterns = new HashSet<>();\n\n public ErrorProneExtension() {\n bugPatterns.add(\"WildcardImport\");\n bugPatterns.add(\"RemoveUnusedImports\");\n bugPatterns.add(\"FieldCanBeFinal\");\n bugPatterns.add(\"ConstantField\");\n bugPatterns.add(\"UnusedMethod\");\n bugPatterns.add(\"UnusedVariable\");\n bugPatterns.add(\"ReturnsNullCollection\");\n bugPatterns.add(\"UnnecessaryBoxedVariable\");\n bugPatterns.add(\"UnnecessaryBoxedAssignment\");\n bugPatterns.add(\"SwitchDefault\");\n bugPatterns.add(\"PrivateConstructorForUtilityClass\");\n bugPatterns.add(\"UseEnumSwitch\");\n bugPatterns.add(\"MultipleTopLevelClasses\");\n bugPatterns.add(\"MissingBraces\");\n bugPatterns.add(\"UnnecessaryStaticImport\");\n bugPatterns.add(\"BadImport\");\n bugPatterns.add(\"MixedArrayDimensions\");\n bugPatterns.add(\"FieldCanBeLocal\");\n\n bugPatterns.add(\"AlreadyChecked\");\n bugPatterns.add(\"AmbiguousMethodReference\");\n bugPatterns.add(\"ArgumentSelectionDefectChecker\");\n bugPatterns.add(\"AttemptedNegativeZero\");\n bugPatterns.add(\"BadComparable\");\n bugPatterns.add(\"BadInstanceof\");\n bugPatterns.add(\"BareDotMetacharacter\");\n bugPatterns.add(\"BigDecimalEquals\");\n bugPatterns.add(\"BigDecimalLiteralDouble\");\n bugPatterns.add(\"BoxedPrimitiveConstructor\");\n bugPatterns.add(\"ByteBufferBackingArray\");\n bugPatterns.add(\"CatchAndPrintStackTrace\");\n bugPatterns.add(\"CatchFail\");\n bugPatterns.add(\"CharacterGetNumericValue\");\n bugPatterns.add(\"ClassNewInstance\");\n bugPatterns.add(\"CloseableProvides\");\n bugPatterns.add(\"ClosingStandardOutputStreams\");\n bugPatterns.add(\"CollectionUndefinedEquality\");\n bugPatterns.add(\"ComplexBooleanConstant\");\n bugPatterns.add(\"CompareToZero\");\n bugPatterns.add(\"ComparableAndComparator\");\n bugPatterns.add(\"CollectorShouldNotUseState\");\n bugPatterns.add(\"DateChecker\");\n bugPatterns.add(\"DateFormatConstant\");\n bugPatterns.add(\"DeprecatedVariable\");\n bugPatterns.add(\"DistinctVarargsChecker\");\n bugPatterns.add(\"DoNotCallSuggester\");\n bugPatterns.add(\"DoNotClaimAnnotations\");\n bugPatterns.add(\"DoubleCheckedLocking\");\n bugPatterns.add(\"DuplicateDateFormatField\");\n bugPatterns.add(\"EmptyCatch\");\n bugPatterns.add(\"EmptyTopLevelDeclaration\");\n bugPatterns.add(\"EqualsIncompatibleType\");\n bugPatterns.add(\"EqualsUnsafeCast\");\n bugPatterns.add(\"EqualsUsingHashCode\");\n bugPatterns.add(\"ExtendsObject\");\n bugPatterns.add(\"FallThrough\");\n bugPatterns.add(\"Finalize\");\n bugPatterns.add(\"Finally\");\n bugPatterns.add(\"FloatCast\");\n bugPatterns.add(\"FloatingPointLiteralPrecision\");\n bugPatterns.add(\"FloggerArgumentToString\");\n bugPatterns.add(\"GetClassOnEnum\");\n bugPatterns.add(\"HidingField\");\n bugPatterns.add(\"IdentityHashMapUsage\");\n bugPatterns.add(\"InconsistentCapitalization\");\n bugPatterns.add(\"InconsistentHashCode\");\n bugPatterns.add(\"IncorrectMainMethod\");\n bugPatterns.add(\"IncrementInForLoopAndHeader\");\n bugPatterns.add(\"InjectInvalidTargetingOnScopingAnnotation\");\n bugPatterns.add(\"IntLongMath\");\n bugPatterns.add(\"InvalidThrows\");\n bugPatterns.add(\"IterableAndIterator\");\n bugPatterns.add(\"JavaDurationGetSecondsGetNano\");\n bugPatterns.add(\"JavaDurationWithNanos\");\n bugPatterns.add(\"JavaDurationWithSeconds\");\n bugPatterns.add(\"JavaInstantGetSecondsGetNano\");\n bugPatterns.add(\"JavaLangClash\");\n bugPatterns.add(\"JavaUtilDate\");\n bugPatterns.add(\"JavaxInjectOnFinalField\");\n bugPatterns.add(\"JdkObsolete\");\n bugPatterns.add(\"LogicalAssignment\");\n bugPatterns.add(\"LoopOverCharArray\");\n bugPatterns.add(\"LongDoubleConversion\");\n bugPatterns.add(\"LongFloatConversion\");\n bugPatterns.add(\"MalformedInlineTag\");\n bugPatterns.add(\"MathAbsoluteNegative\");\n bugPatterns.add(\"MissingCasesInEnumSwitch\");\n bugPatterns.add(\"MissingImplementsComparable\");\n bugPatterns.add(\"MissingOverride\");\n bugPatterns.add(\"MixedMutabilityReturnType\");\n bugPatterns.add(\"ModifyCollectionInEnhancedForLoop\");\n bugPatterns.add(\"ModifySourceCollectionInStream\");\n bugPatterns.add(\"NarrowCalculation\");\n bugPatterns.add(\"NarrowingCompoundAssignment\");\n bugPatterns.add(\"NestedInstanceOfConditions\");\n bugPatterns.add(\"NonCanonicalType\");\n bugPatterns.add(\"NullOptional\");\n bugPatterns.add(\"NullableConstructor\");\n bugPatterns.add(\"NullablePrimitive\");\n bugPatterns.add(\"NullablePrimitiveArray\");\n bugPatterns.add(\"NullableVoid\");\n bugPatterns.add(\"ObjectEqualsForPrimitives\");\n bugPatterns.add(\"ObjectToString\");\n bugPatterns.add(\"ObjectsHashCodePrimitive\");\n bugPatterns.add(\"OptionalMapToOptional\");\n bugPatterns.add(\"OptionalNotPresent\");\n bugPatterns.add(\"OrphanedFormatString\");\n bugPatterns.add(\"OverrideThrowableToString\");\n bugPatterns.add(\"Overrides\");\n bugPatterns.add(\"OverridingMethodInconsistentArgumentNamesChecker\");\n bugPatterns.add(\"QualifierOrScopeOnInjectMethod\");\n bugPatterns.add(\"ReturnAtTheEndOfVoidFunction\");\n bugPatterns.add(\"StreamResourceLeak\");\n bugPatterns.add(\"StreamToIterable\");\n bugPatterns.add(\"StringSplitter\");\n bugPatterns.add(\"SuperEqualsIsObjectEquals\");\n bugPatterns.add(\"ThreadLocalUsage\");\n bugPatterns.add(\"ToStringReturnsNull\");\n bugPatterns.add(\"UndefinedEquals\");\n bugPatterns.add(\"UnicodeEscape\");\n bugPatterns.add(\"UnnecessaryLongToIntConversion\");\n bugPatterns.add(\"UnnecessaryStringBuilder\");\n bugPatterns.add(\"UnusedNestedClass\");\n bugPatterns.add(\"UnusedTypeParameter\");\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public Set<String> getBugPatterns() {\n return bugPatterns;\n }\n\n public void setBugPatterns(Set<String> bugPatterns) {\n this.bugPatterns = bugPatterns;\n }\n\n public String getDependency() {\n return dependency;\n }\n\n public void setDependency(String dependency) {\n this.dependency = dependency;\n }\n\n public String getDependencyJavac() {\n return dependencyJavac;\n }\n\n public void setDependencyJavac(String dependencyJavac) {\n this.dependencyJavac = dependencyJavac;\n }\n}"
},
{
"identifier": "GuardianCheckStyleExtension",
"path": "plugin/src/main/java/io/github/alexeytereshchenko/guardian/extention/GuardianCheckStyleExtension.java",
"snippet": "public class GuardianCheckStyleExtension {\n private boolean enable = true;\n private String fileUrl;\n private int errorThreshold = 0;\n private boolean showViolations = true;\n private String version = \"10.12.6\";\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public String getFileUrl() {\n return fileUrl;\n }\n\n public void setFileUrl(String fileUrl) {\n this.fileUrl = fileUrl;\n }\n\n public int getErrorThreshold() {\n return errorThreshold;\n }\n\n public void setErrorThreshold(int errorThreshold) {\n this.errorThreshold = errorThreshold;\n }\n\n public boolean isShowViolations() {\n return showViolations;\n }\n\n public void setShowViolations(boolean showViolations) {\n this.showViolations = showViolations;\n }\n}"
},
{
"identifier": "GuardianExtension",
"path": "plugin/src/main/java/io/github/alexeytereshchenko/guardian/extention/GuardianExtension.java",
"snippet": "public abstract class GuardianExtension implements ExtensionAware {\n private final ErrorProneExtension errorProne = new ErrorProneExtension();\n private final GuardianCheckStyleExtension checkStyle = new GuardianCheckStyleExtension();\n private boolean enableGitHooks = true;\n\n public boolean isEnableGitHooks() {\n return enableGitHooks;\n }\n\n public void setEnableGitHooks(boolean enableGitHooks) {\n this.enableGitHooks = enableGitHooks;\n }\n\n public ErrorProneExtension getErrorProne() {\n return errorProne;\n }\n\n public GuardianCheckStyleExtension getCheckStyle() {\n return checkStyle;\n }\n\n public void errorProne(Action<? super ErrorProneExtension> action) {\n action.execute(errorProne);\n }\n\n public void checkStyle(Action<? super GuardianCheckStyleExtension> action) {\n action.execute(checkStyle);\n }\n}"
},
{
"identifier": "TaskName",
"path": "plugin/src/main/java/io/github/alexeytereshchenko/guardian/meta/TaskName.java",
"snippet": "public final class TaskName {\n\n private TaskName() {\n }\n\n public static final String VALIDATE_STYLE = \"validateStyle\";\n public static final String DOWNLOAD_CHECKSTYLE_FILE = \"downloadCheckstyleFile\";\n public static final String COPY_GIT_HOOKS = \"copyGitHooks\";\n}"
},
{
"identifier": "DownloadCheckstyleFile",
"path": "plugin/src/main/java/io/github/alexeytereshchenko/guardian/task/DownloadCheckstyleFile.java",
"snippet": "public abstract class DownloadCheckstyleFile extends DefaultTask {\n\n private final HttpClient httpClient;\n private final Logger log;\n\n public DownloadCheckstyleFile() {\n this.httpClient = HttpClient.newHttpClient();\n this.log = LoggerFactory.getLogger(this.getName());\n }\n\n @Input\n @Optional\n public abstract Property<String> getUrl();\n\n @Input\n @Optional\n public abstract Property<String> getDestinationPath();\n\n @TaskAction\n public void downloadCheckstyleFile() throws URISyntaxException, IOException, InterruptedException {\n String destinationPath = getDestinationPath().get();\n String url = getUrl().get();\n\n try {\n HttpRequest request = HttpRequest.newBuilder()\n .uri(new URI(url))\n .GET()\n .build();\n\n HttpResponse<InputStream> response = httpClient.send(request, BodyHandlers.ofInputStream());\n\n int statusCode = response.statusCode();\n if (statusCode > 299) {\n throw new InvalidUserDataException();\n }\n\n File file = new File(destinationPath);\n file.getParentFile().mkdirs();\n file.createNewFile();\n\n try (FileOutputStream fos = new FileOutputStream(file);\n InputStream body = response.body()) {\n fos.write(body.readAllBytes());\n }\n\n } catch (Exception e) {\n String message = String.format(\"Cannot download a checkstyle file by url: %s in %s\", url, destinationPath);\n log.error(message, e);\n throw e;\n }\n }\n}"
}
] | import io.github.alexeytereshchenko.guardian.extention.ErrorProneExtension;
import io.github.alexeytereshchenko.guardian.extention.GuardianCheckStyleExtension;
import io.github.alexeytereshchenko.guardian.extention.GuardianExtension;
import io.github.alexeytereshchenko.guardian.meta.TaskName;
import net.ltgt.gradle.errorprone.CheckSeverity;
import net.ltgt.gradle.errorprone.ErrorProneCompilerArgumentProvider;
import net.ltgt.gradle.errorprone.ErrorProneOptions;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.file.DuplicatesStrategy;
import org.gradle.api.plugins.quality.Checkstyle;
import org.gradle.api.plugins.quality.CheckstyleExtension;
import org.gradle.api.tasks.Copy;
import org.gradle.api.tasks.Delete;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.language.base.internal.plugins.CleanRule;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Set;
import io.github.alexeytereshchenko.guardian.task.DownloadCheckstyleFile; | 3,178 | package io.github.alexeytereshchenko.guardian;
public class GuardianPlugin implements Plugin<Project> {
@Override
public void apply(@NotNull Project project) {
project.getExtensions().create("guardian", GuardianExtension.class);
project.afterEvaluate(evaluatedProject -> {
GuardianExtension guardianExtension = project.getExtensions()
.getByType(GuardianExtension.class);
configurePlugins(evaluatedProject);
configureDependencies(evaluatedProject, guardianExtension);
configureErrorProne(evaluatedProject, guardianExtension);
configureGitHooks(evaluatedProject, guardianExtension);
boolean enableChecker = guardianExtension.getCheckStyle().isEnable();
if (enableChecker) {
project.getPlugins().apply("checkstyle");
configureValidateStyleTask(evaluatedProject);
configureDownloadConfigFileTask(evaluatedProject, guardianExtension);
configureCheckstyle(project, guardianExtension);
}
});
}
private void configurePlugins(Project project) {
Set<String> plugins = Set.of("java", "net.ltgt.errorprone");
plugins.stream()
.filter(plugin -> !project.getPlugins().hasPlugin(plugin))
.forEach(plugin -> project.getPlugins().apply(plugin));
}
private void configureDependencies(Project project, GuardianExtension guardianExtension) { | package io.github.alexeytereshchenko.guardian;
public class GuardianPlugin implements Plugin<Project> {
@Override
public void apply(@NotNull Project project) {
project.getExtensions().create("guardian", GuardianExtension.class);
project.afterEvaluate(evaluatedProject -> {
GuardianExtension guardianExtension = project.getExtensions()
.getByType(GuardianExtension.class);
configurePlugins(evaluatedProject);
configureDependencies(evaluatedProject, guardianExtension);
configureErrorProne(evaluatedProject, guardianExtension);
configureGitHooks(evaluatedProject, guardianExtension);
boolean enableChecker = guardianExtension.getCheckStyle().isEnable();
if (enableChecker) {
project.getPlugins().apply("checkstyle");
configureValidateStyleTask(evaluatedProject);
configureDownloadConfigFileTask(evaluatedProject, guardianExtension);
configureCheckstyle(project, guardianExtension);
}
});
}
private void configurePlugins(Project project) {
Set<String> plugins = Set.of("java", "net.ltgt.errorprone");
plugins.stream()
.filter(plugin -> !project.getPlugins().hasPlugin(plugin))
.forEach(plugin -> project.getPlugins().apply(plugin));
}
private void configureDependencies(Project project, GuardianExtension guardianExtension) { | ErrorProneExtension errorProne = guardianExtension.getErrorProne(); | 0 | 2023-12-21 17:03:07+00:00 | 4k |
chamithKavinda/layered-architecture-ChamithKavinda | src/main/java/com/example/layeredarchitecture/bo/custom/impl/PlaceOrderBOImpl.java | [
{
"identifier": "PlaceOrderBO",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/PlaceOrderBO.java",
"snippet": "public interface PlaceOrderBO extends SuperBO {\n\n boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException ;\n\n CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException;\n\n ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException;\n\n boolean existItem(String code)throws SQLException, ClassNotFoundException;\n\n boolean existCustomer(String id)throws SQLException, ClassNotFoundException;\n\n String generateOrderID()throws SQLException, ClassNotFoundException;\n\n ArrayList<CustomerDTO> getAllCustomer()throws SQLException, ClassNotFoundException;\n\n ArrayList<ItemDTO> getAllItems()throws SQLException, ClassNotFoundException;\n\n}"
},
{
"identifier": "DAOFactory",
"path": "src/main/java/com/example/layeredarchitecture/dao/DAOFactory.java",
"snippet": "public class DAOFactory {\n private static DAOFactory daoFactory;\n\n private DAOFactory(){\n }\n\n public static DAOFactory getDaoFactory(){\n return (daoFactory==null)?daoFactory = new DAOFactory():daoFactory;\n }\n\n public enum DAOTypes{\n CUSTOMER,ITEM,ORDER,ORDER_DETAIL,QUERY\n }\n public SuperDAO getDAO(DAOTypes daoTypes){\n switch (daoTypes){\n case CUSTOMER:\n return new CustomerDAOImpl();\n case ITEM:\n return new ItemDAOImpl();\n case ORDER:\n return new OrderDAOImpl();\n case ORDER_DETAIL:\n return new OrderDetailsDAOImpl();\n case QUERY:\n return new QueryDAOImpl();\n default:\n return null;\n }\n }\n\n}"
},
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLException {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/company\", \"root\", \"CK13\");\n }\n\n public static DBConnection getDbConnection() throws SQLException, ClassNotFoundException {\n return dbConnection == null ? dbConnection= new DBConnection() : dbConnection;\n }\n\n public Connection getConnection() {\n return connection;\n }\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO(String id) {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "OrderDetailDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/OrderDetailDTO.java",
"snippet": "public class OrderDetailDTO implements Serializable {\n\n private String oid;\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public OrderDetailDTO() {\n }\n\n public OrderDetailDTO(String itemCode, int qty, BigDecimal unitPrice) {\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public OrderDetailDTO(String oid, String itemCode, int qty, BigDecimal unitPrice) {\n this.oid = oid;\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailDTO{\" +\n \"itemCode='\" + itemCode + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n '}';\n }\n}"
},
{
"identifier": "Customer",
"path": "src/main/java/com/example/layeredarchitecture/entity/Customer.java",
"snippet": "public class Customer {\n private String id;\n private String name;\n private String address;\n\n public Customer(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public Customer() {\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n}"
},
{
"identifier": "Item",
"path": "src/main/java/com/example/layeredarchitecture/entity/Item.java",
"snippet": "public class Item {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public Item(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public Item() {\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n}"
},
{
"identifier": "Order",
"path": "src/main/java/com/example/layeredarchitecture/entity/Order.java",
"snippet": "public class Order {\n private String orderId;\n private LocalDate orderDate;\n private String customerId;\n private String customerName;\n private BigDecimal orderTotal;\n\n public Order(String orderId, LocalDate orderDate, String customerId, String customerName, BigDecimal orderTotal) {\n this.orderId = orderId;\n this.orderDate = orderDate;\n this.customerId = customerId;\n this.customerName = customerName;\n this.orderTotal = orderTotal;\n }\n\n public Order() {\n }\n\n public Order(String orderId, LocalDate orderDate, String customerId) {\n this.orderId = orderId;\n this.orderDate = orderDate;\n this.customerId = customerId;\n }\n\n public String getOrderId() {\n return orderId;\n }\n\n public void setOrderId(String orderId) {\n this.orderId = orderId;\n }\n\n public LocalDate getOrderDate() {\n return orderDate;\n }\n\n public void setOrderDate(LocalDate orderDate) {\n this.orderDate = orderDate;\n }\n\n public String getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(String customerId) {\n this.customerId = customerId;\n }\n\n public String getCustomerName() {\n return customerName;\n }\n\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n\n public BigDecimal getOrderTotal() {\n return orderTotal;\n }\n\n public void setOrderTotal(BigDecimal orderTotal) {\n this.orderTotal = orderTotal;\n }\n}"
},
{
"identifier": "OrderDetail",
"path": "src/main/java/com/example/layeredarchitecture/entity/OrderDetail.java",
"snippet": "public class OrderDetail {\n private String oid;\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public OrderDetail(String oid, String itemCode, int qty, BigDecimal unitPrice) {\n this.oid = oid;\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public OrderDetail() {\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n}"
}
] | import com.example.layeredarchitecture.bo.custom.PlaceOrderBO;
import com.example.layeredarchitecture.dao.DAOFactory;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.dto.CustomerDTO;
import com.example.layeredarchitecture.dto.ItemDTO;
import com.example.layeredarchitecture.dto.OrderDetailDTO;
import com.example.layeredarchitecture.entity.Customer;
import com.example.layeredarchitecture.entity.Item;
import com.example.layeredarchitecture.entity.Order;
import com.example.layeredarchitecture.entity.OrderDetail;
import com.example.layeredarchitecture.dao.custom.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List; | 3,328 | package com.example.layeredarchitecture.bo.custom.impl;
public class PlaceOrderBOImpl implements PlaceOrderBO {
OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER);
CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);
ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM);
OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL);
QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY);
@Override
public boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {
Connection connection = null;
connection= DBConnection.getDbConnection().getConnection();
boolean b1 = orderDAO.exist(orderId);
if (b1) {
return false;
}
connection.setAutoCommit(false);
boolean b2 = orderDAO.save(new Order(orderId, orderDate, customerId));
if (!b2) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
for (OrderDetailDTO detail : orderDetails) {
boolean b3 = orderDetailsDAO.save(new OrderDetail(detail.getOid(),detail.getItemCode(),detail.getQty(),detail.getUnitPrice()));
if (!b3) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
ItemDTO item = findItem(detail.getItemCode());
item.setQtyOnHand(item.getQtyOnHand() - detail.getQty());
| package com.example.layeredarchitecture.bo.custom.impl;
public class PlaceOrderBOImpl implements PlaceOrderBO {
OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER);
CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);
ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM);
OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL);
QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY);
@Override
public boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {
Connection connection = null;
connection= DBConnection.getDbConnection().getConnection();
boolean b1 = orderDAO.exist(orderId);
if (b1) {
return false;
}
connection.setAutoCommit(false);
boolean b2 = orderDAO.save(new Order(orderId, orderDate, customerId));
if (!b2) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
for (OrderDetailDTO detail : orderDetails) {
boolean b3 = orderDetailsDAO.save(new OrderDetail(detail.getOid(),detail.getItemCode(),detail.getQty(),detail.getUnitPrice()));
if (!b3) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
ItemDTO item = findItem(detail.getItemCode());
item.setQtyOnHand(item.getQtyOnHand() - detail.getQty());
| boolean b = itemDAO.update(new Item(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand())); | 7 | 2023-12-16 04:21:25+00:00 | 4k |
akpaevj/OpenAPI.1C | ru.akpaev.dt.openapi/src/ru/akpaev/dt/openapi/models/OpenApiRoot.java | [
{
"identifier": "Activator",
"path": "ru.akpaev.dt.openapi/src/ru/akpaev/dt/openapi/Activator.java",
"snippet": "public class Activator\n extends AbstractUIPlugin\n{\n public static final String PLUGIN_ID = \"ru.akpaev.dt.openapi\"; //$NON-NLS-1$\n private static Activator plugin;\n private Injector injector;\n\n private BundleContext bundleContext;\n\n /**\n * ะะพะปััะธัั ัะบะทะตะผะฟะปัั ะฟะปะฐะณะธะฝะฐ. ะงะตัะตะท ัะบะทะตะผะฟะปัั ะฟะปะฐะณะธะฝะฐ ะผะพะถะฝะพ ะฟะพะปััะฐัั ะดะพัััะฟ ะบ ัะฐะทะฝะพะพะฑัะฐะทะฝัะผ ะผะตั
ะฐะฝะธะทะผะฐะผ Eclipse,\n * ัะฐะบะธะผ ะบะฐะบ:\n * <ul>\n * <li>ะััะฝะฐะป ะปะพะณะธัะพะฒะฐะฝะธั ะพัะธะฑะพะบ ะฟะปะฐะณะธะฝะฐ</li>\n * <li>ะะตั
ะฐะฝะธะทะผ ะฝะฐัััะพะนะบะธ ัะฒะพะนััะฒ ะฟะปะฐะณะธะฝะฐ</li>\n * <li>ะะตั
ะฐะฝะธะทะผ ะดะตัะบัะธะฟัะพัะพะฒ</li>\n * </ul>\n *\n * @return ัะบะทะตะผะฟะปัั ะฟะปะฐะณะธะฝะฐ, ะฝะธะบะพะณะดะฐ ะฝะต ะดะพะปะถะตะฝ ะฒะพะทะฒัะฐัะฐัั <code>null</code>\n */\n public static Activator getDefault()\n {\n return plugin;\n }\n\n public synchronized Injector getInjector()\n {\n if (injector == null)\n injector = createInjector();\n\n return injector;\n }\n\n private Injector createInjector()\n {\n try\n {\n return Guice.createInjector(new ExternalDependenciesModule(this));\n }\n catch (Exception e)\n {\n log(createErrorStatus(\"Failed to create injector for \" //$NON-NLS-1$\n + getBundle().getSymbolicName(), e));\n throw new RuntimeException(\"Failed to create injector for \" //$NON-NLS-1$\n + getBundle().getSymbolicName(), e);\n }\n }\n\n /**\n * ะะฐะฟะธัั ััะฐัััะฐ ัะพะฑััะธั ะฒ ะปะพะณ ะถััะฝะฐะป ะฟะปะฐะณะธะฝะฐ.\n *\n * @param status ััะฐััั ัะพะฑััะธั ะดะปั ะปะพะณะธัะพะฒะฐะฝะธั, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>.\n * ะะฐะฝะฝัะน ััะฐััั ัะพะดะตัะถะธั ะฒ ัะตะฑะต ะธะฝัะพัะผะฐัะธั ะพ ะฟัะพะธะทะพัะตะดัะตะผ ัะพะฑััะธะธ (ะพัะธะฑะบะฐ ะฒัะฟะพะปะฝะตะฝะธั,\n * ัะฐะทะฝะพะพะฑัะฐะทะฝัะต ะฟัะตะดัะฟัะตะถะดะตะฝะธั), ะบะพัะพััะต ะฑัะปะธ ะทะฐัะธะบัะธัะพะฒะฐะฝั ะฒ ะปะพะณะธะบะต ัะฐะฑะพัั ะฟะปะฐะณะธะฝะฐ.\n */\n public static void log(IStatus status)\n {\n plugin.getLog().log(status);\n }\n\n /**\n * ะะฐะฟะธัั ะธัะบะปััะตะฝะธั ะฒ ะปะพะณ ะถััะฝะฐะป ะฟะปะฐะณะธะฝะฐ\n *\n * @param throwable ะฒัะบะธะฝััะพะต ะธัะบะปััะตะฝะธะต, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n */\n public static void logError(Throwable throwable)\n {\n log(createErrorStatus(throwable.getMessage(), throwable));\n }\n\n /**\n * ะกะพะทะดะฐะฝะธะต ะทะฐะฟะธัะธ ั ะพะฟะธัะฐะฝะธะตะผ ะพัะธะฑะบะธ ะฒ ะปะพะณ ะถััะฝะฐะปะต ะฟะปะฐะณะธะฝะฐ ะฟะพ ะฒัะบะธะฝะพัะพะผั ะธัะบะปััะตะฝะธั ะธ ัะพะพะฑัะตะฝะธั, ะตะณะพ ะพะฟะธััะฒะฐััะธะผ\n *\n * @param message ะพะฟะธัะฐะฝะธะต ะฒัะบะธะฝััะพะณะพ ะธัะบะปััะตะฝะธั, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n * @param throwable ะฒัะบะธะฝััะพะต ะธัะบะปััะตะฝะธะต, ะผะพะถะตั ะฑััั <code>null</code>\n * @return ัะพะทะดะฐะฝะฝะพะต ััะฐััั ัะพะฑััะธะต, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n */\n public static IStatus createErrorStatus(String message, Throwable throwable)\n {\n return new Status(IStatus.ERROR, PLUGIN_ID, 0, message, throwable);\n }\n\n /**\n * ะกะพะทะดะฐะฝะธะต ะทะฐะฟะธัะธ ั ะพะฟะธัะฐะฝะธะตะผ ะฟัะตะดัะฟัะตะถะดะตะฝะธั ะฒ ะปะพะณ ะถััะฝะฐะปะต ะฟะปะฐะณะธะฝะฐ\n *\n * @param message ะพะฟะธัะฐะฝะธะต ะฟัะตะดัะฟัะตะถะดะตะฝะธั, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n * @return ัะพะทะดะฐะฝะฝะพะต ััะฐััั ัะพะฑััะธะต, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n */\n public static IStatus createWarningStatus(String message)\n {\n return new Status(IStatus.WARNING, PLUGIN_ID, 0, message, null);\n }\n\n /**\n * ะกะพะทะดะฐะฝะธะต ะทะฐะฟะธัะธ ั ะพะฟะธัะฐะฝะธะตะผ ะฟัะตะดัะฟัะตะถะดะตะฝะธั ะฒ ะปะพะณ ะถััะฝะฐะปะต ะฟะปะฐะณะธะฝะฐ ะฟะพ ะฒัะบะธะฝะพัะพะผั ะธัะบะปััะตะฝะธั ะธ ัะพะพะฑัะตะฝะธั,\n * ะตะณะพ ะพะฟะธััะฒะฐััะธะผ\n *\n * @param message ะพะฟะธัะฐะฝะธะต ะฒัะบะธะฝััะพะณะพ ะธัะบะปััะตะฝะธั, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n * @param throwable ะฒัะบะธะฝััะพะต ะธัะบะปััะตะฝะธะต, ะผะพะถะตั ะฑััั <code>null</code>\n * @return ัะพะทะดะฐะฝะฝะพะต ััะฐััั ัะพะฑััะธะต, ะฝะต ะผะพะถะตั ะฑััั <code>null</code>\n */\n public static IStatus createWarningStatus(final String message,\n Exception throwable)\n {\n return new Status(IStatus.WARNING, PLUGIN_ID, 0, message, throwable);\n }\n\n /**\n * ะะฐะฝะฝัะน ะผะตัะพะด ัะฒะปัะตััั ะฝะฐัะฐะปัะฝะพะน ัะพัะบะพะน ัะฐะฑะพัั ะฟะปะฐะณะธะฝะฐ\n *\n * @param bundleContext ะพะฑัะตะบั, ัะพะทะดะฐะฒะฐะตะผัะน OSGi Framework, ะดะปั ะดะพัััะฟะฐ ะบ ัะฐะทะฝะพะพะฑัะฐะทะฝัะผ ัะตัะฒะธัะฐะผ, ะฝะฐะฟัะธะผะตั,\n * ะฟะพ ัะฐะฑะพัะต ั ัะฐะนะปะพะฒัะผะธ ัะตััััะฐะผะธ ะฒะฝัััะธ ะฟัะพะตะบัะฐ\n */\n @Override\n public void start(BundleContext bundleContext) throws Exception\n {\n super.start(bundleContext);\n\n this.bundleContext = bundleContext;\n plugin = this;\n }\n\n /**\n * ะะฐะฝะฝัะน ะผะตัะพะด ะฒัะทัะฒะฐะตััั ะฟัะธ ะทะฐะฒะตััะตะฝะธะธ ัะฐะฑะพัั ะฟะปะฐะณะธะฝะฐ\n *\n * @param bundleContext ะพะฑัะตะบั, ัะพะทะดะฐะฒะฐะตะผัะน OSGi Framework, ะดะปั ะดะพัััะฟะฐ ะบ ัะฐะทะฝะพะพะฑัะฐะทะฝัะผ ัะตัะฒะธัะฐะผ, ะฝะฐะฟัะธะผะตั,\n * ะฟะพ ัะฐะฑะพัะต ั ัะฐะนะปะพะฒัะผะธ ัะตััััะฐะผะธ ะฒะฝัััะธ ะฟัะพะตะบัะฐ\n */\n @Override\n public void stop(BundleContext bundleContext) throws Exception\n {\n plugin = null;\n super.stop(bundleContext);\n }\n\n /**\n * ะะพะปััะธัั ะพะฑัะตะบั, ัะพะทะดะฐะฒะฐะตะผัะน OSGi Framework, ะดะปั ะดะพัััะฟะฐ ะบ ัะฐะทะฝะพะพะฑัะฐะทะฝัะผ ัะตัะฒะธัะฐะผ, ะฝะฐะฟัะธะผะตั, ะฟะพ ัะฐะฑะพัะต ั\n * ัะฐะนะปะพะฒัะผะธ ัะตััััะฐะผะธ ะฒะฝัััะธ ะฟัะพะตะบัะฐ\n *\n * @return ะพะฑัะตะบั, ัะพะทะดะฐะฒะฐะตะผัะน OSGi Framework, ะดะปั ะดะพัััะฟะฐ ะบ ัะฐะทะฝะพะพะฑัะฐะทะฝัะผ ัะตัะฒะธัะฐะผ, ะฝะฐะฟัะธะผะตั, ะฟะพ ัะฐะฑะพัะต ั\n * ัะฐะนะปะพะฒัะผะธ ัะตััััะฐะผะธ ะฒะฝัััะธ ะฟัะพะตะบัะฐ\n */\n protected BundleContext getContext()\n {\n return bundleContext;\n }\n}"
},
{
"identifier": "StringUtil",
"path": "ru.akpaev.dt.openapi/src/ru/akpaev/dt/openapi/StringUtil.java",
"snippet": "public class StringUtil\n{\n public static ArrayList<String> allMatches(Pattern pattern, String input)\n {\n var result = new ArrayList<String>();\n Matcher m = pattern.matcher(input);\n while (m.find())\n {\n result.add(m.group());\n }\n\n return result;\n }\n\n public static StringBuilder capitalizeFirstChar(String word)\n {\n var result = new StringBuilder();\n\n result.append(word.substring(0, 1).toUpperCase());\n result.append(word.substring(1).toLowerCase());\n\n return result;\n }\n}"
}
] | import java.io.FileInputStream;
import java.util.Map;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.base.Charsets;
import ru.akpaev.dt.openapi.Activator;
import ru.akpaev.dt.openapi.StringUtil; | 2,064 | /**
*
*/
package ru.akpaev.dt.openapi.models;
/**
* @author akpaev.e
*
*/
public class OpenApiRoot
{
private static Pattern inFileRefPartsPattern = Pattern.compile("(?<=/).+?(?=(/|$))"); //$NON-NLS-1$
private String fileContent;
private OpenApiInfo info;
private Map<String, OpenApiPath> paths;
private OpenApiComponents components;
public static OpenApiRoot deserializeFromFile(String path)
{
var root = new OpenApiRoot();
try (var stream = new FileInputStream(path))
{
var fileContent = new String(stream.readAllBytes(), Charsets.UTF_8);
var mapper = new ObjectMapper(new YAMLFactory());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.findAndRegisterModules();
root = mapper.readValue(fileContent, OpenApiRoot.class);
root.setFileContent(fileContent);
}
catch (Exception e)
{ | /**
*
*/
package ru.akpaev.dt.openapi.models;
/**
* @author akpaev.e
*
*/
public class OpenApiRoot
{
private static Pattern inFileRefPartsPattern = Pattern.compile("(?<=/).+?(?=(/|$))"); //$NON-NLS-1$
private String fileContent;
private OpenApiInfo info;
private Map<String, OpenApiPath> paths;
private OpenApiComponents components;
public static OpenApiRoot deserializeFromFile(String path)
{
var root = new OpenApiRoot();
try (var stream = new FileInputStream(path))
{
var fileContent = new String(stream.readAllBytes(), Charsets.UTF_8);
var mapper = new ObjectMapper(new YAMLFactory());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.findAndRegisterModules();
root = mapper.readValue(fileContent, OpenApiRoot.class);
root.setFileContent(fileContent);
}
catch (Exception e)
{ | Activator.logError(e); | 0 | 2023-12-15 22:41:41+00:00 | 4k |
ZakariaAitAli/MesDepensesTelecom | app/src/main/java/com/gi3/mesdepensestelecom/ui/recharge/RechargeSupplementFragment.java | [
{
"identifier": "getKeyByValue",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/ui/abonnement_form/AbonnementFragment.java",
"snippet": "public static int getKeyByValue(HashMap<Integer, String> hashMap, String value) {\n for (HashMap.Entry<Integer, String> entry : hashMap.entrySet()) {\n if (entry.getValue().equals(value)) {\n return entry.getKey();\n }\n }\n // Handle the case where the value is not found\n return -1;\n}"
},
{
"identifier": "Abonnement",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/Models/Abonnement.java",
"snippet": "public class Abonnement {\n\n public int Id;\n public String dateDebut;\n public String dateFin;\n public float prix;\n public int operateur;\n public int userId ;\n public int typeAbonnement;\n public Abonnement(String dateDebut, String dateFin, float prix, int operateur, int userId, int typeAbonnement) {\n this.dateDebut = dateDebut;\n this.dateFin = dateFin;\n this.prix = prix;\n this.operateur = operateur;\n this.userId = userId;\n this.typeAbonnement = typeAbonnement;\n }\npublic Abonnement(){}\n\n}"
},
{
"identifier": "Recharge",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/Models/Recharge.java",
"snippet": "public class Recharge {\n\n public int Id;\n public int idUser;\n public float prix;\n public String date;\n public int operateur;\n\n\n public Recharge(float v, int operator, int userId, String date) {\n this.prix= v;\n this.operateur= operator;\n this.idUser= userId;\n this.date = date;\n }\n public Recharge() {\n\n }\n}"
},
{
"identifier": "Supplement",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/Models/Supplement.java",
"snippet": "public class Supplement {\n public int id ;\n public int idAbonnement ;\n public float prix ;\n\n public String date ;\n\n public Supplement( int idAbonnement, float prix, String date ){\n this.idAbonnement =idAbonnement;\n this.prix=prix;\n this.date=date;\n }\n public Supplement() {\n\n }\n}"
},
{
"identifier": "RechargeRepository",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/database/RechargeRepository.java",
"snippet": "public class RechargeRepository {\n private final DatabaseHelper databaseHelper;\n\n public RechargeRepository(Context context) {\n this.databaseHelper = new DatabaseHelper(context);\n\n }\n public long insertRechargeSimple(Recharge recharge) {\n SQLiteDatabase db = databaseHelper.getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(\"somme\", recharge.prix);\n values.put(\"operateur\", recharge.operateur);\n values.put(\"userId\", recharge.idUser);\n values.put(\"date\", recharge.date);\n long result = db.insert(\"recharges\", null, values);\n db.close();\n return result;\n }\n}"
},
{
"identifier": "SupplementRepository",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/database/SupplementRepository.java",
"snippet": "public class SupplementRepository {\n private final DatabaseHelper databaseHelper;\n\n public SupplementRepository(Context context) {\n this.databaseHelper = new DatabaseHelper(context);\n\n }\n\n public HashMap<Integer, String> getAbonnementsMapByUserId(int userId){\n SQLiteDatabase db = databaseHelper.getReadableDatabase();\n String[] projection = {\"id\", \"typeAbonnement\" /* Add other columns as needed */};\n String selection = \"userId = ?\";\n String[] selectionArgs = {String.valueOf(userId)};\n Cursor cursor = db.query(\"abonnements\", projection, selection, selectionArgs, null, null, null);\n\n HashMap<Integer, String> abonnementsMap = new HashMap<>();\n if (cursor != null && cursor.moveToFirst()) {\n do {\n int id_abonnement = cursor.getInt(cursor.getColumnIndexOrThrow(\"id\"));\n int typeAbonnement = cursor.getInt(cursor.getColumnIndexOrThrow(\"typeAbonnement\"));\n String transformedType = transformTypeAbonnement(typeAbonnement);\n\n // Concatenate transformedType with id\n String value = transformedType + \"-\" + id_abonnement;\n\n // Add to the HashMap\n abonnementsMap.put(id_abonnement, value);\n } while (cursor.moveToNext());\n\n // Close the cursor after use\n cursor.close();\n }\n\n Log.d(\"abonnementsMapSize\", String.valueOf(abonnementsMap.size()));\n\n\n return abonnementsMap;\n }\n\n static String transformTypeAbonnement(int typeAbonnement) {\n // You can implement your transformation logic here\n switch (typeAbonnement) {\n case 0:\n return \"fibreOptique\";\n case 1:\n return \"WIFI\";\n case 2:\n return \"MobileAppel\";\n case 3:\n return \"Fixe\";\n case 4:\n return \"MobileInternet\";\n default:\n return \"Unknown\";\n }\n }\n\n\n public long insertRechargeSupplement(Supplement supplement) {\n SQLiteDatabase db = databaseHelper.getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(\"prix\", supplement.prix);\n values.put(\"abonnementId\", supplement.idAbonnement);\n values.put(\"date\", supplement.date);\n long result = db.insert(\"supplements\", null, values);\n db.close();\n return result;\n }\n}"
}
] | import static android.content.Context.MODE_PRIVATE;
import static com.gi3.mesdepensestelecom.R.*;
import static com.gi3.mesdepensestelecom.ui.abonnement_form.AbonnementFragment.getKeyByValue;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.gi3.mesdepensestelecom.Models.Abonnement;
import com.gi3.mesdepensestelecom.Models.Recharge;
import com.gi3.mesdepensestelecom.Models.Supplement;
import com.gi3.mesdepensestelecom.R;
import com.gi3.mesdepensestelecom.database.RechargeRepository;
import com.gi3.mesdepensestelecom.database.SupplementRepository;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; | 2,402 | package com.gi3.mesdepensestelecom.ui.recharge;
/**
* A simple {@link Fragment} subclass.
* Use the {@link RechargeSupplementFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RechargeSupplementFragment extends Fragment {
SharedPreferences sharedPreferences;
private Button btnSubmit;
private EditText editTextAmount;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Spinner spinnerAbonnement;
HashMap<Integer,String> abonnementHashMap ;
public RechargeSupplementFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment RechargeSupplementFragment.
*/
// TODO: Rename and change types and number of parameters
public static RechargeSupplementFragment newInstance(String param1, String param2) {
RechargeSupplementFragment fragment = new RechargeSupplementFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(layout.fragment_recharge_supplement, container, false) ;
sharedPreferences = requireContext().getSharedPreferences("user_session", MODE_PRIVATE);
String displayName = sharedPreferences.getString("display_name", "");
String userIdString = sharedPreferences.getString("user_id", "");
int userId = Integer.parseInt(userIdString);
abonnementHashMap = new SupplementRepository(requireContext()).getAbonnementsMapByUserId(userId);
spinnerAbonnement = view.findViewById(id.spinnerAbonnement);
editTextAmount = view.findViewById(R.id.editTextAmount);
btnSubmit = view.findViewById(R.id.btnSubmit);
populateAbonnementSpinner();
btnSubmit.setOnClickListener(view1 -> {
// Call a method to handle the insertion of data
insertRechargeSupplementData();
});
return view;
}
private void populateAbonnementSpinner(){
// Ici je vais faire appel ร une methode pour afficher la liste des abonnements de l'utilisateur avec id= id_session
List<String> nameAbonnementList = new ArrayList<>(abonnementHashMap.values());
Log.d("AbonnementListSize", String.valueOf(nameAbonnementList.size()));
ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, nameAbonnementList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAbonnement.setAdapter(adapter);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void insertRechargeSupplementData() {
// Retrieve data from UI elements
String prix = editTextAmount.getText().toString();
String selectedAbonnement = spinnerAbonnement.getSelectedItem().toString();
LocalDateTime currentDateTime = LocalDateTime.now();
// Define a formatter with the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// Format LocalDateTime to a string
String date = currentDateTime.format(formatter);
int idAbonnement = getKeyByValue(abonnementHashMap, selectedAbonnement);
// Create an Recharge object with the retrieved data | package com.gi3.mesdepensestelecom.ui.recharge;
/**
* A simple {@link Fragment} subclass.
* Use the {@link RechargeSupplementFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RechargeSupplementFragment extends Fragment {
SharedPreferences sharedPreferences;
private Button btnSubmit;
private EditText editTextAmount;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Spinner spinnerAbonnement;
HashMap<Integer,String> abonnementHashMap ;
public RechargeSupplementFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment RechargeSupplementFragment.
*/
// TODO: Rename and change types and number of parameters
public static RechargeSupplementFragment newInstance(String param1, String param2) {
RechargeSupplementFragment fragment = new RechargeSupplementFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(layout.fragment_recharge_supplement, container, false) ;
sharedPreferences = requireContext().getSharedPreferences("user_session", MODE_PRIVATE);
String displayName = sharedPreferences.getString("display_name", "");
String userIdString = sharedPreferences.getString("user_id", "");
int userId = Integer.parseInt(userIdString);
abonnementHashMap = new SupplementRepository(requireContext()).getAbonnementsMapByUserId(userId);
spinnerAbonnement = view.findViewById(id.spinnerAbonnement);
editTextAmount = view.findViewById(R.id.editTextAmount);
btnSubmit = view.findViewById(R.id.btnSubmit);
populateAbonnementSpinner();
btnSubmit.setOnClickListener(view1 -> {
// Call a method to handle the insertion of data
insertRechargeSupplementData();
});
return view;
}
private void populateAbonnementSpinner(){
// Ici je vais faire appel ร une methode pour afficher la liste des abonnements de l'utilisateur avec id= id_session
List<String> nameAbonnementList = new ArrayList<>(abonnementHashMap.values());
Log.d("AbonnementListSize", String.valueOf(nameAbonnementList.size()));
ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, nameAbonnementList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAbonnement.setAdapter(adapter);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void insertRechargeSupplementData() {
// Retrieve data from UI elements
String prix = editTextAmount.getText().toString();
String selectedAbonnement = spinnerAbonnement.getSelectedItem().toString();
LocalDateTime currentDateTime = LocalDateTime.now();
// Define a formatter with the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// Format LocalDateTime to a string
String date = currentDateTime.format(formatter);
int idAbonnement = getKeyByValue(abonnementHashMap, selectedAbonnement);
// Create an Recharge object with the retrieved data | Supplement supplement = new Supplement(idAbonnement, Float.parseFloat(prix), date); | 3 | 2023-12-20 13:43:21+00:00 | 4k |
litongjava/next-jfinal | src/main/java/com/jfinal/core/paragetter/JsonRequest.java | [
{
"identifier": "AsyncContext",
"path": "src/main/java/com/jfinal/servlet/AsyncContext.java",
"snippet": "public class AsyncContext {\n\n}"
},
{
"identifier": "DispatcherType",
"path": "src/main/java/com/jfinal/servlet/DispatcherType.java",
"snippet": "public class DispatcherType {\n\n}"
},
{
"identifier": "RequestDispatcher",
"path": "src/main/java/com/jfinal/servlet/RequestDispatcher.java",
"snippet": "public class RequestDispatcher {\n\n public void forward(HttpServletRequest request, HttpServletResponse response) {\n // TODO Auto-generated method stub\n \n }\n\n}"
},
{
"identifier": "ServletContext",
"path": "src/main/java/com/jfinal/servlet/ServletContext.java",
"snippet": "public class ServletContext {\n private String contextPath = null;\n\n public String getContextPath() {\n return contextPath;\n }\n\n public String getRealPath(String string) {\n // TODO Auto-generated method stub\n return null;\n }\n\n public String getMimeType(String name) {\n // TODO Auto-generated method stub\n return null;\n }\n\n public void setContextPath(String contextPath) {\n this.contextPath=contextPath;\n }\n\n}"
},
{
"identifier": "ServletException",
"path": "src/main/java/com/jfinal/servlet/ServletException.java",
"snippet": "public class ServletException extends RuntimeException{\n\n}"
},
{
"identifier": "ServletInputStream",
"path": "src/main/java/com/jfinal/servlet/ServletInputStream.java",
"snippet": "public class ServletInputStream extends InputStream {\n\n @Override\n public int read() throws IOException {\n // TODO Auto-generated method stub\n return 0;\n }\n\n}"
},
{
"identifier": "ServletRequest",
"path": "src/main/java/com/jfinal/servlet/ServletRequest.java",
"snippet": "public class ServletRequest {\n\n}"
},
{
"identifier": "ServletResponse",
"path": "src/main/java/com/jfinal/servlet/ServletResponse.java",
"snippet": "public class ServletResponse {\n\n}"
},
{
"identifier": "Cookie",
"path": "src/main/java/com/jfinal/servlet/http/Cookie.java",
"snippet": "public class Cookie {\n\n public Cookie(String key, String value) {\n }\n\n public void setMaxAge(int i) {\n // TODO Auto-generated method stub\n \n }\n\n public void setPath(String string) {\n // TODO Auto-generated method stub\n \n }\n\n public String getValue() {\n // TODO Auto-generated method stub\n return null;\n }\n\n public Object getName() {\n // TODO Auto-generated method stub\n return null;\n }\n\n public void setDomain(String domain) {\n // TODO Auto-generated method stub\n \n }\n\n public void setHttpOnly(Boolean isHttpOnly) {\n // TODO Auto-generated method stub\n \n }\n\n}"
},
{
"identifier": "HttpServletRequest",
"path": "src/main/java/com/jfinal/servlet/http/HttpServletRequest.java",
"snippet": "public interface HttpServletRequest {\n\n Map<String, String[]> getParameterMap();\n\n String getParameter(String name);\n\n /**\n * ่ฏฅๆนๆณๅฐ่งฆๅ createParaMap()๏ผๆกๆถๅ
้จๅบๅฐฝๅฏ่ฝ้ฟๅ
่ฏฅไบๆ
ๅ็๏ผไปฅไผๅๆง่ฝ\n */\n String[] getParameterValues(String name);\n\n Enumeration<String> getParameterNames();\n\n ServletInputStream getInputStream() throws IOException;\n\n BufferedReader getReader() throws IOException;\n\n Object getAttribute(String name);\n\n Enumeration<String> getAttributeNames();\n\n String getCharacterEncoding();\n\n void setCharacterEncoding(String env) throws UnsupportedEncodingException;\n\n int getContentLength();\n\n long getContentLengthLong();\n\n String getContentType();\n\n String getProtocol();\n\n String getScheme();\n\n String getServerName();\n\n int getServerPort();\n\n String getRemoteAddr();\n\n String getRemoteHost();\n\n void setAttribute(String name, Object o);\n\n void removeAttribute(String name);\n\n Locale getLocale();\n\n Enumeration<Locale> getLocales();\n\n boolean isSecure();\n\n RequestDispatcher getRequestDispatcher(String path);\n\n String getRealPath(String path);\n\n int getRemotePort();\n\n String getLocalName();\n\n String getLocalAddr();\n\n int getLocalPort();\n\n ServletContext getServletContext();\n\n AsyncContext startAsync() throws IllegalStateException;\n\n AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException;\n\n boolean isAsyncStarted();\n\n boolean isAsyncSupported();\n\n AsyncContext getAsyncContext();\n\n DispatcherType getDispatcherType();\n\n String getAuthType();\n\n Cookie[] getCookies();\n\n long getDateHeader(String name);\n\n String getHeader(String name);\n\n Enumeration<String> getHeaders(String name);\n\n Enumeration<String> getHeaderNames();\n\n int getIntHeader(String name);\n\n String getMethod();\n\n String getPathInfo();\n\n String getPathTranslated();\n\n String getContextPath();\n\n String getQueryString();\n\n String getRemoteUser();\n\n boolean isUserInRole(String role);\n\n Principal getUserPrincipal();\n\n String getRequestedSessionId();\n\n String getRequestURI();\n\n StringBuffer getRequestURL();\n\n String getServletPath();\n\n HttpSession getSession(boolean create);\n\n HttpSession getSession();\n\n String changeSessionId();\n\n boolean isRequestedSessionIdValid();\n\n boolean isRequestedSessionIdFromCookie();\n\n boolean isRequestedSessionIdFromURL();\n\n boolean isRequestedSessionIdFromUrl();\n\n boolean authenticate(HttpServletResponse response) throws IOException;\n\n void login(String username, String password);\n\n void logout();\n\n Collection<Part> getParts() throws IOException;\n\n Part getPart(String name) throws IOException, ServletException;\n\n <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException;\n\n}"
},
{
"identifier": "HttpServletResponse",
"path": "src/main/java/com/jfinal/servlet/http/HttpServletResponse.java",
"snippet": "public interface HttpServletResponse {\n\n int SC_NOT_FOUND = 0;\n int SC_MOVED_PERMANENTLY = 0;\n int SC_PARTIAL_CONTENT = 206;\n\n void setStatus(int errorCode);\n\n void addCookie(Cookie cookie);\n\n void setContentType(String contentType);\n\n PrintWriter getWriter() throws IOException;\n\n void setHeader(String string, String url);\n\n void sendRedirect(String url) throws IOException;\n\n void setCharacterEncoding(String defaultEncoding);\n\n ServletOutputStream getOutputStream();\n\n void setDateHeader(String string, int i);\n\n HttpResponse finish() throws IOException;\n\n}"
},
{
"identifier": "HttpSession",
"path": "src/main/java/com/jfinal/servlet/http/HttpSession.java",
"snippet": "public interface HttpSession {\n\n public Object getAttribute(String key);\n\n public void setAttribute(String key, Object value) ;\n\n public void removeAttribute(String key);\n\n public Enumeration<String> getAttributeNames();\n\n public long getCreationTime();\n\n public String getId();\n\n public long getLastAccessedTime();\n\n public int getMaxInactiveInterval();\n\n public ServletContext getServletContext();\n\n public HttpSessionContext getSessionContext();\n\n public Object getValue(String key);\n\n public String[] getValueNames();\n\n public void invalidate();\n\n public boolean isNew();\n\n public void putValue(String key, Object value);\n\n public void removeValue(String key);\n\n public void setMaxInactiveInterval(int maxInactiveInterval);\n\n}"
},
{
"identifier": "HttpUpgradeHandler",
"path": "src/main/java/com/jfinal/servlet/http/HttpUpgradeHandler.java",
"snippet": "public class HttpUpgradeHandler {\n\n}"
},
{
"identifier": "Part",
"path": "src/main/java/com/jfinal/servlet/multipart/Part.java",
"snippet": "public class Part {\n\n}"
}
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import com.jfinal.servlet.AsyncContext;
import com.jfinal.servlet.DispatcherType;
import com.jfinal.servlet.RequestDispatcher;
import com.jfinal.servlet.ServletContext;
import com.jfinal.servlet.ServletException;
import com.jfinal.servlet.ServletInputStream;
import com.jfinal.servlet.ServletRequest;
import com.jfinal.servlet.ServletResponse;
import com.jfinal.servlet.http.Cookie;
import com.jfinal.servlet.http.HttpServletRequest;
import com.jfinal.servlet.http.HttpServletResponse;
import com.jfinal.servlet.http.HttpSession;
import com.jfinal.servlet.http.HttpUpgradeHandler;
import com.jfinal.servlet.multipart.Part; | 3,370 | throws IllegalStateException {
return req.startAsync(servletRequest, servletResponse);
}
@Override
public boolean isAsyncStarted() {
return req.isAsyncStarted();
}
@Override
public boolean isAsyncSupported() {
return req.isAsyncSupported();
}
@Override
public AsyncContext getAsyncContext() {
return req.getAsyncContext();
}
@Override
public DispatcherType getDispatcherType() {
return req.getDispatcherType();
}
@Override
public String getAuthType() {
return req.getAuthType();
}
@Override
public Cookie[] getCookies() {
return req.getCookies();
}
@Override
public long getDateHeader(String name) {
return req.getDateHeader(name);
}
@Override
public String getHeader(String name) {
return req.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
return req.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
return req.getHeaderNames();
}
@Override
public int getIntHeader(String name) {
return req.getIntHeader(name);
}
@Override
public String getMethod() {
return req.getMethod();
}
@Override
public String getPathInfo() {
return req.getPathInfo();
}
@Override
public String getPathTranslated() {
return req.getPathTranslated();
}
@Override
public String getContextPath() {
return req.getContextPath();
}
@Override
public String getQueryString() {
return req.getQueryString();
}
@Override
public String getRemoteUser() {
return req.getRemoteUser();
}
@Override
public boolean isUserInRole(String role) {
return req.isUserInRole(role);
}
@Override
public Principal getUserPrincipal() {
return req.getUserPrincipal();
}
@Override
public String getRequestedSessionId() {
return req.getRequestedSessionId();
}
@Override
public String getRequestURI() {
return req.getRequestURI();
}
@Override
public StringBuffer getRequestURL() {
return req.getRequestURL();
}
@Override
public String getServletPath() {
return req.getServletPath();
}
@Override | /**
* Copyright (c) 2011-2023, James Zhan ่ฉนๆณข ([email protected]) / ็้
็ (myaniu AT gmail dot 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.paragetter;
/**
* JsonRequest ๅ
่ฃ
json ่ฏทๆฑ๏ผไปๅบๅฑๆฅ็ฎกๆๆ parameter ๆไฝ
*/
public class JsonRequest implements HttpServletRequest {
// ็ผๅญ JSONObjectใJSONArray ๅฏน่ฑก
private com.alibaba.fastjson.JSONObject jsonObject;
private com.alibaba.fastjson.JSONArray jsonArray;
// ๅ
่ฃ
่ฏทๆฑๅฏน่ฑก
private HttpServletRequest req;
// ้่ฟ JSONObject ๅปถ่ฟ็ๆ paraMap
private HashMap<String, String[]> paraMap;
public JsonRequest(String jsonString, HttpServletRequest req) {
Object json = com.alibaba.fastjson.JSON.parse(jsonString);
if (json instanceof com.alibaba.fastjson.JSONObject) {
jsonObject = (com.alibaba.fastjson.JSONObject) json;
} else if (json instanceof com.alibaba.fastjson.JSONArray) {
jsonArray = (com.alibaba.fastjson.JSONArray) json;
}
this.req = req;
}
/**
* ็ฌฌไธไธช็ๆฌๅชๅ็ฎๅ่ฝฌๆข๏ผ็จๆท่ทๅ JSONObject ไธ JSONArray ๅๅฏไปฅ่ฟไธๆญฅ่ฟ่กๅคๆ่ฝฌๆข
*/
public com.alibaba.fastjson.JSONObject getJSONObject() {
return jsonObject;
}
public com.alibaba.fastjson.JSONArray getJSONArray() {
return jsonArray;
}
/*
* public Map<String, Object> getJsonMap() { return jsonObject; } public java.util.List<Object> getJsonList() { return jsonArray; }
*/
/**
* ่ทๅๅ
้จ HttpServletRequest ๅฏน่ฑก
*/
public HttpServletRequest getInnerRequest() {
return req;
}
/**
* ่ฏทๆฑๅๆฐๆฏๅฆไธบ JSONObject ๅฏน่ฑก
*/
public boolean isJSONObject() {
return jsonObject != null;
}
/**
* ่ฏทๆฑๅๆฐๆฏๅฆไธบ JSONArray ๅฏน่ฑก
*/
public boolean isJSONArray() {
return jsonArray != null;
}
// ๅปถ่ฟๅๅปบ๏ผไธๆฏๆฏๆฌก้ฝไผ่ฐ็จ parameter ็ธๅ
ณๆนๆณ
private HashMap<String, String[]> getParaMap() {
if (paraMap == null) {
paraMap = (jsonObject != null ? createParaMap(jsonObject) : new HashMap<>());
}
return paraMap;
}
private HashMap<String, String[]> createParaMap(com.alibaba.fastjson.JSONObject jsonPara) {
HashMap<String, String[]> newPara = new HashMap<>();
// ๅ
่ฏปๅ parameter๏ผๅฆๅๅ็ปญไปๆตไธญ่ฏปๅ rawData ๅๅฐๆ ๆณ่ฏปๅ parameter๏ผ้จๅ servlet ๅฎนๅจ๏ผ
Map<String, String[]> oldPara = req.getParameterMap();
if (oldPara != null && oldPara.size() > 0) {
newPara.putAll(oldPara);
}
for (Map.Entry<String, Object> e : jsonPara.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
// ๅช่ฝฌๆขๆๅค้ขไธๅฑ json ๆฐๆฎ๏ผๅฆๆๅญๅจๅคๅฑ json ็ปๆ๏ผไป
ๅฐๅ
ถ่งไธบ String ็็ปๅ็ปญๆต็จ่ฝฌๆข
if (value instanceof com.alibaba.fastjson.JSON) {
newPara.put(key, new String[] { ((com.alibaba.fastjson.JSON) value).toJSONString() });
} else if (value != null) {
newPara.put(key, new String[] { value.toString() });
} else {
// ้่ฆ่่ value ๆฏๅฆ่ฝฌๆ String[] array = {""}๏ผActionRepoter.getParameterValues() ๆไพ่ต
newPara.put(key, null);
}
}
return newPara;
}
@Override
public String getParameter(String name) {
// String[] ret = getParaMap().get(name);
// return ret != null && ret.length != 0 ? ret[0] : null;
// ไผๅๆง่ฝ๏ผ้ฟๅ
่ฐ็จ getParaMap() ่งฆๅ่ฐ็จ createParaMap()๏ผไป่ๅคงๆฆ็้ฟๅ
ๅฏนๆดไธช jsonObject ่ฟ่ก่ฝฌๆข
if (jsonObject != null && jsonObject.containsKey(name)) {
Object value = jsonObject.get(name);
if (value instanceof com.alibaba.fastjson.JSON) {
return ((com.alibaba.fastjson.JSON) value).toJSONString();
} else if (value != null) {
return value.toString();
} else {
// ้่ฆ่่ๆฏๅฆ่ฟๅ ""๏ผ่กจๅๆไบค่ฏทๆฑๅช่ฆ name ๅญๅจๅๅผไธไผไธบ null
return null;
}
} else {
return req.getParameter(name);
}
}
/**
* ่ฏฅๆนๆณๅฐ่งฆๅ createParaMap()๏ผๆกๆถๅ
้จๅบๅฐฝๅฏ่ฝ้ฟๅ
่ฏฅไบๆ
ๅ็๏ผไปฅไผๅๆง่ฝ
*/
@Override
public Map<String, String[]> getParameterMap() {
return getParaMap();
}
/**
* ่ฏฅๆนๆณๅฐ่งฆๅ createParaMap()๏ผๆกๆถๅ
้จๅบๅฐฝๅฏ่ฝ้ฟๅ
่ฏฅไบๆ
ๅ็๏ผไปฅไผๅๆง่ฝ
*/
@Override
public String[] getParameterValues(String name) {
return getParaMap().get(name);
}
@Override
public Enumeration<String> getParameterNames() {
// return Collections.enumeration(getParaMap().keySet());
if (jsonObject != null) {
return Collections.enumeration(jsonObject.keySet());
} else {
return Collections.emptyEnumeration();
}
}
// ---------------------------------------------------------------
// ไปฅไธๆนๆณไป
ไธบๅฏน req ๅฏน่ฑก็่ฝฌ่ฐ -------------------------------------
@Override
public ServletInputStream getInputStream() throws IOException {
return req.getInputStream();
}
@Override
public BufferedReader getReader() throws IOException {
return req.getReader();
}
@Override
public Object getAttribute(String name) {
return req.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return req.getAttributeNames();
}
@Override
public String getCharacterEncoding() {
return req.getCharacterEncoding();
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
req.setCharacterEncoding(env);
}
@Override
public int getContentLength() {
return req.getContentLength();
}
@Override
public long getContentLengthLong() {
return req.getContentLengthLong();
}
@Override
public String getContentType() {
return req.getContentType();
}
@Override
public String getProtocol() {
return req.getProtocol();
}
@Override
public String getScheme() {
return req.getScheme();
}
@Override
public String getServerName() {
return req.getServerName();
}
@Override
public int getServerPort() {
return req.getServerPort();
}
@Override
public String getRemoteAddr() {
return req.getRemoteAddr();
}
@Override
public String getRemoteHost() {
return req.getRemoteHost();
}
@Override
public void setAttribute(String name, Object o) {
req.setAttribute(name, o);
}
@Override
public void removeAttribute(String name) {
req.removeAttribute(name);
}
@Override
public Locale getLocale() {
return req.getLocale();
}
@Override
public Enumeration<Locale> getLocales() {
return req.getLocales();
}
@Override
public boolean isSecure() {
return req.isSecure();
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return req.getRequestDispatcher(path);
}
@Override
public String getRealPath(String path) {
return req.getRealPath(path);
}
@Override
public int getRemotePort() {
return req.getRemotePort();
}
@Override
public String getLocalName() {
return req.getLocalName();
}
@Override
public String getLocalAddr() {
return req.getLocalAddr();
}
@Override
public int getLocalPort() {
return req.getLocalPort();
}
@Override
public ServletContext getServletContext() {
return req.getServletContext();
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return req.startAsync();
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
return req.startAsync(servletRequest, servletResponse);
}
@Override
public boolean isAsyncStarted() {
return req.isAsyncStarted();
}
@Override
public boolean isAsyncSupported() {
return req.isAsyncSupported();
}
@Override
public AsyncContext getAsyncContext() {
return req.getAsyncContext();
}
@Override
public DispatcherType getDispatcherType() {
return req.getDispatcherType();
}
@Override
public String getAuthType() {
return req.getAuthType();
}
@Override
public Cookie[] getCookies() {
return req.getCookies();
}
@Override
public long getDateHeader(String name) {
return req.getDateHeader(name);
}
@Override
public String getHeader(String name) {
return req.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
return req.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
return req.getHeaderNames();
}
@Override
public int getIntHeader(String name) {
return req.getIntHeader(name);
}
@Override
public String getMethod() {
return req.getMethod();
}
@Override
public String getPathInfo() {
return req.getPathInfo();
}
@Override
public String getPathTranslated() {
return req.getPathTranslated();
}
@Override
public String getContextPath() {
return req.getContextPath();
}
@Override
public String getQueryString() {
return req.getQueryString();
}
@Override
public String getRemoteUser() {
return req.getRemoteUser();
}
@Override
public boolean isUserInRole(String role) {
return req.isUserInRole(role);
}
@Override
public Principal getUserPrincipal() {
return req.getUserPrincipal();
}
@Override
public String getRequestedSessionId() {
return req.getRequestedSessionId();
}
@Override
public String getRequestURI() {
return req.getRequestURI();
}
@Override
public StringBuffer getRequestURL() {
return req.getRequestURL();
}
@Override
public String getServletPath() {
return req.getServletPath();
}
@Override | public HttpSession getSession(boolean create) { | 11 | 2023-12-19 10:58:33+00:00 | 4k |
ViniciusJPSilva/TSI-PizzeriaExpress | PizzeriaExpress/src/main/java/br/vjps/tsi/pe/managedbeans/ChefMB.java | [
{
"identifier": "DAO",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/DAO.java",
"snippet": "public class DAO<T> {\n\tprivate Class<T> tClass;\n\n\t/**\n * Construtor que recebe a classe da entidade para ser manipulada pelo DAO.\n *\n * @param tClass A classe da entidade.\n */\n\tpublic DAO(Class<T> tClass) {\n\t\tthis.tClass = tClass;\n\t}\n\n\t/**\n * Adiciona uma nova entidade ao banco de dados.\n *\n * @param t A entidade a ser adicionada.\n */\n\tpublic void add(T t) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\n\t\tmanager.getTransaction().begin();\n\t\tmanager.persist(t);\n\t\tmanager.getTransaction().commit();\n\t\tmanager.close();\n\t}\n\n\t/**\n * Atualiza uma entidade no banco de dados.\n *\n * @param t A entidade a ser atualizada.\n */\n\tpublic void update(T t) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\n\t\tmanager.getTransaction().begin();\n\t\tmanager.merge(t);\n\t\tmanager.getTransaction().commit();\n\t\tmanager.close();\n\t}\n\n\t/**\n * Remove uma entidade do banco de dados.\n *\n * @param t A entidade a ser removida.\n */\n\tpublic void remove(T t) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\n\t\tmanager.getTransaction().begin();\n\t\tmanager.remove(manager.merge(t));\n\t\tmanager.getTransaction().commit();\n\t\tmanager.close();\n\t}\n\n\t/**\n * Busca uma entidade pelo seu identificador รบnico (ID) no banco de dados.\n *\n * @param id O identificador รบnico da entidade.\n * @return A entidade correspondente ao ID fornecido ou null se nรฃo encontrada.\n */\n\tpublic T findById(Long id) {\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\t\treturn manager.find(tClass, id);\n\t}\n\t\n\t/**\n * Retorna uma lista de todas as entidades do tipo especificado no banco de dados.\n *\n * @return Uma lista contendo todas as entidades do tipo especificado.\n */\n\tpublic List<T> list(){\n\t\tEntityManager manager = new JPAUtil().getEntityManager();\n\t\tCriteriaQuery<T> query = manager.getCriteriaBuilder().createQuery(tClass);\n\t\tquery.select(query.from(tClass));\n\t\tList<T> list = manager.createQuery(query).getResultList();\n\t\tmanager.close();\n\t\treturn list;\n\t}\n}"
},
{
"identifier": "RequestDAO",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/RequestDAO.java",
"snippet": "public class RequestDAO implements Closeable {\n\tprivate EntityManager manager;\n\n\t/**\n\t * Construtor padrรฃo que inicializa o EntityManager usando a classe utilitรกria\n\t * JPAUtil.\n\t */\n\tpublic RequestDAO() {\n\t\tmanager = new JPAUtil().getEntityManager();\n\t}\n\t\n\t/**\n\t * Obtรฉm o pedido corrente, em aberto, do cliente informado.\n\t * \n\t * @param client O cliente cujo pedido serรก buscado.\n\t * @return O pedido encontrado ou null se nรฃo encontrado.\n\t * \n\t * @throws IllegalArgumentException Se o client fornecido for nulo.\n\t */\n\tpublic Request getOpenRequestForClient(Client client) {\n\t\tif (client == null)\n\t\t\tthrow new IllegalArgumentException(\"Login nรฃo pode ser nulo!\");\n\t\t\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Request u WHERE u.client = :client AND u.open = TRUE\", Request.class);\n\t\tquery.setParameter(\"client\", client);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Request> list = query.getResultList();\n\n\t\treturn list.isEmpty() ? null : list.get(0);\n\t}\n\t\n\t/**\n\t * Obtรฉm a lista de pedidos fechadas.\n\t * \n\t * @return Lista de pedidos fechadas.\n\t */\n\tpublic List<Request> getClosedRequests(Calendar date) {\n\t\tif(date == null)\n\t\t\tthrow new IllegalArgumentException(\"Data nรฃo pode ser nulo!\");\n\t\t\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Request u WHERE u.open = FALSE AND u.date = :date\", Request.class);\n\t\tquery.setParameter(\"date\", date, TemporalType.DATE);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Request> list = query.getResultList();\n\n\t\treturn list;\n\t}\n\t\n\t/**\n\t * Obtรฉm a lista de pedidos em aberto.\n\t * \n\t * @return Lista de pedidos em aberto.\n\t */\n\tpublic List<Request> getOpenedRequests() {\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Request u WHERE u.open = TRUE\", Request.class);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Request> list = query.getResultList();\n\n\t\treturn list;\n\t}\n\t\n\t/**\n * Fecha o EntityManager quando este objeto ClientDAO รฉ fechado.\n *\n * @throws IOException Se ocorrer um erro ao fechar o EntityManager.\n */\n\t@Override\n\tpublic void close() throws IOException {\n\t\tmanager.close();\n\t}\n}"
},
{
"identifier": "Item",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Item.java",
"snippet": "@Entity\npublic class Item {\n\t\n\t@Id\n\t@SequenceGenerator(name = \"item_id\", sequenceName = \"item_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"item_id\")\n\tprivate Long id;\n\t\n\t@Min(value = 1L, message = \"A quantidade deve ser maior ou igual a 1\")\n\tprivate Integer quantity;\n\t\n\tprivate Double unitPrice;\n\t\n\tprivate Double totalCost;\n\t\n\t@ManyToOne\n\tprivate Product product;\n\t\n\t@ManyToOne\n\tprivate Request request;\n\t\n\tprivate boolean delivered;\n\t\n\t// Inicia o valor do atributo no momento da instanciaรงรฃo do objeto.\n\t{\n\t\tunitPrice = 0.0;\n\t\ttotalCost = 0.0;\n\t\tdelivered = false;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Integer getQuantity() {\n\t\treturn quantity;\n\t}\n\n\tpublic void setQuantity(Integer quantity) {\n\t\tthis.quantity = quantity;\n\t}\n\n\tpublic Double getUnitPrice() {\n\t\treturn unitPrice;\n\t}\n\n\tpublic void setUnitPrice(Double unitPrice) {\n\t\tthis.unitPrice = unitPrice;\n\t}\n\n\tpublic Double getTotalCost() {\n\t\ttotalCost = (unitPrice != null && quantity != null) ? (unitPrice * quantity) : 0.0;\n\t\treturn totalCost;\n\t}\n\n\tpublic void setTotalCost(Double totalCost) {\n\t\tthis.totalCost = totalCost;\n\t}\n\n\tpublic Product getProduct() {\n\t\treturn product;\n\t}\n\n\tpublic void setProduct(Product product) {\n\t\tthis.product = product;\n\t}\n\n\tpublic Request getRequest() {\n\t\treturn request;\n\t}\n\n\tpublic void setRequest(Request request) {\n\t\tthis.request = request;\n\t}\n\n\tpublic boolean isDelivered() {\n\t\treturn delivered;\n\t}\n\n\tpublic void setDelivered(boolean delivered) {\n\t\tthis.delivered = delivered;\n\t}\n\t\n}"
},
{
"identifier": "Request",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Request.java",
"snippet": "@Entity\npublic class Request {\n\n\t@Id\n\t@SequenceGenerator(name = \"request_id\", sequenceName = \"request_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"request_id\")\n\tprivate Long id;\n\t\n\t@Temporal(TemporalType.DATE)\n\tprivate Calendar date = Calendar.getInstance();\n\t\n\t@OneToMany(cascade = CascadeType.ALL, mappedBy=\"request\", fetch = FetchType.EAGER)\n private List<Item> items = new ArrayList<>();\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"client\")\n\tprivate Client client;\n\t\n\tprivate Double value;\n\t\n\t@NotNull(message = \"Forneรงa uma mesa\")\n\tprivate Integer tableNumber;\n\t\n\tprivate boolean open;\n\t\n\tprivate boolean voucher;\n\t\n\t{\n\t\topen = true;\n\t\tvoucher = false;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Calendar getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setDate(Calendar date) {\n\t\tthis.date = date;\n\t}\n\n\tpublic List<Item> getItems() {\n\t\treturn items;\n\t}\n\n\tpublic void setItems(List<Item> items) {\n\t\tthis.items = items;\n\t}\n\n\tpublic Client getClient() {\n\t\treturn client;\n\t}\n\n\tpublic void setClient(Client client) {\n\t\tthis.client = client;\n\t}\n\n\tpublic Double getValue() {\n\t\tif(open)\n\t\t\tvalue = items.stream().mapToDouble(Item::getTotalCost).sum();\n\t\treturn value;\n\t}\n\n\tpublic void setValue(Double value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic Integer getTableNumber() {\n\t\treturn tableNumber;\n\t}\n\n\tpublic void setTableNumber(Integer tableNumber) {\n\t\tthis.tableNumber = tableNumber;\n\t}\n\n\tpublic boolean isOpen() {\n\t\treturn open;\n\t}\n\n\tpublic void setOpen(boolean open) {\n\t\tthis.open = open;\n\t}\n\n\tpublic boolean isVoucher() {\n\t\treturn voucher;\n\t}\n\n\tpublic void setVoucher(boolean voucher) {\n\t\tthis.voucher = voucher;\n\t}\n\t\n}"
}
] | import java.io.IOException;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import br.vjps.tsi.pe.dao.DAO;
import br.vjps.tsi.pe.dao.RequestDAO;
import br.vjps.tsi.pe.model.Item;
import br.vjps.tsi.pe.model.Request; | 2,673 | package br.vjps.tsi.pe.managedbeans;
@SessionScoped
@ManagedBean
public class ChefMB {
private Request chefRequest;
private List<Request> openRequests;
/**
* Define o pedido que estรก sendo servido pelo chef e redireciona para a pรกgina de serviรงo.
*
* @param request Pedido que estรก sendo servido.
* @return Redireciona para a pรกgina de serviรงo.
*/
public String serve(Request request) {
setChefRequest(request);
return"serve-request?faces-redirect=true";
}
/**
* Atualiza o estado do pedido.
* Imprime no console o estado de entrega de cada item do pedido do chef.
*/
public void updateRequest() { | package br.vjps.tsi.pe.managedbeans;
@SessionScoped
@ManagedBean
public class ChefMB {
private Request chefRequest;
private List<Request> openRequests;
/**
* Define o pedido que estรก sendo servido pelo chef e redireciona para a pรกgina de serviรงo.
*
* @param request Pedido que estรก sendo servido.
* @return Redireciona para a pรกgina de serviรงo.
*/
public String serve(Request request) {
setChefRequest(request);
return"serve-request?faces-redirect=true";
}
/**
* Atualiza o estado do pedido.
* Imprime no console o estado de entrega de cada item do pedido do chef.
*/
public void updateRequest() { | for(Item item : chefRequest.getItems()) | 2 | 2023-12-16 01:25:27+00:00 | 4k |
my-virtual-hub/omni-comm-domain | src/main/java/br/com/myvirtualhub/omni/domain/sms/model/SmsPayload.java | [
{
"identifier": "PhoneNumberException",
"path": "src/main/java/br/com/myvirtualhub/omni/domain/core/exceptions/PhoneNumberException.java",
"snippet": "public class PhoneNumberException extends OmniException{\n /**\n * Constructs a new PhoneNumberException with the specified message.\n *\n * @param message the detail message for the exception\n */\n public PhoneNumberException(String message) {\n super(message);\n }\n\n /**\n * Constructs a new PhoneNumberException with the specified message and cause.\n *\n * @param message the detail message for the exception\n * @param cause the cause of the exception\n * @throws NullPointerException if the message is null\n */\n public PhoneNumberException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Exception used to indicate issues with phone number operations.\n *\n * <p>This is a specific type of {@link OmniException}. It should be used\n * for exceptional conditions related to phone number processing such as\n * validation, formatting, parsing, or other phone number related errors.\n *\n * @param message the detail message for the exception\n * @param throwableCause the cause of the exception as a string\n */\n public PhoneNumberException( String message , String throwableCause) {\n super(message, throwableCause);\n }\n}"
},
{
"identifier": "Copyable",
"path": "src/main/java/br/com/myvirtualhub/omni/domain/core/model/interfaces/Copyable.java",
"snippet": "public interface Copyable<T> {\n /**\n * Creates a copy of the object.\n *\n * @return a copy of the object\n * @throws PhoneNumberException if there is an issue with phone number operations while creating the copy\n */\n T copy() throws PhoneNumberException;\n}"
},
{
"identifier": "Model",
"path": "src/main/java/br/com/myvirtualhub/omni/domain/core/model/interfaces/Model.java",
"snippet": "public interface Model {\n\n /**\n * Masks the sensitive data. If the sensitive data length is smaller than 5 or is null, the returned string will contain only asterisks.\n * If the length is equal or larger than 5, the first 20% of the characters will be visible and the remaining characters will be replaced by asterisks.\n *\n * @param sensitiveData The sensitive data in form of a string that should be masked.\n * @return The masked string. If sensitiveData is null, a single asterisk is returned.\n */\n default String printSensitiveData(String sensitiveData) {\n if (sensitiveData == null) {\n return \"*\";\n }\n else if (sensitiveData.length() < 5) {\n return \"*\".repeat(sensitiveData.length());\n }\n\n int visibleLength = (int)Math.ceil(sensitiveData.length() * 0.2);\n StringBuilder output = new StringBuilder(sensitiveData.length());\n\n output.append(sensitiveData, 0, visibleLength);\n while (output.length() < sensitiveData.length()) {\n output.append('*');\n }\n\n return output.toString();\n }\n}"
}
] | import br.com.myvirtualhub.omni.domain.core.exceptions.PhoneNumberException;
import br.com.myvirtualhub.omni.domain.core.model.interfaces.Copyable;
import br.com.myvirtualhub.omni.domain.core.model.interfaces.Model;
import java.util.Objects; | 1,678 | /*
* Copyright (c) 2024.
*
* This software is provided under the BSD-2-Clause license. By using this software,
* * you agree to respect the terms and conditions of the BSD-2-Clause license.
*/
package br.com.myvirtualhub.omni.domain.sms.model;
/**
* Represents an SMS Payload message with details for sending and tracking.
*
* @author Marco Quiรงula
* @version 1.0
* @since 2024-01-09
*/
public class SmsPayload implements Model, Copyable<SmsPayload> {
private SmsRecipient recipient;
private SmsMessage message;
private String clientMessageId;
private final SmsOmniProcessId smsOmniProcessId;
/**
* Constructs a new SmsPayload.
*
* @param recipient The phone number of the message recipient.
* @param message The text content of the message.
* @param clientMessageId A unique identifier provided by the client for tracking.
*/
public SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = new SmsOmniProcessId();
}
private SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId, SmsOmniProcessId smsOmniProcessId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = smsOmniProcessId;
}
/**
* Retrieves the recipient of the SMS payload.
*
* @return The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public SmsRecipient getRecipient() {
return recipient;
}
/**
* Sets the recipient of the SMS payload.
*
* @param recipient The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public void setRecipient(SmsRecipient recipient) {
this.recipient = recipient;
}
/**
* Retrieves the message of the SMS payload.
*
* @return The message of the SMS payload as an instance of the SmsMessage class.
* @see SmsPayload
* @see SmsMessage
*/
public SmsMessage getMessage() {
return message;
}
/**
* Sets the message of the SMS payload.
*
* @param message The message of the SMS payload as an instance of the SmsMessage class.
*/
public void setMessage(SmsMessage message) {
this.message = message;
}
/**
* Retrieves the client message ID associated with the SMS payload.
*
* @return The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public String getClientMessageId() {
return clientMessageId;
}
/**
* Sets the client message ID associated with the SMS payload.
* This method sets the client message ID provided by the client for tracking purposes.
* The client message ID is a unique identifier associated with the SMS payload.
*
* @param clientMessageId The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public void setClientMessageId(String clientMessageId) {
this.clientMessageId = clientMessageId;
}
/**
* Retrieves the OmniMessageId associated with the SMS payload.
*
* @return The OmniMessageId of the SMS payload as an instance of the SmsOmniProcessId class.
* @see SmsPayload
* @see SmsOmniProcessId
*/
public SmsOmniProcessId getOmniMessageId() {
return smsOmniProcessId;
}
/**
* Creates a copy of the SmsPayload object.
*
* @return A copy of the SmsPayload object.
* @throws PhoneNumberException if there is an issue with the phone number
* @see SmsPayload
* @see PhoneNumberException
*/
@Override | /*
* Copyright (c) 2024.
*
* This software is provided under the BSD-2-Clause license. By using this software,
* * you agree to respect the terms and conditions of the BSD-2-Clause license.
*/
package br.com.myvirtualhub.omni.domain.sms.model;
/**
* Represents an SMS Payload message with details for sending and tracking.
*
* @author Marco Quiรงula
* @version 1.0
* @since 2024-01-09
*/
public class SmsPayload implements Model, Copyable<SmsPayload> {
private SmsRecipient recipient;
private SmsMessage message;
private String clientMessageId;
private final SmsOmniProcessId smsOmniProcessId;
/**
* Constructs a new SmsPayload.
*
* @param recipient The phone number of the message recipient.
* @param message The text content of the message.
* @param clientMessageId A unique identifier provided by the client for tracking.
*/
public SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = new SmsOmniProcessId();
}
private SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId, SmsOmniProcessId smsOmniProcessId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = smsOmniProcessId;
}
/**
* Retrieves the recipient of the SMS payload.
*
* @return The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public SmsRecipient getRecipient() {
return recipient;
}
/**
* Sets the recipient of the SMS payload.
*
* @param recipient The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public void setRecipient(SmsRecipient recipient) {
this.recipient = recipient;
}
/**
* Retrieves the message of the SMS payload.
*
* @return The message of the SMS payload as an instance of the SmsMessage class.
* @see SmsPayload
* @see SmsMessage
*/
public SmsMessage getMessage() {
return message;
}
/**
* Sets the message of the SMS payload.
*
* @param message The message of the SMS payload as an instance of the SmsMessage class.
*/
public void setMessage(SmsMessage message) {
this.message = message;
}
/**
* Retrieves the client message ID associated with the SMS payload.
*
* @return The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public String getClientMessageId() {
return clientMessageId;
}
/**
* Sets the client message ID associated with the SMS payload.
* This method sets the client message ID provided by the client for tracking purposes.
* The client message ID is a unique identifier associated with the SMS payload.
*
* @param clientMessageId The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public void setClientMessageId(String clientMessageId) {
this.clientMessageId = clientMessageId;
}
/**
* Retrieves the OmniMessageId associated with the SMS payload.
*
* @return The OmniMessageId of the SMS payload as an instance of the SmsOmniProcessId class.
* @see SmsPayload
* @see SmsOmniProcessId
*/
public SmsOmniProcessId getOmniMessageId() {
return smsOmniProcessId;
}
/**
* Creates a copy of the SmsPayload object.
*
* @return A copy of the SmsPayload object.
* @throws PhoneNumberException if there is an issue with the phone number
* @see SmsPayload
* @see PhoneNumberException
*/
@Override | public SmsPayload copy() throws PhoneNumberException { | 0 | 2023-12-18 03:42:25+00:00 | 4k |
IzanagiCraft/izanagi-librarian | izanagi-librarian-shared/src/main/java/com/izanagicraft/librarian/players/IzanagiPlayer.java | [
{
"identifier": "DiscordConnection",
"path": "izanagi-librarian-shared/src/main/java/com/izanagicraft/librarian/connection/DiscordConnection.java",
"snippet": "public interface DiscordConnection {\n\n /**\n * Link the Discord user's account with their Minecraft account.\n *\n * @param discordId The unique ID of the user in Discord.\n * @param playerId The unique ID of the player in Minecraft.\n * @return true if the connection is successful, false otherwise.\n */\n boolean linkDiscordToMinecraft(String discordId, String playerId);\n\n /**\n * Get the Minecraft ID linked to the specified Discord user.\n *\n * @param discordId The unique ID of the user in Discord.\n * @return The Minecraft ID linked to the Discord user, or null if not linked.\n */\n String getMinecraftId(String discordId);\n\n /**\n * Remove the link between the Discord user's account and their Minecraft account.\n *\n * @param discordId The unique ID of the user in Discord.\n * @return true if the disconnection is successful, false otherwise.\n */\n boolean unlinkDiscordFromMinecraft(String discordId);\n\n /**\n * Check if a connection exists between the Discord user and Minecraft player.\n *\n * @param discordId The unique ID of the user in Discord.\n * @return true if a connection is present, false otherwise.\n */\n boolean isConnectionPresent(String discordId);\n\n /**\n * Asynchronously link the Discord user's account with their Minecraft account.\n *\n * @param discordId The unique ID of the user in Discord.\n * @param playerId The unique ID of the player in Minecraft.\n * @return A CompletableFuture representing the success of the connection.\n */\n default CompletableFuture<Boolean> linkDiscordToMinecraftAsync(String discordId, String playerId) {\n return CompletableFuture.supplyAsync(() -> linkDiscordToMinecraft(discordId, playerId));\n }\n\n /**\n * Asynchronously get the Minecraft ID linked to the specified Discord user.\n *\n * @param discordId The unique ID of the user in Discord.\n * @return A CompletableFuture with the Minecraft ID linked to the Discord user,\n * or null if not linked.\n */\n default CompletableFuture<String> getMinecraftIdAsync(String discordId) {\n return CompletableFuture.supplyAsync(() -> getMinecraftId(discordId));\n }\n\n /**\n * Asynchronously remove the link between the Discord user's account and their Minecraft account.\n *\n * @param discordId The unique ID of the user in Discord.\n * @return A CompletableFuture representing the success of the disconnection.\n */\n default CompletableFuture<Boolean> unlinkDiscordFromMinecraftAsync(String discordId) {\n return CompletableFuture.supplyAsync(() -> unlinkDiscordFromMinecraft(discordId));\n }\n\n /**\n * Asynchronously check if a connection exists between the Discord user and Minecraft player.\n *\n * @param discordId The unique ID of the user in Discord.\n * @return A CompletableFuture with a boolean indicating if a connection is present.\n */\n default CompletableFuture<Boolean> isConnectionPresentAsync(String discordId) {\n return CompletableFuture.supplyAsync(() -> isConnectionPresent(discordId));\n }\n\n}"
},
{
"identifier": "MinecraftConnection",
"path": "izanagi-librarian-shared/src/main/java/com/izanagicraft/librarian/connection/MinecraftConnection.java",
"snippet": "public interface MinecraftConnection {\n\n /**\n * Link the player's Minecraft account with their Discord account.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @param discordId The unique ID of the user in Discord.\n * @return true if the connection is successful, false otherwise.\n */\n boolean linkMinecraftToDiscord(String playerId, String discordId);\n\n /**\n * Get the Discord ID linked to the specified Minecraft player.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @return The Discord ID linked to the Minecraft player, or null if not linked.\n */\n String getDiscordId(String playerId);\n\n /**\n * Remove the link between the player's Minecraft and Discord accounts.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @return true if the disconnection is successful, false otherwise.\n */\n boolean unlinkMinecraftFromDiscord(String playerId);\n\n /**\n * Check if a connection exists between the Minecraft player and Discord user.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @return true if a connection is present, false otherwise.\n */\n boolean isConnectionPresent(String playerId);\n\n /**\n * Asynchronously link the player's Minecraft account with their Discord account.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @param discordId The unique ID of the user in Discord.\n * @return A CompletableFuture representing the success of the connection.\n */\n default CompletableFuture<Boolean> linkMinecraftToDiscordAsync(String playerId, String discordId) {\n return CompletableFuture.supplyAsync(() -> linkMinecraftToDiscord(playerId, discordId));\n }\n\n /**\n * Asynchronously get the Discord ID linked to the specified Minecraft player.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @return A CompletableFuture with the Discord ID linked to the Minecraft player,\n * or null if not linked.\n */\n default CompletableFuture<String> getDiscordIdAsync(String playerId) {\n return CompletableFuture.supplyAsync(() -> getDiscordId(playerId));\n }\n\n /**\n * Asynchronously remove the link between the player's Minecraft and Discord accounts.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @return A CompletableFuture representing the success of the disconnection.\n */\n default CompletableFuture<Boolean> unlinkMinecraftFromDiscordAsync(String playerId) {\n return CompletableFuture.supplyAsync(() -> unlinkMinecraftFromDiscord(playerId));\n }\n\n /**\n * Asynchronously check if a connection exists between the Minecraft player and Discord user.\n *\n * @param playerId The unique ID of the player in Minecraft.\n * @return A CompletableFuture with a boolean indicating if a connection is present.\n */\n default CompletableFuture<Boolean> isConnectionPresentAsync(String playerId) {\n return CompletableFuture.supplyAsync(() -> isConnectionPresent(playerId));\n }\n\n}"
},
{
"identifier": "EconomicAgent",
"path": "izanagi-librarian-shared/src/main/java/com/izanagicraft/librarian/economy/EconomicAgent.java",
"snippet": "public interface EconomicAgent {\n\n /**\n * Retrieves the balance of the economic agent in the specified currency.\n *\n * @param currency The {@code EconomicCurrency} for which the balance is requested.\n * @return The balance of the economic agent in the specified currency.\n */\n double getBalance(EconomicCurrency currency);\n\n /**\n * Sets the balance of the economic agent in the specified currency.\n *\n * @param currency The {@code EconomicCurrency} for which the balance is set.\n * @param newBalance The new balance to set for the economic agent in the specified currency.\n */\n void setBalance(EconomicCurrency currency, double newBalance);\n\n}"
}
] | import com.izanagicraft.librarian.connection.DiscordConnection;
import com.izanagicraft.librarian.connection.MinecraftConnection;
import com.izanagicraft.librarian.economy.EconomicAgent; | 2,774 | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.librarian.players;
/**
* izanagi-librarian; com.izanagicraft.librarian.players:IzanagiPlayer
* <p>
* Represents a player in the Izanagi systems.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 14.12.2023
*/
public interface IzanagiPlayer extends EconomicAgent {
/**
* Get the connection manager for the player's Minecraft account.
*
* @return The {@link MinecraftConnection} instance for the player.
*/
MinecraftConnection getMinecraftConnection();
/**
* Get the connection manager for the player's Discord account.
*
* @return The {@link DiscordConnection} instance for the player.
*/ | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.librarian.players;
/**
* izanagi-librarian; com.izanagicraft.librarian.players:IzanagiPlayer
* <p>
* Represents a player in the Izanagi systems.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 14.12.2023
*/
public interface IzanagiPlayer extends EconomicAgent {
/**
* Get the connection manager for the player's Minecraft account.
*
* @return The {@link MinecraftConnection} instance for the player.
*/
MinecraftConnection getMinecraftConnection();
/**
* Get the connection manager for the player's Discord account.
*
* @return The {@link DiscordConnection} instance for the player.
*/ | DiscordConnection getDiscordConnection(); | 0 | 2023-12-14 00:52:33+00:00 | 4k |
ThomasGorisseGit/TodoList | backend/src/main/java/fr/gorisse/todoApp/TodoListApp/controller/UserController.java | [
{
"identifier": "EmailAlreadyExistException",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/exception/EmailAlreadyExistException.java",
"snippet": "@ResponseStatus(value = HttpStatus.CONFLICT)\npublic class EmailAlreadyExistException extends RuntimeException{\n public EmailAlreadyExistException(V_Email email) {\n super(\"L'email \" + email.getEmail() + \" est dรฉjร utilisรฉ\");\n }\n}"
},
{
"identifier": "UsernameAlreadyExistException",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/exception/UsernameAlreadyExistException.java",
"snippet": "@ResponseStatus(value = HttpStatus.CONFLICT)\npublic class UsernameAlreadyExistException extends RuntimeException{\n\n public UsernameAlreadyExistException(String username) {\n super(\"Le nom d'utilisateur \" + username + \" est dรฉjร utilisรฉ\");\n }\n}"
},
{
"identifier": "TodoList",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/entity/TodoList.java",
"snippet": "@Data\n@ToString\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class TodoList {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer idTodoList;\n\n private String title;\n private String description;\n\n\n @Convert(converter = TypeConverter.class)\n private V_Type type; //publique privรฉ ou partagรฉ\n\n @Convert(converter = VisibilityConverter.class)\n private V_Visibility taskVisibility; //commun ou solo\n\n @JsonIgnore\n @ManyToOne\n @JsonManagedReference\n private User author;\n\n\n\n @OneToMany(mappedBy = \"referenceTodoList\", cascade = CascadeType.ALL)\n @JsonManagedReference\n private List<Task> tasks;\n\n\n\n}"
},
{
"identifier": "User",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/entity/User.java",
"snippet": "@Data\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class User implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer idUser;\n\n\n private String lastName;\n private String firstName;\n private String username;\n private String password;\n\n private boolean isActived;\n @JsonIgnore\n private String activationCode;\n\n @Convert(converter = EmailConverter.class)\n private V_Email email;\n\n\n @Convert(converter = PhoneConverter.class)\n private V_Phone phone;\n\n\n @CreationTimestamp\n @JsonFormat(pattern = \"dd/MM/yyyy\")\n private LocalDate dateCreation;\n\n @JsonIgnore\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return Collections.singletonList(new SimpleGrantedAuthority(\"ROLE_USER\"));\n }\n\n @JsonIgnore\n @Override\n public boolean isAccountNonExpired() {\n return this.isActived;\n }\n\n @JsonIgnore\n @Override\n public boolean isAccountNonLocked() {\n return this.isActived;\n }\n\n @JsonIgnore\n @Override\n public boolean isCredentialsNonExpired() {\n return this.isActived;\n }\n\n @JsonIgnore\n @Override\n public boolean isEnabled() {\n return this.isActived;\n }\n}"
},
{
"identifier": "TodoListService",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/services/TodoListService.java",
"snippet": "@Service\n\npublic class TodoListService {\n\n TodoListRepository todoListRepository;\n UserRepository userRepository;\n UseTableRepository useTableRepository;\n\n public TodoList findTodoListById(Integer id) {\n Optional<TodoList> todoList = todoListRepository.findById(id);\n if (todoList.isPresent()) {\n return todoList.get();\n }\n else\n throw new TodoListIntrouvableException(id);\n }\n\n public TodoListService(TodoListRepository todoListRepository, UserRepository userRepository, UseTableRepository useTableRepository) {\n\n this.todoListRepository = todoListRepository;\n this.userRepository = userRepository;\n this.useTableRepository = useTableRepository;\n }\n public List<TodoList> findListEnableFromUser(Integer id) {\n return todoListRepository.findTodoListsEnableByIdUser(id);\n }\n\n\n\n\n\n public TodoList addTodoList(TodoList todoList){\n //addLinkBetweenUserAndTodoList(todoList.getAuthor(),todoList);\n return this.todoListRepository.save(todoList);\n }\n\n\n public void delete(int idCurrentEntity) {\n TodoList toDelete = this.findTodoListById(idCurrentEntity);\n\n this.todoListRepository.delete(toDelete);\n\n //TODO : On ne peut pas delete si il y a un lien avec un user\n }\n\n\n\n\n}"
},
{
"identifier": "UserService",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/services/UserService.java",
"snippet": "@Service\npublic class UserService implements IUserService, UserDetailsService {\n\n UserRepository userRepository;\n MailService mailService;\n\n\n public UserService(UserRepository userRepository,MailService mailService) {\n this.userRepository = userRepository;\n this.mailService = mailService;\n }\n private PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n private boolean doEmailAlreadyExist(User user) {\n return this.findUserByEmail(user.getEmail()) != null;\n }\n\n private boolean doUsernameAlreadyExist(User user) {\n return userRepository.existsByUsername(user.getUsername());\n }\n\n public boolean existUser(Integer id) {\n return userRepository.existsById(id);\n }\n public User findUserByEmail(V_Email email) {\n return userRepository.findByEmail(email).orElse(null);\n }\n\n public User findUserById(Integer id) {\n Optional<User> user = userRepository.findById(id);\n if (user.isPresent()) {\n return user.get();\n }\n else {\n throw new UserIntrouvableException(id);\n }\n }\n\n @Override\n public User findUserByUsername(String username) {\n return userRepository.findByUsername(username).orElse(null);\n }\n\n public List<User> findFollowersFromList(int idList) {\n return this.userRepository.findUsersByTodoListId(idList);\n }\n\n public User addUser(User user) {\n // SI l'utilisateur modifie son adresse email ou alors est nouveau :\n // On vรฉrifie que l'adresse email n'est pas dรฉjร utilisรฉe\n if (this.doEmailAlreadyExist(user)) {\n throw new EmailAlreadyExistException(user.getEmail());\n }\n if (this.doUsernameAlreadyExist(user)) {\n throw new UsernameAlreadyExistException(user.getUsername());\n }\n user.setPassword(this.passwordEncoder().encode(user.getPassword()));\n user.setActived(false);\n Random random = new Random();\n user.setActivationCode(String.valueOf(random.nextInt(999999)));\n\n this.mailService.sendActivationCode(user);\n\n return user;\n }\n\n\n @Override\n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n return this.findUserByUsername(username);\n }\n\n public boolean activate(User user, String code){\n if(user.getActivationCode().equals(code)){\n user.setActived(true);\n this.userRepository.save(user);\n return true;\n }\n return false;\n\n\n }\n}"
}
] | import fr.gorisse.todoApp.TodoListApp.exception.EmailAlreadyExistException;
import fr.gorisse.todoApp.TodoListApp.exception.UsernameAlreadyExistException;
import fr.gorisse.todoApp.TodoListApp.entity.TodoList;
import fr.gorisse.todoApp.TodoListApp.entity.User;
import fr.gorisse.todoApp.TodoListApp.services.TodoListService;
import fr.gorisse.todoApp.TodoListApp.services.UserService;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,981 | package fr.gorisse.todoApp.TodoListApp.controller;
@RestController // Is a Bean -> Injection de dรฉpendance
@RequestMapping("/api/user")
public class UserController {
private final UserService userService;
private final TodoListService todoListService;
public UserController(UserService userService, TodoListService todoListService) {
this.userService = userService;
this.todoListService = todoListService;
}
// ? Get / find
// ? Rรฉcupรจre un utilisateur par id
@GetMapping("/find/idUser") | package fr.gorisse.todoApp.TodoListApp.controller;
@RestController // Is a Bean -> Injection de dรฉpendance
@RequestMapping("/api/user")
public class UserController {
private final UserService userService;
private final TodoListService todoListService;
public UserController(UserService userService, TodoListService todoListService) {
this.userService = userService;
this.todoListService = todoListService;
}
// ? Get / find
// ? Rรฉcupรจre un utilisateur par id
@GetMapping("/find/idUser") | public User findUserById( | 3 | 2023-12-15 17:32:43+00:00 | 4k |
Konloch/HeadlessIRC | src/main/java/com/konloch/ircbot/listener/event/PrivateMessageEvent.java | [
{
"identifier": "Server",
"path": "src/main/java/com/konloch/ircbot/server/Server.java",
"snippet": "public class Server implements Runnable\n{\n\tprivate static final CharsetEncoder ENCODER = StandardCharsets.UTF_8.newEncoder();\n\tprivate static final CharsetDecoder DECODER = StandardCharsets.UTF_8.newDecoder();\n\tprivate static final Pattern IS_NUMBER = Pattern.compile(\"\\\\d+\");\n\tprivate static final Pattern LINE_SPLITTER = Pattern.compile(\"\\\\r?\\\\n\");\n\t\n\tprivate final IRCBot bot;\n\tprivate final String serverAddress;\n\tprivate final int port;\n\tprivate boolean active = true;\n\tprivate boolean encounteredError;\n\t\n\tprivate Selector selector;\n\tprivate SocketChannel socketChannel;\n\t\n\tprivate final Map<String,Channel> channels = new HashMap<>();\n\tprivate final Map<String,User> users = new HashMap<>();\n\tprivate final Object USER_LOCK = new Object();\n\t\n\tpublic Server(IRCBot bot, String serverAddress, int port)\n\t{\n\t\tthis.bot = bot;\n\t\tthis.serverAddress = serverAddress;\n\t\tthis.port = port;\n\t}\n\t\n\tpublic Channel join(String channelName)\n\t{\n\t\tChannel channel = new Channel(this, channelName);\n\t\tchannels.put(channelName, channel);\n\t\treturn channel;\n\t}\n\t\n\tpublic void process()\n\t{\n\t\ttry\n\t\t{\n\t\t\tinternalProcess();\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\t\n\t\t\tencounteredError = true; //trip error flag\n\t\t}\n\t}\n\t\n\tprivate void internalProcess() throws IOException\n\t{\n\t\t//wait till connected\n\t\tif(socketChannel == null || socketChannel.isConnectionPending() || !socketChannel.isConnected())\n\t\t\treturn;\n\t\t\n\t\t//remove any non-active channels\n\t\tchannels.values().removeIf(channel -> !channel.isActive());\n\t\t\n\t\t//process all channels\n\t\tfor(Channel channel : channels.values())\n\t\t{\n\t\t\tchannel.process();\n\t\t}\n\t\t\n\t\tsynchronized (USER_LOCK)\n\t\t{\n\t\t\t//process all private messages\n\t\t\tfor (User user : users.values())\n\t\t\t{\n\t\t\t\tif (user.getMessageQueue().isEmpty())\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t\t{\n\t\t\t\t\tif (user.getMessageQueue().isEmpty())\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\t\tString message = user.getMessageQueue().poll();\n\t\t\t\t\tsend(\"PRIVMSG \" + user.getNickname() + \" :\" + message);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void run()\n\t{\n\t\twhile(active)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tencounteredError = false; //reset error flag\n\t\t\t\tselector = Selector.open();\n\t\t\t\t\n\t\t\t\tsocketChannel = SocketChannel.open();\n\t\t\t\tsocketChannel.configureBlocking(false);\n\t\t\t\tsocketChannel.connect(new InetSocketAddress(serverAddress, port));\n\t\t\t\tsocketChannel.register(selector, SelectionKey.OP_CONNECT);\n\t\t\t\t\n\t\t\t\twhile (!encounteredError)\n\t\t\t\t{\n\t\t\t\t\tselector.select();\n\t\t\t\t\t\n\t\t\t\t\tSet<SelectionKey> keys = selector.selectedKeys();\n\t\t\t\t\tIterator<SelectionKey> keyIterator = keys.iterator();\n\t\t\t\t\t\n\t\t\t\t\twhile (keyIterator.hasNext())\n\t\t\t\t\t{\n\t\t\t\t\t\tSelectionKey key = keyIterator.next();\n\t\t\t\t\t\tkeyIterator.remove();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (key.isConnectable())\n\t\t\t\t\t\t\tconnect();\n\t\t\t\t\t\telse if (key.isReadable())\n\t\t\t\t\t\t\tread();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (IOException e)\n\t\t\t{\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tclose();\n\t\t\t\t\n\t\t\t\t//call on listener event\n\t\t\t\tbot.getListeners().callOnConnectionLost(this);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void connect() throws IOException\n\t{\n\t\tif (socketChannel.isConnectionPending())\n\t\t\tsocketChannel.finishConnect();\n\t\t\n\t\tsocketChannel.register(selector, SelectionKey.OP_READ);\n\t\t\n\t\t//send NICK and USER commands to identify with the IRC server\n\t\tsend(\"NICK \" + bot.getNickname());\n\t\tsend(\"USER \" + bot.getNickname() + \" 8 * :\" + bot.getClient());\n\t\t\n\t\t//call on listener event\n\t\tbot.getListeners().callOnConnectionEstablished(this);\n\t}\n\t\n\tprivate void read() throws IOException\n\t{\n\t\tByteBuffer buffer = ByteBuffer.allocate(1024);\n\t\tsocketChannel.read(buffer);\n\t\t\n\t\t//decode into buffer\n\t\tbuffer.flip();\n\t\tCharBuffer charBuffer = DECODER.decode(buffer);\n\t\tString[] stringBuffer = LINE_SPLITTER.split(charBuffer.toString());\n\t\t\n\t\t//parse each message\n\t\tfor(String message : stringBuffer)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tString messageLower = message.toLowerCase();\n\t\t\t\t\n\t\t\t\tif(messageLower.isEmpty())\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tboolean handled = false;\n\t\t\t\t\n\t\t\t\t//respond to PING with PONG\n\t\t\t\tif (messageLower.startsWith(\"ping\"))\n\t\t\t\t{\n\t\t\t\t\thandled = true;\n\t\t\t\t\tsend(\"PONG \" + message.substring(5));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//decode messages\n\t\t\t\telse if (message.startsWith(\":\"))\n\t\t\t\t{\n\t\t\t\t\tString[] splitPartMessage = split(message, \" \", 5);\n\t\t\t\t\t\n\t\t\t\t\tif (splitPartMessage.length >= 3)\n\t\t\t\t\t{\n\t\t\t\t\t\tString command = splitPartMessage[1];\n\t\t\t\t\t\tString commandLowerCase = command.toLowerCase();\n\t\t\t\t\t\t\n\t\t\t\t\t\t//handle integer based commands\n\t\t\t\t\t\tif (splitPartMessage.length >= 4 && IS_NUMBER.matcher(command).matches())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint opcode = Integer.parseInt(splitPartMessage[1]);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//look up the integer message\n\t\t\t\t\t\t\tIntegerMessage intMsg = IntegerMessage.opcode(opcode);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//process the message\n\t\t\t\t\t\t\tif(intMsg != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tintMsg.getEvent().handle(this, splitPartMessage);\n\t\t\t\t\t\t\t\thandled = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//handle text based commands\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//only a maximum of 4 parameters\n\t\t\t\t\t\t\tsplitPartMessage = split(message, \" \", 4);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//look up the integer message\n\t\t\t\t\t\t\tTextMessage textMsg = TextMessage.opcode(commandLowerCase);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//process the message\n\t\t\t\t\t\t\tif(textMsg != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttextMsg.getEvent().handle(this, splitPartMessage);\n\t\t\t\t\t\t\t\thandled = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//call on the global event listeners\n\t\t\t\tgetBot().getListeners().callServerMessage(this, message, handled);\n\t\t\t}\n\t\t\tcatch (Exception e)\n\t\t\t{\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\t\n\t\t\tbuffer.clear();\n\t\t}\n\t}\n\t\n\tpublic void send(String message) throws IOException\n\t{\n\t\t//call on the global event listeners\n\t\tgetBot().getListeners().callOutboundMessage(this, message, true);\n\t\t\n\t\tString formattedMessage = message + \"\\r\\n\";\n\t\tByteBuffer buffer = ENCODER.encode(CharBuffer.wrap(formattedMessage));\n\t\tsocketChannel.write(buffer);\n\t}\n\t\n\tprivate void close()\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (socketChannel != null)\n\t\t\t\tsocketChannel.close();\n\t\t\tif (selector != null)\n\t\t\t\tselector.close();\n\t\t}\n\t\tcatch (IOException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic Channel getChannel(String channelName)\n\t{\n\t\tif(channelName.startsWith(\":\"))\n\t\t\tchannelName = channelName.substring(1);\n\t\t\n\t\tChannel channel = channels.get(channelName);\n\t\t\n\t\tif(channel != null)\n\t\t\treturn channel;\n\t\t\n\t\tchannel = channels.get(\"#\" + channelName);\n\t\t\n\t\treturn channel;\n\t}\n\t\n\tpublic User getUser(String nickname)\n\t{\n\t\tUser user = users.get(nickname);\n\t\t\n\t\tif(user == null)\n\t\t{\n\t\t\tuser = new User(this, nickname);\n\t\t\t\n\t\t\tsynchronized (USER_LOCK)\n\t\t\t{\n\t\t\t\tusers.put(nickname, user);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn user;\n\t}\n\t\n\tpublic void onJoin(IRCJoin join)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onJoin(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tjoin.join(event);\n\t\t});\n\t}\n\t\n\tpublic void onConnectionEstablished(IRCConnectionEstablished established)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onConnectionEstablished(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\testablished.established(event);\n\t\t});\n\t}\n\t\n\tpublic void onConnectionLost(IRCConnectionLost lost)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onConnectionLost(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tlost.lost(event);\n\t\t});\n\t}\n\t\n\tpublic void onLeave(IRCLeave leave)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onLeave(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tleave.leave(event);\n\t\t});\n\t}\n\t\n\tpublic void onServerMessage(IRCServerMessage message)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onServerMessage(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tmessage.message(event);\n\t\t});\n\t}\n\t\n\tpublic void onOutboundMessage(IRCServerMessage message)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onOutboundMessage(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tmessage.message(event);\n\t\t});\n\t}\n\t\n\tpublic void onChannelMessage(IRCChannelMessage message)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onChannelMessage(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tmessage.message(event);\n\t\t});\n\t}\n\t\n\tpublic void onPrivateMessage(IRCPrivateMessage message)\n\t{\n\t\t//filter listener events to only call for this server\n\t\tbot.getListeners().onPrivateMessage(event ->\n\t\t{\n\t\t\tif(event.getServer() != this)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tmessage.message(event);\n\t\t});\n\t}\n\t\n\tpublic IRCBot getBot()\n\t{\n\t\treturn bot;\n\t}\n\t\n\tpublic String getServerAddress()\n\t{\n\t\treturn serverAddress;\n\t}\n\t\n\tpublic Collection<Channel> getChannels()\n\t{\n\t\treturn channels.values();\n\t}\n\t\n\tpublic Collection<User> getUsers()\n\t{\n\t\treturn users.values();\n\t}\n\t\n\t@Override\n\tpublic String toString()\n\t{\n\t\treturn getServerAddress();\n\t}\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/konloch/ircbot/server/User.java",
"snippet": "public class User\n{\n\tprivate final Server server;\n\tprivate final String nickname;\n\tprivate final Queue<String> messageQueue = new LinkedList<>();\n\t\n\tprotected User(Server server, String nickname)\n\t{\n\t\tthis.server = server;\n\t\tthis.nickname = nickname;\n\t}\n\t\n\tpublic Server getServer()\n\t{\n\t\treturn server;\n\t}\n\t\n\tpublic String getNickname()\n\t{\n\t\treturn nickname;\n\t}\n\t\n\tpublic Queue<String> getMessageQueue()\n\t{\n\t\treturn messageQueue;\n\t}\n\t\n\tpublic void send(String message)\n\t{\n\t\tmessageQueue.add(message);\n\t}\n\t\n\tpublic boolean isSelfBot()\n\t{\n\t\treturn nickname.equals(server.getBot().getNickname());\n\t}\n\t\n\t@Override\n\tpublic String toString()\n\t{\n\t\treturn server + \"/\" + nickname;\n\t}\n}"
}
] | import com.konloch.ircbot.server.Server;
import com.konloch.ircbot.server.User; | 3,076 | package com.konloch.ircbot.listener.event;
/**
* @author Konloch
* @since 12/15/2023
*/
public class PrivateMessageEvent extends GenericServerEvent
{ | package com.konloch.ircbot.listener.event;
/**
* @author Konloch
* @since 12/15/2023
*/
public class PrivateMessageEvent extends GenericServerEvent
{ | private final User user; | 1 | 2023-12-16 02:09:21+00:00 | 4k |
sasmithx/layered-architecture-Sasmithx | src/main/java/lk/sasax/layeredarchitecture/controller/MainFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/lk/sasax/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n\n private static BOFactory boFactory;\n\n private BOFactory() {\n }\n\n public static BOFactory getBoFactory() {\n return (boFactory == null) ? boFactory = new BOFactory() : boFactory;\n }\n\n public enum BOTypes {\n CUSTOMER, ITEM, PLACE_ORDER, QUERY\n }\n\n public SuperBO getTypes(BOTypes boTypes) {\n switch (boTypes) {\n case CUSTOMER:\n return new CustomerBOImpl();\n case ITEM:\n return new ItemBOImpl();\n case PLACE_ORDER:\n return new PlaceOrderBOImpl();\n case QUERY:\n return new QueryBOImpl();\n default:\n return null;\n }\n }\n}"
},
{
"identifier": "QueryBO",
"path": "src/main/java/lk/sasax/layeredarchitecture/bo/custom/QueryBO.java",
"snippet": "public interface QueryBO extends SuperBO {\n\n List<CustomerOrderDTO> customerOrderDetails() throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "CustomerOrderDTO",
"path": "src/main/java/lk/sasax/layeredarchitecture/dto/CustomerOrderDTO.java",
"snippet": "public class CustomerOrderDTO {\n private String id;\n private String name;\n private String date;\n private String total;\n\n public CustomerOrderDTO() {\n }\n\n public CustomerOrderDTO(String id, String name, String date, String total) {\n this.id = id;\n this.name = name;\n this.date = date;\n this.total = total;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getTotal() {\n return total;\n }\n\n public void setTotal(String total) {\n this.total = total;\n }\n\n @Override\n public String toString() {\n return \"CustomDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", date='\" + date + '\\'' +\n \", total='\" + total + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "QueryDAOImpl",
"path": "src/main/java/lk/sasax/layeredarchitecture/dao/custom/impl/QueryDAOImpl.java",
"snippet": "public class QueryDAOImpl implements QueryDAO {\n\n @Override\n public List<CustomerOrderDTO> customerOrderDetails() throws SQLException, ClassNotFoundException {\n //join Query\n ResultSet resultSet = SQLUtil.execute(\"SELECT \" +\n \"o.oid as ID, \" +\n \"c.name as CUSTOMER, \" +\n \"o.date as DATE, \" +\n \"SUM(od.qty * od.unitPrice) as TOTAL \" +\n \"FROM Customer c \" +\n \"LEFT JOIN Orders o \" +\n \"ON c.id = o.customerID \" +\n \"LEFT JOIN OrderDetails od \" +\n \"ON o.oid = od.oid \" +\n \"GROUP BY o.oid, c.name \" +\n \"ORDER BY o.oid ASC \"\n );\n\n List<CustomerOrderDTO> queryOutput = new ArrayList<>();\n\n while (resultSet.next()) {\n CustomerOrderDTO dto = new CustomerOrderDTO(\n resultSet.getString(1),\n resultSet.getString(2),\n resultSet.getString(3),\n resultSet.getString(4)\n );\n\n queryOutput.add(dto);\n }\n return queryOutput;\n }\n}"
}
] | import lk.sasax.layeredarchitecture.bo.BOFactory;
import lk.sasax.layeredarchitecture.bo.custom.QueryBO;
import lk.sasax.layeredarchitecture.dto.CustomerOrderDTO;
import lk.sasax.layeredarchitecture.dao.custom.impl.QueryDAOImpl;
import javafx.animation.FadeTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.TranslateTransition;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle; | 1,803 | package lk.sasax.layeredarchitecture.controller;
public class MainFormController {
@FXML
private AnchorPane root;
@FXML
private ImageView imgCustomer;
@FXML
private ImageView imgItem;
@FXML
private ImageView imgOrder;
@FXML
private ImageView imgViewOrders;
@FXML
private Label lblMenu;
@FXML
private Label lblDescription;
QueryBO queryBO = (QueryBO) BOFactory.getBoFactory().getTypes(BOFactory.BOTypes.QUERY);
/**
* Initializes the controller class.
*/
public void initialize(URL url, ResourceBundle rb) {
FadeTransition fadeIn = new FadeTransition(Duration.millis(2000), root);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
fadeIn.play();
}
@FXML
private void playMouseExitAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1);
scaleT.setToY(1);
scaleT.play();
icon.setEffect(null);
lblMenu.setText("Welcome");
lblDescription.setText("Please select one of above main operations to proceed");
}
}
@FXML
private void playMouseEnterAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
switch (icon.getId()) {
case "imgCustomer":
lblMenu.setText("Manage Customers");
lblDescription.setText("Click to add, edit, delete, search or view customers");
break;
case "imgItem":
lblMenu.setText("Manage Items");
lblDescription.setText("Click to add, edit, delete, search or view items");
break;
case "imgOrder":
lblMenu.setText("Place Orders");
lblDescription.setText("Click here if you want to place a new order");
break;
case "imgViewOrders":
lblMenu.setText("Search Orders");
lblDescription.setText("Click if you want to search orders");
break;
}
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1.2);
scaleT.setToY(1.2);
scaleT.play();
DropShadow glow = new DropShadow();
glow.setColor(Color.CORNFLOWERBLUE);
glow.setWidth(20);
glow.setHeight(20);
glow.setRadius(20);
icon.setEffect(glow);
}
}
@FXML
private void navigate(MouseEvent event) throws IOException, SQLException, ClassNotFoundException {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
Parent root = null;
switch (icon.getId()) {
case "imgCustomer":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-customers-form.fxml"));
break;
case "imgItem":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-items-form.fxml"));
break;
case "imgOrder":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/place-order-form.fxml"));
break;
case "imgViewOrders":
QueryDAOImpl queryDAO = new QueryDAOImpl(); | package lk.sasax.layeredarchitecture.controller;
public class MainFormController {
@FXML
private AnchorPane root;
@FXML
private ImageView imgCustomer;
@FXML
private ImageView imgItem;
@FXML
private ImageView imgOrder;
@FXML
private ImageView imgViewOrders;
@FXML
private Label lblMenu;
@FXML
private Label lblDescription;
QueryBO queryBO = (QueryBO) BOFactory.getBoFactory().getTypes(BOFactory.BOTypes.QUERY);
/**
* Initializes the controller class.
*/
public void initialize(URL url, ResourceBundle rb) {
FadeTransition fadeIn = new FadeTransition(Duration.millis(2000), root);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
fadeIn.play();
}
@FXML
private void playMouseExitAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1);
scaleT.setToY(1);
scaleT.play();
icon.setEffect(null);
lblMenu.setText("Welcome");
lblDescription.setText("Please select one of above main operations to proceed");
}
}
@FXML
private void playMouseEnterAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
switch (icon.getId()) {
case "imgCustomer":
lblMenu.setText("Manage Customers");
lblDescription.setText("Click to add, edit, delete, search or view customers");
break;
case "imgItem":
lblMenu.setText("Manage Items");
lblDescription.setText("Click to add, edit, delete, search or view items");
break;
case "imgOrder":
lblMenu.setText("Place Orders");
lblDescription.setText("Click here if you want to place a new order");
break;
case "imgViewOrders":
lblMenu.setText("Search Orders");
lblDescription.setText("Click if you want to search orders");
break;
}
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1.2);
scaleT.setToY(1.2);
scaleT.play();
DropShadow glow = new DropShadow();
glow.setColor(Color.CORNFLOWERBLUE);
glow.setWidth(20);
glow.setHeight(20);
glow.setRadius(20);
icon.setEffect(glow);
}
}
@FXML
private void navigate(MouseEvent event) throws IOException, SQLException, ClassNotFoundException {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
Parent root = null;
switch (icon.getId()) {
case "imgCustomer":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-customers-form.fxml"));
break;
case "imgItem":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-items-form.fxml"));
break;
case "imgOrder":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/place-order-form.fxml"));
break;
case "imgViewOrders":
QueryDAOImpl queryDAO = new QueryDAOImpl(); | List<CustomerOrderDTO> customerOrderDTOS1 = queryDAO.customerOrderDetails(); | 2 | 2023-12-16 04:19:42+00:00 | 4k |
madhushiillesinghe/layered-architecture-madhushi | src/main/java/com/example/layeredarchitecture/dao/BOFactory.java | [
{
"identifier": "SuperBo",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/SuperBo.java",
"snippet": "public interface SuperBo {\n}"
},
{
"identifier": "CustomerBoImpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/impl/CustomerBoImpl.java",
"snippet": "public class CustomerBoImpl implements CustomerBo {\n CustomerDao customerDao= (CustomerDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.CUSTOMER);\n @Override\n public boolean saveCustomer(CustomerDTO customer) throws SQLException, ClassNotFoundException {\n return customerDao.save(new Customer(customer.getId(),customer.getName(),customer.getAddress()));\n }\n @Override\n public boolean updateCustomer(CustomerDTO customer) throws SQLException, ClassNotFoundException {\n return customerDao.update(new Customer(customer.getName(), customer.getAddress(), customer.getId()));\n }\n @Override\n public boolean existCustomer(String id) throws SQLException, ClassNotFoundException{\n return customerDao.exist(id);\n }\n @Override\n public boolean deleteCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDao.delete(id);\n }\n @Override\n public ResultSet genarateCustomerId() throws SQLException, ClassNotFoundException{\n return customerDao.genarateId();\n }\n @Override\n public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException{\n Customer customer=customerDao.search(id);\n CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress());\n return customerDTO;\n }\n\n}"
},
{
"identifier": "ItemBoImpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/impl/ItemBoImpl.java",
"snippet": "public class ItemBoImpl implements ItemBo {\n ItemDao itemDao= (ItemDao) (ItemDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.ITEM);\n @Override\n public boolean saveItem(ItemDTO dto) throws SQLException, ClassNotFoundException{\n return itemDao.save(new Item(dto.getCode(),dto.getDescription(),dto.getUnitPrice(),dto.getQtyOnHand()));\n }\n @Override\n public boolean UpdateItem(ItemDTO dto) throws SQLException, ClassNotFoundException{\n return itemDao.update(new Item(dto.getCode(),dto.getDescription(),dto.getUnitPrice(),dto.getQtyOnHand()));\n }\n @Override\n public boolean ExistItem(String id) throws SQLException, ClassNotFoundException{\n return itemDao.exist(id);\n }\n @Override\n public boolean deleteItem(String id) throws SQLException, ClassNotFoundException{\n return itemDao.delete(id);\n }\n @Override\n public ResultSet genarateItemId() throws SQLException, ClassNotFoundException{\n return itemDao.genarateId();\n }\n @Override\n public ArrayList<ItemDTO> getAllItem()throws SQLException,ClassNotFoundException{\n ArrayList<Item> items=itemDao.getAll();\n ArrayList<ItemDTO> itemDTOS=new ArrayList<>();\n for (Item item:items) {\n itemDTOS.add(new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(),item.getQtyOnHand()));\n }\n return itemDTOS;\n }\n /*@Override\n public ItemDTO search(String newItemCode) throws SQLException, ClassNotFoundException{\n return itemDao.search(newItemCode);\n }*/\n}"
},
{
"identifier": "PlaceOrderBoImpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/impl/PlaceOrderBoImpl.java",
"snippet": "public class PlaceOrderBoImpl implements PlaceOrderBo {\n CustomerDao customerDao= (CustomerDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.CUSTOMER);\n ItemDao itemDao= (ItemDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.ITEM);\n OrderDao orderDao= (OrderDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.ORDER);\n OrderDetailDao orderDetailDao= (OrderDetailDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.ORDERDETAIL);\n public boolean saveOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {\n /*Transaction*/\n Connection connection = null;\n boolean isOrderSaved;\n boolean isOrderDetailSaved=false;\n boolean isUpdated=false;\n /*connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement stm = connection.prepareStatement(\"SELECT oid FROM `Orders` WHERE oid=?\");\n stm.setString(1, orderId);\n *//*if order id already exist*//*\n if (stm.executeQuery().next()) {}\n*/\n connection = DBConnection.getDbConnection().getConnection();\n orderDao.selectOrderId(orderId);\n connection.setAutoCommit(false);\n isOrderSaved = orderDao.saveOrder(orderId, orderDate, customerId);\n if (!(isOrderSaved)) {\n connection.rollback();\n connection.setAutoCommit(true);\n return false;\n }\n /*connection.setAutoCommit(false);\n stm = connection.prepareStatement(\"INSERT INTO `Orders` (oid, date, customerID) VALUES (?,?,?)\");\n stm.setString(1, orderId);\n stm.setDate(2, Date.valueOf(orderDate));\n stm.setString(3, customerId);*/\n\n /*if (stm.executeUpdate() != 1) {\n connection.rollback();\n connection.setAutoCommit(true);\n return false;\n }*/\n\n //stm = connection.prepareStatement(\"INSERT INTO OrderDetails (oid, itemCode, unitPrice, qty) VALUES (?,?,?,?)\");\n\n for (OrderDetailDTO detail : orderDetails) {\n isOrderDetailSaved = orderDetailDao.saveOrderDetail(orderId, detail);\n if (!(isOrderDetailSaved)) {\n connection.rollback();\n ;\n connection.setAutoCommit(true);\n return false;\n }\n// //Search & Update Item\n ItemDTO item= findItem(detail.getItemCode());\n item.setQtyOnHand(item.getQtyOnHand() - detail.getQty());\n\n /*PreparedStatement pstm = connection.prepareStatement(\"UPDATE Item SET description=?, unitPrice=?, qtyOnHand=? WHERE code=?\");\n pstm.setString(1, item.getDescription());\n pstm.setBigDecimal(2, item.getUnitPrice());\n pstm.setInt(3, item.getQtyOnHand());\n pstm.setString(4, item.getCode());*/\n\n isUpdated = itemDao.update(new Item(item.getCode(),item.getDescription(),item.getUnitPrice(),item.getQtyOnHand()));\n if (!(isUpdated)) {\n connection.rollback();\n ;\n connection.setAutoCommit(true);\n return false;\n }\n }\n\n /* if (!(pstm.executeUpdate() > 0)) {\n connection.rollback();\n connection.setAutoCommit(true);\n return false;\n }*/\n //System.out.println(isOrderDetailSaved);\n if (isOrderSaved && isOrderDetailSaved && isUpdated) {\n connection.commit();\n connection.setAutoCommit(true);\n return true;\n }\n return false;\n }\n public ItemDTO findItem(String code) throws SQLException, ClassNotFoundException {\n Item item = itemDao.search(code);\n return new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand());\n }\n @Override\n public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException {\n Customer customer = customerDao.search(id);\n return new CustomerDTO(customer.getId(), customer.getName(),customer.getAddress());\n\n }\n @Override\n public ItemDTO searchItem(String id) throws SQLException, ClassNotFoundException {\n Item item = itemDao.search(id);\n return new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand());\n\n }\n @Override\n public boolean existCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDao.exist(id);\n\n }\n @Override\n public boolean existItem(String id) throws SQLException, ClassNotFoundException {\n return itemDao.exist(id);\n }\n @Override\n public ResultSet genareteOrderId() throws SQLException, ClassNotFoundException {\n return orderDao.generateNewOrderId();\n }\n @Override\n public ArrayList<CustomerDTO> loadAllCustomer() throws SQLException, ClassNotFoundException {\n ArrayList<Customer> items=customerDao.getAll();\n ArrayList<CustomerDTO> customerDTOS=new ArrayList<>();\n for (Customer customer:items) {\n customerDTOS.add(new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()));\n }\n return customerDTOS;\n\n }\n @Override\n public ArrayList<ItemDTO> loadAllItem() throws SQLException, ClassNotFoundException {\n ArrayList<Item> items=itemDao.getAll();\n ArrayList<ItemDTO> itemDTOS=new ArrayList<>();\n for (Item item:items) {\n itemDTOS.add(new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(),item.getQtyOnHand()));\n }\n return itemDTOS;\n }\n\n\n\n}"
},
{
"identifier": "CustomerDao",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/CustomerDao.java",
"snippet": "public interface CustomerDao extends CRUDDao<Customer> {\n /*ArrayList<CustomerDTO> getAllCustomer()throws SQLException,ClassNotFoundException ;\n boolean updateCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException ;\n boolean existsCustomer(String id) throws SQLException, ClassNotFoundException;\n boolean deleteCustomer(String id) throws SQLException, ClassNotFoundException ;\n ResultSet genarateCustomerId() throws SQLException, ClassNotFoundException;\n CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException ;\n boolean saveCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException;*/\n}"
}
] | import com.example.layeredarchitecture.bo.custom.SuperBo;
import com.example.layeredarchitecture.bo.custom.impl.CustomerBoImpl;
import com.example.layeredarchitecture.bo.custom.impl.ItemBoImpl;
import com.example.layeredarchitecture.bo.custom.impl.PlaceOrderBoImpl;
import com.example.layeredarchitecture.dao.custom.CustomerDao; | 2,254 | package com.example.layeredarchitecture.dao;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory==null)?boFactory=new BOFactory():boFactory;
}
public static SuperBo getBo(BOType boType){
switch (boType){ | package com.example.layeredarchitecture.dao;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory==null)?boFactory=new BOFactory():boFactory;
}
public static SuperBo getBo(BOType boType){
switch (boType){ | case CUSTOM:return new CustomerBoImpl(); | 1 | 2023-12-17 02:17:36+00:00 | 4k |
HypixelSkyblockmod/ChromaHud | src/java/xyz/apfelmus/cheeto/client/modules/render/TPSViewer.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": "PacketReceivedEvent",
"path": "src/java/xyz/apfelmus/cheeto/client/events/PacketReceivedEvent.java",
"snippet": "public class PacketReceivedEvent\nextends Listener {\n public Packet<?> packet;\n\n public PacketReceivedEvent(Packet<?> packet) {\n super(Listener.At.HEAD);\n this.packet = packet;\n }\n}"
},
{
"identifier": "Render2DEvent",
"path": "src/java/xyz/apfelmus/cheeto/client/events/Render2DEvent.java",
"snippet": "public class Render2DEvent\nextends Listener {\n public Render2DEvent() {\n super(Listener.At.HEAD);\n }\n}"
},
{
"identifier": "WorldUnloadEvent",
"path": "src/java/xyz/apfelmus/cheeto/client/events/WorldUnloadEvent.java",
"snippet": "public class WorldUnloadEvent\nextends Listener {\n public WorldUnloadEvent() {\n super(Listener.At.HEAD);\n }\n}"
},
{
"identifier": "BooleanSetting",
"path": "src/java/xyz/apfelmus/cheeto/client/settings/BooleanSetting.java",
"snippet": "public class BooleanSetting {\n private boolean enabled;\n\n public BooleanSetting(boolean enable) {\n this.enabled = enable;\n }\n\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public void setState(boolean enable) {\n this.enabled = enable;\n }\n}"
},
{
"identifier": "IntegerSetting",
"path": "src/java/xyz/apfelmus/cheeto/client/settings/IntegerSetting.java",
"snippet": "public class IntegerSetting {\n private Integer current;\n private Integer min;\n private Integer max;\n\n public IntegerSetting(Integer current, Integer min, Integer max) {\n this.current = current;\n this.min = min;\n this.max = max;\n }\n\n public Integer getCurrent() {\n return this.current;\n }\n\n public void setCurrent(Integer current) {\n this.current = current < this.min ? this.min : (current > this.max ? this.max : current);\n }\n\n public Integer getMin() {\n return this.min;\n }\n\n public void setMin(Integer min) {\n this.min = min;\n }\n\n public Integer getMax() {\n return this.max;\n }\n\n public void setMax(Integer max) {\n this.max = max;\n }\n}"
},
{
"identifier": "FontUtils",
"path": "src/java/xyz/apfelmus/cheeto/client/utils/client/FontUtils.java",
"snippet": "public class FontUtils {\n private static FontRenderer fr = Minecraft.func_71410_x().field_71466_p;\n\n public static void drawString(String text, int x, int y, int color) {\n fr.func_175065_a(text, (float)x, (float)y, color, true);\n }\n\n public static void drawVCenteredString(String text, int x, int y, int color) {\n fr.func_175065_a(text, (float)x, (float)(y - FontUtils.fr.field_78288_b / 2), color, true);\n }\n\n public static void drawHVCenteredString(String text, int x, int y, int color) {\n fr.func_175065_a(text, (float)(x - fr.func_78256_a(text) / 2), (float)(y - FontUtils.fr.field_78288_b / 2), color, true);\n }\n\n public static void drawHVCenteredChromaString(String text, int x, int y, int offset) {\n FontUtils.drawChromaString(text, x - fr.func_78256_a(text) / 2, y - FontUtils.fr.field_78288_b / 2, offset);\n }\n\n public static int getStringWidth(String text) {\n return fr.func_78256_a(text);\n }\n\n public static int getFontHeight() {\n return FontUtils.fr.field_78288_b;\n }\n\n public static void drawChromaString(String text, int x, int y, int offset) {\n double tmpX = x;\n for (char tc : text.toCharArray()) {\n long t = System.currentTimeMillis() - ((long)((int)tmpX) * 10L - (long)y - (long)offset * 10L);\n int i = Color.HSBtoRGB((float)(t % 2000L) / 2000.0f, 0.88f, 0.88f);\n String tmp = String.valueOf(tc);\n fr.func_175065_a(tmp, (float)((int)tmpX), (float)y, i, true);\n tmpX += (double)fr.func_78263_a(tc);\n }\n }\n}"
}
] | import java.util.ArrayList;
import java.util.List;
import net.minecraft.network.play.server.S03PacketTimeUpdate;
import xyz.apfelmus.cf4m.annotation.Event;
import xyz.apfelmus.cf4m.annotation.Setting;
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.PacketReceivedEvent;
import xyz.apfelmus.cheeto.client.events.Render2DEvent;
import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent;
import xyz.apfelmus.cheeto.client.settings.BooleanSetting;
import xyz.apfelmus.cheeto.client.settings.IntegerSetting;
import xyz.apfelmus.cheeto.client.utils.client.FontUtils; | 1,618 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.network.play.server.S03PacketTimeUpdate
*/
package xyz.apfelmus.cheeto.client.modules.render;
@Module(name="TPSViewer", category=Category.RENDER)
public class TPSViewer {
@Setting(name="xPos")
private IntegerSetting xPos = new IntegerSetting(0, 0, 1000);
@Setting(name="yPos")
private IntegerSetting yPos = new IntegerSetting(0, 0, 1000);
@Setting(name="RGB")
private BooleanSetting rgb = new BooleanSetting(true);
public static List<Float> serverTPS = new ArrayList<Float>();
private static long systemTime = 0L;
private static long serverTime = 0L;
@Enable
public void onEnable() {
serverTPS.clear();
systemTime = 0L;
serverTime = 0L;
}
@Event
public void onRender(Render2DEvent event) {
if (this.rgb.isEnabled()) {
FontUtils.drawHVCenteredChromaString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), 0);
} else {
FontUtils.drawHVCenteredString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), -1);
}
}
@Event | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.network.play.server.S03PacketTimeUpdate
*/
package xyz.apfelmus.cheeto.client.modules.render;
@Module(name="TPSViewer", category=Category.RENDER)
public class TPSViewer {
@Setting(name="xPos")
private IntegerSetting xPos = new IntegerSetting(0, 0, 1000);
@Setting(name="yPos")
private IntegerSetting yPos = new IntegerSetting(0, 0, 1000);
@Setting(name="RGB")
private BooleanSetting rgb = new BooleanSetting(true);
public static List<Float> serverTPS = new ArrayList<Float>();
private static long systemTime = 0L;
private static long serverTime = 0L;
@Enable
public void onEnable() {
serverTPS.clear();
systemTime = 0L;
serverTime = 0L;
}
@Event
public void onRender(Render2DEvent event) {
if (this.rgb.isEnabled()) {
FontUtils.drawHVCenteredChromaString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), 0);
} else {
FontUtils.drawHVCenteredString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), -1);
}
}
@Event | public void onPacket(PacketReceivedEvent event) { | 1 | 2023-12-21 16:22:25+00:00 | 4k |
vitri-ent/finorza | src/main/java/io/pyke/vitri/finorza/inference/gui/ModOptionsScreen.java | [
{
"identifier": "Config",
"path": "src/main/java/io/pyke/vitri/finorza/inference/config/Config.java",
"snippet": "public class Config {\r\n\tpublic static final BooleanConfigOption SYNCHRONIZE_INTEGRATED_SERVER = new BooleanConfigOption(\r\n\t\t\"synchronizeIntegratedServer\", false, (ignored, value) -> {\r\n\t\tMinecraft mc = Minecraft.getInstance();\r\n\t\tif (mc.hasSingleplayerServer()) {\r\n\t\t\tmc.level.disconnect();\r\n\t\t\tmc.clearLevel(new GenericDirtMessageScreen(new TextComponent(\"Saving world\")));\r\n\t\t\tmc.setScreen(new ModOptionsScreen(new TitleScreen()));\r\n\t\t}\r\n\t});\r\n\tpublic static final EnumConfigOption<CursorSize> CURSOR_SIZE = new EnumConfigOption<>(\r\n\t\t\"cursorSize\", CursorSize.PX_16);\r\n\tpublic static final EnumConfigOption<WindowSize> WINDOW_SIZE = new EnumConfigOption<>(\r\n\t\t\"windowSize\", WindowSize.R_360, (ignored, value) -> {\r\n\t\t((IWindow) (Object) Minecraft.getInstance().getWindow()).vitri$resize(\r\n\t\t\tvalue.width, value.height);\r\n\t});\r\n\r\n\tpublic static Option[] asOptions() {\r\n\t\tArrayList<Option> options = new ArrayList<>();\r\n\t\tfor (Field field : Config.class.getDeclaredFields()) {\r\n\t\t\tif (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(\r\n\t\t\t\tfield.getModifiers()) && Option.class.isAssignableFrom(field.getType())) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\toptions.add((Option) field.get(null));\r\n\t\t\t\t} catch (IllegalAccessException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn options.toArray(Option[]::new);\r\n\t}\r\n\r\n\tpublic enum CursorSize {\r\n\t\t@SerializedName(\"4x4\") PX_4(4), @SerializedName(\"8x8\") PX_8(8), @SerializedName(\"16x16\") PX_16(16);\r\n\r\n\t\tpublic final int size;\r\n\r\n\t\tCursorSize(int size) {\r\n\t\t\tthis.size = size;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic enum WindowSize {\r\n\t\t@SerializedName(\"360p\") R_360(640, 360), @SerializedName(\"720p\") R_720(1280, 720), @SerializedName(\r\n\t\t\t\"1080p\"\r\n\t\t) R_1080(1920, 1080);\r\n\r\n\t\tpublic final int width;\r\n\t\tpublic final int height;\r\n\r\n\t\tWindowSize(int width, int height) {\r\n\t\t\tthis.width = width;\r\n\t\t\tthis.height = height;\r\n\t\t}\r\n\t}\r\n}\r"
},
{
"identifier": "ConfigManager",
"path": "src/main/java/io/pyke/vitri/finorza/inference/config/ConfigManager.java",
"snippet": "public class ConfigManager {\r\n\tprivate static File file;\r\n\r\n\tprivate static void prepareConfigFile() {\r\n\t\tif (file != null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfile = new File(FabricLoader.getInstance().getConfigDir().toFile(), FinorzaInference.MOD_ID + \".json\");\r\n\t}\r\n\r\n\tpublic static void initializeConfig() {\r\n\t\tload();\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tprivate static void load() {\r\n\t\tprepareConfigFile();\r\n\r\n\t\ttry {\r\n\t\t\tif (!file.exists()) {\r\n\t\t\t\tsave();\r\n\t\t\t}\r\n\r\n\t\t\tif (file.exists()) {\r\n\t\t\t\tBufferedReader br = new BufferedReader(new FileReader(file));\r\n\t\t\t\tJsonObject json = JsonParser.parseReader(br).getAsJsonObject();\r\n\r\n\t\t\t\tfor (Field field : Config.class.getDeclaredFields()) {\r\n\t\t\t\t\tif (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) {\r\n\t\t\t\t\t\tif (BooleanConfigOption.class.isAssignableFrom(field.getType())) {\r\n\t\t\t\t\t\t\tJsonPrimitive primitive = json.getAsJsonPrimitive(field.getName().toLowerCase(Locale.ROOT));\r\n\t\t\t\t\t\t\tif (primitive != null && primitive.isBoolean()) {\r\n\t\t\t\t\t\t\t\tBooleanConfigOption option = (BooleanConfigOption) field.get(null);\r\n\t\t\t\t\t\t\t\tConfigOptionStorage.setBoolean(option.getKey(), primitive.getAsBoolean());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else if (EnumConfigOption.class.isAssignableFrom(\r\n\t\t\t\t\t\t\tfield.getType()) && field.getGenericType() instanceof ParameterizedType) {\r\n\t\t\t\t\t\t\tJsonPrimitive primitive = json.getAsJsonPrimitive(field.getName().toLowerCase(Locale.ROOT));\r\n\t\t\t\t\t\t\tif (primitive != null && primitive.isString()) {\r\n\t\t\t\t\t\t\t\tType generic = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];\r\n\t\t\t\t\t\t\t\tif (generic instanceof Class<?>) {\r\n\t\t\t\t\t\t\t\t\tEnumConfigOption<?> option = (EnumConfigOption<?>) field.get(null);\r\n\t\t\t\t\t\t\t\t\tEnum<?> found = null;\r\n\t\t\t\t\t\t\t\t\tfor (Enum<?> value : ((Class<Enum<?>>) generic).getEnumConstants()) {\r\n\t\t\t\t\t\t\t\t\t\tif (value.name().toLowerCase(Locale.ROOT).equals(primitive.getAsString())) {\r\n\t\t\t\t\t\t\t\t\t\t\tfound = value;\r\n\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tif (found != null) {\r\n\t\t\t\t\t\t\t\t\t\tConfigOptionStorage.setEnumTypeless(option.getKey(), found);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (FileNotFoundException | IllegalAccessException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic static void save() {\r\n\t\tprepareConfigFile();\r\n\r\n\t\tJsonObject config = new JsonObject();\r\n\r\n\t\ttry {\r\n\t\t\tfor (Field field : Config.class.getDeclaredFields()) {\r\n\t\t\t\tif (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) {\r\n\t\t\t\t\tif (BooleanConfigOption.class.isAssignableFrom(field.getType())) {\r\n\t\t\t\t\t\tBooleanConfigOption option = (BooleanConfigOption) field.get(null);\r\n\t\t\t\t\t\tconfig.addProperty(field.getName().toLowerCase(Locale.ROOT),\r\n\t\t\t\t\t\t ConfigOptionStorage.getBoolean(option.getKey())\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t} else if (EnumConfigOption.class.isAssignableFrom(\r\n\t\t\t\t\t\tfield.getType()) && field.getGenericType() instanceof ParameterizedType) {\r\n\t\t\t\t\t\tType generic = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];\r\n\t\t\t\t\t\tif (generic instanceof Class<?>) {\r\n\t\t\t\t\t\t\tEnumConfigOption<?> option = (EnumConfigOption<?>) field.get(null);\r\n\t\t\t\t\t\t\tconfig.addProperty(field.getName().toLowerCase(Locale.ROOT),\r\n\t\t\t\t\t\t\t ConfigOptionStorage.getEnumTypeless(option.getKey(),\r\n\t\t\t\t\t\t\t (Class<Enum<?>>) generic\r\n\t\t\t\t\t\t\t ).name().toLowerCase(Locale.ROOT)\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (IllegalAccessException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\r\n\t\tString jsonString = FinorzaInference.GSON.toJson(config);\r\n\r\n\t\ttry (FileWriter fileWriter = new FileWriter(file)) {\r\n\t\t\tfileWriter.write(jsonString);\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n}\r"
}
] | import java.util.List;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.OptionsList;
import net.minecraft.client.gui.screens.OptionsSubScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.util.FormattedCharSequence;
import io.pyke.vitri.finorza.inference.config.Config;
import io.pyke.vitri.finorza.inference.config.ConfigManager;
| 1,782 | package io.pyke.vitri.finorza.inference.gui;
public class ModOptionsScreen extends OptionsSubScreen {
private final Screen previous;
private OptionsList list;
public ModOptionsScreen(Screen previous) {
super(previous, Minecraft.getInstance().options, new TextComponent("Finorza Options"));
this.previous = previous;
}
protected void init() {
this.minecraft.keyboardHandler.setSendRepeatsToGui(true);
this.list = new OptionsList(this.minecraft, this.width, this.height, 32, this.height - 32, 25);
| package io.pyke.vitri.finorza.inference.gui;
public class ModOptionsScreen extends OptionsSubScreen {
private final Screen previous;
private OptionsList list;
public ModOptionsScreen(Screen previous) {
super(previous, Minecraft.getInstance().options, new TextComponent("Finorza Options"));
this.previous = previous;
}
protected void init() {
this.minecraft.keyboardHandler.setSendRepeatsToGui(true);
this.list = new OptionsList(this.minecraft, this.width, this.height, 32, this.height - 32, 25);
| this.list.addSmall(Config.asOptions());
| 0 | 2023-12-20 05:19:21+00:00 | 4k |
ciallo-dev/JWSystemLib | src/test/java/TestMyCourse.java | [
{
"identifier": "JWSystem",
"path": "src/main/java/moe/snowflake/jwSystem/JWSystem.java",
"snippet": "public class JWSystem {\n public Connection.Response jwLoggedResponse;\n public Connection.Response courseSelectSystemResponse;\n public Map<String, String> headers = new HashMap<>();\n private final boolean loginCourseSelectWeb;\n private final CourseSelectManager courseSelectManager;\n private final CourseReviewManager courseReviewManager;\n\n public JWSystem() {\n this(true);\n }\n\n public JWSystem(boolean loginCourseSelectWeb) {\n this.loginCourseSelectWeb = loginCourseSelectWeb;\n this.courseSelectManager = new CourseSelectManager(this);\n this.courseReviewManager = new CourseReviewManager(this);\n }\n\n /**\n * ๅคๆญๆๅกๆฏๅฆ็ปๅฝๆๅ\n *\n * @return ๆฏๅฆ็ปๅฝๆๅ\n */\n public boolean isJWLogged() {\n try {\n if (this.jwLoggedResponse != null) {\n // ๅช่ฆๆ่ฟไธชๅ
็ด ๅณ็ปๅฝๅคฑ่ดฅ\n Element element = this.jwLoggedResponse.parse().getElementById(\"showMsg\");\n if (element != null) return false;\n }\n } catch (Exception e) {\n return false;\n }\n return true;\n }\n\n /**\n * ๅคๆญ้่ฏพ็ณป็ปๆฏๅฆ็ปๅฝๆๅ\n *\n * @return ้่ฏพ็ณป็ปๆฏๅฆ็ปๅฝ\n */\n public boolean isCourseLogged() {\n try {\n return this.isJWLogged() &&\n this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains(\"็ปๅฝ\");\n } catch (IOException e) {\n return false;\n }\n }\n\n /**\n * ่ฎพ็ฝฎๅ
จๅฑ็ headers,ๅ
ๅซcookie\n * jsoup่ฎพ็ฝฎ็cookieๆ ๆณ่ฏๅซ\n *\n * @param cookie cookie\n */\n private void setHeaders(String cookie) {\n headers.put(\"Cookie\", \"JSESSIONID=\" + cookie);\n }\n\n /**\n * ็ดๆฅๅฏผๅ็ฎๆ API็็ปๅฝ\n *\n * @param username ็จๆทๅ\n * @param password ๅฏ็ \n */\n public JWSystem login(String username, String password) {\n Map<String, String> formData = new HashMap<>();\n formData.put(\"userAccount\", username);\n formData.put(\"userPassword\", \"\");\n // ๅพๆๆพ็ไธคไธชbase64ๅ ๅฏ\n formData.put(\"encoded\", new String(Base64.getEncoder().encode(username.getBytes())) + \"%%%\" + new String(Base64.getEncoder().encode(password.getBytes())));\n\n // ็ปๅฝๆๅ็ ๅๅบ\n Connection.Response response = HttpUtil.sendPost(URLManager.LOGIN, formData);\n\n if (response == null) {\n System.err.println(\"network error...\");\n return this;\n }\n this.jwLoggedResponse = response;\n this.setHeaders(response.cookie(\"JSESSIONID\"));\n this.loginCourseWeb();\n return this;\n }\n\n /**\n * ็จไบ็ดๆฅ็ปๅฝ้่ฏพ็ณป็ป\n * ๅ
็ปๅฝๅญฆ็้่ฏพ็ณป็ป,่ฎฉๅๅฐๅญJSESSIONID\n * ๅนถไธ่ฎพ็ฝฎ็ปๅฝๆๅ็\n */\n public void loginCourseWeb() {\n // ๆฏๅฆ็ปๅฝ้่ฏพ็ณป็ป\n if (isLoginCourseSelectWeb()) {\n this.courseSelectSystemResponse = HttpUtil.sendGet(URLManager.COURSE_LOGIN_WEB, this.headers);\n\n if (this.courseSelectSystemResponse == null) {\n System.out.println(\"network error !\");\n return;\n }\n\n // ๆฃๆตๆฏๅฆๅจ้่ฏพๆถ้ดๅ
\n if (this.courseSelectSystemResponse.body().contains(\"ๆถ้ด่ๅด\")) this.courseSelectSystemResponse = null;\n\n }\n }\n\n /**\n * ๆดๆ
ข็็ปๅฝ\n *\n * @param username ่ดฆๅท\n * @param password ๅฏ็ \n */\n @Deprecated\n public void login1(String username, String password) {\n Connection.Response keyGet = HttpUtil.sendGet(URLManager.LOGIN_DATA);\n if (keyGet == null || keyGet.statusCode() != 200) {\n System.err.println(\"network error\");\n return;\n }\n // ๆฟๆฐๆฎ็\n String dataStr = keyGet.body();\n\n // ๅ
ๆฃๆตไป่ฝๅฆๆฟๅฐๅ ๅฏๆฐๆฎ็ๅฏ้ฅ\n if (dataStr.split(\"#\").length < 2) {\n throw new RuntimeException(\"server or network error !\");\n }\n\n // ่ทๅๅ ๅฏๅ็ๅฏ็ ๆฐๆฎ\n String encoded = PasswordUtil.encodeUserData(dataStr, username + \"%%%\" + password);\n // ๆต่ฏๆฐๆฎ\n\n Map<String, String> formData = new HashMap<>();\n formData.put(\"userAccount\", \"\");\n formData.put(\"userPassword\", \"\");\n formData.put(\"encoded\", encoded);\n\n Connection.Response response = HttpUtil.sendPost(URLManager.LOGIN2, formData, this.headers);\n\n if (response == null) {\n throw new RuntimeException(\"network error !\");\n }\n\n // ้ๅฎๅๅฐ URLManager.LOGIN2 + method= jwxt + ticqzket= token\n Connection.Response ref = HttpUtil.sendGet(response.header(\"Location\"));\n // ็ปๅฝๆๅๅๅ cookie\n this.jwLoggedResponse = ref;\n\n if (this.jwLoggedResponse != null) {\n this.setHeaders(ref.cookie(\"JSESSIONID\"));\n this.loginCourseWeb();\n } else {\n System.err.println(\"response error....\");\n }\n }\n\n /**\n * ้ๅบ็ณป็ปไฝฟ็จ\n */\n public void exit() {\n // ้ๅบ้่ฏพ็ณป็ป\n Connection.Response exitSelect = HttpUtil.sendGet(URLManager.EXIT_COURSE_WEB, this.headers);\n // ้ๅบJWๆดไธช็ณป็ป\n Connection.Response exitAll = HttpUtil.sendGet(URLManager.EXIT_JWSYSTEM, this.headers);\n\n // DEBUG INFO\n if (exitSelect != null && exitAll != null) {\n // ้ๅบ้่ฏพ็ณป็ป็response body\n if (exitSelect.body().contains(\"true\")) System.out.println(\"้ๅบ้่ฏพ็ณป็ปๆๅ\");\n // ๆๅก็ณป็ป้ๅบ\n if (exitAll.body().contains(\"jsxsd\")) System.out.println(\"้ๅบๆๅก็ณป็ปๆๅ\");\n return;\n }\n System.err.println(\"unknown error !\");\n }\n\n public boolean isLoginCourseSelectWeb() {\n return this.loginCourseSelectWeb;\n }\n\n public CourseSelectManager getCourseSelectManager() {\n return courseSelectManager;\n }\n\n public CourseReviewManager getCourseReviewManager() {\n return courseReviewManager;\n }\n\n}"
},
{
"identifier": "Course",
"path": "src/main/java/moe/snowflake/jwSystem/course/Course.java",
"snippet": "public class Course {\n private String kcid;\n private String jxID;\n private String area;\n private String teacher;\n private String score;\n private String type;\n private String name;\n\n private int remain;\n\n private boolean isRequiredCourse;\n\n public Course(){\n }\n\n /**\n * ่ช่กๅๅปบไฝฟ็จ\n * @param kcid ่ฏพ็จID\n * @param jxID jxID\n */\n public Course(String kcid, String jxID) {\n this.kcid = kcid;\n this.jxID = jxID;\n }\n\n /**\n *\n * <p>\n * ๅๆฐ้ป่ฎคๅผ\n * <p>\n * trjf: ๆๅ
ฅ็งฏๅ\n * <p>\n * xkzy: ้่ฏพๅฟๆฟ\n * <p>\n * cfbs: null\n * <p>\n * @param kcid ่ฏพ็จID jx02id\n * @param jxID jxID jx0404id\n * @param teacher ่ๅธ skls\n */\n public Course(String kcid, String jxID, String teacher) {\n this.kcid = kcid;\n this.jxID = jxID;\n this.teacher = teacher;\n }\n\n public boolean isRequiredCourse() {\n return isRequiredCourse;\n }\n\n public void setRequiredCourse(boolean requiredCourse) {\n isRequiredCourse = requiredCourse;\n }\n\n public void setKCID(String KCID) {\n this.kcid = KCID;\n }\n\n public void setJxID(String jxID) {\n this.jxID = jxID;\n }\n\n public void setArea(String area) {\n this.area = area;\n }\n\n public void setTeacher(String teacher) {\n this.teacher = teacher;\n }\n\n public void setScore(String score) {\n this.score = score;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setRemain(String remain) {\n this.remain = Integer.parseInt(remain);\n }\n\n public String getKcid() {\n return kcid;\n }\n\n public String getJxID() {\n return jxID;\n }\n\n public String getArea() {\n return area;\n }\n\n public String getTeacher() {\n return teacher;\n }\n\n public String getScore() {\n return score;\n }\n\n public String getType() {\n return type;\n }\n\n public String getName() {\n return name;\n }\n\n public int getRemain() {\n return remain;\n }\n\n @Override\n public String toString() {\n return \"Course{\" +\n \"kcid='\" + kcid + '\\'' +\n \", jxID='\" + jxID + '\\'' +\n \", area='\" + area + '\\'' +\n \", teacher='\" + teacher + '\\'' +\n \", score='\" + score + '\\'' +\n \", type='\" + type + '\\'' +\n \", name='\" + name + '\\'' +\n \", remain='\" + remain + '\\'' +\n '}';\n }\n}"
}
] | import moe.snowflake.jwSystem.JWSystem;
import moe.snowflake.jwSystem.course.Course;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner; | 2,570 |
public class TestMyCourse {
@Test
public void test() throws IOException {
JWSystem system = new JWSystem().login("username", "password");
if (system.isCourseLogged()) {
System.out.println("ๅฝๅ่ฏพ็จๆฅ่ฏข็ปๆ: "); |
public class TestMyCourse {
@Test
public void test() throws IOException {
JWSystem system = new JWSystem().login("username", "password");
if (system.isCourseLogged()) {
System.out.println("ๅฝๅ่ฏพ็จๆฅ่ฏข็ปๆ: "); | ArrayList<Course> courses = system.getCourseSelectManager().getCurrentCourses(); | 1 | 2023-12-21 10:58:12+00:00 | 4k |
IzanagiCraft/Velocity-Maintenance | src/main/java/com/izanagicraft/velocity/maintenance/VelocityMaintenancePlugin.java | [
{
"identifier": "MaintenanceCommand",
"path": "src/main/java/com/izanagicraft/velocity/maintenance/commands/MaintenanceCommand.java",
"snippet": "public class MaintenanceCommand implements RawCommand {\n private final VelocityMaintenancePlugin plugin;\n\n public MaintenanceCommand(VelocityMaintenancePlugin plugin) {\n this.plugin = plugin;\n }\n\n\n @Override\n public void execute(Invocation invocation) {\n\n boolean enablePerm = hasEnablePermission(invocation.source());\n boolean disablePerm = hasDisablePermission(invocation.source());\n\n if (!enablePerm && !disablePerm) return;\n\n String error = plugin.getConfig().getString(\"messages.maintenance-error\");\n\n switch (invocation.arguments()) {\n case \"on\": {\n try {\n plugin.getMaintenanceData().get().setEnabled(true);\n try {\n plugin.getMaintenanceData().save(true);\n } catch (IOException e) {\n }\n String enabled = plugin.getConfig().getString(\"messages.maintenance-enabled\");\n MessageUtils.sendPrefixedMessage(invocation.source(), enabled);\n } catch (Exception e) {\n MessageUtils.sendPrefixedMessage(invocation.source(), error);\n e.printStackTrace();\n }\n break;\n }\n\n case \"off\": {\n try {\n plugin.getMaintenanceData().get().setEnabled(false);\n try {\n plugin.getMaintenanceData().save(true);\n } catch (IOException e) {\n }\n String disabled = plugin.getConfig().getString(\"messages.maintenance-disabled\");\n MessageUtils.sendPrefixedMessage(invocation.source(), disabled);\n } catch (Exception e) {\n MessageUtils.sendPrefixedMessage(invocation.source(), error);\n e.printStackTrace();\n }\n break;\n }\n default:\n String usage = plugin.getConfig().getString(\"messages.maintenance-usage\");\n MessageUtils.sendPrefixedMessage(invocation.source(), usage);\n break;\n }\n\n }\n\n private boolean hasEnablePermission(CommandSource source) {\n String permission = String.valueOf(plugin.getConfig().getString(\"permissions.enable\"));\n return source.hasPermission(permission);\n }\n\n private boolean hasDisablePermission(CommandSource source) {\n String permission = String.valueOf(plugin.getConfig().getString(\"permissions.disable\"));\n return source.hasPermission(permission);\n }\n\n @Override\n public CompletableFuture<List<String>> suggestAsync(Invocation invocation) {\n String[] args = invocation.arguments().split(\"\\\\s+\");\n List<String> completions = new ArrayList<>();\n List<String> available = new ArrayList<>();\n\n switch (args.length) {\n case 1:\n available.add(\"on\");\n available.add(\"off\");\n break;\n default:\n break;\n }\n\n MessageUtils.copyPartialMatches(args[args.length - 1], available, completions);\n Collections.sort(completions);\n return CompletableFuture.completedFuture(completions);\n }\n}"
},
{
"identifier": "JsonData",
"path": "src/main/java/com/izanagicraft/velocity/maintenance/data/JsonData.java",
"snippet": "public class JsonData<T> {\n\n private final File dataFile;\n\n private Class<T> dataClazz;\n\n private T data;\n\n public JsonData(Class<T> clazz, File dataFile) {\n this.dataFile = dataFile;\n this.dataClazz = clazz;\n }\n\n public void setDefault(Class clazz, Object defaultConfig) {\n this.dataClazz = clazz;\n this.data = (T) defaultConfig;\n }\n\n public void load() throws IOException {\n if (dataFile.exists()) {\n data = DataLoader.loadConfig(dataClazz, dataFile);\n }\n }\n\n public void load(boolean overrideDefault) throws IOException {\n if (!overrideDefault && data != null) {\n return;\n }\n load();\n }\n\n public void save() throws IOException {\n DataLoader.saveConfig(data, dataFile);\n }\n\n public void save(boolean overwrite) throws IOException {\n if (!overwrite && dataFile.exists()) {\n return;\n }\n save();\n }\n\n public T get() {\n return data;\n }\n\n}"
},
{
"identifier": "MaintenanceData",
"path": "src/main/java/com/izanagicraft/velocity/maintenance/data/types/MaintenanceData.java",
"snippet": "public class MaintenanceData {\n private boolean enabled;\n\n public MaintenanceData(boolean enabled) {\n this.enabled = enabled;\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public static MaintenanceData getDefault() {\n return new MaintenanceData(false);\n }\n}"
},
{
"identifier": "LoginEventListener",
"path": "src/main/java/com/izanagicraft/velocity/maintenance/listener/LoginEventListener.java",
"snippet": "public class LoginEventListener {\n\n private final VelocityMaintenancePlugin plugin;\n\n public LoginEventListener(VelocityMaintenancePlugin plugin) {\n this.plugin = plugin;\n }\n\n\n @Subscribe(order = PostOrder.FIRST)\n public void onPlayerConnect(final LoginEvent event) {\n if (!plugin.getMaintenanceData().get().isEnabled()) return;\n if (event.getPlayer() == null) return;\n Player player = event.getPlayer();\n String permission = String.valueOf(plugin.getConfig().getString(\"permissions.join\"));\n if (permission == null || permission.isEmpty() || !player.hasPermission(permission)) {\n MessageUtils.kickPlayerForMaintenance(player);\n }\n }\n\n}"
},
{
"identifier": "PingEventListener",
"path": "src/main/java/com/izanagicraft/velocity/maintenance/listener/PingEventListener.java",
"snippet": "public class PingEventListener {\n private final VelocityMaintenancePlugin plugin;\n\n public PingEventListener(VelocityMaintenancePlugin plugin) {\n this.plugin = plugin;\n }\n\n @Subscribe(order = PostOrder.FIRST)\n public void onProxyPing(final ProxyPingEvent event) {\n if (!plugin.getMaintenanceData().get().isEnabled()) return;\n\n final ServerPing ping = event.getPing();\n final ServerPing.Builder builder = ping.asBuilder();\n\n String prefix = VelocityMaintenancePlugin.getInstance().getConfig().getString(\"plugin.prefix\", \"[M]\");\n\n String version = plugin.getConfig().getString(\"ping.version\");\n if (version != null && !version.isEmpty()) {\n builder.version(new ServerPing.Version(0, version));\n }\n\n String motd = plugin.getConfig().getString(\"ping.motd\");\n if (motd != null && !motd.isEmpty()) {\n builder.description(\n MessageUtils.getComponentSerializer().deserialize(\n motd.replace(\"%prefix%\", prefix)\n )\n );\n }\n\n if ((version != null && !version.isEmpty()) || (motd != null && !motd.isEmpty())) {\n event.setPing(builder.build());\n }\n }\n}"
}
] | import com.google.inject.Inject;
import com.izanagicraft.velocity.maintenance.commands.MaintenanceCommand;
import com.izanagicraft.velocity.maintenance.data.JsonData;
import com.izanagicraft.velocity.maintenance.data.types.MaintenanceData;
import com.izanagicraft.velocity.maintenance.listener.LoginEventListener;
import com.izanagicraft.velocity.maintenance.listener.PingEventListener;
import com.moandjiezana.toml.Toml;
import com.velocitypowered.api.command.CommandManager;
import com.velocitypowered.api.event.EventManager;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger; | 2,825 | /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.velocity.maintenance;
/**
* Velocity-Maintenance; com.izanagicraft.velocity.maintenance:VelocityMaintenancePlugin
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 16.12.2023
*/
@Plugin(
id = "velocity-maintenance",
name = "VelocityMaintenance",
version = "1.0-SNAPSHOT",
description = "A customizable maintenance plugin for Velocity.",
authors = {"sanguine6660"},
url = "https://github.com/IzanagiCraft/Velocity-Maintenance",
dependencies = {}
)
public class VelocityMaintenancePlugin {
private static VelocityMaintenancePlugin instance;
public static VelocityMaintenancePlugin getInstance() {
return instance;
}
private ProxyServer server;
private Logger logger;
private @DataDirectory Path dataDir;
private File dataFolder;
private Toml config;
| /*
* โช ยทโโโโโข โโโยท โ โ โโโยท โโ โข โช โโยท โโโ โโโยท ยทโโโโโโโโ
* โโ โชโยท.โโโโ โโ โขโโโโโโ โโ โโ โ โชโโ โโ โโชโโ โยทโโ โโ โโโยทโขโโ
* โโยทโโโโโโขโโโโโ โโโโโโโโโโ โโ โโโโโยทโโ โโโโโโ โโโโโ โโโช โโ.โช
* โโโโโโชโโโโโ โชโโโโโโโโโ โชโโโโโโชโโโโโโโโโโโโโขโโโโ โชโโโโโ. โโโยท
* โโโยทโโโ โข โ โ โโ โโช โ โ ยทโโโโ โโโยทโโโ .โ โ โ โ โโโ โโโ
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com <[email protected]>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.velocity.maintenance;
/**
* Velocity-Maintenance; com.izanagicraft.velocity.maintenance:VelocityMaintenancePlugin
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 16.12.2023
*/
@Plugin(
id = "velocity-maintenance",
name = "VelocityMaintenance",
version = "1.0-SNAPSHOT",
description = "A customizable maintenance plugin for Velocity.",
authors = {"sanguine6660"},
url = "https://github.com/IzanagiCraft/Velocity-Maintenance",
dependencies = {}
)
public class VelocityMaintenancePlugin {
private static VelocityMaintenancePlugin instance;
public static VelocityMaintenancePlugin getInstance() {
return instance;
}
private ProxyServer server;
private Logger logger;
private @DataDirectory Path dataDir;
private File dataFolder;
private Toml config;
| private JsonData<MaintenanceData> maintenanceData; | 2 | 2023-12-16 14:17:06+00:00 | 4k |
emtee40/ApkSignatureKill-pc | app/src/main/java/org/jf/dexlib2/util/SyntheticAccessorFSM.java | [
{
"identifier": "Opcodes",
"path": "app/src/main/java/org/jf/dexlib2/Opcodes.java",
"snippet": "public class Opcodes {\n\n /**\n * Either the api level for dalvik opcodes, or the art version for art opcodes\n */\n public final int api;\n public final int artVersion;\n @NonNull\n private final Opcode[] opcodesByValue = new Opcode[255];\n @NonNull\n private final EnumMap<Opcode, Short> opcodeValues;\n @NonNull\n private final HashMap<String, Opcode> opcodesByName;\n\n private Opcodes(int api, int artVersion) {\n\n\n if (api >= 21) {\n this.api = api;\n this.artVersion = mapApiToArtVersion(api);\n } else if (artVersion >= 0 && artVersion < 39) {\n this.api = mapArtVersionToApi(artVersion);\n this.artVersion = artVersion;\n } else {\n this.api = api;\n this.artVersion = artVersion;\n }\n\n opcodeValues = new EnumMap<Opcode, Short>(Opcode.class);\n opcodesByName = Maps.newHashMap();\n\n int version;\n if (isArt()) {\n version = this.artVersion;\n } else {\n version = this.api;\n }\n\n for (Opcode opcode : Opcode.values()) {\n RangeMap<Integer, Short> versionToValueMap;\n\n if (isArt()) {\n versionToValueMap = opcode.artVersionToValueMap;\n } else {\n versionToValueMap = opcode.apiToValueMap;\n }\n\n Short opcodeValue = versionToValueMap.get(version);\n if (opcodeValue != null) {\n if (!opcode.format.isPayloadFormat) {\n opcodesByValue[opcodeValue] = opcode;\n }\n opcodeValues.put(opcode, opcodeValue);\n opcodesByName.put(opcode.name.toLowerCase(), opcode);\n }\n }\n }\n\n @NonNull\n public static Opcodes forApi(int api) {\n return new Opcodes(api, NO_VERSION);\n }\n\n @NonNull\n public static Opcodes forArtVersion(int artVersion) {\n return new Opcodes(NO_VERSION, artVersion);\n }\n\n /**\n * @return a default Opcodes instance for when the exact Opcodes to use doesn't matter or isn't known\n */\n @NonNull\n public static Opcodes getDefault() {\n // The last pre-art api\n return forApi(20);\n }\n\n @Nullable\n public Opcode getOpcodeByName(@NonNull String opcodeName) {\n return opcodesByName.get(opcodeName.toLowerCase());\n }\n\n @Nullable\n public Opcode getOpcodeByValue(int opcodeValue) {\n switch (opcodeValue) {\n case 0x100:\n return Opcode.PACKED_SWITCH_PAYLOAD;\n case 0x200:\n return Opcode.SPARSE_SWITCH_PAYLOAD;\n case 0x300:\n return Opcode.ARRAY_PAYLOAD;\n default:\n if (opcodeValue >= 0 && opcodeValue < opcodesByValue.length) {\n return opcodesByValue[opcodeValue];\n }\n return null;\n }\n }\n\n @Nullable\n public Short getOpcodeValue(@NonNull Opcode opcode) {\n return opcodeValues.get(opcode);\n }\n\n public boolean isArt() {\n return artVersion != NO_VERSION;\n }\n}"
},
{
"identifier": "Instruction",
"path": "app/src/main/java/org/jf/dexlib2/iface/instruction/Instruction.java",
"snippet": "public interface Instruction {\n /**\n * Gets the opcode of this instruction.\n *\n * @return The Opcode of this instruction.\n */\n Opcode getOpcode();\n\n /**\n * Gets the size of this instruction.\n *\n * @return The size of this instruction, as a count of the number of 16-bit code units that make up this\n * instruction.\n */\n int getCodeUnits();\n}"
},
{
"identifier": "OneRegisterInstruction",
"path": "app/src/main/java/org/jf/dexlib2/iface/instruction/OneRegisterInstruction.java",
"snippet": "public interface OneRegisterInstruction extends Instruction {\n int getRegisterA();\n}"
},
{
"identifier": "WideLiteralInstruction",
"path": "app/src/main/java/org/jf/dexlib2/iface/instruction/WideLiteralInstruction.java",
"snippet": "public interface WideLiteralInstruction extends Instruction {\n long getWideLiteral();\n}"
}
] | import androidx.annotation.NonNull;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.OneRegisterInstruction;
import org.jf.dexlib2.iface.instruction.WideLiteralInstruction;
import java.util.List; | 2,023 | // line 1 "SyntheticAccessorFSM.rl"
/*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.util;
public class SyntheticAccessorFSM {
// line 43 "SyntheticAccessorFSM.rl"
// math type constants
public static final int ADD = SyntheticAccessorResolver.ADD_ASSIGNMENT;
public static final int SUB = SyntheticAccessorResolver.SUB_ASSIGNMENT;
public static final int MUL = SyntheticAccessorResolver.MUL_ASSIGNMENT;
public static final int DIV = SyntheticAccessorResolver.DIV_ASSIGNMENT;
public static final int REM = SyntheticAccessorResolver.REM_ASSIGNMENT;
public static final int AND = SyntheticAccessorResolver.AND_ASSIGNMENT;
public static final int OR = SyntheticAccessorResolver.OR_ASSIGNMENT;
public static final int XOR = SyntheticAccessorResolver.XOR_ASSIGNMENT;
public static final int SHL = SyntheticAccessorResolver.SHL_ASSIGNMENT;
public static final int SHR = SyntheticAccessorResolver.SHR_ASSIGNMENT;
public static final int USHR = SyntheticAccessorResolver.USHR_ASSIGNMENT;
public static final int INT = 0;
public static final int LONG = 1;
public static final int FLOAT = 2;
public static final int DOUBLE = 3;
public static final int POSITIVE_ONE = 1;
public static final int NEGATIVE_ONE = -1;
public static final int OTHER = 0;
static final int SyntheticAccessorFSM_start = 1;
static final int SyntheticAccessorFSM_first_final = 17;
static final int SyntheticAccessorFSM_error = 0;
static final int SyntheticAccessorFSM_en_main = 1;
// line 44 "SyntheticAccessorFSM.rl"
private static final byte _SyntheticAccessorFSM_actions[] = init__SyntheticAccessorFSM_actions_0();
private static final short _SyntheticAccessorFSM_key_offsets[] = init__SyntheticAccessorFSM_key_offsets_0();
private static final short _SyntheticAccessorFSM_trans_keys[] = init__SyntheticAccessorFSM_trans_keys_0();
private static final byte _SyntheticAccessorFSM_single_lengths[] = init__SyntheticAccessorFSM_single_lengths_0();
private static final byte _SyntheticAccessorFSM_range_lengths[] = init__SyntheticAccessorFSM_range_lengths_0();
private static final short _SyntheticAccessorFSM_index_offsets[] = init__SyntheticAccessorFSM_index_offsets_0();
private static final byte _SyntheticAccessorFSM_indicies[] = init__SyntheticAccessorFSM_indicies_0();
private static final byte _SyntheticAccessorFSM_trans_targs[] = init__SyntheticAccessorFSM_trans_targs_0();
private static final byte _SyntheticAccessorFSM_trans_actions[] = init__SyntheticAccessorFSM_trans_actions_0();
@NonNull | // line 1 "SyntheticAccessorFSM.rl"
/*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.util;
public class SyntheticAccessorFSM {
// line 43 "SyntheticAccessorFSM.rl"
// math type constants
public static final int ADD = SyntheticAccessorResolver.ADD_ASSIGNMENT;
public static final int SUB = SyntheticAccessorResolver.SUB_ASSIGNMENT;
public static final int MUL = SyntheticAccessorResolver.MUL_ASSIGNMENT;
public static final int DIV = SyntheticAccessorResolver.DIV_ASSIGNMENT;
public static final int REM = SyntheticAccessorResolver.REM_ASSIGNMENT;
public static final int AND = SyntheticAccessorResolver.AND_ASSIGNMENT;
public static final int OR = SyntheticAccessorResolver.OR_ASSIGNMENT;
public static final int XOR = SyntheticAccessorResolver.XOR_ASSIGNMENT;
public static final int SHL = SyntheticAccessorResolver.SHL_ASSIGNMENT;
public static final int SHR = SyntheticAccessorResolver.SHR_ASSIGNMENT;
public static final int USHR = SyntheticAccessorResolver.USHR_ASSIGNMENT;
public static final int INT = 0;
public static final int LONG = 1;
public static final int FLOAT = 2;
public static final int DOUBLE = 3;
public static final int POSITIVE_ONE = 1;
public static final int NEGATIVE_ONE = -1;
public static final int OTHER = 0;
static final int SyntheticAccessorFSM_start = 1;
static final int SyntheticAccessorFSM_first_final = 17;
static final int SyntheticAccessorFSM_error = 0;
static final int SyntheticAccessorFSM_en_main = 1;
// line 44 "SyntheticAccessorFSM.rl"
private static final byte _SyntheticAccessorFSM_actions[] = init__SyntheticAccessorFSM_actions_0();
private static final short _SyntheticAccessorFSM_key_offsets[] = init__SyntheticAccessorFSM_key_offsets_0();
private static final short _SyntheticAccessorFSM_trans_keys[] = init__SyntheticAccessorFSM_trans_keys_0();
private static final byte _SyntheticAccessorFSM_single_lengths[] = init__SyntheticAccessorFSM_single_lengths_0();
private static final byte _SyntheticAccessorFSM_range_lengths[] = init__SyntheticAccessorFSM_range_lengths_0();
private static final short _SyntheticAccessorFSM_index_offsets[] = init__SyntheticAccessorFSM_index_offsets_0();
private static final byte _SyntheticAccessorFSM_indicies[] = init__SyntheticAccessorFSM_indicies_0();
private static final byte _SyntheticAccessorFSM_trans_targs[] = init__SyntheticAccessorFSM_trans_targs_0();
private static final byte _SyntheticAccessorFSM_trans_actions[] = init__SyntheticAccessorFSM_trans_actions_0();
@NonNull | private final Opcodes opcodes; | 0 | 2023-12-16 11:11:16+00:00 | 4k |
nimashidewanmini/layered-architecture-nimashi | src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java | [
{
"identifier": "ItemDAOImpl",
"path": "src/main/java/com/example/layeredarchitecture/dao/ItemDAOImpl.java",
"snippet": "public class ItemDAOImpl implements ItemDao {\n @Override\n public ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n Statement stm = connection.createStatement();\n ResultSet rst = stm.executeQuery(\"SELECT * FROM Item\");\n\n ArrayList <ItemDTO> itemDTOS=new ArrayList<>();\n\n while (rst.next()){\n itemDTOS.add(new ItemDTO(\n rst.getString(\"code\"),\n rst.getString(\"description\"),\n rst.getBigDecimal(\"unitPrice\"),\n rst.getInt(\"qtyOnHand\")\n ));\n }\n return getAllItems();\n }\n\n @Override\n public boolean SaveItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"INSERT INTO Item (code, description, unitPrice, qtyOnHand) VALUES (?,?,?,?)\");\n\n pstm.setString(1, dto.getCode());\n pstm.setString(2, dto.getDescription());\n pstm.setBigDecimal(3, dto.getUnitPrice());\n pstm.setInt(4,dto.getQtyOnHand());\n\n return pstm.executeUpdate()>0;\n }\n\n @Override\n public boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"UPDATE Item SET description=?, unitPrice=?, qtyOnHand=? WHERE code=?\");\n\n pstm.setString(1, dto.getDescription());\n pstm.setBigDecimal(2,dto.getUnitPrice());\n pstm.setInt(3, dto.getQtyOnHand());\n pstm.setString(4, dto.getCode());\n return pstm.executeUpdate() >0;\n }\n\n @Override\n public boolean deleteItem(String code) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"DELETE FROM Item WHERE code=?\");\n pstm.setString(1,code);\n return pstm.executeUpdate()>0;\n\n }\n\n @Override\n public boolean existItem (String code) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"SELECT code FROM Item WHERE code=?\");\n pstm.setString(1, code);\n return pstm.executeQuery().next();\n }\n\n @Override\n public ResultSet generateNewId() throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n ResultSet rst = connection.createStatement().executeQuery(\"SELECT code FROM Item ORDER BY code DESC LIMIT 1;\");\n\n return rst;\n }\n\n}"
},
{
"identifier": "ItemDao",
"path": "src/main/java/com/example/layeredarchitecture/dao/ItemDao.java",
"snippet": "public interface ItemDao {\n ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException;\n\n boolean SaveItem(ItemDTO dto) throws SQLException, ClassNotFoundException;\n\n boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException;\n\n boolean deleteItem(String code) throws SQLException, ClassNotFoundException;\n\n boolean existItem(String code) throws SQLException, ClassNotFoundException;\n ResultSet generateNewId() throws SQLException, ClassNotFoundException;\n\n }"
},
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLException {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/company\", \"root\", \"Ijse@1234\");\n }\n\n public static DBConnection getDbConnection() throws SQLException, ClassNotFoundException {\n return dbConnection == null ? dbConnection= new DBConnection() : dbConnection;\n }\n\n public Connection getConnection() {\n return connection;\n }\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "ItemTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/ItemTM.java",
"snippet": "public class ItemTM {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemTM() {\n }\n\n public ItemTM(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.dao.ItemDAOImpl;
import com.example.layeredarchitecture.dao.ItemDao;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.view.tdm.ItemTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*; | 2,201 | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
| package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
| ItemDao itemDAO=new ItemDAOImpl(); | 0 | 2023-12-16 04:14:29+00:00 | 4k |
J-SPOT/playground | backend/funnyboard/src/test/java/funnyboard/CommentServiceTest.java | [
{
"identifier": "CommentNotFoundException",
"path": "backend/funnyboard/src/main/java/funnyboard/config/error/exception/comment/CommentNotFoundException.java",
"snippet": "public class CommentNotFoundException extends NotFoundException {\n public CommentNotFoundException() {\n super(ErrorCode.COMMENT_NOT_FOUND);\n }\n}"
},
{
"identifier": "Article",
"path": "backend/funnyboard/src/main/java/funnyboard/domain/Article.java",
"snippet": "@Entity\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@ToString\npublic class Article {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String title;\n private String content;\n\n public static ArticleForm toForm(Article article) {\n return new ArticleForm(article.getId(), article.getTitle(), article.getContent());\n }\n\n public static ArticleUpdateRequest toUpdateRequest(Article article) {\n return new ArticleUpdateRequest(article.getId(), article.getTitle(), article.getContent());\n }\n\n public void patch(ArticleUpdateRequest dto) {\n if (dto.getTitle() != null) {\n this.title = dto.getTitle();\n }\n if (dto.getContent() != null) {\n this.content = dto.getContent();\n }\n }\n}"
},
{
"identifier": "Comment",
"path": "backend/funnyboard/src/main/java/funnyboard/domain/Comment.java",
"snippet": "@Entity\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Comment {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n @ManyToOne\n @JoinColumn(name = \"article_id\")\n private Article article;\n @Column\n private String nickname;\n @Column\n private String content;\n\n public static Comment createComment(CommentForm dto, Article article) {\n if (dto.getId() != null)\n throw new CommentCreationHasId();\n if (dto.getArticleId() != article.getId())\n throw new CommentCreationWrongArticleId();\n return new Comment(\n dto.getId(),\n article,\n dto.getNickname(),\n dto.getContent()\n );\n }\n\n public void patch(CommentForm dto) {\n if (dto.getNickname() != null)\n this.nickname = dto.getNickname();\n if (dto.getContent() != null)\n this.content = dto.getContent();\n }\n}"
},
{
"identifier": "CommentForm",
"path": "backend/funnyboard/src/main/java/funnyboard/dto/CommentForm.java",
"snippet": "@ToString\n@Getter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommentForm {\n private Long id;\n private Long articleId;\n private String nickname;\n private String content;\n\n public static CommentForm createCommentDto(Comment comment) {\n return new CommentForm(\n comment.getId(),\n comment.getArticle().getId(),\n comment.getNickname(),\n comment.getContent()\n );\n }\n}"
},
{
"identifier": "ArticleRepository",
"path": "backend/funnyboard/src/main/java/funnyboard/repository/ArticleRepository.java",
"snippet": "@Repository\npublic interface ArticleRepository extends JpaRepository<Article, Long> {\n}"
},
{
"identifier": "CommentRepository",
"path": "backend/funnyboard/src/main/java/funnyboard/repository/CommentRepository.java",
"snippet": "@Repository\npublic interface CommentRepository extends JpaRepository<Comment, Long> {\n\n @Query(value = \"SELECT * FROM comment WHERE article_id = :articleId\",\n nativeQuery = true)\n List<Comment> findByArticleId(@Param(\"articleId\") Long articleId);\n}"
},
{
"identifier": "CommentService",
"path": "backend/funnyboard/src/main/java/funnyboard/service/CommentService.java",
"snippet": "@Service\n@Slf4j\npublic class CommentService {\n\n private final CommentRepository commentRepository;\n private final ArticleRepository articleRepository;\n\n public CommentService(CommentRepository commentRepository, ArticleRepository articleRepository) {\n this.commentRepository = commentRepository;\n this.articleRepository = articleRepository;\n }\n\n public CommentForm create(Long articleId, CommentForm dto) {\n Article article = articleRepository.findById(articleId).orElseThrow(\n () -> new ArticleNotFoundException());\n if (article == null)\n return null;\n Comment comment = Comment.createComment(dto, article);\n Comment created = commentRepository.save(comment);\n return CommentForm.createCommentDto(created);\n }\n\n public List<CommentForm> findAllComments(Long articleId) {\n return commentRepository.findByArticleId(articleId)\n .stream()\n .map(comment -> CommentForm.createCommentDto(comment))\n .collect(Collectors.toList());\n }\n\n public CommentForm update(Long id, CommentForm dto) {\n Comment comment = commentRepository.findById(id).orElseThrow(\n () -> new CommentNotFoundException());\n if (comment.getId() != dto.getId())\n throw new CommentUpdateIdNotValid();\n comment.patch(dto);\n Comment updated = commentRepository.save(comment);\n return CommentForm.createCommentDto(updated);\n }\n\n public CommentForm delete(Long id) {\n Comment comment = commentRepository.findById(id).orElseThrow(\n () -> new CommentNotFoundException());\n commentRepository.delete(comment);\n return CommentForm.createCommentDto(comment);\n }\n}"
}
] | import funnyboard.config.error.exception.comment.CommentNotFoundException;
import funnyboard.domain.Article;
import funnyboard.domain.Comment;
import funnyboard.dto.CommentForm;
import funnyboard.repository.ArticleRepository;
import funnyboard.repository.CommentRepository;
import funnyboard.service.CommentService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat; | 2,206 | package funnyboard;
@ExtendWith(MockitoExtension.class)
public class CommentServiceTest {
@Mock
private CommentRepository commentRepository;
@Mock
private ArticleRepository articleRepository;
@InjectMocks
private CommentService commentService;
Article article1, article2;
Comment comment1, comment2, comment3, beforeUpdateComment, updatedComment, createdComment;
CommentForm createForm, updateForm;
@BeforeEach
void setup() {
article1 = new Article(1L, "์ ๋ชฉ 1", "๋ด์ฉ 1");
article2 = new Article(2L, "์ ๋ชฉ 2", "๋ด์ฉ 2");
comment1 = new Comment(null, article1, "์์ฑ์ 1", "๋ด์ฉ 1");
comment2 = new Comment(null, article1, "์์ฑ์ 1", "๋ด์ฉ 2");
comment3 = new Comment(null, article1, "์์ฑ์ 2", "๋ด์ฉ 3");
beforeUpdateComment = new Comment(1L, article1, "์์ฑ์ 1", "๋ด์ฉ 1");
updatedComment = new Comment(1L, article1, "์์ฑ์ 1 ์์ ", "๋ด์ฉ 1 ์์ ");
createdComment = new Comment(1L, article1, "์์ฑ์ 1", "๋ด์ฉ 1");
updateForm = new CommentForm(1L, article1.getId(), "์์ฑ์ 1 ์์ ", "๋ด์ฉ 1 ์์ ");
createForm = new CommentForm(null, article1.getId(), "์์ฑ์ 1", "๋ด์ฉ 1");
}
@DisplayName("ํน์ ๊ฒ์๊ธ์ ๋ชจ๋ ๋๊ธ ๊ฐ์ ธ์ค๊ธฐ")
@Test
void FindComments_ReturnFindComments() {
//given
List<Comment> comments = Arrays.asList(comment1, comment2, comment3);
Mockito.when(commentRepository.findByArticleId(article1.getId())).thenReturn(comments);
//when
List<CommentForm> findCommentsDto = commentService.findAllComments(article1.getId());
List<Comment> findComments = findCommentsDto.stream()
.map(comment -> Comment.createComment(comment, article1))
.collect(Collectors.toList());
//then
assertThat(findComments).isNotNull();
assertThat(findComments).usingRecursiveComparison().isEqualTo(comments);
}
@DisplayName("ํน์ ๊ฒ์๊ธ์ ํน์ ๋๊ธ ์์ ํ๊ธฐ")
@Test
void UpdateComment_ReturnUpdatedComment() {
//given
Mockito.when(commentRepository.findById(beforeUpdateComment.getId())).thenReturn(Optional.of(updatedComment));
Mockito.when(commentRepository.save(updatedComment)).thenReturn(updatedComment);
//when
CommentForm updatedForm = commentService.update(beforeUpdateComment.getId(), updateForm);
//then
assertThat(updatedForm).isNotNull();
assertThat(updatedForm).usingRecursiveComparison().isEqualTo(updateForm);
}
@DisplayName("ํน์ ๋๊ธ ์์ฑํ๊ธฐ")
@Test
void CreateComment_ReturnCreatedComment() {
//given
Mockito.when(articleRepository.findById(article1.getId())).thenReturn(Optional.of(article1));
Mockito.when(commentRepository.save(Mockito.any(Comment.class))).thenReturn(comment1);
//when
CommentForm createdForm = commentService.create(article1.getId(), createForm);
//then
assertThat(createdForm).isNotNull();
assertThat(createdForm).usingRecursiveComparison().isEqualTo(createForm);
}
@DisplayName("์กด์ฌํ๋ ํน์ ๊ฒ์๊ธ ์ญ์ ํ๊ธฐ")
@Test
void DeleteArticle_ReturnDeletedArticle() {
//given
Mockito.when(commentRepository.findById(createdComment.getId())).thenReturn(Optional.of(createdComment));
Mockito.doNothing().when(commentRepository).delete(createdComment);
//when
CommentForm deletedForm = commentService.delete(article1.getId());
//then
Mockito.verify(commentRepository).delete(createdComment);
}
@DisplayName("์กด์ฌ ํ์ง ์๋ ํน์ ๊ฒ์๊ธ ์ญ์ ํ๊ธฐ")
@Test
void DeleteArticleNotExist_ReturnNull() {
//given
Mockito.when(commentRepository.findById(comment1.getId())).thenReturn(Optional.empty());
//when
//then
Assertions.assertThatThrownBy(() -> {
commentService.delete(comment1.getId()); | package funnyboard;
@ExtendWith(MockitoExtension.class)
public class CommentServiceTest {
@Mock
private CommentRepository commentRepository;
@Mock
private ArticleRepository articleRepository;
@InjectMocks
private CommentService commentService;
Article article1, article2;
Comment comment1, comment2, comment3, beforeUpdateComment, updatedComment, createdComment;
CommentForm createForm, updateForm;
@BeforeEach
void setup() {
article1 = new Article(1L, "์ ๋ชฉ 1", "๋ด์ฉ 1");
article2 = new Article(2L, "์ ๋ชฉ 2", "๋ด์ฉ 2");
comment1 = new Comment(null, article1, "์์ฑ์ 1", "๋ด์ฉ 1");
comment2 = new Comment(null, article1, "์์ฑ์ 1", "๋ด์ฉ 2");
comment3 = new Comment(null, article1, "์์ฑ์ 2", "๋ด์ฉ 3");
beforeUpdateComment = new Comment(1L, article1, "์์ฑ์ 1", "๋ด์ฉ 1");
updatedComment = new Comment(1L, article1, "์์ฑ์ 1 ์์ ", "๋ด์ฉ 1 ์์ ");
createdComment = new Comment(1L, article1, "์์ฑ์ 1", "๋ด์ฉ 1");
updateForm = new CommentForm(1L, article1.getId(), "์์ฑ์ 1 ์์ ", "๋ด์ฉ 1 ์์ ");
createForm = new CommentForm(null, article1.getId(), "์์ฑ์ 1", "๋ด์ฉ 1");
}
@DisplayName("ํน์ ๊ฒ์๊ธ์ ๋ชจ๋ ๋๊ธ ๊ฐ์ ธ์ค๊ธฐ")
@Test
void FindComments_ReturnFindComments() {
//given
List<Comment> comments = Arrays.asList(comment1, comment2, comment3);
Mockito.when(commentRepository.findByArticleId(article1.getId())).thenReturn(comments);
//when
List<CommentForm> findCommentsDto = commentService.findAllComments(article1.getId());
List<Comment> findComments = findCommentsDto.stream()
.map(comment -> Comment.createComment(comment, article1))
.collect(Collectors.toList());
//then
assertThat(findComments).isNotNull();
assertThat(findComments).usingRecursiveComparison().isEqualTo(comments);
}
@DisplayName("ํน์ ๊ฒ์๊ธ์ ํน์ ๋๊ธ ์์ ํ๊ธฐ")
@Test
void UpdateComment_ReturnUpdatedComment() {
//given
Mockito.when(commentRepository.findById(beforeUpdateComment.getId())).thenReturn(Optional.of(updatedComment));
Mockito.when(commentRepository.save(updatedComment)).thenReturn(updatedComment);
//when
CommentForm updatedForm = commentService.update(beforeUpdateComment.getId(), updateForm);
//then
assertThat(updatedForm).isNotNull();
assertThat(updatedForm).usingRecursiveComparison().isEqualTo(updateForm);
}
@DisplayName("ํน์ ๋๊ธ ์์ฑํ๊ธฐ")
@Test
void CreateComment_ReturnCreatedComment() {
//given
Mockito.when(articleRepository.findById(article1.getId())).thenReturn(Optional.of(article1));
Mockito.when(commentRepository.save(Mockito.any(Comment.class))).thenReturn(comment1);
//when
CommentForm createdForm = commentService.create(article1.getId(), createForm);
//then
assertThat(createdForm).isNotNull();
assertThat(createdForm).usingRecursiveComparison().isEqualTo(createForm);
}
@DisplayName("์กด์ฌํ๋ ํน์ ๊ฒ์๊ธ ์ญ์ ํ๊ธฐ")
@Test
void DeleteArticle_ReturnDeletedArticle() {
//given
Mockito.when(commentRepository.findById(createdComment.getId())).thenReturn(Optional.of(createdComment));
Mockito.doNothing().when(commentRepository).delete(createdComment);
//when
CommentForm deletedForm = commentService.delete(article1.getId());
//then
Mockito.verify(commentRepository).delete(createdComment);
}
@DisplayName("์กด์ฌ ํ์ง ์๋ ํน์ ๊ฒ์๊ธ ์ญ์ ํ๊ธฐ")
@Test
void DeleteArticleNotExist_ReturnNull() {
//given
Mockito.when(commentRepository.findById(comment1.getId())).thenReturn(Optional.empty());
//when
//then
Assertions.assertThatThrownBy(() -> {
commentService.delete(comment1.getId()); | }).isInstanceOf(CommentNotFoundException.class) | 0 | 2023-12-15 16:05:45+00:00 | 4k |
matthiasbergneels/dhbwmawwi2023seb | src/excersises/chapter5/hausbau/builderpattern/constructionarea/HouseExampleRun.java | [
{
"identifier": "House",
"path": "src/excersises/chapter5/hausbau/builderpattern/house/House.java",
"snippet": "public class House {\n final static int DEFAULT_DOOR = 1;\n final static int DEFAULT_WINDOW = 1;\n final static int DEFAULT_FLOOR = 1;\n final static int DEFAULT_FLOOR_SPACE = 100;\n final static String DEFAULT_STREET = \"Coblitzallee\";\n final static String DEFAULT_HOUSENUMBER = \"7\";\n final static int DEFAULT_ZIP_CODE = 69782;\n final static String DEFAULT_CITY = \"Mannheim\";\n\n private int doors;\n private int windows;\n private int floors;\n private int floorSpace;\n private String street;\n private String housenumber;\n private int zipCode;\n private String city;\n private boolean hasFlatRoof;\n\n private static int objCnt = 0;\n\n House(int doors, int windows, int floors, int floorSpace, String street, String housenumber, int zipCode, String city, boolean hasFlatRoof){\n this.setFloors(floors);\n this.setWindows(windows);\n this.setDoors(doors);\n this.setFloorSpace(floorSpace);\n this.setStreet(street);\n this.setHouseNumber(housenumber);\n this.setZipCode(zipCode);\n this.setCity(city);\n this.setHasFlatRoof(hasFlatRoof);\n\n objCnt++;\n }\n\n public int getDoors() {\n return doors;\n }\n public void setDoors(int doors) {\n this.doors = isNegativNumber(doors) ? DEFAULT_DOOR : doors;\n }\n public int getWindows() {\n return windows;\n }\n public void setWindows(int windows) {\n this.windows = isNegativNumber(windows) ? DEFAULT_WINDOW : windows;\n }\n public int getFloors() {\n return floors;\n }\n public void setFloors(int floors) {\n this.floors = isNegativNumber(floors) ? DEFAULT_FLOOR : floors;\n }\n public int getFloorSpace() {\n return floorSpace;\n }\n public void setFloorSpace(int floorSpace) {\n if(floorSpace >= 100 && floorSpace <= 500){\n this.floorSpace = floorSpace;\n }else{\n this.floorSpace = DEFAULT_FLOOR_SPACE;\n }\n }\n\n public String getStreet() {\n return street;\n }\n public void setStreet(String street) {\n this.street = isEmptyOrDefault(street, DEFAULT_STREET);\n }\n public String getHousenumber() {\n return housenumber;\n }\n public void setHouseNumber(String houseNumber) {\n this.housenumber = isEmptyOrDefault(houseNumber, DEFAULT_HOUSENUMBER);\n }\n public int getZipCode() {\n return zipCode;\n }\n public void setZipCode(int zipCode) {\n this.zipCode = isNegativNumber(zipCode) ? DEFAULT_ZIP_CODE : zipCode;\n }\n public String getCity() {\n return city;\n }\n public void setCity(String city) {\n this.city = isEmptyOrDefault(city, DEFAULT_CITY);\n }\n public boolean hasFlatRoof() {\n return hasFlatRoof;\n }\n public void setHasFlatRoof(boolean hasFlatRoof) {\n this.hasFlatRoof = hasFlatRoof;\n }\n\n private boolean isNegativNumber(int zahl){\n return (zahl > 0) ? false : true;\n }\n\n private String isEmptyOrDefault(String pruefen, String defaultString){\n return (pruefen == null || pruefen.isEmpty()) ? defaultString : pruefen;\n }\n\n @Override\n public String toString() {\n return \"Hausinformationen: \"\n + \"Etagen: \" + getFloors() + \"; \"\n + \"Tueren: \" + getDoors() + \"; \"\n + \"Fenster: \" + getWindows() + \"; \"\n + \"Flaeche: \" + getFloorSpace() + \"qm; \"\n + \"Flachdach: \" + (hasFlatRoof() ? \"ja\" : \"nein\") + \"; \"\n + \"Adresse: \" + getStreet() + \" \" + getHousenumber() + \", \" + getZipCode() + \" \" + getCity()\n ;\n }\n\n @Override\n protected void finalize(){\n System.out.println(\"Das Haus \" + this + \" wurde abgerissen.\");\n objCnt--;\n }\n\n public static int getObjCnt() {\n return objCnt;\n }\n}"
},
{
"identifier": "HouseBuilder",
"path": "src/excersises/chapter5/hausbau/builderpattern/house/HouseBuilder.java",
"snippet": "public class HouseBuilder {\n\n private House constructionHouse;\n\n public HouseBuilder() {\n //private House(int doors, int windows, int floors, int floorSpace, String street, String housenumber, int zipCode, String city, boolean hasFlatRoof){\n constructionHouse = new House(House.DEFAULT_DOOR, House.DEFAULT_WINDOW, House.DEFAULT_FLOOR, House.DEFAULT_FLOOR_SPACE, House.DEFAULT_STREET, House.DEFAULT_HOUSENUMBER, House.DEFAULT_ZIP_CODE, House.DEFAULT_CITY, false);\n }\n\n public HouseBuilder buildDoors(int doors) {\n constructionHouse.setDoors(doors);\n return this;\n }\n\n public HouseBuilder buildWindows(int windows) {\n constructionHouse.setWindows(windows);\n return this;\n }\n\n public HouseBuilder buildFloors(int floors) {\n constructionHouse.setFloors(floors);\n return this;\n }\n\n public HouseBuilder setFloorSpace(int floorSpace) {\n constructionHouse.setFloorSpace(floorSpace);\n return this;\n }\n\n public HouseBuilder buildFlatRoof() {\n constructionHouse.setHasFlatRoof(true);\n return this;\n }\n\n public HouseBuilder setAddress(String street, String houseNumber, String city, int zipCode) {\n constructionHouse.setStreet(street);\n constructionHouse.setHouseNumber(houseNumber);\n constructionHouse.setCity(city);\n constructionHouse.setZipCode(zipCode);\n\n return this;\n }\n\n public HouseBuilder setStreet(String street) {\n constructionHouse.setStreet(street);\n return this;\n }\n\n public HouseBuilder setCity(String city) {\n constructionHouse.setCity(city);\n return this;\n }\n\n public HouseBuilder setZipCode(int zipCode) {\n constructionHouse.setZipCode(zipCode);\n return this;\n }\n\n public HouseBuilder setHouseNumber(String houseNumber) {\n constructionHouse.setHouseNumber(houseNumber);\n return this;\n }\n\n public House finalizeHouseBuilding() {\n return constructionHouse;\n }\n}"
}
] | import excersises.chapter5.hausbau.builderpattern.house.House;
import excersises.chapter5.hausbau.builderpattern.house.HouseBuilder; | 1,744 | package excersises.chapter5.hausbau.builderpattern.constructionarea;
public class HouseExampleRun {
public static void main(String[] args) {
System.out.println("Aktuelle Anzahl Hรคuser: " + House.getObjCnt()); | package excersises.chapter5.hausbau.builderpattern.constructionarea;
public class HouseExampleRun {
public static void main(String[] args) {
System.out.println("Aktuelle Anzahl Hรคuser: " + House.getObjCnt()); | House myHouse = new HouseBuilder().buildFloors(5).buildDoors(3).buildWindows(20).setFloorSpace(300).buildFlatRoof().finalizeHouseBuilding(); | 1 | 2023-12-20 21:17:12+00:00 | 4k |
aborroy/alfresco-genai | alfresco-ai/alfresco-ai-listener/src/main/java/org/alfresco/genai/service/GenAiClient.java | [
{
"identifier": "Answer",
"path": "alfresco-ai/alfresco-ai-listener/src/main/java/org/alfresco/genai/model/Answer.java",
"snippet": "public class Answer {\n\n /**\n * The generated answer content.\n */\n private String answer;\n\n /**\n * The model information associated with the generated answer.\n */\n private String model;\n\n /**\n * Gets the generated answer content.\n *\n * @return The answer content.\n */\n public String getAnswer() {\n return answer;\n }\n\n /**\n * Sets the answer content and returns the current instance for method chaining.\n *\n * @param answer The answer content to set.\n * @return The current {@code Answer} instance.\n */\n public Answer answer(String answer) {\n this.answer = answer;\n return this;\n }\n\n /**\n * Gets the model information associated with the generated answer.\n *\n * @return The model information.\n */\n public String getModel() {\n return model;\n }\n\n /**\n * Sets the model information and returns the current instance for method chaining.\n *\n * @param model The model information to set.\n * @return The current {@code Answer} instance.\n */\n public Answer model(String model) {\n this.model = model;\n return this;\n }\n}"
},
{
"identifier": "Summary",
"path": "alfresco-ai/alfresco-ai-applier/src/main/java/org/alfresco/genai/model/Summary.java",
"snippet": "public class Summary {\n\n /**\n * The summarized text content of the document.\n */\n private String summary;\n\n /**\n * A list of tags associated with the document.\n */\n private List<String> tags;\n\n /**\n * The model used for summarization.\n */\n private String model;\n\n /**\n * Gets the summarized text content of the document.\n *\n * @return The summary text.\n */\n public String getSummary() {\n return summary;\n }\n\n /**\n * Sets the summarized text content of the document.\n *\n * @param summary The summary text.\n * @return This {@code Summary} instance for method chaining.\n */\n public Summary summary(String summary) {\n this.summary = summary;\n return this;\n }\n\n /**\n * Gets the list of tags associated with the document.\n *\n * @return The list of tags.\n */\n public List<String> getTags() {\n return tags;\n }\n\n /**\n * Sets the list of tags associated with the document.\n *\n * @param tags The list of tags.\n * @return This {@code Summary} instance for method chaining.\n */\n public Summary tags(List<String> tags) {\n this.tags = tags;\n return this;\n }\n\n /**\n * Gets the model used for summarization.\n *\n * @return The summarization model.\n */\n public String getModel() {\n return model;\n }\n\n /**\n * Sets the model used for summarization.\n *\n * @param model The summarization model.\n * @return This {@code Summary} instance for method chaining.\n */\n public Summary model(String model) {\n this.model = model;\n return this;\n }\n\n}"
},
{
"identifier": "Term",
"path": "alfresco-ai/alfresco-ai-applier/src/main/java/org/alfresco/genai/model/Term.java",
"snippet": "public class Term {\n\n /**\n * The selected term content.\n */\n private String term;\n\n /**\n * The model information associated with the generated answer.\n */\n private String model;\n\n /**\n * Gets the generated term content.\n *\n * @return The term content.\n */\n public String getTerm() {\n return term;\n }\n\n /**\n * Sets the term content and returns the current instance for method chaining.\n *\n * @param term The term content to set.\n * @return The current {@code Term} instance.\n */\n public Term term(String term) {\n this.term = term;\n return this;\n }\n\n /**\n * Gets the model information associated with the generated answer.\n *\n * @return The model information.\n */\n public String getModel() {\n return model;\n }\n\n /**\n * Sets the model information and returns the current instance for method chaining.\n *\n * @param model The model information to set.\n * @return The current {@code Answer} instance.\n */\n public Term model(String model) {\n this.model = model;\n return this;\n }\n}"
}
] | import jakarta.annotation.PostConstruct;
import okhttp3.*;
import org.alfresco.genai.model.Answer;
import org.alfresco.genai.model.Summary;
import org.alfresco.genai.model.Term;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit; | 1,893 | package org.alfresco.genai.service;
/**
* The {@code GenAiClient} class is a Spring service that interacts with the GenAI service to obtain document summaries
* and answers to specific questions. It uses an {@link OkHttpClient} to perform HTTP requests to the GenAI service
* endpoint, and it is configured with properties such as the GenAI service URL and request timeout.
*/
@Service
public class GenAiClient {
/**
* The base URL of the GenAI service obtained from configuration.
*/
@Value("${genai.url}")
String genaiUrl;
/**
* The request timeout for GenAI service requests obtained from configuration.
*/
@Value("${genai.request.timeout}")
Integer genaiTimeout;
/**
* Static instance of {@link JsonParser} to parse JSON responses from the GenAI service.
*/
static final JsonParser JSON_PARSER = JsonParserFactory.getJsonParser();
/**
* The OkHttpClient instance for making HTTP requests to the GenAI service.
*/
OkHttpClient client;
/**
* Initializes the OkHttpClient with specified timeouts during bean creation.
*/
@PostConstruct
public void init() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(genaiTimeout, TimeUnit.SECONDS)
.build();
}
/**
* Retrieves a document summary from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file for which the summary is requested.
* @return A {@link Summary} object containing the summary, tags, and model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/
public Summary getSummary(File pdfFile) throws IOException {
RequestBody requestBody = new MultipartBody
.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", pdfFile.getName(), RequestBody.create(pdfFile, MediaType.parse("application/pdf")))
.build();
Request request = new Request
.Builder()
.url(genaiUrl + "/summary")
.post(requestBody)
.build();
String response = client.newCall(request).execute().body().string();
Map<String, Object> aiResponse = JSON_PARSER.parseMap(response);
return new Summary()
.summary(aiResponse.get("summary").toString().trim())
.tags(Arrays.asList(aiResponse.get("tags").toString().split(",", -1)))
.model(aiResponse.get("model").toString());
}
/**
* Retrieves an answer to a specific question from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file containing the document related to the question.
* @param question The question for which an answer is requested.
* @return An {@link Answer} object containing the answer and the model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/ | package org.alfresco.genai.service;
/**
* The {@code GenAiClient} class is a Spring service that interacts with the GenAI service to obtain document summaries
* and answers to specific questions. It uses an {@link OkHttpClient} to perform HTTP requests to the GenAI service
* endpoint, and it is configured with properties such as the GenAI service URL and request timeout.
*/
@Service
public class GenAiClient {
/**
* The base URL of the GenAI service obtained from configuration.
*/
@Value("${genai.url}")
String genaiUrl;
/**
* The request timeout for GenAI service requests obtained from configuration.
*/
@Value("${genai.request.timeout}")
Integer genaiTimeout;
/**
* Static instance of {@link JsonParser} to parse JSON responses from the GenAI service.
*/
static final JsonParser JSON_PARSER = JsonParserFactory.getJsonParser();
/**
* The OkHttpClient instance for making HTTP requests to the GenAI service.
*/
OkHttpClient client;
/**
* Initializes the OkHttpClient with specified timeouts during bean creation.
*/
@PostConstruct
public void init() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(genaiTimeout, TimeUnit.SECONDS)
.build();
}
/**
* Retrieves a document summary from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file for which the summary is requested.
* @return A {@link Summary} object containing the summary, tags, and model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/
public Summary getSummary(File pdfFile) throws IOException {
RequestBody requestBody = new MultipartBody
.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", pdfFile.getName(), RequestBody.create(pdfFile, MediaType.parse("application/pdf")))
.build();
Request request = new Request
.Builder()
.url(genaiUrl + "/summary")
.post(requestBody)
.build();
String response = client.newCall(request).execute().body().string();
Map<String, Object> aiResponse = JSON_PARSER.parseMap(response);
return new Summary()
.summary(aiResponse.get("summary").toString().trim())
.tags(Arrays.asList(aiResponse.get("tags").toString().split(",", -1)))
.model(aiResponse.get("model").toString());
}
/**
* Retrieves an answer to a specific question from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file containing the document related to the question.
* @param question The question for which an answer is requested.
* @return An {@link Answer} object containing the answer and the model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/ | public Answer getAnswer(File pdfFile, String question) throws IOException { | 0 | 2023-12-21 12:28:53+00:00 | 4k |
dishantharuka/layered-architecture | src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java | [
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLException {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/company\", \"root\", \"12345678\");\n }\n\n public static DBConnection getDbConnection() throws SQLException, ClassNotFoundException {\n return dbConnection == null ? dbConnection= new DBConnection() : dbConnection;\n }\n\n public Connection getConnection() {\n return connection;\n }\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "OrderDetailDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/OrderDetailDTO.java",
"snippet": "public class OrderDetailDTO implements Serializable {\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public OrderDetailDTO() {\n }\n\n public OrderDetailDTO(String itemCode, int qty, BigDecimal unitPrice) {\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailDTO{\" +\n \"itemCode='\" + itemCode + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n '}';\n }\n}"
},
{
"identifier": "OrderDetailTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/OrderDetailTM.java",
"snippet": "public class OrderDetailTM{\n private String code;\n private String description;\n private int qty;\n private BigDecimal unitPrice;\n private BigDecimal total;\n\n public OrderDetailTM() {\n }\n\n public OrderDetailTM(String code, String description, int qty, BigDecimal unitPrice, BigDecimal total) {\n this.code = code;\n this.description = description;\n this.qty = qty;\n this.unitPrice = unitPrice;\n this.total = total;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public BigDecimal getTotal() {\n return total;\n }\n\n public void setTotal(BigDecimal total) {\n this.total = total;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n \", total=\" + total +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.model.OrderDetailDTO;
import com.example.layeredarchitecture.view.tdm.OrderDetailTM;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 2,573 | package com.example.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId;
public void initialize() throws SQLException, ClassNotFoundException {
tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty"));
tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total"));
TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5);
lastCol.setCellValueFactory(param -> {
Button btnDelete = new Button("Delete");
btnDelete.setOnAction(event -> {
tblOrderDetails.getItems().remove(param.getValue());
tblOrderDetails.getSelectionModel().clearSelection();
calculateTotal();
enableOrDisablePlaceOrderButton();
});
return new ReadOnlyObjectWrapper<>(btnDelete);
});
orderId = generateNewOrderId();
lblId.setText("Order ID: " + orderId);
lblDate.setText(LocalDate.now().toString());
btnPlaceOrder.setDisable(true);
txtCustomerName.setFocusTraversable(false);
txtCustomerName.setEditable(false);
txtDescription.setFocusTraversable(false);
txtDescription.setEditable(false);
txtUnitPrice.setFocusTraversable(false);
txtUnitPrice.setEditable(false);
txtQtyOnHand.setFocusTraversable(false);
txtQtyOnHand.setEditable(false);
txtQty.setOnAction(event -> btnSave.fire());
txtQty.setEditable(false);
btnSave.setDisable(true);
cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
enableOrDisablePlaceOrderButton();
if (newValue != null) {
try {
/*Search Customer*/
Connection connection = DBConnection.getDbConnection().getConnection();
try {
if (!existCustomer(newValue + "")) {
// "There is no such customer associated with the id " + id
new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show();
}
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?");
pstm.setString(1, newValue + "");
ResultSet rst = pstm.executeQuery();
rst.next();
CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address"));
txtCustomerName.setText(customerDTO.getName());
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
txtCustomerName.clear();
}
});
cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> {
txtQty.setEditable(newItemCode != null);
btnSave.setDisable(newItemCode == null);
if (newItemCode != null) {
/*Find Item*/
try {
if (!existItem(newItemCode + "")) {
// throw new NotFoundException("There is no such item associated with the id " + code);
}
Connection connection = DBConnection.getDbConnection().getConnection();
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?");
pstm.setString(1, newItemCode + "");
ResultSet rst = pstm.executeQuery();
rst.next(); | package com.example.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId;
public void initialize() throws SQLException, ClassNotFoundException {
tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty"));
tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total"));
TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5);
lastCol.setCellValueFactory(param -> {
Button btnDelete = new Button("Delete");
btnDelete.setOnAction(event -> {
tblOrderDetails.getItems().remove(param.getValue());
tblOrderDetails.getSelectionModel().clearSelection();
calculateTotal();
enableOrDisablePlaceOrderButton();
});
return new ReadOnlyObjectWrapper<>(btnDelete);
});
orderId = generateNewOrderId();
lblId.setText("Order ID: " + orderId);
lblDate.setText(LocalDate.now().toString());
btnPlaceOrder.setDisable(true);
txtCustomerName.setFocusTraversable(false);
txtCustomerName.setEditable(false);
txtDescription.setFocusTraversable(false);
txtDescription.setEditable(false);
txtUnitPrice.setFocusTraversable(false);
txtUnitPrice.setEditable(false);
txtQtyOnHand.setFocusTraversable(false);
txtQtyOnHand.setEditable(false);
txtQty.setOnAction(event -> btnSave.fire());
txtQty.setEditable(false);
btnSave.setDisable(true);
cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
enableOrDisablePlaceOrderButton();
if (newValue != null) {
try {
/*Search Customer*/
Connection connection = DBConnection.getDbConnection().getConnection();
try {
if (!existCustomer(newValue + "")) {
// "There is no such customer associated with the id " + id
new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show();
}
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?");
pstm.setString(1, newValue + "");
ResultSet rst = pstm.executeQuery();
rst.next();
CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address"));
txtCustomerName.setText(customerDTO.getName());
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
txtCustomerName.clear();
}
});
cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> {
txtQty.setEditable(newItemCode != null);
btnSave.setDisable(newItemCode == null);
if (newItemCode != null) {
/*Find Item*/
try {
if (!existItem(newItemCode + "")) {
// throw new NotFoundException("There is no such item associated with the id " + code);
}
Connection connection = DBConnection.getDbConnection().getConnection();
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?");
pstm.setString(1, newItemCode + "");
ResultSet rst = pstm.executeQuery();
rst.next(); | ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); | 2 | 2023-12-16 04:23:56+00:00 | 4k |
drSolutions-OpenSource/Cotacao_Moedas_Estrangeiras | src/cotacao/Cotacao.java | [
{
"identifier": "ConverterJsonString",
"path": "src/classes/ConverterJsonString.java",
"snippet": "public class ConverterJsonString {\n /**\n * Converter um JSON recebido via webservice em uma String\n *\n * @param buffereReader sendo o JSON recebido do webservice\n * @return uma Srting onde ocorreu a conversรฃo do JSON\n * @throws IOException erro caso ocorra uma falha na conversรฃo\n */\n public static String converteJsonEmString(BufferedReader buffereReader) throws IOException {\n String resposta, jsonEmString = \"\";\n while ((resposta = buffereReader.readLine()) != null) {\n jsonEmString += resposta;\n }\n return jsonEmString;\n }\n}"
},
{
"identifier": "Moeda",
"path": "src/classes/Moeda.java",
"snippet": "public class Moeda {\n String code;\n String codein;\n String name;\n String high;\n String low;\n String varBid;\n String pctChange;\n String bid;\n String ask;\n String timestamp;\n String create_date;\n\n public Moeda() {\n }\n\n public Moeda(String code, String codein, String name, String high, String low, String varBid, String pctChange,\n String bid, String ask, String timestamp, String create_date) {\n this.code = code;\n this.codein = codein;\n this.name = name;\n this.high = high;\n this.low = low;\n this.varBid = varBid;\n this.pctChange = pctChange;\n this.bid = bid;\n this.ask = ask;\n this.timestamp = timestamp;\n this.create_date = create_date;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getCodein() {\n return codein;\n }\n\n public void setCodein(String codein) {\n this.codein = codein;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getHigh() {\n return high;\n }\n\n public void setHigh(String high) {\n this.high = high;\n }\n\n public String getLow() {\n return low;\n }\n\n public void setLow(String low) {\n this.low = low;\n }\n\n public String getVarBid() {\n return varBid;\n }\n\n public void setVarBid(String varBid) {\n this.varBid = varBid;\n }\n\n public String getPctChange() {\n return pctChange;\n }\n\n public void setPctChange(String pctChange) {\n this.pctChange = pctChange;\n }\n\n public String getBid() {\n return bid;\n }\n\n public void setBid(String bid) {\n this.bid = bid;\n }\n\n public String getAsk() {\n return ask;\n }\n\n public void setAsk(String ask) {\n this.ask = ask;\n }\n\n public String getTimestamp() {\n return timestamp;\n }\n\n\n public void setTimestamp(String timestamp) {\n this.timestamp = timestamp;\n }\n\n public String getCreate_date() {\n return create_date;\n }\n\n public void setCreate_date(String create_date) {\n this.create_date = create_date;\n }\n\n @Override\n public String toString() {\n return \"classes.Moeda{\" +\n \"code='\" + code + '\\'' +\n \", codein='\" + codein + '\\'' +\n \", name='\" + name + '\\'' +\n \", high='\" + high + '\\'' +\n \", low='\" + low + '\\'' +\n \", varBid='\" + varBid + '\\'' +\n \", pctChange='\" + pctChange + '\\'' +\n \", bid='\" + bid + '\\'' +\n \", ask='\" + ask + '\\'' +\n \", timestamp='\" + timestamp + '\\'' +\n \", create_date='\" + create_date + '\\'' +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Moeda moeda = (Moeda) o;\n return Objects.equals(code, moeda.code) && Objects.equals(codein, moeda.codein) &&\n Objects.equals(name, moeda.name) && Objects.equals(high, moeda.high) &&\n Objects.equals(low, moeda.low) && Objects.equals(varBid, moeda.varBid) &&\n Objects.equals(pctChange, moeda.pctChange) && Objects.equals(bid, moeda.bid) &&\n Objects.equals(ask, moeda.ask) && Objects.equals(timestamp, moeda.timestamp) &&\n Objects.equals(create_date, moeda.create_date);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(code, codein, name, high, low, varBid, pctChange, bid, ask, timestamp, create_date);\n }\n\n /**\n * Devolver a cotaรงรฃo da moeda formatada em 999,9999\n *\n * @return sendo a contaรงรฃo da moeda formatada\n */\n public String getCotacaoFormatada() {\n DecimalFormat df = new DecimalFormat(\"##0.0000\");\n BigDecimal valor = new BigDecimal(this.getAsk());\n return df.format(valor);\n }\n\n /**\n * Retornar a data formatada em dd/MM/yyyy HH:mm:ss\n *\n * @return sendo a data formatada, ou null caso ocorra um erro na conversรฃo\n */\n public String getDataCotacaoFormatada() {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd hh:mm:ss\");\n SimpleDateFormat dateFormatExibicao = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\");\n Date dataCotacao = null;\n\n try {\n dataCotacao = dateFormat.parse(this.getCreate_date());\n } catch (ParseException e) {\n e.printStackTrace();\n return null;\n }\n\n return dateFormatExibicao.format(dataCotacao);\n }\n}"
}
] | import classes.ConverterJsonString;
import classes.Moeda;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; | 1,795 | package cotacao;
/**
* Obter a contaรงรฃo atual de moedas estrangeiras atravรฉs do webservice: https://economia.awesomeapi.com.br/last/USD-BRL
* As seguintes cotaรงรตes estรฃo disponรญveis:
* - Dรณlar Americano Comercial (USD-BRL)
* - Dรณlar Americano Turismo (USD-BRLT)
* - Euro (EUR-BRL)
* - Franco Suรญรงo (CHF-BRL)
* - Libra Esterlina (GBP-BRL)
* - Peso Chileno (CLP-BRL)
*
* @author Diego Mendes Rodrigues
*/
public class Cotacao {
static String webService = "https://economia.awesomeapi.com.br/last/";
static int codigoSucesso = 200;
/**
* Realiza a cotaรงรฃo atual de uma moeda estrangeira
*
* @param moeda sendo a moeda em que a cotaรงรฃo serรก realizada (USD, USDT, EUR, CHF, GBP ou CLP)
* @return a cotaรงรฃo atual da moeda como umo instรขncia da classe Maeda
*/ | package cotacao;
/**
* Obter a contaรงรฃo atual de moedas estrangeiras atravรฉs do webservice: https://economia.awesomeapi.com.br/last/USD-BRL
* As seguintes cotaรงรตes estรฃo disponรญveis:
* - Dรณlar Americano Comercial (USD-BRL)
* - Dรณlar Americano Turismo (USD-BRLT)
* - Euro (EUR-BRL)
* - Franco Suรญรงo (CHF-BRL)
* - Libra Esterlina (GBP-BRL)
* - Peso Chileno (CLP-BRL)
*
* @author Diego Mendes Rodrigues
*/
public class Cotacao {
static String webService = "https://economia.awesomeapi.com.br/last/";
static int codigoSucesso = 200;
/**
* Realiza a cotaรงรฃo atual de uma moeda estrangeira
*
* @param moeda sendo a moeda em que a cotaรงรฃo serรก realizada (USD, USDT, EUR, CHF, GBP ou CLP)
* @return a cotaรงรฃo atual da moeda como umo instรขncia da classe Maeda
*/ | public Moeda realizarCotacao(String moeda) { | 1 | 2023-12-16 14:27:51+00:00 | 4k |
123yyh123/xiaofanshu | xfs-third-server/src/main/java/com/yyh/xfs/third/sevice/impl/AliyunOssServiceImpl.java | [
{
"identifier": "Result",
"path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java",
"snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n private T data;\n}"
},
{
"identifier": "ExceptionMsgEnum",
"path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/myEnum/ExceptionMsgEnum.java",
"snippet": "@Getter\n@ToString\npublic enum ExceptionMsgEnum {\n /**\n * ไธๅกๅผๅธธ\n */\n NOT_LOGIN(StatusCode.NOT_LOGIN,\"ๆช็ปๅฝ\"),\n TOKEN_EXPIRED(StatusCode.TOKEN_EXPIRED,\"็ปๅฝ็ถๆ่ฟๆ\"),\n TOKEN_INVALID(StatusCode.TOKEN_INVALID,\"็ปๅฝ็ถๆๆ ๆ\"),\n ACCOUNT_OPERATION_ERROR(StatusCode.ACCOUNT_OPERATION_ERROR,\"่ดฆๅทๆไฝๅผๅธธ\"),\n ACCOUNT_OTHER_LOGIN(StatusCode.ACCOUNT_OTHER_LOGIN,\"่ดฆๅทๅจๅ
ถไป่ฎพๅค็ปๅฝ\"),\n PASSWORD_ERROR(StatusCode.PASSWORD_ERROR,\"ๅฏ็ ้่ฏฏ\"),\n SMS_CODE_ERROR(StatusCode.SMS_CODE_ERROR,\"้ช่ฏ็ ้่ฏฏ\"),\n PHONE_NUMBER_EXIST(StatusCode.PHONE_NUMBER_EXIST,\"ๆๆบๅทๅทฒ็ปๅฎ\"),\n PHONE_NUMBER_NOT_REGISTER(StatusCode.PHONE_NUMBER_NOT_REGISTER,\"ๆๆบๅทๆชๆณจๅ\"),\n LOGIN_TYPE_ERROR(StatusCode.LOGIN_TYPE_ERROR,\"็ปๅฝ็ฑปๅ้่ฏฏ\"),\n OPEN_ID_NULL(StatusCode.OPEN_ID_NULL,\"่ดฆๅทopenIdไธบ็ฉบ\"),\n ACCOUNT_EXCEPTION(StatusCode.ACCOUNT_EXCEPTION,\"่ดฆๅทๅผๅธธ\"),\n PARAMETER_ERROR(StatusCode.PARAMETER_ERROR,\"ๅๆฐ้่ฏฏ\"),\n FILE_SIZE_TOO_LARGE(StatusCode.FILE_SIZE_TOO_LARGE,\"ๆไปถ่ฟๅคง\"),\n FILE_NOT_NULL(StatusCode.FILE_NOT_NULL,\"ๆไปถไธ่ฝไธบ็ฉบ\"),\n SMS_CODE_SEND_FREQUENTLY(StatusCode.SMS_CODE_SEND_FREQUENTLY,\"็ญไฟกๅ้้ข็น,่ฏท็จๅๅ่ฏ\"),\n /**\n * ็ณป็ปๅผๅธธ\n */\n ALIYUN_SMS_SEND_ERROR(StatusCode.ALIYUN_SMS_SEND_ERROR,\"็ญไฟกๅ้ๅคฑ่ดฅ\"),\n ALIYUN_SMS_INIT_ERROR(StatusCode.ALIYUN_SMS_INIT_ERROR,\"็ญไฟกๆๅกๅๅงๅๅผๅธธ\"),\n ALIYUN_OSS_INIT_ERROR(StatusCode.ALIYUN_OSS_INIT_ERROR,\"OSSๆๅกๅๅงๅๅผๅธธ\"),\n REDIS_ERROR(StatusCode.REDIS_ERROR,\"redisๆไฝๅผๅธธ\"),\n DB_ERROR(StatusCode.DB_ERROR,\"ๆฐๆฎๅบๆไฝๅผๅธธ\"),\n SERVER_ERROR(StatusCode.SERVER_ERROR,\"ๆๅกๅจๅผๅธธ\");\n private Integer code;\n private String msg;\n\n ExceptionMsgEnum(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n}"
},
{
"identifier": "ResultUtil",
"path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/utils/ResultUtil.java",
"snippet": "public class ResultUtil {\n public static final String SUCCESS = \"success\";\n public static final String ERROR = \"error\";\n\n public static <T> Result<T> successGet(T data) {\n return new Result<>(StatusCode.GET_SUCCESS, SUCCESS, data);\n }\n public static <T> Result<T> successGet(String msg, T data) {\n return new Result<>(StatusCode.GET_SUCCESS, msg, data);\n }\n public static <T> Result<T> successPost(T data) {\n return new Result<>(StatusCode.POST_SUCCESS, SUCCESS, data);\n }\n public static <T> Result<T> successPost(String msg, T data) {\n return new Result<>(StatusCode.POST_SUCCESS, msg, data);\n }\n\n public static <T> Result<T> successPut(T data) {\n return new Result<>(StatusCode.PUT_SUCCESS, SUCCESS, data);\n }\n public static <T> Result<T> successPut(String msg, T data) {\n return new Result<>(StatusCode.PUT_SUCCESS, msg, data);\n }\n public static <T> Result<T> successDelete(T data) {\n return new Result<>(StatusCode.DELETE_SUCCESS, SUCCESS, data);\n }\n public static <T> Result<T> successDelete(String msg, T data) {\n return new Result<>(StatusCode.DELETE_SUCCESS, msg, data);\n }\n public static <T> Result<T> errorGet(String msg){\n return new Result<>(StatusCode.GET_ERROR, msg, null);\n }\n public static <T> Result<T> errorGet(T data) {\n return new Result<>(StatusCode.GET_ERROR, ERROR, data);\n }\n\n public static <T> Result<T> errorPost(String msg){\n return new Result<>(StatusCode.POST_ERROR, msg, null);\n }\n public static <T> Result<T> errorPost(T data) {\n return new Result<>(StatusCode.POST_ERROR, ERROR, data);\n }\n\n public static <T> Result<T> errorPut(String msg){\n return new Result<>(StatusCode.PUT_ERROR, msg, null);\n }\n public static <T> Result<T> errorPut(T data) {\n return new Result<>(StatusCode.PUT_ERROR, ERROR, data);\n }\n\n public static <T> Result<T> errorDelete(String msg){\n return new Result<>(StatusCode.DELETE_ERROR, msg, null);\n }\n public static <T> Result<T> errorDelete(T data) {\n return new Result<>(StatusCode.DELETE_ERROR, ERROR, data);\n }\n\n\n}"
},
{
"identifier": "BusinessException",
"path": "xfs-common/common-web/src/main/java/com/yyh/xfs/common/web/exception/BusinessException.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class BusinessException extends RuntimeException{\n private ExceptionMsgEnum exceptionMsgEnum;\n public BusinessException(ExceptionMsgEnum exceptionMsgEnum) {\n this.exceptionMsgEnum=exceptionMsgEnum;\n }\n public BusinessException(ExceptionMsgEnum exceptionMsgEnum,Throwable e){\n super(e);\n this.exceptionMsgEnum=exceptionMsgEnum;\n }\n\n}"
},
{
"identifier": "SystemException",
"path": "xfs-common/common-web/src/main/java/com/yyh/xfs/common/web/exception/SystemException.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class SystemException extends RuntimeException{\n private ExceptionMsgEnum exceptionMsgEnum;\n public SystemException(ExceptionMsgEnum exceptionMsgEnum) {\n this.exceptionMsgEnum=exceptionMsgEnum;\n }\n public SystemException(ExceptionMsgEnum exceptionMsgEnum,Throwable e){\n super(e);\n this.exceptionMsgEnum=exceptionMsgEnum;\n }\n}"
},
{
"identifier": "AliyunOss",
"path": "xfs-third-server/src/main/java/com/yyh/xfs/third/config/AliyunOss.java",
"snippet": "@Configuration\n@Slf4j\n@Getter\npublic class AliyunOss {\n @Value(\"${aliyun.oss.endpoint}\")\n private String endpoint;\n @Value(\"${aliyun.oss.accessKeyId}\")\n private String accessKeyId;\n @Value(\"${aliyun.oss.accessKeySecret}\")\n private String accessKeySecret;\n @Value(\"${aliyun.oss.bucketName}\")\n private String bucketName;\n @Value(\"${spring.servlet.multipart.max-file-size}\")\n private String maxFileSize;\n @Value(\"${spring.servlet.multipart.max-request-size}\")\n private String maxRequestSize;\n}"
},
{
"identifier": "AliyunOssService",
"path": "xfs-third-server/src/main/java/com/yyh/xfs/third/sevice/AliyunOssService.java",
"snippet": "public interface AliyunOssService {\n Result<String> uploadImg(MultipartFile file);\n\n Result<List<String>> uploadImgs(MultipartFile[] file);\n\n Result<String> uploadAudio(MultipartFile file);\n}"
}
] | import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yyh.xfs.common.domain.Result;
import com.yyh.xfs.common.myEnum.ExceptionMsgEnum;
import com.yyh.xfs.common.utils.ResultUtil;
import com.yyh.xfs.common.web.exception.BusinessException;
import com.yyh.xfs.common.web.exception.SystemException;
import com.yyh.xfs.third.config.AliyunOss;
import com.yyh.xfs.third.sevice.AliyunOssService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID; | 2,009 | package com.yyh.xfs.third.sevice.impl;
/**
* @author yyh
* @date 2023-12-21
*/
@Service
public class AliyunOssServiceImpl implements AliyunOssService {
private final AliyunOss aliyunOss;
public AliyunOssServiceImpl(AliyunOss aliyunOss) {
this.aliyunOss = aliyunOss;
}
@Override
public Result<String> uploadImg(MultipartFile file) {
OSS ossClient = getOssClient(file);
try {
String s = uploadAndCreateUrl(ossClient, file,".png");
return ResultUtil.successPost(s);
} catch (Exception e) { | package com.yyh.xfs.third.sevice.impl;
/**
* @author yyh
* @date 2023-12-21
*/
@Service
public class AliyunOssServiceImpl implements AliyunOssService {
private final AliyunOss aliyunOss;
public AliyunOssServiceImpl(AliyunOss aliyunOss) {
this.aliyunOss = aliyunOss;
}
@Override
public Result<String> uploadImg(MultipartFile file) {
OSS ossClient = getOssClient(file);
try {
String s = uploadAndCreateUrl(ossClient, file,".png");
return ResultUtil.successPost(s);
} catch (Exception e) { | throw new SystemException(ExceptionMsgEnum.ALIYUN_OSS_INIT_ERROR, e); | 1 | 2023-12-15 08:13:42+00:00 | 4k |
catools2/athena | athena-api-boot/src/test/java/org/catools/athena/rest/core/mapper/AthenaCoreMapperIT.java | [
{
"identifier": "EnvironmentDto",
"path": "athena-core/src/main/java/org/catools/athena/core/model/EnvironmentDto.java",
"snippet": "@Data\n@Accessors(chain = true)\n@NoArgsConstructor\npublic class EnvironmentDto {\n private Long id;\n\n @NotBlank\n @Size(max = 5)\n private String code;\n\n @NotBlank\n @Size(max = 50)\n private String name;\n\n @NotBlank\n @Size(min = 1, max = 5)\n private String projectCode;\n}"
},
{
"identifier": "ProjectDto",
"path": "athena-core/src/main/java/org/catools/athena/core/model/ProjectDto.java",
"snippet": "@Data\n@Accessors(chain = true)\n@NoArgsConstructor\npublic class ProjectDto {\n\n private Long id;\n\n @NotBlank\n @Size(max = 5)\n private String code;\n\n @NotBlank\n @Size(max = 50)\n private String name;\n}"
},
{
"identifier": "UserDto",
"path": "athena-core/src/main/java/org/catools/athena/core/model/UserDto.java",
"snippet": "@Data\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class UserDto implements Serializable {\n private Long id;\n\n @NotBlank\n @Size(max = 300)\n private String name;\n}"
},
{
"identifier": "AthenaBaseTest",
"path": "athena-api-boot/src/test/java/org/catools/athena/rest/AthenaBaseTest.java",
"snippet": "@ExtendWith(SpringExtension.class)\n@ContextConfiguration(classes = AthenaBaseTest.SpringTestConfig.class)\n@TestInstance(TestInstance.Lifecycle.PER_CLASS)\npublic class AthenaBaseTest {\n\n @Configuration\n @ComponentScan({\"org.catools.athena.rest\"})\n @PropertySource(\"classpath:application.properties\")\n public static class SpringTestConfig {\n }\n\n protected static void verifyMetadata(PipelineScenarioExecution execution, MetadataDto expected) {\n PipelineExecutionMetadata actual = getMetadataDto(execution.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n protected static void verifyMetadata(PipelineScenarioExecutionDto execution, PipelineExecutionMetadata expected) {\n MetadataDto actual = getMetadataDto(execution.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n protected static void verifyMetadata(PipelineExecutionDto execution, PipelineExecutionMetadata expected) {\n MetadataDto actual = getMetadataDto(execution.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n protected static void verifyMetadata(PipelineExecution execution, MetadataDto expected) {\n PipelineExecutionMetadata actual = getMetadataDto(execution.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n protected static void verifyMetadata(Pipeline pipeline, MetadataDto expected) {\n PipelineMetadata actual = getMetadataDto(pipeline.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n protected static void verifyMetadata(PipelineDto pipeline, PipelineMetadata expected) {\n MetadataDto actual = getMetadataDto(pipeline.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n protected static void verifyMetadata(PipelineDto pipeline, MetadataDto expected) {\n MetadataDto actual = getMetadataDto(pipeline.getMetadata(), m -> Objects.equals(m.getName(), expected.getName()));\n assertThat(actual.getName(), equalTo(expected.getName()));\n assertThat(actual.getValue(), equalTo(expected.getValue()));\n }\n\n @NotNull\n private static <T> T getMetadataDto(Collection<T> actuals, Predicate<? super T> predicate) {\n T actual = actuals.stream().filter(predicate).findFirst().orElse(null);\n assertThat(actual, notNullValue());\n return actual;\n }\n}"
},
{
"identifier": "AthenaCoreBuilder",
"path": "athena-api-boot/src/test/java/org/catools/athena/rest/core/builder/AthenaCoreBuilder.java",
"snippet": "@UtilityClass\npublic class AthenaCoreBuilder {\n public static UserDto buildUserDto() {\n return Instancio.of(UserDto.class)\n .ignore(field(UserDto::getId))\n .create();\n }\n\n public static User buildUser(UserDto userDto) {\n return new User()\n .setId(userDto.getId())\n .setName(userDto.getName());\n }\n\n public static ProjectDto buildProjectDto() {\n return Instancio.of(ProjectDto.class)\n .ignore(field(ProjectDto::getId))\n .generate(field(ProjectDto::getCode), gen -> gen.string().length(1, 5))\n .create();\n }\n\n public static Project buildProject(ProjectDto projectDto) {\n return new Project()\n .setId(projectDto.getId())\n .setCode(projectDto.getCode())\n .setName(projectDto.getName());\n }\n\n public static EnvironmentDto buildEnvironmentDto(ProjectDto project) {\n return Instancio.of(EnvironmentDto.class)\n .ignore(field(EnvironmentDto::getId))\n .generate(field(EnvironmentDto::getCode), gen -> gen.string().length(1, 5))\n .set(field(EnvironmentDto::getProjectCode), project.getCode())\n .create();\n }\n\n public static Environment buildEnvironment(EnvironmentDto environmentDto, Project project) {\n return new Environment()\n .setId(environmentDto.getId())\n .setName(environmentDto.getName())\n .setCode(environmentDto.getCode())\n .setProject(project);\n }\n}"
},
{
"identifier": "Environment",
"path": "athena-api-boot/src/main/java/org/catools/athena/rest/core/entity/Environment.java",
"snippet": "@Entity\n@Table(name = \"environment\", schema = ATHENA_SCHEMA)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Accessors(chain = true)\npublic class Environment implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(updatable = false, nullable = false)\n private Long id;\n\n @NotBlank\n @Size(max = 10)\n @Column(name = \"code\", length = 10, unique = true, nullable = false)\n private String code;\n\n @NotBlank\n @Size(max = 100)\n @Column(name = \"name\", length = 100)\n private String name;\n\n @NotNull\n @ManyToOne(\n cascade = CascadeType.MERGE,\n targetEntity = Project.class,\n fetch = FetchType.EAGER)\n @JoinColumn(name = \"project_code\",\n referencedColumnName = \"id\",\n nullable = false,\n foreignKey = @ForeignKey(name = \"FK_ENVIRONMENT_PROJECT\"))\n private Project project;\n}"
},
{
"identifier": "Project",
"path": "athena-api-boot/src/main/java/org/catools/athena/rest/core/entity/Project.java",
"snippet": "@Entity\n@Table(name = \"project\", schema = ATHENA_SCHEMA)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Accessors(chain = true)\npublic class Project implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(updatable = false, nullable = false)\n private Long id;\n\n @NotBlank\n @Size(max = 5)\n @Column(name = \"code\", length = 5, unique = true, updatable = false, nullable = false)\n private String code;\n\n @NotBlank\n @Size(max = 50)\n @Column(name = \"name\", length = 50, unique = true, nullable = false)\n private String name;\n}"
},
{
"identifier": "User",
"path": "athena-api-boot/src/main/java/org/catools/athena/rest/core/entity/User.java",
"snippet": "@Entity\n@Table(name = \"user\", schema = ATHENA_SCHEMA)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Accessors(chain = true)\npublic class User implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(updatable = false, nullable = false)\n private Long id;\n\n @NotBlank\n @Size(max = 300)\n @Column(name = \"name\", length = 300, unique = true, nullable = false)\n private String name;\n}"
},
{
"identifier": "AthenaCoreService",
"path": "athena-api-boot/src/main/java/org/catools/athena/rest/core/service/AthenaCoreService.java",
"snippet": "public interface AthenaCoreService {\n\n /**\n * Returns a list of all available projects.\n */\n Set<ProjectDto> getProjects();\n\n /**\n * Get project by code\n */\n Optional<ProjectDto> getProjectByCode(String code);\n\n /**\n * Get project by code\n */\n Optional<ProjectDto> getProjectByName(String code);\n\n /**\n * Get project by id\n */\n Optional<ProjectDto> getProjectById(Long id);\n\n /**\n * Save project\n */\n ProjectDto saveProject(ProjectDto project);\n\n /**\n * Returns a list of all available environments.\n */\n Set<EnvironmentDto> getEnvironments();\n\n /**\n * Get environment by code\n */\n Optional<EnvironmentDto> getEnvironmentByCode(String code);\n\n /**\n * Get environment by id\n */\n Optional<EnvironmentDto> getEnvironmentById(Long id);\n\n /**\n * Save environment\n */\n EnvironmentDto saveEnvironment(EnvironmentDto environmentDto);\n\n /**\n * Returns a list of all available users.\n */\n Set<UserDto> getUsers();\n\n /**\n * Get user by name\n */\n Optional<UserDto> getUserByName(String name);\n\n /**\n * Get user by id\n */\n Optional<UserDto> getUserById(Long id);\n\n /**\n * Save user and return user id\n */\n UserDto saveUser(UserDto userDto);\n\n}"
}
] | import org.catools.athena.core.model.EnvironmentDto;
import org.catools.athena.core.model.ProjectDto;
import org.catools.athena.core.model.UserDto;
import org.catools.athena.rest.AthenaBaseTest;
import org.catools.athena.rest.core.builder.AthenaCoreBuilder;
import org.catools.athena.rest.core.entity.Environment;
import org.catools.athena.rest.core.entity.Project;
import org.catools.athena.rest.core.entity.User;
import org.catools.athena.rest.core.service.AthenaCoreService;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo; | 2,559 | package org.catools.athena.rest.core.mapper;
public class AthenaCoreMapperIT extends AthenaBaseTest {
private static ProjectDto PROJECT_DTO;
private static Project PROJECT; | package org.catools.athena.rest.core.mapper;
public class AthenaCoreMapperIT extends AthenaBaseTest {
private static ProjectDto PROJECT_DTO;
private static Project PROJECT; | private static EnvironmentDto ENVIRONMENT_DTO; | 0 | 2023-12-16 22:30:49+00:00 | 4k |
premiering/permad-game | src/main/java/club/premiering/permad/format/v2/V2MapDataSkapConverter.java | [
{
"identifier": "EntityLavaSpike",
"path": "src/main/java/club/premiering/permad/entity/spawners/EntityLavaSpike.java",
"snippet": "public class EntityLavaSpike extends SpawnerEntity {\n public EntityLavaSpike() {\n this.setSolid(false);\n this.setCollideWithSolids(false);\n this.setCanBeOutsideWorld(false);\n }\n\n @Override\n public void onAddedToWorld() {\n super.onAddedToWorld();\n\n this.velocity = this.getBounceVelocity().clone();\n this.velocity.x = Math.random() > 0.5 ? -this.velocity.x : this.velocity.x;\n this.velocity.y = Math.random() > 0.5 ? -this.velocity.y : this.velocity.y;\n }\n\n @Override\n public void doTick() {\n this.pos.x += this.velocity.x;\n this.pos.y += this.velocity.y;\n\n super.doTick();\n }\n\n @Override\n public void onCollision(RigidEntity entity, AABBCollisionInfo colInfo) {\n if (entity instanceof EntityPlayer player) {\n player.killPlayer(colInfo);\n }\n // TODO: 9/10/2023 Bouncing off of obstacles is broken because of the weird physics drop-in\n /*else if (entity.isSolid() && entity instanceof EntityObstacle) {\n this.bounceOffCollision(colInfo, this.getBounceVelocity());\n }*/\n }\n}"
},
{
"identifier": "Vector2",
"path": "src/main/java/club/premiering/permad/math/Vector2.java",
"snippet": "public class Vector2 implements Cloneable {\n public float x, y;\n\n public Vector2(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public Vector2(double x, double y) {\n this.x = (float) x;\n this.y = (float) y;\n }\n\n public Vector2() {\n this(0, 0);\n }\n\n public float dist(Vector2 point) {\n return Math.abs(this.x - point.x) + Math.abs(this.y - point.y);\n }\n\n public Vector2 distVec(Vector2 b) {\n return new Vector2(b.x - this.x, b.y - this.y);\n }\n\n public Vector2 rotate(float angle, Vector2 rotationAxis) {\n float cos = (float)Math.cos(angle);\n float sin = (float)Math.sin(angle);\n\n this.sub(rotationAxis);\n\n float newX = this.x * cos - this.y * sin;\n float newY = this.x * sin + this.y * cos;\n\n this.x = newX;\n this.y = newY;\n\n this.add(rotationAxis);\n return this;\n }\n \n public Vector2 set(float x, float y) {\n this.x = x;\n this.y = y;\n return this;\n }\n\n public Vector2 add(Vector2 vec) {\n return this.add(vec.x, vec.y);\n }\n\n public Vector2 add(float x, float y) {\n this.x += x;\n this.y += y;\n return this;\n }\n\n public Vector2 sub(Vector2 v) {\n x -= v.x;\n y -= v.y;\n return this;\n }\n\n public Vector2 sub(float x, float y) {\n this.x -= x;\n this.y -= y;\n return this;\n }\n\n public Vector2 mul(float x) {\n this.mul(x, x);\n return this;\n }\n\n public Vector2 mul(float x, float y) {\n this.x *= x;\n this.y *= y;\n return this;\n }\n\n public Vector2 divide(float x) {\n return this.divide(x, x);\n }\n\n public Vector2 divide(float x, float y) {\n this.x /= x;\n this.y /= y;\n return this;\n }\n\n public Vector2 lerpTo(Vector2 destination, float o) {\n o = MathUtil.clamp(o, 0, 1);//Pass by value with primitives, so we're fine (at least I think)\n this.x += (destination.x - this.x) * o;\n this.y += (destination.y - this.y) * o;\n return this;\n }\n\n @Override\n public String toString() {\n return \"Vector2{\" +\n \"x=\" + x +\n \", y=\" + y +\n '}';\n }\n\n @Override\n public Vector2 clone() {\n try {\n Vector2 clone = (Vector2) super.clone();\n clone.x = this.x;\n clone.y = this.y;\n return clone;\n } catch (CloneNotSupportedException e) {\n throw new AssertionError();\n }\n }\n}"
},
{
"identifier": "Vector4",
"path": "src/main/java/club/premiering/permad/math/Vector4.java",
"snippet": "public class Vector4 implements Cloneable {\n public float x, y, z, w;\n\n public Vector4(float x, float y, float z, float w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n\n public Vector4() {\n this(0, 0, 0, 0);\n }\n\n @Override\n public String toString() {\n return \"Vector4{\" +\n \"x=\" + x +\n \", y=\" + y +\n \", z=\" + z +\n \", w=\" + w +\n '}';\n }\n\n @Override\n public Vector4 clone() {\n try {\n Vector4 clone = (Vector4) super.clone();\n clone.x = this.x;\n clone.y = this.y;\n clone.z = this.z;\n clone.w = this.w;\n return clone;\n } catch (CloneNotSupportedException e) {\n throw new AssertionError();\n }\n }\n}"
}
] | import club.premiering.permad.entity.*;
import club.premiering.permad.entity.spawners.EntityLavaSpike;
import club.premiering.permad.math.Vector2;
import club.premiering.permad.math.Vector4;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.awt.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Objects; | 1,916 | package club.premiering.permad.format.v2;
public class V2MapDataSkapConverter extends V2MapData {
//If set to false, then all obstacle colors won't work (does not affect blocks!)
private static final boolean OBSTACLES_USE_CUSTOM_COLOR = false;
@Override
public void loadMapData(byte[] mapData) {
super.loadMapData(this.convertMapFromSkap(new String(mapData)).getBytes(StandardCharsets.UTF_8));
}
public String convertMapFromSkap(String skapMap) {
JsonObject json = GSON.fromJson(skapMap, JsonObject.class);
var v2Map = new V2Map();
v2Map.worlds = new ArrayList<>();
var settings = json.getAsJsonObject("settings");
v2Map.metadata.name = settings.get("name").getAsString();
v2Map.metadata.creator = settings.get("creator").getAsString();
var worlds = json.getAsJsonArray("maps");
var nameOfSpawn = settings.get("spawnArea").getAsString();
var spawnPos = readSkapVec2(settings.getAsJsonArray("spawnPosition"));
int worldIdCounter = 0;
for (int i = 0; i < worlds.size(); i++) {
var world = new V2World();
world.entities = new ArrayList<>();
world.worldId = worldIdCounter;
worldIdCounter++;
var sWorld = worlds.get(i).getAsJsonObject();
world.worldName = sWorld.get("name").getAsString();
if (world.worldName.equals(nameOfSpawn)) {
world.worldSpawn = spawnPos;
v2Map.spawnWorldId = world.worldId;
}
var worldSize = readSkapVec2(sWorld.get("size").getAsJsonArray()); | package club.premiering.permad.format.v2;
public class V2MapDataSkapConverter extends V2MapData {
//If set to false, then all obstacle colors won't work (does not affect blocks!)
private static final boolean OBSTACLES_USE_CUSTOM_COLOR = false;
@Override
public void loadMapData(byte[] mapData) {
super.loadMapData(this.convertMapFromSkap(new String(mapData)).getBytes(StandardCharsets.UTF_8));
}
public String convertMapFromSkap(String skapMap) {
JsonObject json = GSON.fromJson(skapMap, JsonObject.class);
var v2Map = new V2Map();
v2Map.worlds = new ArrayList<>();
var settings = json.getAsJsonObject("settings");
v2Map.metadata.name = settings.get("name").getAsString();
v2Map.metadata.creator = settings.get("creator").getAsString();
var worlds = json.getAsJsonArray("maps");
var nameOfSpawn = settings.get("spawnArea").getAsString();
var spawnPos = readSkapVec2(settings.getAsJsonArray("spawnPosition"));
int worldIdCounter = 0;
for (int i = 0; i < worlds.size(); i++) {
var world = new V2World();
world.entities = new ArrayList<>();
world.worldId = worldIdCounter;
worldIdCounter++;
var sWorld = worlds.get(i).getAsJsonObject();
world.worldName = sWorld.get("name").getAsString();
if (world.worldName.equals(nameOfSpawn)) {
world.worldSpawn = spawnPos;
v2Map.spawnWorldId = world.worldId;
}
var worldSize = readSkapVec2(sWorld.get("size").getAsJsonArray()); | world.worldSize = new Vector4(0, 0, worldSize.x, worldSize.y); | 2 | 2023-12-20 03:13:05+00:00 | 4k |
VRavindu/layered-architecture-Vimukthi-Ravindu | src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java | [
{
"identifier": "ItemBO",
"path": "src/main/java/com/example/layeredarchitecture/bo/ItemBO.java",
"snippet": "public interface ItemBO {\n ArrayList<ItemDTO> getAllItem() throws SQLException, ClassNotFoundException;\n\n boolean deleteItem(String code) throws SQLException, ClassNotFoundException;\n\n boolean saveItem(ItemDTO dto) throws SQLException, ClassNotFoundException;\n\n boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException;\n\n boolean existItem(String code) throws SQLException, ClassNotFoundException;\n\n String generateNewId() throws SQLException, ClassNotFoundException;\n\n ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "ItemBOimpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/ItemBOimpl.java",
"snippet": "public class ItemBOimpl implements ItemBO{\n ItemDAO itemDAO = new ItemDAOimpl();\n @Override\n public ArrayList<ItemDTO> getAllItem() throws SQLException, ClassNotFoundException {\n return itemDAO.getAll();\n }\n\n @Override\n public boolean deleteItem(String code) throws SQLException, ClassNotFoundException {\n return itemDAO.delete(code);\n }\n\n @Override\n public boolean saveItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return itemDAO.save(dto);\n }\n\n @Override\n public boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return itemDAO.update(dto);\n }\n\n @Override\n public boolean existItem(String code) throws SQLException, ClassNotFoundException {\n return itemDAO.exist(code);\n }\n\n @Override\n public String generateNewId() throws SQLException, ClassNotFoundException {\n return itemDAO.generateNewId();\n }\n\n @Override\n public ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException {\n return itemDAO.search(code);\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "ItemTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/ItemTM.java",
"snippet": "public class ItemTM {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemTM() {\n }\n\n public ItemTM(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.bo.ItemBO;
import com.example.layeredarchitecture.bo.ItemBOimpl;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.view.tdm.ItemTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList; | 1,680 | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
ItemBO itemBO = new ItemBOimpl();
public void initialize() {
tblItems.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblItems.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblItems.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qtyOnHand"));
tblItems.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
initUI();
tblItems.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
btnDelete.setDisable(newValue == null);
btnSave.setText(newValue != null ? "Update" : "Save");
btnSave.setDisable(newValue == null);
if (newValue != null) {
txtCode.setText(newValue.getCode());
txtDescription.setText(newValue.getDescription());
txtUnitPrice.setText(newValue.getUnitPrice().setScale(2).toString());
txtQtyOnHand.setText(newValue.getQtyOnHand() + "");
txtCode.setDisable(false);
txtDescription.setDisable(false);
txtUnitPrice.setDisable(false);
txtQtyOnHand.setDisable(false);
}
});
txtQtyOnHand.setOnAction(event -> btnSave.fire());
loadAllItems();
}
private void loadAllItems() {
tblItems.getItems().clear();
try {
/*Get all items*/
| package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
ItemBO itemBO = new ItemBOimpl();
public void initialize() {
tblItems.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblItems.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblItems.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qtyOnHand"));
tblItems.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
initUI();
tblItems.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
btnDelete.setDisable(newValue == null);
btnSave.setText(newValue != null ? "Update" : "Save");
btnSave.setDisable(newValue == null);
if (newValue != null) {
txtCode.setText(newValue.getCode());
txtDescription.setText(newValue.getDescription());
txtUnitPrice.setText(newValue.getUnitPrice().setScale(2).toString());
txtQtyOnHand.setText(newValue.getQtyOnHand() + "");
txtCode.setDisable(false);
txtDescription.setDisable(false);
txtUnitPrice.setDisable(false);
txtQtyOnHand.setDisable(false);
}
});
txtQtyOnHand.setOnAction(event -> btnSave.fire());
loadAllItems();
}
private void loadAllItems() {
tblItems.getItems().clear();
try {
/*Get all items*/
| ArrayList<ItemDTO> allItems = itemBO.getAllItem(); | 2 | 2023-12-16 04:19:18+00:00 | 4k |
egisac/ethicalvoting | src/main/java/net/egis/ethicalvoting/data/ProfileManager.java | [
{
"identifier": "EthicalVoting",
"path": "src/main/java/net/egis/ethicalvoting/EthicalVoting.java",
"snippet": "@Getter\npublic final class EthicalVoting extends JavaPlugin {\n\n @Getter\n private static EthicalVoting self;\n\n private StorageInterface storage;\n private ProfileManager profiles;\n private PlayerConnectionListener connectionListener;\n private VotifierVoteListener voteListener;\n private FireworkDamageListener fireworkDamageListener;\n private VotePartyHandler votePartyHandler;\n private VoteRewardHandler voteRewardHandler;\n\n @Override\n public void onEnable() {\n self = this;\n\n new InventoryAPI(this).init();\n\n saveDefaultConfig();\n pickStorageType();\n loadPluginData();\n loadFeatures();\n registerEventListeners();\n registerCommands();\n registerIntegrations();\n\n getLogger().info(\"Storage Type: \" + storage.getAdapterType());\n checkUpdates();\n\n getLogger().info(\"EthicalVoting has been successfully enabled.\");\n }\n\n @Override\n public void onDisable() {\n profiles.shutdown();\n voteRewardHandler.getVoteQueue().shutdown();\n\n getLogger().info(\"EthicalVoting has been successfully disabled.\");\n }\n\n public void registerIntegrations() {\n if (getServer().getPluginManager().getPlugin(\"PlaceholderAPI\") != null) {\n new EthicalPAPI().register();\n getLogger().info(\"PlaceholderAPI integration has been successfully enabled.\");\n } else {\n getLogger().warning(\"PlaceholderAPI integration has failed to load.\");\n }\n }\n\n /*\n Defines which database type will be used to store user data.\n Current options:\n - MySQL\n - YAML (Bukkit internal)\n */\n public void pickStorageType() {\n String storageInterface = getConfig().getString(\"database.type\");\n\n if (storageInterface == null) {\n getLogger().severe(\"Storage Interface is null. Report this to plugin developer.\");\n getServer().shutdown();\n return;\n }\n\n if (storageInterface.equalsIgnoreCase(\"mysql\")) {\n storage = new MySQLInterface();\n\n String host = getConfig().getString(\"database.host\");\n int port = getConfig().getInt(\"database.port\");\n String database = getConfig().getString(\"database.database\");\n String username = getConfig().getString(\"database.username\");\n String password = getConfig().getString(\"database.password\");\n\n if (host == null || database == null || username == null || password == null) {\n getLogger().severe(\"MySQL credentials are null. Report this to plugin developer.\");\n getServer().shutdown();\n return;\n }\n\n if (!storage.jdbcInit(\"jdbc:mysql://\" + host + \":\" + port + \"/\" + database, username, password)) {\n getLogger().severe(\"Failed to connect to MySQL database. Report this to plugin developer.\");\n getServer().shutdown();\n return;\n }\n } else {\n storage = new YamlInterface(this);\n }\n }\n\n public void registerCommands() {\n EthicalVotingCommand ethicalVotingCommand = new EthicalVotingCommand();\n getCommand(\"ethicalvoting\").setExecutor(ethicalVotingCommand);\n getCommand(\"ethicalvoting\").setTabCompleter(ethicalVotingCommand);\n VoteCommand voteCommand = new VoteCommand();\n getCommand(\"vote\").setExecutor(voteCommand);\n getCommand(\"vote\").setTabCompleter(voteCommand);\n }\n\n public void loadPluginData() {\n this.profiles = new ProfileManager(storage);\n }\n\n public void registerEventListeners() {\n this.connectionListener = new PlayerConnectionListener(this);\n this.voteListener = new VotifierVoteListener(this);\n this.fireworkDamageListener = new FireworkDamageListener();\n getServer().getPluginManager().registerEvents(connectionListener, this);\n getServer().getPluginManager().registerEvents(voteListener, this);\n getServer().getPluginManager().registerEvents(fireworkDamageListener, this);\n }\n\n public void loadFeatures() {\n votePartyHandler = new VotePartyHandler(this);\n voteRewardHandler = new VoteRewardHandler(this);\n }\n\n public void checkUpdates() {\n new UpdateChecker(this, 12345).getVersion(version -> {\n if (!this.getDescription().getVersion().equals(version)) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (player.isOp()) {\n String prefix = getConfig().getString(\"messages.prefix\");\n player.sendMessage(Translate.translate(prefix + \"&7There is a new &aupdate &7available &fhttps://www.spigot.org/\"));\n getLogger().warning(\"There is a new update available at https://www.spigot.org/ [\" + version + \"]\");\n }\n }\n }\n });\n }\n\n}"
},
{
"identifier": "EthicalProfile",
"path": "src/main/java/net/egis/ethicalvoting/data/player/EthicalProfile.java",
"snippet": "@Getter @Setter @AllArgsConstructor\r\npublic class EthicalProfile implements Comparable<EthicalProfile> {\r\n\r\n private UUID uuid;\r\n private String lastUsername;\r\n private int votes;\r\n\r\n public void incrementVotes(int v) {\r\n votes+=v;\r\n EthicalVoting plugin = EthicalVoting.getSelf();\r\n plugin.getProfiles().saveProfile(this);\r\n }\r\n\r\n public void updateUsername(String username) {\r\n lastUsername = username;\r\n EthicalVoting plugin = EthicalVoting.getSelf();\r\n plugin.getProfiles().saveProfile(this);\r\n }\r\n\r\n @Override\r\n public int compareTo(EthicalProfile o) {\r\n return o.getVotes() - votes;\r\n }\r\n\r\n}\r"
},
{
"identifier": "PagedList",
"path": "src/main/java/net/egis/ethicalvoting/lists/PagedList.java",
"snippet": "public class PagedList {\r\n\r\n private final List<?> list;\r\n\r\n public PagedList(List<?> list) {\r\n this.list = list;\r\n }\r\n\r\n public int getPages(int elementsPerPage) {\r\n //Get the number of pages in the list using the elementsPerPage.\r\n\r\n if (list == null || list.isEmpty()) {\r\n return 0;\r\n }\r\n\r\n return (int) Math.ceil((double) list.size() / elementsPerPage);\r\n }\r\n\r\n public List<?> getPage(int page, int elementsPerPage) {\r\n //Split a list into pages using the current page and elementsPerPage.\r\n\r\n int fromIndex = page * elementsPerPage;\r\n if (list == null || list.size() < fromIndex) {\r\n return null;\r\n }\r\n\r\n // toIndex exclusive\r\n return list.subList(fromIndex, Math.min(fromIndex + elementsPerPage, list.size()));\r\n }\r\n\r\n}\r"
}
] | import lombok.Getter;
import net.egis.ethicalvoting.EthicalVoting;
import net.egis.ethicalvoting.data.player.EthicalProfile;
import net.egis.ethicalvoting.lists.PagedList;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
import java.util.List;
import java.util.UUID;
| 1,714 | package net.egis.ethicalvoting.data;
@Getter
public class ProfileManager {
private final StorageInterface storage;
private final List<EthicalProfile> profiles;
private final BukkitTask sortProfilesTask;
public ProfileManager(StorageInterface storage) {
profiles = storage.getProfiles();
this.storage = storage;
| package net.egis.ethicalvoting.data;
@Getter
public class ProfileManager {
private final StorageInterface storage;
private final List<EthicalProfile> profiles;
private final BukkitTask sortProfilesTask;
public ProfileManager(StorageInterface storage) {
profiles = storage.getProfiles();
this.storage = storage;
| sortProfilesTask = Bukkit.getScheduler().runTaskTimerAsynchronously(EthicalVoting.getSelf(), new SortPlayersTask(this), 0, 20*60*5);
| 0 | 2023-12-15 16:48:38+00:00 | 4k |
SAMJ-CSDC26BB/samj-javafx | samj/src/main/java/com/samj/shared/DatabaseAPI.java | [
{
"identifier": "CallForwardingRecordsDAO",
"path": "samj/src/main/java/com/samj/backend/CallForwardingRecordsDAO.java",
"snippet": "public class CallForwardingRecordsDAO {\n\n private static final String LOAD_RECORDS_SQL = \"SELECT c.*, u.number, u.username FROM call_forwarding_records as c JOIN user as u ON u.username=c.username\";\n private static final String LOAD_RECORDS_BY_ID = \"SELECT c.*, u.number, u.username FROM call_forwarding_records as c JOIN user as u ON u.username=c.username WHERE c.ID=?\";\n private static final String LOAD_RECORDS_BY_DATE_SQL = \"SELECT * FROM call_forwarding_records WHERE startDate >= ? AND endDate <= ?\";\n private static final String ADD_RECORD_SQL = \"INSERT INTO call_forwarding_records (calledNumber, username, startDate, endDate) VALUES (?, ?, ?, ?)\";\n private static final String UPDATE_RECORD_SET_DESTINATION_USER = \"UPDATE call_forwarding_records SET username = ? WHERE ID = ?\";\n private static final String UPDATE_RECORD_SET_DATES_SQL = \"UPDATE call_forwarding_records SET startDate = ?, endDate = ? WHERE ID = ?\";\n private static final String UPDATE_RECORD_SET_ALL_FIELDS = \"UPDATE call_forwarding_records SET calledNumber = ?, username = ?, startDate = ?, endDate = ? WHERE ID = ?\";\n private static final String DELETE_RECORD_SQL = \"DELETE FROM call_forwarding_records WHERE ID = ?\";\n\n\n public static Set<CallForwardingDTO> loadRecords() {\n Set<CallForwardingDTO> callForwardingDTOS = new HashSet<>();\n\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(LOAD_RECORDS_SQL);\n ResultSet resultSet = preparedStatement.executeQuery()) {\n\n _updateCallingForwardingSetFromResultSet(resultSet, callForwardingDTOS);\n\n } catch (Exception e) {\n // log some message\n }\n\n return callForwardingDTOS;\n }\n\n\n public static Set<CallForwardingDTO> loadRecordsByID(int id) {\n Set<CallForwardingDTO> callForwardingDTOS = new HashSet<>();\n\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(LOAD_RECORDS_BY_ID)) {\n\n preparedStatement.setInt(1, id);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n\n _updateCallingForwardingSetFromResultSet(resultSet, callForwardingDTOS);\n\n } catch (Exception e) {\n // log error\n }\n\n } catch (Exception e) {\n // log some message\n }\n\n return callForwardingDTOS;\n }\n\n public static Set<CallForwardingDTO> loadRecordsBetweenDates(LocalDateTime startDate, LocalDateTime endDate) {\n Set<CallForwardingDTO> callForwardingDTOS = new HashSet<>();\n\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(LOAD_RECORDS_BY_DATE_SQL)) {\n\n Timestamp startTimestamp = Timestamp.valueOf(startDate);\n Timestamp endTimestamp = Timestamp.valueOf(endDate);\n\n int index = 0;\n preparedStatement.setTimestamp(++index, startTimestamp);\n preparedStatement.setTimestamp(++index, endTimestamp);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n\n _updateCallingForwardingSetFromResultSet(resultSet, callForwardingDTOS);\n\n } catch (Exception e) {\n // log error\n }\n\n } catch (Exception e) {\n // log some message\n }\n\n return callForwardingDTOS;\n }\n\n public static boolean addRecord(CallForwardingDTO callForwardingDTO) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(ADD_RECORD_SQL)) {\n\n int index = 0;\n preparedStatement.setString(++index, callForwardingDTO.getCalledNumber());\n preparedStatement.setString(++index, callForwardingDTO.getDestinationUsername());\n preparedStatement.setTimestamp(++index, Timestamp.valueOf(callForwardingDTO.getBeginTime()));\n preparedStatement.setTimestamp(++index, Timestamp.valueOf(callForwardingDTO.getEndTime()));\n\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n //add logger here\n }\n\n return false;\n }\n\n public static boolean updateDestinationUser(int id, String username) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_RECORD_SET_DESTINATION_USER)) {\n\n int index = 0;\n preparedStatement.setString(++index, username);\n preparedStatement.setInt(++index, id);\n\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n //add logger here\n }\n\n return false;\n }\n\n public static boolean updateDate(CallForwardingDTO callForwardingDTO) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_RECORD_SET_DATES_SQL)) {\n\n int index = 0;\n preparedStatement.setTimestamp(++index, Timestamp.valueOf(callForwardingDTO.getBeginTime()));\n preparedStatement.setTimestamp(++index, Timestamp.valueOf(callForwardingDTO.getEndTime()));\n preparedStatement.setInt(++index, callForwardingDTO.getId());\n\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n //add logger here\n }\n\n return false;\n }\n\n public static boolean updateCallForwardingAllFields(CallForwardingDTO callForwardingDTO) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_RECORD_SET_ALL_FIELDS)) {\n\n int index = 0;\n preparedStatement.setString(++index, callForwardingDTO.getCalledNumber());\n preparedStatement.setString(++index, callForwardingDTO.getDestinationUsername());\n preparedStatement.setTimestamp(++index, Timestamp.valueOf(callForwardingDTO.getBeginTime()));\n preparedStatement.setTimestamp(++index, Timestamp.valueOf(callForwardingDTO.getEndTime()));\n preparedStatement.setInt(++index, callForwardingDTO.getId());\n\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n //add logger here\n }\n\n return false;\n }\n\n public static boolean deleteRecord(int id) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(DELETE_RECORD_SQL)) {\n\n preparedStatement.setInt(1, id);\n\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n //add logger\n }\n\n return false;\n }\n\n /**\n * Helper method for updating the given callingForwardingSet using the data from the resultSet.\n */\n private static void _updateCallingForwardingSetFromResultSet(ResultSet resultSet,\n Set<CallForwardingDTO> callingForwardingSet)\n throws SQLException {\n\n if (resultSet == null || !resultSet.next() || callingForwardingSet == null) {\n return;\n }\n\n while (resultSet.next()) {\n CallForwardingDTO currentCallForwardingDTO = new CallForwardingDTO(\n resultSet.getInt(\"ID\"),\n resultSet.getString(\"callednumber\"),\n resultSet.getTimestamp(\"startDate\").toLocalDateTime(),\n resultSet.getTimestamp(\"endDate\").toLocalDateTime(),\n resultSet.getString(\"destinationNumber\"),\n resultSet.getString(\"username\"),\n resultSet.getString(\"fullname\"));\n\n callingForwardingSet.add(currentCallForwardingDTO);\n }\n }\n\n}"
},
{
"identifier": "UserDAO",
"path": "samj/src/main/java/com/samj/backend/UserDAO.java",
"snippet": "public class UserDAO {\n private static final String ACTIVE_STRING = \"active\";\n private static final String INACTIVE_STRING = \"inactive\";\n\n private static final String LOAD_USERS_SQL = \"SELECT * FROM user WHERE status=?\";\n private static final String LOAD_USER_BY_USERNAME_SQL = \"SELECT * FROM user WHERE username=?\";\n private static final String ADD_USER_SQL = \"INSERT INTO user (username, fullname, password, number) VALUES (?, ?, ?, ?)\";\n private static final String UPDATE_USER_PASSWORD_SQL = \"UPDATE user SET password = ? WHERE username = ?\";\n private static final String UPDATE_USER_FULL_NAME_SQL = \"UPDATE user SET fullname = ? WHERE username = ?\";\n private static final String UPDATE_USER_NUMBER_SQL = \"UPDATE user SET number = ? WHERE username = ?\";\n private static final String UPDATE_USER_STATUS_SQL = \"UPDATE user SET status = ? WHERE username = ?\";\n private static final String UPDATE_USER_SET_ALL_FIELDS = \"UPDATE user SET fullname = ?, password = ?, number = ?, status = ? WHERE username = ?\";\n private static final String DELETE_USER_SQL = \"DELETE FROM user WHERE username=?\";\n\n public static Set<UserDTO> loadAllActiveUsers() {\n return _loadAllUsersHelper(true);\n }\n\n public static Set<UserDTO> loadAllInActiveUsers() {\n return _loadAllUsersHelper(false);\n }\n\n public static UserDTO loadUserByUsername(String username) {\n\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(LOAD_USER_BY_USERNAME_SQL)) {\n\n preparedStatement.setString(1, username);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n\n return new UserDTO(resultSet.getString(\"username\"),\n resultSet.getString(\"fullname\"),\n resultSet.getString(\"password\"),\n resultSet.getString(\"number\"),\n resultSet.getString(\"status\"));\n\n } catch (Exception e) {\n // log error\n }\n\n } catch (Exception e) {\n // log some message\n }\n\n return null;\n }\n\n public static boolean createUser(UserDTO userDTO) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(ADD_USER_SQL)) {\n\n int index = 0;\n preparedStatement.setString(++index, userDTO.getUsername());\n preparedStatement.setString(++index, userDTO.getFullName());\n preparedStatement.setString(++index, userDTO.getPassword());\n preparedStatement.setString(++index, userDTO.getNumber());\n\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n // log some error\n System.out.println(e.getMessage());\n }\n\n return false;\n }\n\n public static boolean deleteUser(String username) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(DELETE_USER_SQL)) {\n\n preparedStatement.setString(1, username);\n\n return true;\n\n } catch (Exception e) {\n // log some error\n }\n\n return false;\n }\n\n public static boolean updateUserPassword(String username, String password) {\n return updateUserHelper(UPDATE_USER_PASSWORD_SQL, username, password);\n }\n\n public static boolean updateUserFullName(String username, String fullName) {\n return updateUserHelper(UPDATE_USER_FULL_NAME_SQL, username, fullName);\n }\n\n public static boolean updateUserNumber(String username, String number) {\n return updateUserHelper(UPDATE_USER_NUMBER_SQL, username, number);\n }\n\n public static boolean updateUserStatus(String username, String status) {\n return updateUserHelper(UPDATE_USER_STATUS_SQL, username, status);\n }\n\n public static boolean updateUserAllFields(UserDTO userDTO) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USER_SET_ALL_FIELDS)) {\n\n int index = 0;\n preparedStatement.setString(++index, userDTO.getFullName());\n preparedStatement.setString(++index, userDTO.getPassword());\n preparedStatement.setString(++index, userDTO.getNumber());\n\n String status = userDTO.getStatus() == null ? ACTIVE_STRING : userDTO.getStatus();\n preparedStatement.setString(++index, status);\n\n preparedStatement.setString(++index, userDTO.getUsername());\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n // log some error message\n }\n\n return false;\n }\n\n /**\n * Helper method for update.\n * Used to set exactly 2 Strings in the update statement.\n */\n private static boolean updateUserHelper(String sqlQuery, String username, String valueToSet) {\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {\n\n int index = 0;\n preparedStatement.setString(++index, valueToSet);\n preparedStatement.setString(++index, username);\n preparedStatement.executeUpdate();\n\n return true;\n\n } catch (Exception e) {\n // log some error\n }\n\n return false;\n }\n\n private static Set<UserDTO> _loadAllUsersHelper(boolean isLoadOnlyActiveUsers) {\n Set<UserDTO> userDTOs = new HashSet<>();\n\n try (Connection connection = Database.getDbConnection();\n PreparedStatement preparedStatement = connection.prepareStatement(LOAD_USERS_SQL)) {\n\n String status = isLoadOnlyActiveUsers ? ACTIVE_STRING : INACTIVE_STRING;\n\n preparedStatement.setString(1, status);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n\n _updateUserDTOSetFromResultSet(resultSet, userDTOs);\n\n } catch (Exception e) {\n // log some message\n }\n\n } catch (Exception e) {\n // log some message\n }\n\n return userDTOs;\n }\n\n private static void _updateUserDTOSetFromResultSet(ResultSet resultSet,\n Set<UserDTO> userDTOSet)\n throws SQLException {\n\n if (resultSet == null || !resultSet.next() || userDTOSet == null) {\n return;\n }\n\n while (resultSet.next()) {\n UserDTO currentUserDTO = new UserDTO(\n resultSet.getString(\"username\"),\n resultSet.getString(\"fullname\"),\n resultSet.getString(\"password\"),\n resultSet.getString(\"number\"),\n resultSet.getString(\"status\"));\n\n userDTOSet.add(currentUserDTO);\n }\n }\n}"
}
] | import com.samj.backend.CallForwardingRecordsDAO;
import com.samj.backend.UserDAO;
import java.time.LocalDateTime;
import java.util.Set; | 3,274 | package com.samj.shared;
public class DatabaseAPI {
public static boolean createNewUser(UserDTO userDTO) {
// todo hash the user psw. | package com.samj.shared;
public class DatabaseAPI {
public static boolean createNewUser(UserDTO userDTO) {
// todo hash the user psw. | return UserDAO.createUser(userDTO); | 1 | 2023-12-18 09:42:06+00:00 | 4k |
approachcircle/Pong | src/main/java/net/approachcircle/game/PauseScreen.java | [
{
"identifier": "Button",
"path": "src/main/java/net/approachcircle/game/backend/Button.java",
"snippet": "public class Button implements Renderable, Transformable {\n private float x;\n private float y;\n private final boolean background;\n private TransformableRect buttonBackground;\n private final TextRenderable textRenderable;\n private final float padding = 50;\n private final ButtonClickListener listener;\n private InputAdapter inputProcessor;\n private final InputManager inputManager;\n\n public Button(String text, boolean background, ButtonClickListener listener, InputManager inputManager, float scale) {\n this.background = background;\n this.listener = listener;\n this.inputManager = inputManager;\n setX(0);\n setY(0);\n textRenderable = new TextRenderable(text, scale);\n textRenderable.setX(getX());\n textRenderable.setY(getY());\n textRenderable.setColor(Color.WHITE);\n if (background) {\n buttonBackground = new TransformableRect(Color.GRAY);\n setWidth(textRenderable.getWidth() - textRenderable.getScale() + padding);\n setHeight(textRenderable.getHeight() + padding + textRenderable.getScale());\n }\n }\n public Button(String text, boolean background) {\n this(text, background, null, null);\n }\n public Button(String text, boolean background, float scale) {\n this(text, background, null, null, scale);\n }\n\n public Button(String text, boolean background, ButtonClickListener listener, InputManager inputManager) {\n this(text, background, listener, inputManager, DefaultTextScaling.BUTTON);\n }\n\n private void updateInputProcessor() {\n // no input manager or listener provided, don't bother setting input processor\n if (inputManager == null || listener == null) {\n return;\n }\n if (inputProcessor != null) {\n inputManager.removeInputProcessor(inputProcessor);\n }\n inputProcessor = new InputAdapter() {\n @Override\n public boolean touchUp(int x, int y, int pointer, int button) {\n // cursor coordinates must be subtracted from screen height to get absolute coordinates\n if (x >= getX() && x <= getX() + getWidth() && Gdx.graphics.getHeight() - y >= getY() && Gdx.graphics.getHeight() - y <= getY() + getHeight()) {\n listener.onClick(x, Gdx.graphics.getHeight() - y, button);\n // after a click, remove the processor unless specifically instructed\n // to re-add it on the next frame.\n inputManager.removeInputProcessor(inputProcessor);\n return true;\n }\n return false;\n }\n };\n inputManager.addInputProcessor(inputProcessor);\n }\n\n @Override\n public void render() {\n updateInputProcessor();\n if (background) {\n buttonBackground.setX(getX());\n buttonBackground.setY(getY());\n textRenderable.centerRelativeTo(buttonBackground);\n buttonBackground.render();\n } else {\n textRenderable.setX(getX());\n textRenderable.setY(getY());\n }\n textRenderable.render();\n }\n\n @Override\n public float getWidth() {\n if (!background) {\n return textRenderable.getWidth();\n }\n return buttonBackground.getWidth();\n }\n\n @Override\n public float getHeight() {\n if (!background) {\n return textRenderable.getHeight();\n }\n return buttonBackground.getHeight();\n }\n\n @Override\n public void setWidth(float width) {\n if (!background) {\n throw new IllegalStateException(\"button has no background, so a width cannot be set. scale the text instead\");\n }\n this.buttonBackground.setWidth(width);\n }\n\n @Override\n public void setHeight(float height) {\n if (!background) {\n throw new IllegalStateException(\"button has no background, so a height cannot be set. scale the text instead\");\n }\n this.buttonBackground.setHeight(height);\n }\n\n @Override\n public float getX() {\n return x;\n }\n\n @Override\n public float getY() {\n return y;\n }\n\n @Override\n public void setX(float x) {\n this.x = x;\n updateInputProcessor();\n }\n\n @Override\n public void setY(float y) {\n this.y = y;\n updateInputProcessor();\n }\n\n @Override\n public void center() {\n centerX();\n centerY();\n }\n\n @Override\n public void centerX() {\n setX(ScreenUtility.getScreenCenter().x - (buttonBackground.getWidth() / 2));\n }\n\n @Override\n public void centerY() {\n setY(ScreenUtility.getScreenCenter().y - (buttonBackground.getHeight() / 2));\n }\n}"
},
{
"identifier": "DefaultTextScaling",
"path": "src/main/java/net/approachcircle/game/backend/DefaultTextScaling.java",
"snippet": "public interface DefaultTextScaling {\n float TITLE = 0.55f;\n float BUTTON = 0.32f;\n float SUBTITLE = 0.45f;\n float SMALL = BUTTON - 0.1f;\n}"
},
{
"identifier": "Screen",
"path": "src/main/java/net/approachcircle/game/backend/Screen.java",
"snippet": "public abstract class Screen implements Renderable {\n @Override\n public String toString() {\n return this.getClass().getSimpleName();\n }\n public EscapeBehaviour getEscapeBehaviour() {\n return EscapeBehaviour.Other;\n }\n}"
},
{
"identifier": "TextRenderable",
"path": "src/main/java/net/approachcircle/game/backend/TextRenderable.java",
"snippet": "public class TextRenderable implements Transformable, Renderable {\n private final BitmapFont font;\n private final Batch batch = new SpriteBatch();\n private GlyphLayout glyphLayout;\n private float x;\n private float y;\n private float maxWidth;\n private boolean recalculateCenterX = false;\n private boolean recalculateCenterY = false;\n private Transformable recalculateCenterXRelative;\n private Transformable recalculateCenterYRelative;\n private float scale;\n private Color color;\n private String text;\n private int autoScalePadding = 0;\n\n public TextRenderable(String text, float scale, Color color) {\n // FileHandle handle = Gdx.files.getFileHandle(\"yu_gothic_ui.fnt\", Files.FileType.Classpath);\n FileHandle handle = Gdx.files.getFileHandle(\"ubuntu.fnt\", Files.FileType.Classpath);\n font = new BitmapFont(handle);\n this.x = 0;\n this.y = 0;\n this.maxWidth = 0;\n this.scale = scale;\n font.getData().setScale(scale);\n this.text = text;\n setText(text);\n setColor(color);\n }\n\n public TextRenderable(String text, float scale) {\n this(text, scale, Color.WHITE);\n }\n\n public TextRenderable(String text, Color color) {\n this(text, DefaultTextScaling.SUBTITLE, color);\n }\n public TextRenderable(String text) {\n this(text, DefaultTextScaling.SUBTITLE, Color.WHITE);\n }\n\n public TextRenderable(float scale, Color color) {\n this(\"\", scale, color);\n }\n\n public TextRenderable(float scale) {\n this(\"\", scale, Color.WHITE);\n }\n\n public TextRenderable(Color color) {\n this(\"\", 0.5f, color);\n }\n\n public TextRenderable() {\n this(\"\", 0.5f, Color.WHITE);\n }\n\n @Override\n public void render() {\n if (recalculateCenterX) {\n centerX(true);\n }\n if (recalculateCenterY) {\n centerY(true);\n }\n if (maxWidth > 0) {\n scaleToMaxWidth();\n }\n if (recalculateCenterXRelative != null) {\n centerXRelativeTo(recalculateCenterXRelative, true);\n }\n if (recalculateCenterYRelative != null) {\n centerYRelativeTo(recalculateCenterYRelative, true);\n }\n batch.begin();\n font.draw(batch, glyphLayout, getX(), getY());\n batch.end();\n }\n\n @Override\n public float getX() {\n return x;\n }\n\n @Override\n public float getY() {\n return y;\n }\n\n @Override\n public void setX(float x) {\n recalculateCenterX = false;\n recalculateCenterXRelative = null;\n this.x = x;\n }\n\n @Override\n public void setY(float y) {\n recalculateCenterY = false;\n recalculateCenterYRelative = null;\n this.y = y;\n }\n\n @Override\n public void center() {\n center(false);\n }\n\n public void center(boolean recalculate) {\n centerX(recalculate);\n centerY(recalculate);\n }\n\n @Override\n public void centerX() {\n centerX(false);\n }\n\n @Override\n public void centerY() {\n centerY(false);\n }\n\n public void centerX(boolean recalculate) {\n recalculateCenterX = recalculate;\n // directly access x to bypass the center recalculate disable behaviour\n x = ScreenUtility.getScreenCenter().x - (glyphLayout.width / 2) - scale;\n }\n\n public void centerY(boolean recalculate) {\n recalculateCenterY = recalculate;\n // directly access y to bypass the center recalculate disable behaviour\n y = ScreenUtility.getScreenCenter().y + (glyphLayout.height / 2) + scale;\n }\n\n public void centerXRelativeTo(Transformable transformable, boolean recalculate) {\n if (recalculate) {\n recalculateCenterXRelative = transformable;\n }\n x = (transformable.getX() + (transformable.getWidth() / 2)) - getWidth() / 2;\n }\n\n public void centerXRelativeTo(Transformable transformable) {\n centerXRelativeTo(transformable, false);\n }\n\n public void centerYRelativeTo(Transformable transformable, boolean recalculate) {\n if (recalculate) {\n recalculateCenterYRelative = transformable;\n }\n y = transformable.getY() + (transformable.getHeight() + getHeight()) / 2;\n }\n\n @Override\n public void centerYRelativeTo(Transformable transformable) {\n centerYRelativeTo(transformable, false);\n }\n\n @Override\n public void centerRelativeTo(Transformable transformable) {\n centerXRelativeTo(transformable);\n centerYRelativeTo(transformable);\n }\n\n public void centerRelativeTo(Transformable transformable, boolean recalculate) {\n centerXRelativeTo(transformable, recalculate);\n centerYRelativeTo(transformable, recalculate);\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n updateGlyphLayout();\n }\n\n /**\n * sets the maximum width this text can reach before it begins\n * to auto-scale down to keep its width below it.\n * useful for keeping text from spilling over the edge of other\n * {@code Transformable}s.\n * @param maxWidth the maximum width to constrain this text to\n */\n public void setMaxWidth(float maxWidth) {\n this.maxWidth = maxWidth;\n scaleToMaxWidth();\n }\n\n private void scaleToMaxWidth() {\n while (getWidth() + autoScalePadding > maxWidth) {\n setScale(getScale() - 0.001f);\n }\n }\n\n /**\n * used in conjunction with the {@code setMaxWidth()} method. this method\n * will add padding to the distance away from the max width value.\n * @param padding the number of pixels to constrain this text away from the max width\n */\n public void setAutoScalePadding(int padding) {\n autoScalePadding = padding;\n if (maxWidth > 0) {\n scaleToMaxWidth();\n }\n }\n\n public float getScale() {\n return scale;\n }\n\n public void setScale(float scale) {\n this.scale = scale;\n font.getData().setScale(scale);\n updateGlyphLayout();\n }\n\n @Override\n public float getWidth() {\n return glyphLayout.width;\n }\n\n @Override\n public float getHeight() {\n return glyphLayout.height;\n }\n\n @Override\n public void setWidth(float width) {\n throw new RuntimeException(\"though this is transformable, the width may not be set manually, only scaled\");\n }\n\n @Override\n public void setHeight(float height) {\n throw new RuntimeException(\"though this is transformable, the height may not be set manually, only scaled\");\n }\n\n private void updateGlyphLayout() {\n glyphLayout = new GlyphLayout(font, text);\n }\n\n public void setColor(Color color) {\n this.color = color;\n font.setColor(color);\n updateGlyphLayout();\n }\n\n public Color getColor() {\n return color;\n }\n}"
}
] | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import net.approachcircle.game.backend.Button;
import net.approachcircle.game.backend.DefaultTextScaling;
import net.approachcircle.game.backend.Screen;
import net.approachcircle.game.backend.TextRenderable; | 3,187 | package net.approachcircle.game;
public class PauseScreen extends Screen {
private final Button resumeButton;
private final Button quitButton; | package net.approachcircle.game;
public class PauseScreen extends Screen {
private final Button resumeButton;
private final Button quitButton; | private final TextRenderable title; | 3 | 2023-12-20 16:25:30+00:00 | 4k |
jollyboss123/astra | modules/app/src/main/java/com/jolly/astra/config/SecurityConfiguration.java | [
{
"identifier": "AuthoritiesConstants",
"path": "modules/app/src/main/java/com/jolly/astra/security/AuthoritiesConstants.java",
"snippet": "public final class AuthoritiesConstants {\n\n public static final String ADMIN = \"ADMIN\";\n\n public static final String USER = \"USER\";\n\n public static final String ANONYMOUS = \"ANONYMOUS\";\n\n private AuthoritiesConstants() {}\n}"
},
{
"identifier": "JwtAbstractAuthenticationTokenConverter",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/JwtAbstractAuthenticationTokenConverter.java",
"snippet": "public interface JwtAbstractAuthenticationTokenConverter extends Converter<Jwt, AbstractAuthenticationToken> {\n}"
},
{
"identifier": "OAuthentication",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/OAuthentication.java",
"snippet": "public class OAuthentication<T extends Map<String, Object> & Serializable & Principal> extends AbstractAuthenticationToken implements\n OAuth2AuthenticatedPrincipal {\n @Serial\n private static final long serialVersionUID = 7566213493599769417L;\n\n /**\n * Bearer string to set as Authorization header if we ever need to call a downstream service on behalf of the same resource-owner.\n */\n private final String tokenString;\n /**\n * Claim-set associated with the access-token (attributes retrieved from the token or introspection end-point).\n */\n private final T claims;\n\n /**\n * @param claims Claim-set of any-type\n * @param authorities Granted authorities associated with this authentication instance\n * @param tokenString Original encoded Bearer string (in case resource-server needs)\n */\n public OAuthentication(T claims, Collection<? extends GrantedAuthority> authorities, String tokenString) {\n super(authorities);\n super.setAuthenticated(true);\n super.setDetails(claims);\n this.claims = claims;\n this.tokenString = Optional.ofNullable(tokenString)\n .map(t -> t.toLowerCase().startsWith(\"bearer \") ? t.substring(7) : t)\n .orElse(null);\n }\n\n @Override\n public void setAuthenticated(boolean authenticated) {\n throw new RuntimeException(\"OAuthentication authentication status is immutable\");\n }\n\n @Override\n public Object getCredentials() {\n return tokenString;\n }\n\n @Override\n public Object getPrincipal() {\n return claims;\n }\n\n @Override\n public Map<String, Object> getAttributes() {\n return claims;\n }\n\n public T getClaims() {\n return claims;\n }\n\n public String getBearerHeader() {\n if (!StringUtils.hasText(tokenString)) {\n return null;\n }\n\n return String.format(\"Bearer %s\", tokenString);\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (object == null || getClass() != object.getClass()) return false;\n if (!super.equals(object)) return false;\n OAuthentication<?> that = (OAuthentication<?>) object;\n return Objects.equals(tokenString, that.tokenString) && Objects.equals(claims, that.claims);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), tokenString, claims);\n }\n}"
},
{
"identifier": "OpenIdClaimSet",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/claimset/OpenIdClaimSet.java",
"snippet": "public class OpenIdClaimSet extends UnmodifiableClaimSet implements IdTokenClaimAccessor, Principal {\n @Serial\n private static final long serialVersionUID = 4908273025927451191L;\n\n /**\n * JSON path for the claim to use as \"name\" source\n */\n private final String usernameClaim;\n\n public OpenIdClaimSet(Map<String, Object> claims, String usernameClaim) {\n super(claims);\n this.usernameClaim = usernameClaim;\n }\n\n public OpenIdClaimSet(Map<String, Object> claims) {\n this(claims, StandardClaimNames.SUB);\n }\n\n @Override\n public String getName() {\n try {\n return getByJsonPath(usernameClaim);\n } catch (PathNotFoundException ex) {\n return getByJsonPath(JwtClaimNames.SUB);\n }\n }\n\n @Override\n public Map<String, Object> getClaims() {\n return this;\n }\n}"
},
{
"identifier": "ExpressionInterceptUrlRegistryPostProcessor",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/hooks/ExpressionInterceptUrlRegistryPostProcessor.java",
"snippet": "public interface ExpressionInterceptUrlRegistryPostProcessor {\n AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorizeHttpRequests(\n AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry registry\n );\n}"
},
{
"identifier": "HeimdallOidcProperties",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/properties/HeimdallOidcProperties.java",
"snippet": "@AutoConfiguration\n@ConfigurationProperties(prefix = \"com.jolly.heimdall.oidc\")\npublic class HeimdallOidcProperties {\n /**\n * OpenID Providers configuration: JWK set URI, issuer URI, audience, and authorities mapping configuration for each issuer. A minimum\n * of one issuer is required. <b>Properties defined here are a replacement for spring.security.oauth2.resourceserver.jwt.*</b> (which\n * will be ignored). Authorities mapping defined here will be used by the resource server filter chain.\n */\n @NestedConfigurationProperty\n private final List<OpenIdProviderProperties> ops = new ArrayList<>();\n /**\n * Autoconfiguration for an OAuth 2.0 resource server {@link SecurityFilterChain} with\n * {@link Ordered#LOWEST_PRECEDENCE}. <p>Default configuration:\n * <ul>\n * <li>no {@link HttpSecurity#securityMatcher(String...)} to process\n * all the requests that were not intercepted by higher {@link Ordered} {@link SecurityFilterChain}</li>\n * <li>no session</li>\n * <li>disabled CSRF protection</li>\n * <li>401 to unauthorized requests</li>\n * </ul>\n */\n private final ResourceServer resourceServer = new ResourceServer();\n\n public List<OpenIdProviderProperties> getOps() {\n return ops;\n }\n\n public ResourceServer getResourceServer() {\n return resourceServer;\n }\n\n public static class ResourceServer {\n /**\n * If true, instantiate resource server {@link SecurityFilterChain} bean and all its dependencies\n */\n private boolean enabled = true;\n /**\n * Path matchers for the routes accessible to anonymous requests.\n */\n private List<String> permitAll = new ArrayList<>();\n private boolean statelessSession = true;\n private Csrf csrf = Csrf.DISABLE;\n /**\n * Fine-grained CORS configuration.\n */\n private final List<Cors> cors = new ArrayList<>();\n\n public ResourceServer() {}\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public List<String> getPermitAll() {\n return permitAll;\n }\n\n public void setPermitAll(List<String> permitAll) {\n this.permitAll = permitAll;\n }\n\n public boolean isStatelessSession() {\n return statelessSession;\n }\n\n public void setStatelessSession(boolean statelessSession) {\n this.statelessSession = statelessSession;\n }\n\n public Csrf getCsrf() {\n return csrf;\n }\n\n public void setCsrf(Csrf csrf) {\n this.csrf = csrf;\n }\n\n public List<Cors> getCors() {\n return cors;\n }\n\n public static class Cors {\n /**\n * Path matcher to which this configuration entry applies.\n */\n private String path = \"/**\";\n private Boolean allowedCredentials = null;\n /**\n * Default is \"*\" which allows all origins\n */\n private List<String> allowedOriginPatterns = List.of(\"*\");\n /**\n * Default is \"*\" which allows all methods\n */\n private List<String> allowedMethods = List.of(\"*\");\n /**\n * Default is \"*\" which allows all headers\n */\n private List<String> allowedHeaders = List.of(\"*\");\n /**\n * Default is \"*\" which exposes all origins\n */\n private List<String> exposedHeaders = List.of(\"*\");\n private Long maxAge = null;\n\n public Cors() {}\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public Boolean getAllowedCredentials() {\n return allowedCredentials;\n }\n\n public void setAllowedCredentials(Boolean allowedCredentials) {\n this.allowedCredentials = allowedCredentials;\n }\n\n public List<String> getAllowedOriginPatterns() {\n return allowedOriginPatterns;\n }\n\n public void setAllowedOriginPatterns(List<String> allowedOriginPatterns) {\n this.allowedOriginPatterns = allowedOriginPatterns;\n }\n\n public List<String> getAllowedMethods() {\n return allowedMethods;\n }\n\n public void setAllowedMethods(List<String> allowedMethods) {\n this.allowedMethods = allowedMethods;\n }\n\n public List<String> getAllowedHeaders() {\n return allowedHeaders;\n }\n\n public void setAllowedHeaders(List<String> allowedHeaders) {\n this.allowedHeaders = allowedHeaders;\n }\n\n public List<String> getExposedHeaders() {\n return exposedHeaders;\n }\n\n public void setExposedHeaders(List<String> exposedHeaders) {\n this.exposedHeaders = exposedHeaders;\n }\n\n public Long getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(Long maxAge) {\n this.maxAge = maxAge;\n }\n }\n }\n\n /**\n * @param iss the issuer URI string\n * @return configuration properties associated with the provided issuer URI\n * @throws MisconfigurationException if configuration properties do not have an entry of the exact issuer\n */\n public OpenIdProviderProperties getOpProperties(String iss) throws MisconfigurationException {\n for (final var op : getOps()) {\n String opIss = null;\n if (op.getIss() != null) {\n opIss = op.getIss().toString();\n }\n\n if (Objects.equals(opIss, iss)) {\n return op;\n }\n }\n\n throw new MisconfigurationException(iss);\n }\n\n /**\n * @param iss the issuer URL\n * @return configuration properties associated with the provided issuer URI\n * @throws MisconfigurationException if configuration properties do not have an entry of the exact issuer\n */\n public OpenIdProviderProperties getOpProperties(Object iss) throws MisconfigurationException {\n if (iss == null && getOps().size() == 1) {\n return getOps().get(0);\n }\n\n String issStr = null;\n if (iss != null) {\n issStr = iss.toString();\n }\n\n return getOpProperties(issStr);\n }\n}"
}
] | import com.jolly.astra.security.AuthoritiesConstants;
import com.jolly.heimdall.JwtAbstractAuthenticationTokenConverter;
import com.jolly.heimdall.OAuthentication;
import com.jolly.heimdall.claimset.OpenIdClaimSet;
import com.jolly.heimdall.hooks.ExpressionInterceptUrlRegistryPostProcessor;
import com.jolly.heimdall.properties.HeimdallOidcProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.Collection;
import java.util.Map; | 2,944 | package com.jolly.astra.config;
/**
* @author jolly
*/
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
JwtAbstractAuthenticationTokenConverter authenticationConverter(
Converter<Map<String, Object>, Collection<? extends GrantedAuthority>> authoritiesConverter,
HeimdallOidcProperties heimdallProperties
) {
return jwt -> new OAuthentication<>(
new OpenIdClaimSet(jwt.getClaims(), heimdallProperties.getOpProperties(jwt.getClaims().get(JwtClaimNames.ISS)).getUsernameClaim()),
authoritiesConverter.convert(jwt.getClaims()),
jwt.getTokenValue()
);
}
@Bean | package com.jolly.astra.config;
/**
* @author jolly
*/
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
JwtAbstractAuthenticationTokenConverter authenticationConverter(
Converter<Map<String, Object>, Collection<? extends GrantedAuthority>> authoritiesConverter,
HeimdallOidcProperties heimdallProperties
) {
return jwt -> new OAuthentication<>(
new OpenIdClaimSet(jwt.getClaims(), heimdallProperties.getOpProperties(jwt.getClaims().get(JwtClaimNames.ISS)).getUsernameClaim()),
authoritiesConverter.convert(jwt.getClaims()),
jwt.getTokenValue()
);
}
@Bean | ExpressionInterceptUrlRegistryPostProcessor expressionInterceptUrlRegistryPostProcessor() { | 4 | 2023-12-17 05:24:05+00:00 | 4k |
Blawuken/MicroG-Extended | play-services-cast/src/main/java/org/microg/gms/cast/CastApiClientBuilder.java | [
{
"identifier": "Cast",
"path": "play-services-cast/src/main/java/com/google/android/gms/cast/Cast.java",
"snippet": "@PublicApi\npublic final class Cast {\n\n /**\n * A constant indicating that the Google Cast device is not the currently active video input.\n */\n public static final int ACTIVE_INPUT_STATE_NO = 0;\n\n /**\n * A constant indicating that it is not known (and/or not possible to know) whether the Google Cast device is\n * the currently active video input. Active input state can only be reported when the Google Cast device is\n * connected to a TV or AVR with CEC support.\n */\n public static final int ACTIVE_INPUT_STATE_UNKNOWN = -1;\n\n /**\n * A constant indicating that the Google Cast device is the currently active video input.\n */\n public static final int ACTIVE_INPUT_STATE_YES = 1;\n\n /**\n * A boolean extra for the connection hint bundle passed to\n * {@link GoogleApiClient.ConnectionCallbacks#onConnected(Bundle)} that indicates that the connection was\n * re-established, but the receiver application that was in use at the time of the connection loss is no longer\n * running on the receiver.\n */\n public static final String EXTRA_APP_NO_LONGER_RUNNING = \"com.google.android.gms.cast.EXTRA_APP_NO_LONGER_RUNNING\";\n\n /**\n * The maximum raw message length (in bytes) that is supported by a Cast channel.\n */\n public static final int MAX_MESSAGE_LENGTH = 65536;\n\n /**\n * The maximum length (in characters) of a namespace name.\n */\n public static final int MAX_NAMESPACE_LENGTH = 128;\n\n /**\n * A constant indicating that the Google Cast device is not currently in standby.\n */\n public static final int STANDBY_STATE_NO = 0;\n\n /**\n * A constant indicating that it is not known (and/or not possible to know) whether the Google Cast device is\n * currently in standby. Standby state can only be reported when the Google Cast device is connected to a TV or\n * AVR with CEC support.\n */\n public static final int STANDBY_STATE_UNKNOWN = -1;\n\n /**\n * A constant indicating that the Google Cast device is currently in standby.\n */\n public static final int STANDBY_STATE_YES = 1;\n\n\n /**\n * Token to pass to {@link GoogleApiClient.Builder#addApi(Api)} to enable the Cast features.\n */\n public static final Api<CastOptions> API = new Api<CastOptions>(new CastApiClientBuilder());\n\n /**\n * An implementation of the CastApi interface. The interface is used to interact with a cast device.\n */\n public static final Cast.CastApi CastApi = new CastApiImpl();\n\n private Cast() {\n }\n\n public interface ApplicationConnectionResult extends Result {\n ApplicationMetadata getApplicationMetadata();\n\n String getApplicationStatus();\n\n String getSessionId();\n\n boolean getWasLaunched();\n }\n\n public interface CastApi {\n int getActiveInputState(GoogleApiClient client);\n\n ApplicationMetadata getApplicationMetadata(GoogleApiClient client);\n\n String getApplicationStatus(GoogleApiClient client);\n\n int getStandbyState(GoogleApiClient client);\n\n double getVolume(GoogleApiClient client);\n\n boolean isMute(GoogleApiClient client);\n\n PendingResult<Cast.ApplicationConnectionResult> joinApplication(GoogleApiClient client);\n\n PendingResult<Cast.ApplicationConnectionResult> joinApplication(GoogleApiClient client, String applicationId, String sessionId);\n\n PendingResult<Cast.ApplicationConnectionResult> joinApplication(GoogleApiClient client, String applicationId);\n\n PendingResult<Cast.ApplicationConnectionResult> launchApplication(GoogleApiClient client, String applicationId, LaunchOptions launchOptions);\n\n PendingResult<Cast.ApplicationConnectionResult> launchApplication(GoogleApiClient client, String applicationId);\n\n @Deprecated\n PendingResult<Cast.ApplicationConnectionResult> launchApplication(GoogleApiClient client, String applicationId, boolean relaunchIfRunning);\n\n PendingResult<Status> leaveApplication(GoogleApiClient client);\n\n void removeMessageReceivedCallbacks(GoogleApiClient client, String namespace) throws IOException;\n\n void requestStatus(GoogleApiClient client) throws IOException;\n\n PendingResult<Status> sendMessage(GoogleApiClient client, String namespace, String message);\n\n void setMessageReceivedCallbacks(GoogleApiClient client, String namespace, Cast.MessageReceivedCallback callbacks) throws IOException;\n\n void setMute(GoogleApiClient client, boolean mute) throws IOException;\n\n void setVolume(GoogleApiClient client, double volume) throws IOException;\n\n PendingResult<Status> stopApplication(GoogleApiClient client);\n\n PendingResult<Status> stopApplication(GoogleApiClient client, String sessionId);\n }\n\n public static class CastOptions implements Api.ApiOptions.HasOptions {\n private final CastDevice castDevice;\n private final Listener castListener;\n private final boolean verboseLoggingEnabled;\n\n public CastOptions(CastDevice castDevice, Listener castListener, boolean verboseLoggingEnabled) {\n this.castDevice = castDevice;\n this.castListener = castListener;\n this.verboseLoggingEnabled = verboseLoggingEnabled;\n }\n\n @Deprecated\n public static Builder builder(CastDevice castDevice, Listener castListener) {\n return new Builder(castDevice, castListener);\n }\n\n public static class Builder {\n private final CastDevice castDevice;\n private final Listener castListener;\n private boolean verboseLoggingEnabled;\n\n public Builder(CastDevice castDevice, Listener castListener) {\n this.castDevice = castDevice;\n this.castListener = castListener;\n }\n\n public CastOptions build() {\n return new CastOptions(castDevice, castListener, verboseLoggingEnabled);\n }\n\n public Builder setVerboseLoggingEnabled(boolean verboseLoggingEnabled) {\n this.verboseLoggingEnabled = verboseLoggingEnabled;\n return this;\n }\n }\n }\n\n public static class Listener {\n public void onActiveInputStateChanged(int activeInputState) {\n\n }\n\n public void onApplicationDisconnected(int statusCode) {\n\n }\n\n public void onApplicationMetadataChanged(ApplicationMetadata applicationMetadata) {\n\n }\n\n public void onApplicationStatusChanged() {\n\n }\n\n public void onStandbyStateChanged(int standbyState) {\n\n }\n\n public void onVolumeChanged() {\n\n }\n }\n\n public interface MessageReceivedCallback {\n void onMessageReceived(CastDevice castDevice, String namespace, String message);\n }\n}"
},
{
"identifier": "Api",
"path": "play-services-base/src/main/java/com/google/android/gms/common/api/Api.java",
"snippet": "@PublicApi\npublic final class Api<O extends Api.ApiOptions> {\n private final ApiClientBuilder<O> builder;\n\n @PublicApi(exclude = true)\n public Api(ApiClientBuilder<O> builder) {\n this.builder = builder;\n }\n\n @PublicApi(exclude = true)\n public ApiClientBuilder<O> getBuilder() {\n return builder;\n }\n\n /**\n * Base interface for API options. These are used to configure specific parameters for\n * individual API surfaces. The default implementation has no parameters.\n */\n @PublicApi\n public interface ApiOptions {\n /**\n * Base interface for {@link ApiOptions} in {@link Api}s that have options.\n */\n @PublicApi\n interface HasOptions extends ApiOptions {\n }\n\n /**\n * Base interface for {@link ApiOptions} that are not required, don't exist.\n */\n @PublicApi\n interface NotRequiredOptions extends ApiOptions {\n }\n\n /**\n * {@link ApiOptions} implementation for {@link Api}s that do not take any options.\n */\n @PublicApi\n final class NoOptions implements NotRequiredOptions {\n }\n\n /**\n * Base interface for {@link ApiOptions} that are optional.\n */\n @PublicApi\n interface Optional extends HasOptions, NotRequiredOptions {\n }\n\n /**\n * An interface for {@link ApiOptions} that include an account.\n */\n @PublicApi\n interface HasAccountOptions extends HasOptions, NotRequiredOptions {\n Account getAccount();\n }\n\n /**\n * An interface for {@link ApiOptions} that includes a {@link GoogleSignInAccount}\n */\n @PublicApi\n interface HasGoogleSignInAccountOptions extends HasOptions {\n GoogleSignInAccount getGoogleSignInAccount();\n }\n }\n\n @Hide\n public interface Client {\n void connect();\n\n void disconnect();\n\n boolean isConnected();\n\n boolean isConnecting();\n }\n}"
},
{
"identifier": "ApiClientBuilder",
"path": "play-services-base/src/main/java/org/microg/gms/common/api/ApiClientBuilder.java",
"snippet": "public interface ApiClientBuilder<O extends Api.ApiOptions> {\n Api.Client build(O options, Context context, Looper looper, ApiClientSettings clientSettings, ConnectionCallbacks callbacks, OnConnectionFailedListener connectionFailedListener);\n}"
},
{
"identifier": "ApiClientSettings",
"path": "play-services-base/src/main/java/org/microg/gms/common/api/ApiClientSettings.java",
"snippet": "public class ApiClientSettings {\n public String accountName;\n public String packageName;\n public Integer sessionId;\n public Set<String> scopes;\n public int gravityForPopups;\n public View viewForPopups;\n}"
},
{
"identifier": "ConnectionCallbacks",
"path": "play-services-base/src/main/java/org/microg/gms/common/api/ConnectionCallbacks.java",
"snippet": "public interface ConnectionCallbacks {\n\n /**\n * After calling {@link #connect()}, this method will be invoked asynchronously when the\n * connect request has successfully completed. After this callback, the application can\n * make requests on other methods provided by the client and expect that no user\n * intervention is required to call methods that use account and scopes provided to the\n * client constructor.\n * <p/>\n * Note that the contents of the {@code connectionHint} Bundle are defined by the specific\n * services. Please see the documentation of the specific implementation of\n * {@link GoogleApiClient} you are using for more information.\n *\n * @param connectionHint Bundle of data provided to clients by Google Play services. May\n * be null if no content is provided by the service.\n */\n void onConnected(Bundle connectionHint);\n\n /**\n * Called when the client is temporarily in a disconnected state. This can happen if there\n * is a problem with the remote service (e.g. a crash or resource problem causes it to be\n * killed by the system). When called, all requests have been canceled and no outstanding\n * listeners will be executed. GoogleApiClient will automatically attempt to restore the\n * connection. Applications should disable UI components that require the service, and wait\n * for a call to {@link #onConnected(Bundle)} to re-enable them.\n *\n * @param cause The reason for the disconnection. Defined by constants {@code CAUSE_*}.\n */\n void onConnectionSuspended(int cause);\n}"
},
{
"identifier": "OnConnectionFailedListener",
"path": "play-services-base/src/main/java/org/microg/gms/common/api/OnConnectionFailedListener.java",
"snippet": "public interface OnConnectionFailedListener {\n /**\n * Called when there was an error connecting the client to the service.\n *\n * @param result A {@link ConnectionResult} that can be used for resolving the error, and\n * deciding what sort of error occurred. To resolve the error, the resolution\n * must be started from an activity with a non-negative {@code requestCode}\n * passed to {@link ConnectionResult#startResolutionForResult(Activity, int)}.\n * Applications should implement {@link Activity#onActivityResult} in their\n * Activity to call {@link #connect()} again if the user has resolved the\n * issue (resultCode is {@link Activity#RESULT_OK}).\n */\n void onConnectionFailed(ConnectionResult result);\n}"
}
] | import android.content.Context;
import android.os.Looper;
import com.google.android.gms.cast.Cast;
import com.google.android.gms.common.api.Api;
import org.microg.gms.common.api.ApiClientBuilder;
import org.microg.gms.common.api.ApiClientSettings;
import org.microg.gms.common.api.ConnectionCallbacks;
import org.microg.gms.common.api.OnConnectionFailedListener; | 3,053 | /*
* Copyright (C) 2013-2017 microG Project Team
*
* 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.microg.gms.cast;
public class CastApiClientBuilder implements ApiClientBuilder<Cast.CastOptions> {
@Override | /*
* Copyright (C) 2013-2017 microG Project Team
*
* 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.microg.gms.cast;
public class CastApiClientBuilder implements ApiClientBuilder<Cast.CastOptions> {
@Override | public Api.Client build(Cast.CastOptions options, Context context, Looper looper, ApiClientSettings clientSettings, ConnectionCallbacks callbacks, OnConnectionFailedListener connectionFailedListener) { | 3 | 2023-12-17 16:14:53+00:00 | 4k |
Yolka5/FTC-Imu3 | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/redCheck.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java",
"snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0);\n public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 0, 0);\n\n public static double LATERAL_MULTIPLIER = 1;\n\n public static double VX_WEIGHT = 1;\n public static double VY_WEIGHT = 1;\n public static double OMEGA_WEIGHT = 1;\n\n private TrajectorySequenceRunner trajectorySequenceRunner;\n\n private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);\n private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL);\n\n private TrajectoryFollower follower;\n\n private DcMotorEx leftFront, leftRear, rightRear, rightFront;\n private List<DcMotorEx> motors;\n\n private BNO055IMU imu;\n private VoltageSensor batteryVoltageSensor;\n\n public SampleMecanumDrive(HardwareMap hardwareMap) {\n super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER);\n\n follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID,\n new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);\n\n LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap);\n\n batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next();\n\n for (LynxModule module : hardwareMap.getAll(LynxModule.class)) {\n module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO);\n }\n\n // TODO: adjust the names of the following hardware devices to match your configuration\n imu = hardwareMap.get(BNO055IMU.class, \"imu\");\n BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();\n parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS;\n imu.initialize(parameters);\n\n // TODO: If the hub containing the IMU you are using is mounted so that the \"REV\" logo does\n // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.)\n //\n // | +Z axis\n // |\n // |\n // |\n // _______|_____________ +Y axis\n // / |_____________/|__________\n // / REV / EXPANSION //\n // / / HUB //\n // /_______/_____________//\n // |_______/_____________|/\n // /\n // / +X axis\n //\n // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf\n // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location\n //\n // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y.\n // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y);\n\n leftFront = hardwareMap.get(DcMotorEx.class, \"leftFront\");\n rightRear = hardwareMap.get(DcMotorEx.class, \"rightRear\");\n leftRear = hardwareMap.get(DcMotorEx.class, \"leftRear\");\n rightFront = hardwareMap.get(DcMotorEx.class, \"rightFront\");\n\n\n motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront);\n\n for (DcMotorEx motor : motors) {\n MotorConfigurationType motorConfigurationType = motor.getMotorType().clone();\n motorConfigurationType.setAchieveableMaxRPMFraction(1.0);\n motor.setMotorType(motorConfigurationType);\n }\n\n if (RUN_USING_ENCODER) {\n setMode(DcMotor.RunMode.RUN_USING_ENCODER);\n }\n\n setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);\n\n if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) {\n setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID);\n }\n\n\n // TODO: reverse any motors using DcMotor.setDirection()\n leftFront.setDirection(DcMotorSimple.Direction.REVERSE);\n leftRear.setDirection(DcMotorSimple.Direction.REVERSE);\n\n\n // TODO: if desired, use setLocalizer() to change the localization method\n // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...));\n // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...));\n\n trajectorySequenceRunner = new TrajectorySequenceRunner(follower, HEADING_PID);\n }\n\n public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) {\n return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT);\n }\n\n public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) {\n return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT);\n }\n\n public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) {\n return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT);\n }\n\n public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) {\n return new TrajectorySequenceBuilder(\n startPose,\n VEL_CONSTRAINT, ACCEL_CONSTRAINT,\n MAX_ANG_VEL, MAX_ANG_ACCEL\n );\n }\n\n\n\n public void turnAsync(double angle) {\n trajectorySequenceRunner.followTrajectorySequenceAsync(\n trajectorySequenceBuilder(getPoseEstimate())\n .turn(angle)\n .build()\n );\n }\n\n public void turn(double angle) {\n turnAsync(angle);\n waitForIdle();\n }\n\n public void followTrajectoryAsync(Trajectory trajectory) {\n trajectorySequenceRunner.followTrajectorySequenceAsync(\n trajectorySequenceBuilder(trajectory.start())\n .addTrajectory(trajectory)\n .build()\n );\n }\n\n public void followTrajectory(Trajectory trajectory) {\n followTrajectoryAsync(trajectory);\n waitForIdle();\n }\n\n public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {\n trajectorySequenceRunner.followTrajectorySequenceAsync(trajectorySequence);\n }\n\n public void followTrajectorySequence(TrajectorySequence trajectorySequence) {\n followTrajectorySequenceAsync(trajectorySequence);\n waitForIdle();\n }\n\n public Pose2d getLastError() {\n return trajectorySequenceRunner.getLastPoseError();\n }\n\n public void update() {\n updatePoseEstimate();\n DriveSignal signal = trajectorySequenceRunner.update(getPoseEstimate(), getPoseVelocity());\n if (signal != null) setDriveSignal(signal);\n }\n\n public void waitForIdle() {\n while (!Thread.currentThread().isInterrupted() && isBusy())\n update();\n }\n\n public boolean isBusy() {\n return trajectorySequenceRunner.isBusy();\n }\n\n public void setMode(DcMotor.RunMode runMode) {\n for (DcMotorEx motor : motors) {\n motor.setMode(runMode);\n }\n }\n\n public void setZeroPowerBehavior(DcMotor.ZeroPowerBehavior zeroPowerBehavior) {\n for (DcMotorEx motor : motors) {\n motor.setZeroPowerBehavior(zeroPowerBehavior);\n }\n }\n\n public void setPIDFCoefficients(DcMotor.RunMode runMode, PIDFCoefficients coefficients) {\n PIDFCoefficients compensatedCoefficients = new PIDFCoefficients(\n coefficients.p, coefficients.i, coefficients.d,\n coefficients.f * 12 / batteryVoltageSensor.getVoltage()\n );\n\n for (DcMotorEx motor : motors) {\n motor.setPIDFCoefficients(runMode, compensatedCoefficients);\n }\n }\n\n public void setWeightedDrivePower(Pose2d drivePower) {\n Pose2d vel = drivePower;\n\n if (Math.abs(drivePower.getX()) + Math.abs(drivePower.getY())\n + Math.abs(drivePower.getHeading()) > 1) {\n // re-normalize the powers according to the weights\n double denom = VX_WEIGHT * Math.abs(drivePower.getX())\n + VY_WEIGHT * Math.abs(drivePower.getY())\n + OMEGA_WEIGHT * Math.abs(drivePower.getHeading());\n\n vel = new Pose2d(\n VX_WEIGHT * drivePower.getX(),\n VY_WEIGHT * drivePower.getY(),\n OMEGA_WEIGHT * drivePower.getHeading()\n ).div(denom);\n }\n\n setDrivePower(vel);\n }\n\n @NonNull\n @Override\n public List<Double> getWheelPositions() {\n List<Double> wheelPositions = new ArrayList<>();\n for (DcMotorEx motor : motors) {\n wheelPositions.add(encoderTicksToInches(motor.getCurrentPosition()));\n }\n return wheelPositions;\n }\n\n @Override\n public List<Double> getWheelVelocities() {\n List<Double> wheelVelocities = new ArrayList<>();\n for (DcMotorEx motor : motors) {\n wheelVelocities.add(encoderTicksToInches(motor.getVelocity()));\n }\n return wheelVelocities;\n }\n\n @Override\n public void setMotorPowers(double v, double v1, double v2, double v3) {\n leftFront.setPower(-v);\n leftRear.setPower(-v1);\n rightRear.setPower(v2);\n rightFront.setPower(v3);\n }\n\n @Override\n public double getRawExternalHeading() {\n return imu.getAngularOrientation().firstAngle;\n }\n\n @Override\n public Double getExternalHeadingVelocity() {\n return (double) imu.getAngularVelocity().zRotationRate;\n }\n\n public static TrajectoryVelocityConstraint getVelocityConstraint(double maxVel, double maxAngularVel, double trackWidth) {\n return new MinVelocityConstraint(Arrays.asList(\n new AngularVelocityConstraint(maxAngularVel),\n new MecanumVelocityConstraint(maxVel, trackWidth)\n ));\n }\n\n public static TrajectoryAccelerationConstraint getAccelerationConstraint(double maxAccel) {\n return new ProfileAccelerationConstraint(maxAccel);\n }\n}"
},
{
"identifier": "TrajectorySequence",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java",
"snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> sequenceList) {\n if (sequenceList.size() == 0) throw new EmptySequenceException();\n\n this.sequenceList = Collections.unmodifiableList(sequenceList);\n }\n\n public Pose2d start() {\n return sequenceList.get(0).getStartPose();\n }\n\n public Pose2d end() {\n return sequenceList.get(sequenceList.size() - 1).getEndPose();\n }\n\n public double duration() {\n double total = 0.0;\n\n for (SequenceSegment segment : sequenceList) {\n total += segment.getDuration();\n }\n\n return total;\n }\n\n public SequenceSegment get(int i) {\n return sequenceList.get(i);\n }\n\n public int size() {\n return sequenceList.size();\n }\n}"
}
] | import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.geometry.Vector2d;
import com.acmerobotics.roadrunner.trajectory.Trajectory;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.OpticalDistanceSensor;
import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; | 3,100 | package org.firstinspires.ftc.teamcode;
/*
* This is an example of a more complex path to really test the tuning.
*/
@Autonomous(group = "drive")
public class redCheck extends LinearOpMode {
public static double SPEED = 0.15;
OpticalDistanceSensor lightSensor;
private ColorSensor colorSensor;
Boolean RedFirstTime = false;
public double correction;
public double BlueCorrection;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode;
/*
* This is an example of a more complex path to really test the tuning.
*/
@Autonomous(group = "drive")
public class redCheck extends LinearOpMode {
public static double SPEED = 0.15;
OpticalDistanceSensor lightSensor;
private ColorSensor colorSensor;
Boolean RedFirstTime = false;
public double correction;
public double BlueCorrection;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 0 | 2023-12-15 16:57:19+00:00 | 4k |
Dhananjay-mygithubcode/CRM-PROJECT | src/main/java/com/inn/cafe/serviceImpl/UserServiceImpl.java | [
{
"identifier": "CustomerUserDetailsService",
"path": "src/main/java/com/inn/cafe/JWT/CustomerUserDetailsService.java",
"snippet": "@Slf4j\n@Service\npublic class CustomerUserDetailsService implements UserDetailsService {\n\n @Autowired\n UserDao userDao;\n\n private com.inn.cafe.POJO.User userDatails;\n\n @Override\n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n// log.info(\"Inside loadUserByUsername {}\", username);\n userDatails = userDao.findByEmailId(username);\n if (!Objects.isNull(userDatails)) {\n return new User(userDatails.getEmail(), userDatails.getPassword(), new ArrayList<>());\n } else {\n throw new UsernameNotFoundException(\"User not found\");\n }\n }\n\n public com.inn.cafe.POJO.User getUserDatails() {\n return userDatails;\n }\n}"
},
{
"identifier": "JwtFilter",
"path": "src/main/java/com/inn/cafe/JWT/JwtFilter.java",
"snippet": "@Configuration\npublic class JwtFilter extends OncePerRequestFilter {\n\n @Autowired\n private jwtUtil jwtUtil;\n\n @Autowired\n private CustomerUserDetailsService service;\n\n Claims claims = null;\n private String username = null;\n\n @Override\n protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {\n if (httpServletRequest.getServletPath().matches(\"/user/login|/user/forgetpassword|/user/signup\")) {\n filterChain.doFilter(httpServletRequest, httpServletResponse);\n } else {\n String authorizationHeader = httpServletRequest.getHeader(\"Authorization\");\n String token = null;\n\n if (authorizationHeader != null && authorizationHeader.startsWith(\"Bearer\")) {\n token = authorizationHeader.substring(7);\n username = jwtUtil.extractUsername(token);\n claims = jwtUtil.extractAllClaims(token);\n }\n if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {\n UserDetails userDetails = service.loadUserByUsername(username);\n if (jwtUtil.validatetoken(token, userDetails)) {\n UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =\n new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());\n usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));\n SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);\n }\n }\n filterChain.doFilter(httpServletRequest, httpServletResponse);\n }\n }\n\n public boolean isAdmin() {\n return \"admin\".equalsIgnoreCase((String) claims.get(\"role\"));\n }\n\n public boolean isUser() {\n return \"user\".equalsIgnoreCase((String) claims.get(\"role\"));\n }\n\n public String getCurrentUsername() {\n return username;\n }\n\n\n}"
},
{
"identifier": "jwtUtil",
"path": "src/main/java/com/inn/cafe/JWT/jwtUtil.java",
"snippet": "@Service\npublic class jwtUtil {\n private String secret = \"btechdays\";\n\n public String extractUsername(String token){\n return extractClamis(token , Claims::getSubject);\n }\n\n public Date extractExpiration(String token){\n return extractClamis(token , Claims::getExpiration);\n }\n\n private <T> T extractClamis(String token, Function<Claims, T> claimsResolver) {\n final Claims claims = extractAllClaims(token);\n return claimsResolver.apply(claims);\n\n }\n public Claims extractAllClaims(String token) {\n return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();\n }\n private Boolean isTokenExpired(String token){\n return extractExpiration(token).before(new Date());\n }\n\n public String generateToken(String Username , String role){\n Map<String , Object> claims = new HashMap<>();\n claims.put(\"role\" , role);\n return createtoken(claims, Username);\n }\n private String createtoken(Map<String , Object> claims , String subject){\n return Jwts.builder()\n .setClaims(claims)\n .setSubject(subject)\n .setIssuedAt(new Date(System.currentTimeMillis()))\n .setExpiration(new Date(System.currentTimeMillis() + 1000*60*60*10))\n .signWith(SignatureAlgorithm.HS256,secret).compact();\n }\n public Boolean validatetoken(String token , UserDetails userDetails){\n final String Username = extractUsername(token);\n return (Username.equals(userDetails.getUsername()) && !isTokenExpired(token) );\n }\n\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/inn/cafe/POJO/User.java",
"snippet": "@NamedQuery(name = \"User.findByEmailId\", query = \"select u from User u where u.email=:email\")\n\n@NamedQuery(name = \"User.getAllUser\" , query = \"select new com.inn.cafe.wrapper.UserWrapper(u.id , u.name , u.email , u.contactNumber , u.status) from User u where u.role = 'user'\")\n\n@NamedQuery(name = \"User.getAllAdmin\" , query = \"select u.email from User u where u.role = 'admin'\")\n\n@NamedQuery(name = \"User.updateStatus\" , query = \"update User u set u.status=:status where u.id =:id\")\n\n@Data\n@Entity\n@DynamicUpdate\n@DynamicInsert\n@Table(name = \"user\")\n\npublic class User implements Serializable {\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\")\n private Integer id;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"contactNumber\")\n private String contactNumber;\n\n @Column(name = \"email\")\n private String email;\n\n @Column(name = \"password\")\n private String password;\n @Column(name = \"status\")\n private String status;\n\n @Column(name = \"role\")\n private String role;\n\n public User() {\n\n }\n public User(String name, String contactNumber, String email, String password, String status, String role) {\n this.name = name;\n this.contactNumber = contactNumber;\n this.email = email;\n this.password = password;\n this.status = status;\n this.role = role;\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getContactNumber() {\n return contactNumber;\n }\n\n public void setContactNumber(String contactNumber) {\n this.contactNumber = contactNumber;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", contactNumber='\" + contactNumber + '\\'' +\n \", email='\" + email + '\\'' +\n \", password='\" + password + '\\'' +\n \", status='\" + status + '\\'' +\n \", role='\" + role + '\\'' +\n '}';\n }\n\n}"
},
{
"identifier": "CafeConstants",
"path": "src/main/java/com/inn/cafe/constents/CafeConstants.java",
"snippet": "public class CafeConstants {\n public static final String SOMETHING_WENT_WRONG = \"Something Went Wrong.\";\n\n public static final String INVALID_INFO = \"Invalid Data.\";\n\n public static final String UNAUTHORIZED_ACCESS = \"unauthorized access.\";\n public static final String INVALID_DATA = \"Invalid Data.\";\n public static final String STORE_LOCATION = \"E:\\\\Cafe System\\\\com.inn.cafe\\\\CafeStoredFiles\";\n\n}"
},
{
"identifier": "UserDao",
"path": "src/main/java/com/inn/cafe/dao/UserDao.java",
"snippet": "public interface UserDao extends JpaRepository<User, Integer> {\n User findByEmailId(@Param(\"email\") String email);\n\n\n List<UserWrapper> getAllUser();\n\n @Transactional\n @Modifying\n Integer updateStatus(@Param(\"status\") String status, @Param(\"id\") Integer id);\n\n List<String> getAllAdmin();\n\n User findByEmail(String email);\n\n\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/com/inn/cafe/service/UserService.java",
"snippet": "public interface UserService {\n ResponseEntity<String> signUp(Map<String,String> requestMap);\n\n ResponseEntity<String> login(Map<String, String> requestMap);\n\n ResponseEntity<List<UserWrapper>> getAllUser();\n\n ResponseEntity<String> update(Map<String, String> requestMap);\n\n ResponseEntity<String> checkToken();\n\n ResponseEntity<String> changePassword(Map<String, String> requestMap);\n\n ResponseEntity<String> forgetPassword(Map<String, String> requestMap);\n}"
},
{
"identifier": "CafeUtils",
"path": "src/main/java/com/inn/cafe/utils/CafeUtils.java",
"snippet": "@Slf4j\npublic class CafeUtils {\n public CafeUtils(){\n\n }\n public static ResponseEntity<String> getResponeEntity(String responseMessage , HttpStatus httpStatus){\n return new ResponseEntity<String>(\"{\\\"messag\\\":\\\"\"+responseMessage+\"\\\"}\", httpStatus);\n }\n\n public static String getUUID(){\n Date data = new Date();\n long time = data.getTime();\n return \"BILL\" + time;\n }\n public static JSONArray getJsonArrayFromString(String data) throws JSONException {\n JSONArray jsonArray = new JSONArray(data);\n return jsonArray;\n }\n\n public static Map<String , Object> getMapFromJson(String data){\n if(!Strings.isNullOrEmpty(data))\n return new Gson().fromJson(data , new TypeToken<Map<String , Object>>(){\n }.getType());\n return new HashMap<>();\n }\n\n public static Boolean isFileExist(String path){\n// log.info(\"Inside isFileExist {}\" , path);\n try {\n File file = new File(path);\n return (file != null && file.exists()) ? Boolean.TRUE : Boolean.FALSE;\n\n }catch (Exception ex){\n ex.printStackTrace();\n }\n return false;\n }\n\n}"
},
{
"identifier": "EmailUtil",
"path": "src/main/java/com/inn/cafe/utils/EmailUtil.java",
"snippet": "@Service\npublic class EmailUtil {\n @Autowired\n private JavaMailSender emailSender;\n\n public void SendSimpleMessage(String to , String subject , String text , List<String> list){\n SimpleMailMessage message = new SimpleMailMessage();\n message.setFrom(\"[email protected]\");\n message.setTo(to);\n message.setSubject(subject);\n message.setText(text);\n if(list != null && list.size() > 0)\n message.setCc(getCcArray(list));\n emailSender.send(message);\n }\n\n public String[] getCcArray(List<String> cclist){\n String[] cc = new String[cclist.size()];\n for (int i = 0 ; i < cclist.size(); i++){\n cc[i] = cclist.get(i);\n }\n return cc;\n }\n public void forgetMail(String to , String subject, String password) throws MessagingException {\n MimeMessage message = emailSender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message, true);\n helper.setFrom(\"[email protected]\");\n helper.setTo(to);\n helper.setSubject(subject);\n String htmlMSG = \"<p><b>Your Login details for Cafe Management System</b></p><b>Email:</b>\"+ to + \"<br><b>Password: </b>\" + password + \"<br><a href=\\\"http://localhost:4200/\\\">Click here to login</a></p>\";\n message.setContent(htmlMSG , \"text/html\");\n emailSender.send(message);\n }\n\n}"
},
{
"identifier": "UserWrapper",
"path": "src/main/java/com/inn/cafe/wrapper/UserWrapper.java",
"snippet": "@Data\n@NoArgsConstructor\npublic class UserWrapper {\n private Integer id;\n private String name;\n private String email;\n private String contactNumber;\n private String status;\n\n public UserWrapper(Integer id, String name, String email, String contactNumber, String status) {\n this.id = id;\n this.name = name;\n this.email = email;\n this.contactNumber = contactNumber;\n this.status = status;\n }\n}"
}
] | import com.google.common.base.Strings;
import com.inn.cafe.JWT.CustomerUserDetailsService;
import com.inn.cafe.JWT.JwtFilter;
import com.inn.cafe.JWT.jwtUtil;
import com.inn.cafe.POJO.User;
import com.inn.cafe.constents.CafeConstants;
import com.inn.cafe.dao.UserDao;
import com.inn.cafe.service.UserService;
import com.inn.cafe.utils.CafeUtils;
import com.inn.cafe.utils.EmailUtil;
import com.inn.cafe.wrapper.UserWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.*; | 3,236 | package com.inn.cafe.serviceImpl;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
jwtUtil jwtUtil;
@Autowired | package com.inn.cafe.serviceImpl;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
jwtUtil jwtUtil;
@Autowired | JwtFilter jwtFilter; | 1 | 2023-12-20 11:47:58+00:00 | 4k |
Frig00/Progetto-Ing-Software | src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/service/TitoloViaggioService.java | [
{
"identifier": "TitoloViaggioDao",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/dao/TitoloViaggioDao.java",
"snippet": "public class TitoloViaggioDao implements ITitoloViaggioDao {\n /**\n * Connessione al database mediante il framework di Hibernate\n */\n private HibernateConnection conn;\n\n /**\n * Viene assegnata all'attributo privato conn l'istanza Singleton della connessione di Hibernate al database\n */\n public TitoloViaggioDao() {\n this.conn = HibernateConnection.getInstance();\n }\n\n public HibernateConnection getConn() {\n return conn;\n }\n\n public void setConn(HibernateConnection conn) {\n this.conn = conn;\n }\n\n /**\n * Metodo che implementa la query al database che ritorna tutte le tuple nella table di riferimento\n *\n * @return una lista di TitoloViaggioEntity\n */\n @SuppressWarnings(\"unchecked\")\n public List<TitoloViaggioEntity> findAll() {\n List<TitoloViaggioEntity> titoloViaggioEntities = (List<TitoloViaggioEntity>) conn.getCurrentSession().createQuery(\"from TitoloViaggioEntity \").list();\n return titoloViaggioEntities;\n }\n\n /**\n * Metodo che implementa la query al database che ritorna la tupla che ha il valore di id pari alla stringa passata come parametro\n *\n * @param id stringa che identifica l'id del titolo di viaggio che vogliamo trovare in database\n * @return una TitoloViaggioEntity\n */\n public TitoloViaggioEntity findById(String id) {\n TitoloViaggioEntity titoloViaggioEntity = conn.getCurrentSession().get(TitoloViaggioEntity.class, id);\n return titoloViaggioEntity;\n }\n\n /**\n * Metodo che salva in database la TitoloViaggioEntity passata come parametro\n *\n * @param titoloViaggio\n */\n public void persist(TitoloViaggioEntity titoloViaggio) {\n conn.getCurrentSession().save(titoloViaggio);\n }\n\n /**\n * Metodo che salva le modifiche in database della TitoloViaggioEntity passata come parametro\n *\n * @param titoloViaggio\n */\n public void update(TitoloViaggioEntity titoloViaggio) {\n conn.getCurrentSession().update(titoloViaggio);\n }\n\n /**\n * Metodo che elimina da database la TitoloViaggioEntity passata come parametro\n *\n * @param titoloViaggio\n */\n public void delete(TitoloViaggioEntity titoloViaggio) {\n conn.getCurrentSession().delete(titoloViaggio);\n }\n}"
},
{
"identifier": "TitoloViaggioEntity",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/entity/TitoloViaggioEntity.java",
"snippet": "@Entity\n@Table(name = \"titolo_viaggio\", schema = \"trenissimo\")\npublic class TitoloViaggioEntity {\n //@GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"titolo_viaggio_id\", nullable = false, length = 100)\n private String titoloViaggioId;\n @Basic\n @Column(name = \"stazione_partenza\", nullable = true, length = 45)\n private String stazionePartenza;\n @Basic\n @Column(name = \"stazione_arrivo\", nullable = true, length = 45)\n private String stazioneArrivo;\n @Basic\n @Column(name = \"data_partenza\", nullable = true)\n private Date dataPartenza;\n @Basic\n @Column(name = \"data_arrivo\", nullable = true)\n private Date dataArrivo;\n @Basic\n @Column(name = \"ora_partenza\", nullable = true)\n private Time oraPartenza;\n @Basic\n @Column(name = \"ora_arrivo\", nullable = true)\n private Time oraArrivo;\n @OneToMany(mappedBy = \"titoloViaggioByTitoloViaggioId\")\n private Collection<StoricoAcquistiEntity> storicoAcquistisByTitoloViaggioId;\n @Basic\n @Column(name = \"num_adulti\")\n private Integer numAdulti;\n @Basic\n @Column(name = \"num_ragazzi\")\n private Integer numRagazzi;\n @Basic\n @Column(name = \"num_bambini\")\n private Integer numBambini;\n @Basic\n @Column(name = \"num_animali\")\n private Integer numAnimali;\n\n public String getTitoloViaggioId() {\n return titoloViaggioId;\n }\n\n public void setTitoloViaggioId(String titoloViaggioId) {\n this.titoloViaggioId = titoloViaggioId;\n }\n\n public String getStazionePartenza() {\n return stazionePartenza;\n }\n\n public void setStazionePartenza(String stazionePartenza) {\n this.stazionePartenza = stazionePartenza;\n }\n\n public String getStazioneArrivo() {\n return stazioneArrivo;\n }\n\n public void setStazioneArrivo(String stazioneArrivo) {\n this.stazioneArrivo = stazioneArrivo;\n }\n\n public Date getDataPartenza() {\n return dataPartenza;\n }\n\n public void setDataPartenza(Date dataPartenza) {\n this.dataPartenza = dataPartenza;\n }\n\n public Date getDataArrivo() {\n return dataArrivo;\n }\n\n public void setDataArrivo(Date dataArrivo) {\n this.dataArrivo = dataArrivo;\n }\n\n public Time getOraPartenza() {\n return oraPartenza;\n }\n\n public void setOraPartenza(Time oraPartenza) {\n this.oraPartenza = oraPartenza;\n }\n\n public Time getOraArrivo() {\n return oraArrivo;\n }\n\n public void setOraArrivo(Time oraArrivo) {\n this.oraArrivo = oraArrivo;\n }\n\n public Integer getNumAdulti() {\n return numAdulti;\n }\n\n public void setNumAdulti(Integer numAdulti) {\n this.numAdulti = numAdulti;\n }\n\n public Integer getNumRagazzi() {\n return numRagazzi;\n }\n\n public void setNumRagazzi(Integer numRagazzi) {\n this.numRagazzi = numRagazzi;\n }\n\n public Integer getNumBambini() {\n return numBambini;\n }\n\n public void setNumBambini(Integer numBambini) {\n this.numBambini = numBambini;\n }\n\n public Integer getNumAnimali() {\n return numAnimali;\n }\n\n public void setNumAnimali(Integer numAnimali) {\n this.numAnimali = numAnimali;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n TitoloViaggioEntity that = (TitoloViaggioEntity) o;\n return Objects.equals(titoloViaggioId, that.titoloViaggioId) && Objects.equals(stazionePartenza, that.stazionePartenza) && Objects.equals(stazioneArrivo, that.stazioneArrivo) && Objects.equals(dataPartenza, that.dataPartenza) && Objects.equals(dataArrivo, that.dataArrivo) && Objects.equals(oraPartenza, that.oraPartenza) && Objects.equals(oraArrivo, that.oraArrivo);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(titoloViaggioId, stazionePartenza, stazioneArrivo, dataPartenza, dataArrivo, oraPartenza, oraArrivo);\n }\n\n public Collection<StoricoAcquistiEntity> getStoricoAcquistisByTitoloViaggioId() {\n return storicoAcquistisByTitoloViaggioId;\n }\n\n public void setStoricoAcquistisByTitoloViaggioId(Collection<StoricoAcquistiEntity> storicoAcquistisByTitoloViaggioId) {\n this.storicoAcquistisByTitoloViaggioId = storicoAcquistisByTitoloViaggioId;\n }\n\n /**\n * Converte il biglietto passato per parametro in una TitoloViaggioEntity per permettere il salvataggio delle informazioni in database\n *\n * @param biglietto istanza della classe CorsaSingola\n * @return\n */\n public TitoloViaggioEntity toTitoloViaggioEntity(@NotNull CorsaSingola biglietto) {\n TitoloViaggioEntity titoloViaggioEntity = new TitoloViaggioEntity();\n titoloViaggioEntity.setTitoloViaggioId(biglietto.getId());\n titoloViaggioEntity.setStazionePartenza(biglietto.getViaggio().getStazionePartenza().getStopName());\n titoloViaggioEntity.setStazioneArrivo(biglietto.getViaggio().getStazioneArrivo().getStopName());\n titoloViaggioEntity.setDataPartenza(Date.valueOf(biglietto.getViaggio().getDataPartenza()));\n titoloViaggioEntity.setDataArrivo(Date.valueOf(biglietto.getViaggio().getDataPartenza()));\n titoloViaggioEntity.setOraPartenza(Time.valueOf(Utils.secondsToTime(biglietto.getViaggio().getOrarioPartenza())));\n titoloViaggioEntity.setOraArrivo(Time.valueOf(Utils.secondsToTime(biglietto.getViaggio().getOrarioArrivo())));\n titoloViaggioEntity.setNumAdulti(biglietto.getViaggio().getNumAdulti());\n titoloViaggioEntity.setNumRagazzi(biglietto.getViaggio().getNumRagazzi());\n titoloViaggioEntity.setNumBambini(biglietto.getViaggio().getNumBambini());\n titoloViaggioEntity.setNumAnimali(biglietto.getViaggio().getNumAnimali());\n return titoloViaggioEntity;\n }\n\n @Override\n public String toString() {\n return \"TitoloViaggioEntity{\" +\n \"titoloViaggioId='\" + titoloViaggioId + '\\'' +\n \", stazionePartenza='\" + stazionePartenza + '\\'' +\n \", stazioneArrivo='\" + stazioneArrivo + '\\'' +\n \", dataPartenza=\" + dataPartenza +\n \", dataArrivo=\" + dataArrivo +\n \", oraPartenza=\" + oraPartenza +\n \", oraArrivo=\" + oraArrivo +\n \", numAdulti=\" + numAdulti +\n \", numRagazzi=\" + numRagazzi +\n \", numBambini=\" + numBambini +\n \", numAnimali=\" + numAnimali +\n '}';\n }\n}"
},
{
"identifier": "ITitoloVIaggioService",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/util/service/ITitoloVIaggioService.java",
"snippet": "public interface ITitoloVIaggioService {\n\n List<TitoloViaggioEntity> findAll();\n\n TitoloViaggioEntity findById(String id);\n\n void persist(TitoloViaggioEntity titoloViaggio);\n\n void update(TitoloViaggioEntity titoloViaggio);\n\n void deleteById(String id);\n}"
}
] | import it.unipv.po.aioobe.trenissimo.model.persistence.dao.TitoloViaggioDao;
import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity;
import it.unipv.po.aioobe.trenissimo.model.persistence.util.service.ITitoloVIaggioService;
import java.util.List; | 3,001 | package it.unipv.po.aioobe.trenissimo.model.persistence.service;
/**
* Classe che, secondo il pattern Facade, implementa gli stessi metodi di TitoloViaggioDao con l'aggiunta della gestione delle sessioni del framework Hibernate.
* Classe progettata per nascondere al modello delle classi la complessitร del sistema sottostante (Hibernate)
*
* @author ArrayIndexOutOfBoundsException
*/
public class TitoloViaggioService implements ITitoloVIaggioService {
private static TitoloViaggioDao titoloViaggioDao;
public TitoloViaggioService() {
titoloViaggioDao = new TitoloViaggioDao();
}
@Override | package it.unipv.po.aioobe.trenissimo.model.persistence.service;
/**
* Classe che, secondo il pattern Facade, implementa gli stessi metodi di TitoloViaggioDao con l'aggiunta della gestione delle sessioni del framework Hibernate.
* Classe progettata per nascondere al modello delle classi la complessitร del sistema sottostante (Hibernate)
*
* @author ArrayIndexOutOfBoundsException
*/
public class TitoloViaggioService implements ITitoloVIaggioService {
private static TitoloViaggioDao titoloViaggioDao;
public TitoloViaggioService() {
titoloViaggioDao = new TitoloViaggioDao();
}
@Override | public List<TitoloViaggioEntity> findAll() { | 1 | 2023-12-21 10:41:11+00:00 | 4k |
Workworks/rule-engine-practice | drools-demo/src/test/java/org/kfaino/test/DroolsTest.java | [
{
"identifier": "ComparisonOperatorEntity",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/ComparisonOperatorEntity.java",
"snippet": "public class ComparisonOperatorEntity {\n private String names;\n private List<String> list;\n\n public String getNames() {\n return names;\n }\n\n public void setNames(String names) {\n this.names = names;\n }\n\n public List<String> getList() {\n return list;\n }\n\n public void setList(List<String> list) {\n this.list = list;\n }\n}"
},
{
"identifier": "Order",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/Order.java",
"snippet": "public class Order {\n private Double originalPrice;//่ฎขๅๅๅงไปทๆ ผ๏ผๅณไผๆ ๅไปทๆ ผ\n private Double realPrice;//่ฎขๅ็ๅฎไปทๆ ผ๏ผๅณไผๆ ๅไปทๆ ผ\n\n public String toString() {\n return \"Order{\" +\n \"originalPrice=\" + originalPrice +\n \", realPrice=\" + realPrice +\n '}';\n }\n\n public Double getOriginalPrice() {\n return originalPrice;\n }\n\n public void setOriginalPrice(Double originalPrice) {\n this.originalPrice = originalPrice;\n }\n\n public Double getRealPrice() {\n return realPrice;\n }\n\n public void setRealPrice(Double realPrice) {\n this.realPrice = realPrice;\n }\n}"
},
{
"identifier": "Student",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/Student.java",
"snippet": "public class Student {\n private int id;\n private String name;\n private int age;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n}"
},
{
"identifier": "UserService",
"path": "drools-demo/src/main/java/org/kfaino/drools/service/UserService.java",
"snippet": "public class UserService {\n public void save(){\n System.out.println(\"UserService.save()...\");\n }\n}"
}
] | import org.kfaino.drools.entity.ComparisonOperatorEntity;
import org.kfaino.drools.entity.Order;
import org.kfaino.drools.entity.Student;
import org.kfaino.drools.service.UserService;
import org.drools.core.base.RuleNameEqualsAgendaFilter;
import org.drools.core.base.RuleNameStartsWithAgendaFilter;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
import java.util.ArrayList;
import java.util.List; | 2,495 | package org.kfaino.test;
public class DroolsTest {
@Test
public void test1(){
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//Factๅฏน่ฑก๏ผไบๅฎๅฏน่ฑก
Order order = new Order();
order.setOriginalPrice(500d);
//ๅฐOrderๅฏน่ฑกๆๅ
ฅๅฐๅทฅไฝๅ
ๅญไธญ
session.insert(order);
System.out.println("----ไผๆ ๅไปทๆ ผ๏ผ"+order.getRealPrice());
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
System.out.println("ไผๆ ๅไปทๆ ผ๏ผ"+order.getRealPrice());
}
//ๆต่ฏๆฏ่พๆไฝ็ฌฆ
@Test
public void test2(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//Factๅฏน่ฑก๏ผไบๅฎๅฏน่ฑก
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("ๆๅ");
List<String> list = new ArrayList<String>();
list.add("ๅผ ไธ2");
//list.add("ๆๅ");
fact.setList(list);
session.insert(fact);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏๆง่กๆๅฎ่งๅ
@Test
public void test3(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//Factๅฏน่ฑก๏ผไบๅฎๅฏน่ฑก
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("ๆๅ");
List<String> list = new ArrayList<String>();
list.add("ๅผ ไธ2");
//list.add("ๆๅ");
fact.setList(list);
session.insert(fact);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
//ไฝฟ็จๆกๆถๆไพ็่งๅ่ฟๆปคๅจๆง่กๆๅฎ่งๅ
//session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_comparison_notcontains"));
session.fireAllRules(new RuleNameStartsWithAgendaFilter("rule_"));
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏDroolsๅ
็ฝฎๆนๆณ---update
@Test
public void test4(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(4);
session.insert(student);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏDroolsๅ
็ฝฎๆนๆณ---insert
@Test
public void test5(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(50);
session.insert(student);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏ่งๅๅฑๆงagenda-groupๅฑๆง
@Test
public void test6(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//ๆๅฎ็ป่ทๅพ็ฆ็น
session.getAgenda().getAgendaGroup("agenda_group_1").setFocus();
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏ่งๅๅฑๆงtimerๅฑๆง
@Test
public void test7() throws Exception{
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
final KieSession session = kieContainer.newKieSession();
new Thread(new Runnable() {
public void run() {
//ๅฏๅจ่งๅๅผๆ่ฟ่ก่งๅๅน้
๏ผ็ดๅฐ่ฐ็จhaltๆนๆณๆ็ปๆ่งๅๅผๆ
session.fireUntilHalt();
}
}).start();
Thread.sleep(10000);
//็ปๆ่งๅๅผๆ
session.halt();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏ่งๅๅฑๆงdate-effectiveๅฑๆง
@Test
public void test8(){
//่ฎพ็ฝฎๆฅๆๆ ผๅผ
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_dateeffective_1"));
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏๅ
จๅฑๅ้
@Test
public void test9(){
//่ฎพ็ฝฎๆฅๆๆ ผๅผ
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//่ฎพ็ฝฎๅ
จๅฑๅ้๏ผๅ้ๅ็งฐๅฟ
้กปๅ่งๅๆไปถไธญๅฎไน็ๅ้ๅไธ่ด
session.setGlobal("count",5);
List<String> list = new ArrayList<String>();
list.add("itheima");
session.setGlobal("gList",list);
| package org.kfaino.test;
public class DroolsTest {
@Test
public void test1(){
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//Factๅฏน่ฑก๏ผไบๅฎๅฏน่ฑก
Order order = new Order();
order.setOriginalPrice(500d);
//ๅฐOrderๅฏน่ฑกๆๅ
ฅๅฐๅทฅไฝๅ
ๅญไธญ
session.insert(order);
System.out.println("----ไผๆ ๅไปทๆ ผ๏ผ"+order.getRealPrice());
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
System.out.println("ไผๆ ๅไปทๆ ผ๏ผ"+order.getRealPrice());
}
//ๆต่ฏๆฏ่พๆไฝ็ฌฆ
@Test
public void test2(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//Factๅฏน่ฑก๏ผไบๅฎๅฏน่ฑก
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("ๆๅ");
List<String> list = new ArrayList<String>();
list.add("ๅผ ไธ2");
//list.add("ๆๅ");
fact.setList(list);
session.insert(fact);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏๆง่กๆๅฎ่งๅ
@Test
public void test3(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//Factๅฏน่ฑก๏ผไบๅฎๅฏน่ฑก
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("ๆๅ");
List<String> list = new ArrayList<String>();
list.add("ๅผ ไธ2");
//list.add("ๆๅ");
fact.setList(list);
session.insert(fact);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
//ไฝฟ็จๆกๆถๆไพ็่งๅ่ฟๆปคๅจๆง่กๆๅฎ่งๅ
//session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_comparison_notcontains"));
session.fireAllRules(new RuleNameStartsWithAgendaFilter("rule_"));
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏDroolsๅ
็ฝฎๆนๆณ---update
@Test
public void test4(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(4);
session.insert(student);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏDroolsๅ
็ฝฎๆนๆณ---insert
@Test
public void test5(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(50);
session.insert(student);
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏ่งๅๅฑๆงagenda-groupๅฑๆง
@Test
public void test6(){
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//ๆๅฎ็ป่ทๅพ็ฆ็น
session.getAgenda().getAgendaGroup("agenda_group_1").setFocus();
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏ่งๅๅฑๆงtimerๅฑๆง
@Test
public void test7() throws Exception{
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
final KieSession session = kieContainer.newKieSession();
new Thread(new Runnable() {
public void run() {
//ๅฏๅจ่งๅๅผๆ่ฟ่ก่งๅๅน้
๏ผ็ดๅฐ่ฐ็จhaltๆนๆณๆ็ปๆ่งๅๅผๆ
session.fireUntilHalt();
}
}).start();
Thread.sleep(10000);
//็ปๆ่งๅๅผๆ
session.halt();
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏ่งๅๅฑๆงdate-effectiveๅฑๆง
@Test
public void test8(){
//่ฎพ็ฝฎๆฅๆๆ ผๅผ
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//ๆฟๆดป่งๅ๏ผ็ฑDroolsๆกๆถ่ชๅจ่ฟ่ก่งๅๅน้
๏ผๅฆๆ่งๅๅน้
ๆๅ๏ผๅๆง่กๅฝๅ่งๅ
session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_dateeffective_1"));
//ๅ
ณ้ญไผ่ฏ
session.dispose();
}
//ๆต่ฏๅ
จๅฑๅ้
@Test
public void test9(){
//่ฎพ็ฝฎๆฅๆๆ ผๅผ
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//่ทๅพKieๅฎนๅจๅฏน่ฑก
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//ไปKieๅฎนๅจๅฏน่ฑกไธญ่ทๅไผ่ฏๅฏน่ฑก
KieSession session = kieContainer.newKieSession();
//่ฎพ็ฝฎๅ
จๅฑๅ้๏ผๅ้ๅ็งฐๅฟ
้กปๅ่งๅๆไปถไธญๅฎไน็ๅ้ๅไธ่ด
session.setGlobal("count",5);
List<String> list = new ArrayList<String>();
list.add("itheima");
session.setGlobal("gList",list);
| session.setGlobal("userService",new UserService()); | 3 | 2023-12-21 06:23:04+00:00 | 4k |
SagenApp/gpt-for-uds | src/main/java/app/sagen/chatgptclient/UnixSocketServer.java | [
{
"identifier": "ChatCompletionRequestMessage",
"path": "src/main/java/app/sagen/chatgptclient/data/ChatCompletionRequestMessage.java",
"snippet": "public final class ChatCompletionRequestMessage {\n @SerializedName(\"role\")\n private final String role;\n @SerializedName(\"content\")\n private final String content;\n\n public ChatCompletionRequestMessage(\n String role,\n String content) {\n this.role = role;\n this.content = content;\n }\n\n @SerializedName(\"role\")\n public String role() {\n return role;\n }\n\n @SerializedName(\"content\")\n public String content() {\n return content;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) return true;\n if (obj == null || obj.getClass() != this.getClass()) return false;\n var that = (ChatCompletionRequestMessage) obj;\n return Objects.equals(this.role, that.role) &&\n Objects.equals(this.content, that.content);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(role, content);\n }\n\n @Override\n public String toString() {\n return \"ChatCompletionRequestMessage[\" +\n \"role=\" + role + \", \" +\n \"content=\" + content + ']';\n }\n\n}"
},
{
"identifier": "ChatGptClient",
"path": "src/main/java/app/sagen/chatgptclient/gpt/ChatGptClient.java",
"snippet": "public class ChatGptClient {\n\n private static final String API_URL = \"https://api.openai.com/v1/chat/completions\";\n private final String apiKey;\n private final HttpClient httpClient;\n private final Gson gson;\n\n public ChatGptClient(String apiKey) {\n this.apiKey = apiKey;\n this.httpClient = HttpClient.newHttpClient();\n this.gson = new GsonBuilder().create();\n }\n\n public Stream<ChatCompletionResponseChunk> streamChatCompletions(List<ChatCompletionRequestMessage> messages) {\n JsonElement messagesJsonElement = gson.toJsonTree(messages);\n JsonObject requestBody = new JsonObject();\n requestBody.addProperty(\"model\", \"gpt-4\");\n requestBody.addProperty(\"stream\", true);\n requestBody.add(\"messages\", messagesJsonElement);\n requestBody.addProperty(\"temperature\", 0.7);\n\n HttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(API_URL))\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", \"Bearer \" + apiKey)\n .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))\n .build();\n\n try {\n HttpResponse<InputStream> response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.body()));\n\n // Parse the buffered stream and map to Stream<ChatCompletionResponse>\n return StreamSupport.stream(new JsonIterator(bufferedReader, gson).spliterator(), false);\n\n } catch (IOException e) {\n throw new UncheckedIOException(\"Error sending the request to the API\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new RuntimeException(\"Thread was interrupted while sending the request to the API\", e);\n }\n }\n\n}"
}
] | import app.sagen.chatgptclient.data.ChatCompletionRequestMessage;
import app.sagen.chatgptclient.gpt.ChatGptClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.Type;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List; | 1,607 | package app.sagen.chatgptclient;
public class UnixSocketServer {
private static final Gson gson = new GsonBuilder().create();
private record ServerConfig(Path socketFile, String apiKey) {}
public static ServerConfig parseConfig(String...args) {
String socketFilePath = "/tmp/gpt_socket"; // Default socket file path
String gptApiToken = ""; // GPT API token
// Parse the command-line arguments
if (args.length >= 2) {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--socket-file":
case "-f":
if (i + 1 < args.length) {
socketFilePath = args[++i];
} else {
System.err.println("Expected argument for socket file path");
throw new IllegalStateException("Expected argument for socket file path");
}
break;
case "--gpt-token":
case "-t":
if (i + 1 < args.length) {
gptApiToken = args[++i];
} else {
throw new IllegalStateException("Expected argument for GPT API token");
}
break;
default:
System.err.println("Unexpected argument: " + args[i]);
throw new IllegalStateException("Unexpected argument: " + args[i]);
}
}
} else {
throw new IllegalStateException("Usage: java -jar app.jar -f <socket-file-path> -t <gpt-api-token>");
}
// Verify that the GPT API token is set
if (gptApiToken.isEmpty()) {
throw new IllegalStateException("GPT API token is required");
}
if (socketFilePath.isEmpty()) {
throw new IllegalStateException("Socket file path is required");
}
try {
Path path = Path.of(socketFilePath);
return new ServerConfig(path, gptApiToken);
} catch (Exception e) {
throw new IllegalStateException("Invalid socket file path: " + socketFilePath, e);
}
}
public static void main(String[] args) throws IOException {
ServerConfig serverConfig = parseConfig(args);
// Delete the socket file if it already exists
Files.deleteIfExists(serverConfig.socketFile());
// Create the server socket channel and bind it
try (ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(serverConfig.socketFile());
serverChannel.bind(address);
System.out.println("Server listening on " + serverConfig.socketFile());
ChatGptClient gpt = new ChatGptClient(serverConfig.apiKey());
// Server loop
while (true) {
// Accept an incoming connection
try (SocketChannel socketChannel = serverChannel.accept()) {
System.out.println("Accepted a connection from " + socketChannel.getRemoteAddress());
// Read the length of the incoming message
ByteBuffer inputLengthBuffer = ByteBuffer.allocate(4);
socketChannel.read(inputLengthBuffer);
inputLengthBuffer.flip();
int length = inputLengthBuffer.getInt();
System.out.println("Incoming message length: " + length);
// Allocate a buffer of the specified size to store the incoming message
ByteBuffer messageBuffer = ByteBuffer.allocate(length);
socketChannel.read(messageBuffer);
messageBuffer.flip();
// Convert the ByteBuffer to a String that contains our JSON message
String jsonMessage = new String(messageBuffer.array());
System.out.println("Incoming message: " + jsonMessage);
| package app.sagen.chatgptclient;
public class UnixSocketServer {
private static final Gson gson = new GsonBuilder().create();
private record ServerConfig(Path socketFile, String apiKey) {}
public static ServerConfig parseConfig(String...args) {
String socketFilePath = "/tmp/gpt_socket"; // Default socket file path
String gptApiToken = ""; // GPT API token
// Parse the command-line arguments
if (args.length >= 2) {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--socket-file":
case "-f":
if (i + 1 < args.length) {
socketFilePath = args[++i];
} else {
System.err.println("Expected argument for socket file path");
throw new IllegalStateException("Expected argument for socket file path");
}
break;
case "--gpt-token":
case "-t":
if (i + 1 < args.length) {
gptApiToken = args[++i];
} else {
throw new IllegalStateException("Expected argument for GPT API token");
}
break;
default:
System.err.println("Unexpected argument: " + args[i]);
throw new IllegalStateException("Unexpected argument: " + args[i]);
}
}
} else {
throw new IllegalStateException("Usage: java -jar app.jar -f <socket-file-path> -t <gpt-api-token>");
}
// Verify that the GPT API token is set
if (gptApiToken.isEmpty()) {
throw new IllegalStateException("GPT API token is required");
}
if (socketFilePath.isEmpty()) {
throw new IllegalStateException("Socket file path is required");
}
try {
Path path = Path.of(socketFilePath);
return new ServerConfig(path, gptApiToken);
} catch (Exception e) {
throw new IllegalStateException("Invalid socket file path: " + socketFilePath, e);
}
}
public static void main(String[] args) throws IOException {
ServerConfig serverConfig = parseConfig(args);
// Delete the socket file if it already exists
Files.deleteIfExists(serverConfig.socketFile());
// Create the server socket channel and bind it
try (ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(serverConfig.socketFile());
serverChannel.bind(address);
System.out.println("Server listening on " + serverConfig.socketFile());
ChatGptClient gpt = new ChatGptClient(serverConfig.apiKey());
// Server loop
while (true) {
// Accept an incoming connection
try (SocketChannel socketChannel = serverChannel.accept()) {
System.out.println("Accepted a connection from " + socketChannel.getRemoteAddress());
// Read the length of the incoming message
ByteBuffer inputLengthBuffer = ByteBuffer.allocate(4);
socketChannel.read(inputLengthBuffer);
inputLengthBuffer.flip();
int length = inputLengthBuffer.getInt();
System.out.println("Incoming message length: " + length);
// Allocate a buffer of the specified size to store the incoming message
ByteBuffer messageBuffer = ByteBuffer.allocate(length);
socketChannel.read(messageBuffer);
messageBuffer.flip();
// Convert the ByteBuffer to a String that contains our JSON message
String jsonMessage = new String(messageBuffer.array());
System.out.println("Incoming message: " + jsonMessage);
| Type listType = new TypeToken<List<ChatCompletionRequestMessage>>() {}.getType(); | 0 | 2023-12-18 22:47:47+00:00 | 4k |
TerronesDiaz/easyOnlineShopApiRest | src/main/java/com/example/easyOnlineShop/easyOnlineShop/Service/impl/ProductIMPL.java | [
{
"identifier": "ProductDTO",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Dto/ProductDTO.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ProductDTO {\n\n private long productId;\n private String productName;\n private String productType;\n private ProductStatus productStatus;\n private List<Long> productImageIds;\n}"
},
{
"identifier": "DigitalProduct",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Entity/DigitalProduct.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Entity\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@DiscriminatorValue(\"DIGITAL\")\npublic class DigitalProduct extends Product {\n\n @Column(name = \"file_size\")\n private double fileSize;\n\n @NonNull\n @Column(name = \"format\")\n private String format;\n\n @NonNull\n @Enumerated(EnumType.STRING)\n @Column(name = \"commission_type\")\n private CommissionType commissionType;\n\n @Column(name = \"commission_value\")\n private double commissionValue;\n}"
},
{
"identifier": "PhysicalProduct",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Entity/PhysicalProduct.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Entity\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@DiscriminatorValue(\"PHYSICAL\")\npublic class PhysicalProduct extends Product {\n\n @Column(name = \"weight\")\n private double weight;\n\n @NonNull\n @Column(name = \"dimensions\")\n private String dimensions;\n\n @Column(name = \"cost\")\n private double cost;\n\n @Column(name = \"price\")\n private double price;\n\n @Column(name = \"stock\")\n private int stock;\n\n @Column(name = \"is_perishable\")\n private boolean perishable;\n\n @Column(name = \"expiration_date\")\n private LocalDate expirationDate;\n}"
},
{
"identifier": "Product",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Entity/Product.java",
"snippet": "@Entity\n@Table(name=\"Product\")\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"product_type\", discriminatorType = DiscriminatorType.STRING)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"product_id\")\n private Long productId;\n\n @NonNull\n @Column(name = \"product_name\")\n private String productName;\n\n @NonNull\n @Column(name=\"product_status\")\n private String productStatus;\n\n @OneToMany(mappedBy = \"product\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n private List<ProductImage> productImages = new ArrayList<>();\n}"
},
{
"identifier": "ProductImage",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Entity/ProductImage.java",
"snippet": "@Entity\r\n@Table(name = \"Product_Image\")\r\n@Data\r\n@NoArgsConstructor\r\n@AllArgsConstructor\r\npublic class ProductImage {\r\n\r\n @Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n @Column(name = \"image_id\")\r\n private long imageId;\r\n\r\n @Lob\r\n @Column(name = \"image_url\", nullable = false)\r\n private String imageURL;\r\n\r\n @NonNull\r\n @Column(name = \"image_name\", nullable = false)\r\n private String imageName;\r\n\r\n @ManyToOne\r\n @JoinColumn(name = \"product_id\") // This is the name of the column in table 'Product_Image' that joins the column 'product_id' in 'Product'\r\n private Product product; // Inverse relationship with the entity Product.\r\n\r\n}\r"
},
{
"identifier": "ProductStatus",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Enums/ProductStatus.java",
"snippet": "public enum ProductStatus {\n AVAILABLE,\n DELETED,\n\n}"
},
{
"identifier": "ProductImageRepository",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Repo/ProductImageRepository.java",
"snippet": "@EnableJpaRepositories\n@Repository\npublic interface ProductImageRepository extends JpaRepository<ProductImage, Long> {\n\n}"
},
{
"identifier": "ProductRepository",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Repo/ProductRepository.java",
"snippet": "@EnableJpaRepositories\n@Repository\npublic interface ProductRepository extends JpaRepository<Product, Long> {\n\n}"
},
{
"identifier": "ProductService",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Service/ProductService.java",
"snippet": "public interface ProductService {\n List<ProductDTO> findAllProducts();\n\n String deleteProductById(Long id);\n}"
}
] | import com.example.easyOnlineShop.easyOnlineShop.Dto.ProductDTO;
import com.example.easyOnlineShop.easyOnlineShop.Entity.DigitalProduct;
import com.example.easyOnlineShop.easyOnlineShop.Entity.PhysicalProduct;
import com.example.easyOnlineShop.easyOnlineShop.Entity.Product;
import com.example.easyOnlineShop.easyOnlineShop.Entity.ProductImage;
import com.example.easyOnlineShop.easyOnlineShop.Enums.ProductStatus;
import com.example.easyOnlineShop.easyOnlineShop.Repo.ProductImageRepository;
import com.example.easyOnlineShop.easyOnlineShop.Repo.ProductRepository;
import com.example.easyOnlineShop.easyOnlineShop.Service.ProductService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 1,622 | package com.example.easyOnlineShop.easyOnlineShop.Service.impl;
@Service
@Transactional
public class ProductIMPL implements ProductService {
private final ProductRepository productRepository;
private final ProductImageRepository productImageRepository;
@Autowired
public ProductIMPL(ProductRepository productRepository, ProductImageRepository productImageRepository) {
this.productRepository = productRepository;
this.productImageRepository = productImageRepository;
}
@Override
public List<ProductDTO> findAllProducts() {
// Retrieve all products from the repository and map them to DTOs
return productRepository.findAll().stream()
.map(this::entityToDto)
.collect(Collectors.toList());
}
@Override
public String deleteProductById(Long productId){
if (productId <= 0){
throw new IllegalArgumentException("A valid ID for the product was not provided");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
if(optionalProduct.isPresent()){
Product existingProduct = optionalProduct.get();
existingProduct.setProductStatus(String.valueOf(ProductStatus.DELETED)); // Establecer el estado directamente como enum
productRepository.save(existingProduct); // Guardar el cambio en la base de datos
return "Product successfully marked as deleted";
} else {
return "Product not found";
}
}
// Helper method to convert an entity to a DTO
private ProductDTO entityToDto(Product entity) {
ProductDTO dto = new ProductDTO();
dto.setProductId(entity.getProductId());
dto.setProductName(entity.getProductName());
dto.setProductStatus(ProductStatus.valueOf(entity.getProductStatus()));
if (entity instanceof DigitalProduct) {
dto.setProductType("Digital Product");
} else if (entity instanceof PhysicalProduct) {
dto.setProductType("Physical Product");
}
if (entity.getProductImages() != null) {
// Map image IDs if present
List<Long> imageIds = entity.getProductImages().stream() | package com.example.easyOnlineShop.easyOnlineShop.Service.impl;
@Service
@Transactional
public class ProductIMPL implements ProductService {
private final ProductRepository productRepository;
private final ProductImageRepository productImageRepository;
@Autowired
public ProductIMPL(ProductRepository productRepository, ProductImageRepository productImageRepository) {
this.productRepository = productRepository;
this.productImageRepository = productImageRepository;
}
@Override
public List<ProductDTO> findAllProducts() {
// Retrieve all products from the repository and map them to DTOs
return productRepository.findAll().stream()
.map(this::entityToDto)
.collect(Collectors.toList());
}
@Override
public String deleteProductById(Long productId){
if (productId <= 0){
throw new IllegalArgumentException("A valid ID for the product was not provided");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
if(optionalProduct.isPresent()){
Product existingProduct = optionalProduct.get();
existingProduct.setProductStatus(String.valueOf(ProductStatus.DELETED)); // Establecer el estado directamente como enum
productRepository.save(existingProduct); // Guardar el cambio en la base de datos
return "Product successfully marked as deleted";
} else {
return "Product not found";
}
}
// Helper method to convert an entity to a DTO
private ProductDTO entityToDto(Product entity) {
ProductDTO dto = new ProductDTO();
dto.setProductId(entity.getProductId());
dto.setProductName(entity.getProductName());
dto.setProductStatus(ProductStatus.valueOf(entity.getProductStatus()));
if (entity instanceof DigitalProduct) {
dto.setProductType("Digital Product");
} else if (entity instanceof PhysicalProduct) {
dto.setProductType("Physical Product");
}
if (entity.getProductImages() != null) {
// Map image IDs if present
List<Long> imageIds = entity.getProductImages().stream() | .map(ProductImage::getImageId) | 4 | 2023-12-21 20:13:34+00:00 | 4k |
kavindumal/layered-architecture-kavindu-malshan-jayasinghe | src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private BOFactory(){}\n\n private static BOFactory boFactory;\n\n public static BOFactory getBOFactory() {\n return (boFactory == null) ? boFactory = new BOFactory() : boFactory;\n }\n\n public enum BOType{\n CUSTOMER,ITEM,PLACE_ORDER\n }\n\n public SuperBO getBO(BOType boType){\n switch (boType){\n case CUSTOMER -> {\n return new CustomerBOImpl();\n }\n case ITEM -> {\n return new ItemBOImpl();\n }\n case PLACE_ORDER -> {\n return new PlaceOrderBOImpl();\n }\n default -> {\n return null;\n }\n }\n }\n}"
},
{
"identifier": "ItemBO",
"path": "src/main/java/com/example/layeredarchitecture/bo/ItemBO.java",
"snippet": "public interface ItemBO extends SuperBO{\n public ArrayList<ItemDTO> getAllItem() throws SQLException, ClassNotFoundException;\n public boolean deleteItem(String id) throws SQLException, ClassNotFoundException;\n public boolean saveItem(ItemDTO dto) throws SQLException, ClassNotFoundException;\n public boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException;\n public boolean existItem(String id) throws SQLException, ClassNotFoundException;\n public String generateIDItem() throws SQLException, ClassNotFoundException;\n public ItemDTO searchItem(String newItemCode) throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "ItemBOImpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/ItemBOImpl.java",
"snippet": "public class ItemBOImpl implements ItemBO {\n ItemDAO itemDAO = (ItemDAO) DAOFactory.getDAOFactory().getDAO(DAOFactory.DAOType.ITEM);\n @Override\n public ArrayList<ItemDTO> getAllItem() throws SQLException, ClassNotFoundException {\n return itemDAO.getAll();\n }\n\n @Override\n public boolean deleteItem(String id) throws SQLException, ClassNotFoundException {\n return itemDAO.delete(id);\n }\n\n @Override\n public boolean saveItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return itemDAO.save(dto);\n }\n\n @Override\n public boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return itemDAO.update(dto);\n }\n\n @Override\n public boolean existItem(String id) throws SQLException, ClassNotFoundException {\n return itemDAO.exist(id);\n }\n\n @Override\n public String generateIDItem() throws SQLException, ClassNotFoundException {\n return itemDAO.generateID();\n }\n\n @Override\n public ItemDTO searchItem(String newItemCode) throws SQLException, ClassNotFoundException {\n return itemDAO.search(newItemCode);\n }\n}"
},
{
"identifier": "ItemDAOImpl",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/impl/ItemDAOImpl.java",
"snippet": "public class ItemDAOImpl implements ItemDAO {\n @Override\n public ArrayList<ItemDTO> getAll() throws SQLException, ClassNotFoundException {\n ResultSet rst = SQLUtil.execute(\"SELECT * FROM item\");\n\n ArrayList<ItemDTO> allItems = new ArrayList<>();\n\n while (rst.next()) {\n ItemDTO itemDTO = new ItemDTO(\n rst.getString( 1 ),\n rst.getString( 2 ),\n rst.getInt( 3 ),\n rst.getBigDecimal( 4 )\n );\n allItems.add( itemDTO );\n }\n\n return allItems;\n }\n\n @Override\n public boolean delete(String id) throws SQLException, ClassNotFoundException {\n return SQLUtil.execute(\"DELETE FROM item WHERE code=?\", id);\n }\n\n @Override\n public boolean save(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return SQLUtil.execute(\"INSERT INTO item (code, description, unitPrice, qtyOnHand) VALUES (?,?,?,?)\",\n dto.getCode(),\n dto.getDescription(),\n dto.getQtyOnHand(),\n dto.getUnitPrice());\n }\n\n @Override\n public boolean update(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return SQLUtil.execute(\"UPDATE item SET description=?, unitPrice=?, qtyOnHand=? WHERE code=?\",\n dto.getDescription(),\n dto.getUnitPrice(),\n dto.getQtyOnHand(),\n dto.getCode());\n }\n\n @Override\n public boolean exist(String id) throws SQLException, ClassNotFoundException {\n ResultSet rst = SQLUtil.execute(\"SELECT code FROM item WHERE code=?\", id);\n\n return rst.next();\n }\n\n @Override\n public String generateID() throws SQLException, ClassNotFoundException {\n\n ResultSet rst = SQLUtil.execute(\"SELECT code FROM item ORDER BY code DESC LIMIT 1;\");\n\n if (rst.next()) {\n return rst.getString( 1 );\n }\n\n return null;\n }\n\n @Override\n public ItemDTO search(String newItemCode) throws SQLException, ClassNotFoundException {\n ResultSet rst = SQLUtil.execute(\"SELECT * FROM item WHERE code=?\", (newItemCode + \"\"));\n\n if (rst.next()) {\n return new ItemDTO(\n rst.getString(1),\n rst.getString(2),\n rst.getInt(3),\n rst.getBigDecimal(4)\n );\n }\n\n return null;\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private int qtyOnHand;\n private BigDecimal unitPrice;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, int qtyOnHand, BigDecimal unitPrice) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "ItemTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/ItemTM.java",
"snippet": "public class ItemTM {\n private String code;\n private String description;\n private int qtyOnHand;\n private BigDecimal unitPrice;\n\n public ItemTM() {\n }\n\n public ItemTM(String code, String description, int qtyOnHand, BigDecimal unitPrice) {\n this.code = code;\n this.description = description;\n this.qtyOnHand = qtyOnHand;\n this.unitPrice = unitPrice;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.bo.BOFactory;
import com.example.layeredarchitecture.bo.ItemBO;
import com.example.layeredarchitecture.bo.ItemBOImpl;
import com.example.layeredarchitecture.dao.custom.impl.ItemDAOImpl;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.view.tdm.ItemTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList; | 2,220 | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem; | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem; | ItemBO itemBO = (ItemBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.ITEM); | 1 | 2023-12-16 04:16:50+00:00 | 4k |
chulakasam/layered | src/main/java/com/example/layeredarchitecture/controller/SearchController.java | [
{
"identifier": "CustomerDAO",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/CustomerDAO.java",
"snippet": "public interface CustomerDAO extends CrudDAO<CustomerDTO> {\n /* ArrayList<CustomerDTO> getAll() throws SQLException, ClassNotFoundException ;\n boolean SaveCustomer(String id, String name, String address) throws SQLException, ClassNotFoundException;\n boolean UpdateCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException;\n boolean deleteCustomer(String id) throws SQLException, ClassNotFoundException;\n String generateNextId() throws SQLException, ClassNotFoundException;\n boolean existCustomer(String id) throws SQLException, ClassNotFoundException;\n\n */\n ArrayList<CustomerDTO> loadAllCustomerIds() throws SQLException, ClassNotFoundException ;\n\n}"
},
{
"identifier": "CustomerDAOImpl",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/Impl/CustomerDAOImpl.java",
"snippet": "public class CustomerDAOImpl implements CustomerDAO {\n\n @Override\n public ArrayList<CustomerDTO> getAll() throws SQLException, ClassNotFoundException {\n\n\n ResultSet rst= SQLUtil.test(\"SELECT * FROM Customer\");\n\n ArrayList<CustomerDTO> getAllCustomer = new ArrayList<>();\n\n while (rst.next()) {\n CustomerDTO customerDTO = new CustomerDTO(rst.getString(\"id\"), rst.getString(\"name\"), rst.getString(\"address\"));\n getAllCustomer.add(customerDTO);\n }\n return getAllCustomer;\n }\n @Override\n public boolean Save(CustomerDTO dto) throws SQLException, ClassNotFoundException {\n\n /* Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"INSERT INTO Customer (id,name, address) VALUES (?,?,?)\");\n pstm.setString(1, id);\n pstm.setString(2, name);\n pstm.setString(3, address);\n return pstm.executeUpdate()>0;\n*/\n return SQLUtil.test(\"INSERT INTO Customer (id,name, address) VALUES (?,?,?)\",dto.getId(),dto.getName(),dto.getAddress());\n }\n @Override\n public boolean Update(CustomerDTO dto) throws SQLException, ClassNotFoundException {\n /* Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"UPDATE Customer SET name=?, address=? WHERE id=?\");\n pstm.setString(1, dto.getName());\n pstm.setString(2, dto.getAddress());\n pstm.setString(3, dto.getId());\n return pstm.executeUpdate() > 0;\n\n */\n return SQLUtil.test(\"UPDATE Customer SET name=?, address=? WHERE id=?\",dto.getName(),dto.getAddress(),dto.getId());\n }\n @Override\n public boolean delete(String id) throws SQLException, ClassNotFoundException {\n /*Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"DELETE FROM Customer WHERE id=?\");\n pstm.setString(1, id);\n return pstm.executeUpdate() > 0;\n */\n return SQLUtil.test(\"DELETE FROM Customer WHERE id=?\",id);\n }\n @Override\n public String generateNextId() throws SQLException, ClassNotFoundException {\n /*Connection connection = DBConnection.getDbConnection().getConnection();\n ResultSet rst = connection.createStatement().executeQuery(\"SELECT id FROM Customer ORDER BY id DESC LIMIT 1;\");\n */\n ResultSet rst=SQLUtil.test(\"SELECT id FROM Customer ORDER BY id DESC LIMIT 1\");\n if (rst.next()) {\n String id = rst.getString(\"id\");\n int newCustomerId = Integer.parseInt(id.replace(\"C00-\", \"\")) + 1;\n return String.format(\"C00-%03d\", newCustomerId);\n } else {\n return \"C00-001\";\n }\n }\n @Override\n public boolean exist(String id) throws SQLException, ClassNotFoundException {\n /*\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"SELECT id FROM Customer WHERE id=?\");\n pstm.setString(1, id);\n return pstm.executeQuery().next();\n */\n ResultSet resultSet= SQLUtil.test(\"SELECT id FROM Customer WHERE id=?\",id);\n return resultSet.next();\n }\n\n @Override\n public CustomerDTO search(String id) throws SQLException, ClassNotFoundException {\n\n ResultSet rst = SQLUtil.test(\"SELECT * FROM Customer WHERE id=?\");\n rst.next();\n return new CustomerDTO(id + \"\", rst.getString(\"name\"), rst.getString(\"address\"));\n\n }\n\n\n public ArrayList<CustomerDTO> loadAllCustomerIds() throws SQLException, ClassNotFoundException {\n /* Connection connection = DBConnection.getDbConnection().getConnection();\n Statement stm = connection.createStatement();\n ResultSet rst = stm.executeQuery(\"SELECT * FROM Customer\");\n */\n ResultSet rst =SQLUtil.test(\"SELECT * FROM Customer\");\n\n ArrayList<CustomerDTO> loadAllCus = new ArrayList<>();\n while (rst.next()){\n CustomerDTO customerDTO = new CustomerDTO(rst.getString(\"id\"),rst.getString(\"name\"),rst.getString(\"address\") );\n loadAllCus.add(customerDTO);\n }\n return loadAllCus;\n }\n}"
},
{
"identifier": "QueryDAOImpl",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/Impl/QueryDAOImpl.java",
"snippet": "public class QueryDAOImpl implements QueryDAO {\n\n\n @Override\n public ArrayList<SearchDto> search(String id) throws SQLException, ClassNotFoundException {\n ResultSet rst = SQLUtil.test(\"SELECT c.name, o.oid, o.date FROM Customer c JOIN Orders o on c.id = o.customerID WHERE c.id = ?\",id);\n\n ArrayList<SearchDto> getAllsearch = new ArrayList<>();\n while (rst.next()) {\n SearchDto searchDto = new SearchDto(rst.getString(1), rst.getString(2), rst.getString(3));\n getAllsearch.add(searchDto);\n }\n return getAllsearch;\n }\n\n @Override\n public ArrayList LoadToTable(String id) throws SQLException, ClassNotFoundException {\n\n ResultSet rst=SQLUtil.test(\"SELECT od.oid, o.date, od.itemCode, i.description, od.qty, od.unitPrice FROM OrderDetails od JOIN Item i on od.itemCode = i.code join Orders o on od.oid = o.oid WHERE o.oid = ?\",id);\n ArrayList<TableDTO> getAlldetails = new ArrayList<>();\n\n while (rst.next()) {\n TableDTO tableDTO = new TableDTO(rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4), rst.getString(5), rst.getString(6));\n getAlldetails.add(tableDTO);\n }\n\n\n return getAlldetails;\n }\n\n\n}"
},
{
"identifier": "QueryDAO",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/QueryDAO.java",
"snippet": "public interface QueryDAO extends SuperDAO {\n\n ArrayList<SearchDto> search(String id) throws SQLException, ClassNotFoundException;\n\n\n ArrayList <TableDTO>LoadToTable(String id) throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "SearchDto",
"path": "src/main/java/com/example/layeredarchitecture/model/SearchDto.java",
"snippet": "public class SearchDto {\n private String name;\n private String oid;\n private String date;\n\n public SearchDto() {\n }\n\n public SearchDto(String name, String oid, String date) {\n this.name = name;\n this.oid = oid;\n this.date = date;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n @Override\n public String toString() {\n return \"SearchDto{\" +\n \"name='\" + name + '\\'' +\n \", oid='\" + oid + '\\'' +\n \", date='\" + date + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "TableDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/TableDTO.java",
"snippet": "public class TableDTO {private String oid;\n private String date;\n private String itemcode;\n private String description;\n private String qty;\n private String unitprice;\n\n public TableDTO() {\n }\n\n public TableDTO(String oid, String date, String itemcode, String description, String qty, String unitprice) {\n this.oid = oid;\n this.date = date;\n this.itemcode = itemcode;\n this.description = description;\n this.qty = qty;\n this.unitprice = unitprice;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getItemcode() {\n return itemcode;\n }\n\n public void setItemcode(String itemcode) {\n this.itemcode = itemcode;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getQty() {\n return qty;\n }\n\n public void setQty(String qty) {\n this.qty = qty;\n }\n\n public String getUnitprice() {\n return unitprice;\n }\n\n public void setUnitprice(String unitprice) {\n this.unitprice = unitprice;\n }\n\n @Override\n public String toString() {\n return \"TableDto{\" +\n \"oid='\" + oid + '\\'' +\n \", date='\" + date + '\\'' +\n \", itemcode='\" + itemcode + '\\'' +\n \", description='\" + description + '\\'' +\n \", qty='\" + qty + '\\'' +\n \", unitprice='\" + unitprice + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "TableTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/TableTM.java",
"snippet": "public class TableTM {\n private String code;\n private String description;\n private String qty;\n private String unitPrice;\n\n\n\n public TableTM() {\n }\n\n public TableTM(String code, String description, String qty, String unitPrice) {\n this.code = code;\n this.description = description;\n this.qty = qty;\n this.unitPrice = unitPrice;\n\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getQty() {\n return qty;\n }\n\n public void setQty(String qty) {\n this.qty = qty;\n }\n\n public String getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(String unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n\n\n @Override\n public String toString() {\n return \"TableTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", qty='\" + qty + '\\'' +\n \", unitPrice='\" + unitPrice + '\\'' +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.dao.custom.CustomerDAO;
import com.example.layeredarchitecture.dao.custom.Impl.CustomerDAOImpl;
import com.example.layeredarchitecture.dao.custom.Impl.QueryDAOImpl;
import com.example.layeredarchitecture.dao.custom.QueryDAO;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.SearchDto;
import com.example.layeredarchitecture.model.TableDTO;
import com.example.layeredarchitecture.view.tdm.TableTM;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList; | 3,598 | package com.example.layeredarchitecture.controller;
public class SearchController {
public AnchorPane root;
public TableColumn colCode;
public TableColumn colQty;
public TableColumn colUnitPrice;
public JFXComboBox cmbcusId;
public Label lblName;
public Label lblDate;
public JFXComboBox cmbOrderId;
public JFXComboBox cmbCode;
public TableView <TableTM> tblOrderDetail;
public TableColumn colDesc;
QueryDAO queryDAO=new QueryDAOImpl();
CustomerDAO customerDAO=new CustomerDAOImpl();
public void btnBackToHome(ActionEvent actionEvent) throws IOException {
URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml");
Parent root = FXMLLoader.load(resource);
Scene scene = new Scene(root);
Stage primaryStage = (Stage) (this.root.getScene().getWindow());
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
Platform.runLater(() -> primaryStage.sizeToScene());
}
private void loadallcustomerIds() {
try {
ArrayList<CustomerDTO> allCustomers = customerDAO.getAll();
for (CustomerDTO c : allCustomers) {
cmbcusId.getItems().add(c.getId());
}
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void initialize(){
loadallcustomerIds();
}
public void cusIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbcusId.getValue();
cmbOrderId.getItems().clear();
try {
ArrayList<SearchDto> dtolist = queryDAO.search(id);
for (SearchDto c : dtolist) {
cmbOrderId.getItems().add(c.getOid());
lblName.setText(c.getName());
lblDate.setText(c.getDate());
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public void orderIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbOrderId.getValue();
try {
tblOrderDetail.getItems().clear(); | package com.example.layeredarchitecture.controller;
public class SearchController {
public AnchorPane root;
public TableColumn colCode;
public TableColumn colQty;
public TableColumn colUnitPrice;
public JFXComboBox cmbcusId;
public Label lblName;
public Label lblDate;
public JFXComboBox cmbOrderId;
public JFXComboBox cmbCode;
public TableView <TableTM> tblOrderDetail;
public TableColumn colDesc;
QueryDAO queryDAO=new QueryDAOImpl();
CustomerDAO customerDAO=new CustomerDAOImpl();
public void btnBackToHome(ActionEvent actionEvent) throws IOException {
URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml");
Parent root = FXMLLoader.load(resource);
Scene scene = new Scene(root);
Stage primaryStage = (Stage) (this.root.getScene().getWindow());
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
Platform.runLater(() -> primaryStage.sizeToScene());
}
private void loadallcustomerIds() {
try {
ArrayList<CustomerDTO> allCustomers = customerDAO.getAll();
for (CustomerDTO c : allCustomers) {
cmbcusId.getItems().add(c.getId());
}
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void initialize(){
loadallcustomerIds();
}
public void cusIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbcusId.getValue();
cmbOrderId.getItems().clear();
try {
ArrayList<SearchDto> dtolist = queryDAO.search(id);
for (SearchDto c : dtolist) {
cmbOrderId.getItems().add(c.getOid());
lblName.setText(c.getName());
lblDate.setText(c.getDate());
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public void orderIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbOrderId.getValue();
try {
tblOrderDetail.getItems().clear(); | ArrayList<TableDTO> details = queryDAO.LoadToTable(id); | 6 | 2023-12-15 04:45:10+00:00 | 4k |
pan2013e/ppt4j | framework/src/main/java/ppt4j/analysis/patch/CrossMatcher.java | [
{
"identifier": "Extractor",
"path": "framework/src/main/java/ppt4j/feature/Extractor.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface Extractor extends Serializable {\n\n void parse();\n\n default void print() {\n getFeaturesMap().values().forEach(System.out::println);\n }\n\n default void print(int line) {\n getFeaturesMap().keySet().stream()\n .filter(l -> l == line)\n .map(getFeaturesMap()::get)\n .forEach(System.out::println);\n }\n\n Map<Integer, Features> getFeaturesMap();\n\n String getClassName();\n\n Features.SourceType getSourceType();\n\n}"
},
{
"identifier": "Features",
"path": "framework/src/main/java/ppt4j/feature/Features.java",
"snippet": "@Getter\npublic class Features implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n public enum SourceType {\n JAVA, BYTECODE\n }\n\n @SuppressWarnings(\"SpellCheckingInspection\")\n public enum InstType {\n THROW, MONITOR, SWITCH, INSTANCEOF, RETURN, LOOP,\n BRLT, BRLE, BRGT, BRGE, SHL, SHR, USHR\n }\n\n @Property(\"ppt4j.features.similarity.threshold\")\n private static double SIM_THRESHOLD;\n\n @Property(\"ppt4j.features.similarity.algorithm\")\n private static String SIM_ALGORITHM;\n\n protected final SourceType sourceType;\n\n protected String className;\n protected int lineNo;\n\n protected final Set<Object> Constants = new HashSet<>();\n protected final Set<String> MethodInvocations = new HashSet<>();\n protected final Set<String> FieldAccesses = new HashSet<>();\n protected final Set<String> ObjCreations = new HashSet<>();\n protected final Set<InstType> Instructions = new HashSet<>();\n protected final Set<String> Misc = new HashSet<>();\n\n protected Features(@NonNull SourceType sourceType,\n @NonNull String className, int lineNo) {\n this.sourceType = sourceType;\n this.className = className;\n this.lineNo = lineNo;\n }\n\n public boolean isEmpty() {\n return Constants.isEmpty() &&\n MethodInvocations.isEmpty() &&\n FieldAccesses.isEmpty() &&\n ObjCreations.isEmpty() &&\n Instructions.isEmpty() &&\n Misc.isEmpty();\n }\n\n public int size() {\n return Constants.size() +\n MethodInvocations.size() +\n FieldAccesses.size() +\n ObjCreations.size() +\n Instructions.size() +\n Misc.size();\n }\n\n @Override\n public String toString() {\n String constants = String.format(\"Constants: %s\\n\",\n StringUtils.printSet(Constants, true, true));\n String methodInvocations = String.format(\"Method Invocations: %s\\n\",\n StringUtils.printSet(MethodInvocations));\n String fieldAccesses = String.format(\"Field Accesses: %s\\n\",\n StringUtils.printSet(FieldAccesses));\n String objCreations = String.format(\"Object Creations: %s\\n\",\n StringUtils.printSet(ObjCreations));\n String instructions = String.format(\"Instructions: %s\\n\",\n StringUtils.printSet(Instructions));\n String misc = String.format(\"Misc: %s\\n\",\n StringUtils.printSet(Misc));\n return constants + methodInvocations + fieldAccesses\n + objCreations + instructions + misc;\n }\n\n @Override\n public boolean equals(Object rhs) {\n if(rhs == null) return false;\n if(!(rhs instanceof Features _rhs)) return false;\n return FeatureMatcher.get(SIM_ALGORITHM).isMatch(this, _rhs, SIM_THRESHOLD);\n }\n\n}"
},
{
"identifier": "BytecodeExtractor",
"path": "framework/src/main/java/ppt4j/feature/bytecode/BytecodeExtractor.java",
"snippet": "@SuppressWarnings(\"unused\")\n@Log4j\npublic final class BytecodeExtractor implements Extractor {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Property(\"org.objectweb.asm.api\")\n private static int ASM_API;\n\n private transient final ClassNode root;\n\n @Getter\n private final Map<String, BytecodeExtractor>\n innerClasses = new HashMap<>();\n\n @Getter\n private final Map<Integer, Features> featuresMap = new TreeMap<>();\n\n private transient final Map<Integer, List<AbstractInsnNode>>\n aggInstMap = new TreeMap<>();\n\n @Getter\n private transient final Map<MethodInsnNode, String>\n methodDescMap = new HashMap<>();\n\n @Getter\n private transient final Set<AbstractInsnNode>\n backwardBranches = new HashSet<>();\n\n private boolean isParsed = false;\n\n @Getter\n private final String className;\n\n public BytecodeExtractor(\n @NonNull InputStream inputStream) throws IOException {\n this(new ClassReader(inputStream));\n }\n\n public BytecodeExtractor(@NonNull String classFile) throws IOException {\n this(new FileInputStream(StringUtils.resolvePath(classFile)));\n }\n\n public BytecodeExtractor(@NonNull ClassReader classReader) {\n root = new ClassNode(ASM_API);\n classReader.accept(root, ClassReader.EXPAND_FRAMES);\n className = root.name;\n }\n\n private BytecodeExtractor() {\n this.root = null;\n className = \"fake\";\n }\n\n public static BytecodeExtractor nil() {\n return new BytecodeExtractor();\n }\n\n @Override\n public void parse() {\n if (isParsed) {\n return;\n }\n root.methods.forEach(m -> {\n if (AsmUtils.isNative(m.access) || AsmUtils.isAbstract(m.access)) {\n log.debug(\"Skipping native or abstract method: \" + m.name);\n } else {\n if(!AsmUtils.hasLineNumberInfo(m)) {\n log.warn(\"Method \" + m.name + \" does not have line number info, skipping\");\n } else {\n new ArgTypeAnalysis(className, m, methodDescMap).analyze();\n new LoopAnalysis(className, m, backwardBranches).analyze();\n cluster(m.instructions, aggInstMap);\n }\n }\n });\n MethodNode clinit = null;\n for (MethodNode method : root.methods) {\n if(method.name.equals(\"<clinit>\")) {\n clinit = method;\n break;\n }\n }\n Map<Integer, List<AbstractInsnNode>> clinitMap = new TreeMap<>();\n if(clinit != null) {\n cluster(clinit.instructions, clinitMap);\n }\n AtomicInteger idx = new AtomicInteger(0);\n aggInstMap.forEach((line, insts) -> {\n Features features = new BytecodeFeatures(\n className, insts, line, idx.get(), this);\n if(clinitMap.containsKey(line)) {\n features.getInstructions().remove(Features.InstType.RETURN);\n }\n featuresMap.put(idx.get(), features);\n idx.incrementAndGet();\n });\n isParsed = true;\n }\n\n public void putInnerClass(@NonNull BytecodeExtractor ex) {\n ex.parse();\n innerClasses.put(ex.getClassName(), ex);\n }\n\n public BytecodeExtractor getInnerClass(@NonNull String className) {\n return innerClasses.get(className);\n }\n\n @Override\n public Features.SourceType getSourceType() {\n return Features.SourceType.BYTECODE;\n }\n\n @Override\n public void print() {\n if(root == null) {\n System.out.println(\"nil extractor\");\n } else {\n getFeaturesMap().values().forEach(System.out::println);\n innerClasses.values().forEach(Extractor::print);\n }\n }\n\n private void cluster(InsnList insts,\n Map<Integer, List<AbstractInsnNode>> map) {\n Iterator<AbstractInsnNode> it = insts.iterator();\n List<AbstractInsnNode> insnList = null;\n while (it.hasNext()) {\n AbstractInsnNode node = it.next();\n if(node instanceof LabelNode || node instanceof FrameNode) {\n continue;\n }\n if(node instanceof LineNumberNode lnn) {\n int line = lnn.line;\n if(map.containsKey(line)) {\n insnList = map.get(line);\n } else {\n insnList = new ArrayList<>();\n map.put(line, insnList);\n }\n } else {\n if(insnList == null) {\n throw new IllegalStateException(\n \"No line number node found\");\n }\n insnList.add(node);\n }\n }\n }\n\n}"
},
{
"identifier": "JavaExtractor",
"path": "framework/src/main/java/ppt4j/feature/java/JavaExtractor.java",
"snippet": "@SuppressWarnings(\"unused\")\n@Log4j\npublic final class JavaExtractor implements Extractor {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private transient final CtClass<?> root;\n\n @Getter\n private final Map<String, JavaExtractor>\n innerClasses = new HashMap<>();\n\n @Getter\n private final Map<Integer, Features> featuresMap = new TreeMap<>();\n\n private boolean isParsed = false;\n\n @Getter\n private final String className;\n\n @Getter\n private final String superClassName;\n\n private final Set<Integer> validLines = new HashSet<>();\n\n private final Map<Integer, Integer> splitLinesToLogical = new TreeMap<>();\n\n public JavaExtractor(InputStream inputStream)\n throws IOException {\n this(Launcher.parseClass(new String(inputStream.readAllBytes())));\n }\n\n public JavaExtractor(String path)\n throws IOException {\n this(new FileInputStream(path));\n }\n\n public JavaExtractor(CtClass<?> clazz) {\n String superClassName1;\n this.root = clazz;\n this.className = clazz.getQualifiedName().replace('.', '/');\n CtTypeReference<?> superClass = clazz.getSuperclass();\n if(superClass != null) {\n superClassName1 = superClass.getQualifiedName().replace('.', '/');\n } else {\n superClassName1 = null;\n }\n this.superClassName = superClassName1;\n }\n\n public JavaExtractor(ClassFactory factory, String className) {\n this(factory.get(className));\n }\n\n private JavaExtractor() {\n root = null;\n className = \"fake\";\n superClassName = \"fake\";\n }\n\n public static JavaExtractor nil() {\n return new JavaExtractor();\n }\n\n @Override\n public Features.SourceType getSourceType() {\n return Features.SourceType.JAVA;\n }\n\n @Override\n public void parse() {\n if (isParsed) {\n return;\n }\n root.getFields().forEach(this::parseField);\n root.getElements(new LineFilter()).forEach(this::parseLine);\n root.getNestedTypes().forEach(ty -> {\n if (ty instanceof CtClass _class) {\n\n JavaExtractor ex = new JavaExtractor(_class);\n innerClasses.put(ex.getClassName(), ex);\n }\n });\n root.getElements(new AnonymousClassFilter()).forEach(ty -> {\n CtClass<?> _class = ty.getAnonymousClass();\n JavaExtractor ex = new JavaExtractor(_class);\n innerClasses.put(ex.getClassName(), ex);\n });\n innerClasses.values().forEach(JavaExtractor::parse);\n isParsed = true;\n }\n\n public Collection<JavaExtractor> getInnerClass() {\n return innerClasses.values();\n }\n\n @SuppressWarnings(\"BooleanMethodIsAlwaysInverted\")\n public boolean isValidLine(int line) {\n return validLines.contains(line);\n }\n\n public int getLogicalLine(int line) {\n if(!splitLinesToLogical.containsKey(line)) {\n return -1;\n }\n return splitLinesToLogical.get(line);\n }\n\n private <T> void parseField(CtField<T> field) {\n if(field.getPosition().equals(SourcePosition.NOPOSITION)) {\n return;\n }\n CtFieldReference<T> fieldRef = field.getReference();\n CtTypeReference<T> fieldTypeRef = fieldRef.getType();\n CtExpression<T> assignment = field.getAssignment();\n ConstPropAnalysis<?> analysis = new ConstPropAnalysis<>(assignment);\n analysis.analyze();\n if(!analysis.isLiteral()) {\n String fieldAccess =\n StringUtils.convertQualifiedName(fieldRef.getQualifiedName(), root.getQualifiedName())\n + \":\" + StringUtils.convertToDescriptor(fieldTypeRef.getQualifiedName());\n JavaFeatures features;\n if(assignment instanceof CtStatement stmt) {\n features = new JavaFeatures(root.getQualifiedName(), stmt);\n features.getFieldAccesses().add(fieldAccess);\n putSplitLines(features);\n validLines.add(stmt.getPosition().getLine());\n putFeatures(stmt.getPosition().getLine(), features);\n }\n } else {\n LibraryConstants.put(fieldRef.getQualifiedName(), analysis.getLiteral().getValue());\n }\n }\n\n private void parseLine(CtStatement stmt) {\n if(stmt.getPosition().equals(SourcePosition.NOPOSITION)) {\n return;\n }\n try {\n JavaFeatures features = new JavaFeatures(root.getQualifiedName(), stmt);\n String text = features.getText();\n if(text.equals(\"do\") || text.equals(\"else\") || text.equals(\"try\")) {\n return;\n }\n putSplitLines(features);\n validLines.add(stmt.getPosition().getLine());\n putFeatures(stmt.getPosition().getLine(), features);\n } catch (IllegalStateException e) {\n // comment in a single line\n }\n }\n\n private void putSplitLines(JavaFeatures features) {\n List<Integer> splitLines = features.getSplitLines();\n int baseLine = splitLines.get(0);\n for (Integer line : splitLines) {\n splitLinesToLogical.put(line, baseLine);\n }\n }\n\n private void putFeatures(int line, JavaFeatures features) {\n if(featuresMap.containsKey(line)) {\n JavaFeatures old = (JavaFeatures) featuresMap.get(line);\n old.merge(features);\n } else {\n featuresMap.put(line, features);\n }\n }\n\n}"
},
{
"identifier": "SourceType",
"path": "framework/src/main/java/ppt4j/feature/Features.java",
"snippet": "public enum SourceType {\n JAVA, BYTECODE\n}"
}
] | import ppt4j.feature.Extractor;
import ppt4j.feature.Features;
import ppt4j.feature.bytecode.BytecodeExtractor;
import ppt4j.feature.java.JavaExtractor;
import org.apache.commons.lang3.tuple.Pair;
import static ppt4j.feature.Features.SourceType; | 3,466 | package ppt4j.analysis.patch;
@SuppressWarnings("unused")
public interface CrossMatcher {
SourceType getKeyType();
SourceType getValueType();
boolean isMatched(int index);
double getScore(int index);
Pair<Integer, Integer> getMatchedRange(int index);
Features query(int index);
| package ppt4j.analysis.patch;
@SuppressWarnings("unused")
public interface CrossMatcher {
SourceType getKeyType();
SourceType getValueType();
boolean isMatched(int index);
double getScore(int index);
Pair<Integer, Integer> getMatchedRange(int index);
Features query(int index);
| static CrossMatcher get(JavaExtractor k, Extractor v, boolean diffType) { | 3 | 2023-12-14 15:33:50+00:00 | 4k |
iagolirapasssos/chatGPTAndDallE | chatgpt/ChatGPT.java | [
{
"identifier": "DallEModel",
"path": "chatgpt/helpers/DallEModel.java",
"snippet": "public enum DallEModel implements OptionList<String> {\n DALL_E_2(\"dall-e-2\"),\n DALL_E_3(\"dall-e-3\");\n\n private String model;\n\n DallEModel(String model) {\n this.model = model;\n }\n\n public String toUnderlyingValue() {\n return model;\n }\n\n private static final Map<String, DallEModel> lookup = new HashMap<>();\n\n static {\n for (DallEModel model : DallEModel.values()) {\n lookup.put(model.toUnderlyingValue(), model);\n }\n }\n\n public static DallEModel fromUnderlyingValue(String model) {\n return lookup.getOrDefault(model, DALL_E_2); // Default to DALL_E_3 if not found\n }\n}"
},
{
"identifier": "ImageSize",
"path": "chatgpt/helpers/ImageSize.java",
"snippet": "public enum ImageSize implements OptionList<String> {\n SIZE_1024x1024(\"1024x1024\"),\n SIZE_1024x1792(\"1024x1792\"),\n SIZE_1792x1024(\"1792x1024\");\n\n private String size;\n\n ImageSize(String size) {\n this.size = size;\n }\n\n public String toUnderlyingValue() {\n return size;\n }\n\n private static final Map<String, ImageSize> lookup = new HashMap<>();\n\n static {\n for (ImageSize imageSize : ImageSize.values()) {\n lookup.put(imageSize.toUnderlyingValue(), imageSize);\n }\n }\n\n public static ImageSize fromUnderlyingValue(String size) {\n return lookup.getOrDefault(size, SIZE_1024x1024);\n }\n}"
},
{
"identifier": "VoiceModel",
"path": "chatgpt/helpers/VoiceModel.java",
"snippet": "public enum VoiceModel implements OptionList<String> {\n ALLOY(\"alloy\"),\n ECHO(\"echo\"),\n FABLE(\"fable\"),\n ONYX(\"onyx\"),\n NOVA(\"nova\"),\n SHIMMER(\"shimmer\");\n\n private String voice;\n\n VoiceModel(String voice) {\n this.voice = voice;\n }\n\n @Override\n public String toUnderlyingValue() {\n return voice;\n }\n\n private static final Map<String, VoiceModel> lookup = new HashMap<>();\n\n static {\n for (VoiceModel voice : VoiceModel.values()) {\n lookup.put(voice.toUnderlyingValue(), voice);\n }\n }\n\n public static VoiceModel fromUnderlyingValue(String voice) {\n return lookup.getOrDefault(voice, ALLOY); // Default to ALLOY if not found\n }\n}"
},
{
"identifier": "AudioQuality",
"path": "chatgpt/helpers/AudioQuality.java",
"snippet": "public enum AudioQuality implements OptionList<String> {\n TTS1(\"tts-1\"),\n TTS1HD(\"tts-1-hd\");\n\n private String voice;\n\n AudioQuality(String voice) {\n this.voice = voice;\n }\n\n @Override\n public String toUnderlyingValue() {\n return voice;\n }\n\n private static final Map<String, AudioQuality> lookup = new HashMap<>();\n\n static {\n for (AudioQuality voice : AudioQuality.values()) {\n lookup.put(voice.toUnderlyingValue(), voice);\n }\n }\n\n public static AudioQuality fromUnderlyingValue(String voice) {\n return lookup.getOrDefault(voice, TTS1); // Default to TTS1 if not found\n }\n}"
},
{
"identifier": "AudioFormats",
"path": "chatgpt/helpers/AudioFormats.java",
"snippet": "public enum AudioFormats implements OptionList<String> {\n MP3(\"mp3\"),\n OPUS(\"opus\"),\n AAC(\"aac\"),\n FLAC(\"flac\");\n\n private String voice;\n\n AudioFormats(String voice) {\n this.voice = voice;\n }\n\n @Override\n public String toUnderlyingValue() {\n return voice;\n }\n\n private static final Map<String, AudioFormats> lookup = new HashMap<>();\n\n static {\n for (AudioFormats voice : AudioFormats.values()) {\n lookup.put(voice.toUnderlyingValue(), voice);\n }\n }\n\n public static AudioFormats fromUnderlyingValue(String voice) {\n return lookup.getOrDefault(voice, MP3); // Default to MP3 if not found\n }\n}"
}
] | import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.common.*;
import com.google.appinventor.components.common.OptionList;
import com.google.appinventor.components.runtime.util.YailList;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.annotations.SimpleEvent;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import com.bosonshiggs.chatgpt.helpers.DallEModel;
import com.bosonshiggs.chatgpt.helpers.ImageSize;
import com.bosonshiggs.chatgpt.helpers.VoiceModel;
import com.bosonshiggs.chatgpt.helpers.AudioQuality;
import com.bosonshiggs.chatgpt.helpers.AudioFormats;
import android.os.Environment;
import android.media.MediaScannerConnection;
import android.util.Log;
import android.app.AlertDialog;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.view.ViewGroup;
import android.graphics.drawable.ColorDrawable;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.SeekBar;
import android.os.Handler; | 3,389 |
// Configuraรงรฃo de layout para o EditText
if (isFullScreen) {
builder.setView(input);
} else {
int margin = 30; // Margem em pixels (ajuste conforme necessรกrio)
FrameLayout frameLayout = new FrameLayout(container.$context());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(margin, margin, margin, margin);
input.setLayoutParams(params);
frameLayout.addView(input);
builder.setView(frameLayout);
}
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botรตes ao diรกlogo
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
if (showOkButton) {
dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String enteredText = input.getText().toString();
TextEntered(enteredText, type);
}
});
}
// Configurar cor de fundo do diรกlogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diรกlogo
dialog.show();
}
@SimpleFunction(description = "Shows a dialog with a list of items.")
public void ShowListDialog(
String title,
YailList items,
final int textColor,
final int listItemBackgroundColor,
final int dialogBackgroundColor,
final boolean isFullScreen,
final boolean showCancelButton,
final String type
) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
builder.setTitle(title);
// Converte YailList para array de Strings
final String[] itemsArray = items.toStringArray();
// Criar ArrayAdapter personalizado
ArrayAdapter<String> adapter = new ArrayAdapter<String>(container.$context(), android.R.layout.simple_list_item_1, itemsArray) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView item = (TextView) super.getView(position, convertView, parent);
item.setTextColor(textColor); // Define a cor do texto
item.setBackgroundColor(listItemBackgroundColor); // Define a cor de fundo
return item;
}
};
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = itemsArray[which];
ListItemSelected(selectedItem, type);
}
});
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botรฃo de cancelamento, se necessรกrio
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
// Configurar cor de fundo do diรกlogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
if (isFullScreen) {
// Aplica a cor de fundo para o modo tela cheia
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diรกlogo
dialog.show();
}
@SimpleFunction(description = "Generate speech from text")
public void GenerateSpeech(
final String prompt,
final String apiKey,
final String audioName,
final String directoryName, | /*
* ChatGPT
* Extension to use OpenAI's ChatGPT API
* Version: 1.0
* Author: Francisco Iago Lira Passos
* Date: 2023-10-15
*/
package com.bosonshiggs.chatgpt;
//Auxiliar methods Dialogs
@DesignerComponent(version = 6, // Update version here, You must do for each new release to upgrade your extension
description = "Extension to use Openai's API",
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = "images/extension.png") // Change your extension's icon from here; can be a direct url
@SimpleObject(external = true)
public class ChatGPT extends AndroidNonvisibleComponent {
private String LOG_NAME = "ChatGPT";
private boolean flagLog = false;
private ComponentContainer container;
public ChatGPT(ComponentContainer container) {
super(container.$form());
this.container = container;
}
@SimpleFunction(description = "Extract Value from JSON Text")
public String jsonDecode(final String jsonText, final String key) {
try {
// Converter o JSON em um objeto JSON
JSONObject jsonObject = new JSONObject(jsonText);
// Use a funรงรฃo auxiliar para buscar o valor da chave no objeto JSON
String value = findValueForKey(jsonObject, key);
if (value != null) {
return value;
} else {
return "Error! Key not found!";
}
} catch (JSONException e) {
ReportError(e.getMessage());
return "Error: " + e.getMessage();
}
}
@SimpleFunction(description = "Send a prompt to ChatGPT")
public void SendPrompt(final String prompt, final String model, final String systemMsg, final float temperature, final String apiKey) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendRequest(prompt, model, systemMsg, temperature, apiKey);
if (responseText != null) {
ResponseReceived(responseText);
} else {
ReportError("None");
}
}
}).start();
}
@SimpleFunction(description = "Generate an image based on a prompt")
public void GenerateImage(
String prompt,
int numberOfImages,
String apiKey,
@Options(DallEModel.class) String model,
@Options(ImageSize.class) String size
)
{
/*
DallEModel model = DallEModel.fromUnderlyingValue(dalleModel);
ImageSize size = ImageSize.fromUnderlyingValue(imageSize);
*/
if (flagLog) Log.i(LOG_NAME, "GenerateImage - model: " + model);
if (flagLog) Log.i(LOG_NAME, "GenerateImage - size: " + size);
if (model == "dall-e-3") {
if (numberOfImages > 1 || numberOfImages < 1) numberOfImages = 1;
} else if (model == "dall-e-2") {
if (numberOfImages > 10 || numberOfImages < 1) numberOfImages = 1;
}
final ArrayList<String[]> headHTTP = new ArrayList<>();
headHTTP.add(new String[]{"Content-Type", "application/json"});
headHTTP.add(new String[]{"Authorization", "Bearer " + apiKey});
final String url = "https://api.openai.com/v1/images/generations";
final String payload = "{\n"
+ " \"model\": \"" + model + "\",\n"
+ " \"prompt\": \"" + prompt + "\",\n"
+ " \"n\": " + numberOfImages + ",\n"
+ " \"size\": \"" + size + "\"\n"
+ "}";
if (flagLog) Log.i(LOG_NAME, "GenerateImage - payload: " + payload);
if (flagLog) Log.i(LOG_NAME, "GenerateImage - headHTTP: " + headHTTP);
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendImageGenerationRequest(url, payload, headHTTP);
if (responseText != null) {
ImageGenerationCompleted(responseText);
} else {
ReportError("None");
}
}
}).start();
}
@SimpleFunction(description = "Create a thread")
public void CreateThread(final String apiKey) {
new Thread(new Runnable() {
@Override
public void run() {
if (flagLog) Log.i(LOG_NAME, "CreateThread - apiKey: " + apiKey);
try {
String responseText = sendThreadRequest("POST", "https://api.openai.com/v1/threads", apiKey, "");
if (responseText != null) {
ThreadCreated(responseText);
} else {
ReportError("None");
}
} catch (Exception e) {
if (flagLog) Log.e(LOG_NAME, "Error: " + e.getMessage(), e);
ReportError("Error: " + e.getMessage());
}
}
}).start();
}
// Mรฉtodo para recuperar uma thread
@SimpleFunction(description = "Retrieve a thread")
public void RetrieveThread(final String apiKey, final String threadId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadRequest("GET", "https://api.openai.com/v1/threads/" + threadId, apiKey, "");
if (responseText != null) {
ThreadRetrieved(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Mรฉtodo para modificar uma thread
@SimpleFunction(description = "Modify a thread")
public void ModifyThread(final String apiKey, final String threadId, final String metadata) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadRequest("POST", "https://api.openai.com/v1/threads/" + threadId, apiKey, metadata);
if (responseText != null) {
ThreadModified(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Mรฉtodo para excluir uma thread
@SimpleFunction(description = "Delete a thread")
public void DeleteThread(final String apiKey, final String threadId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadRequest("DELETE", "https://api.openai.com/v1/threads/" + threadId, apiKey, "");
if (responseText != null) {
ThreadDeleted(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Mรฉtodo para criar uma mensagem em uma thread
@SimpleFunction(description = "Create a message in a thread")
public void CreateMessage(final String apiKey, final String threadId, final String messageContent) {
new Thread(new Runnable() {
@Override
public void run() {
String payload = "{\n" +
" \"role\": \"user\",\n" +
" \"content\": \"" + messageContent + "\"\n" +
"}";
String responseText = sendThreadMessageRequest("POST", "https://api.openai.com/v1/threads/" + threadId + "/messages", apiKey, payload);
if (responseText != null) {
MessageCreated(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Mรฉtodo para recuperar uma mensagem em uma thread
@SimpleFunction(description = "Retrieve a message in a thread")
public void RetrieveMessage(final String apiKey, final String threadId, final String messageId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadMessageRequest("GET", "https://api.openai.com/v1/threads/" + threadId + "/messages/" + messageId, apiKey, "");
if (responseText != null) {
MessageRetrieved(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Mรฉtodo para modificar uma mensagem em uma thread
@SimpleFunction(description = "Modify a message in a thread")
public void ModifyMessage(final String apiKey, final String threadId, final String messageId, final String metadata) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadMessageRequest("POST", "https://api.openai.com/v1/threads/" + threadId + "/messages/" + messageId, apiKey, metadata);
if (responseText != null) {
MessageModified(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Mรฉtodo para listar mensagens em uma thread
@SimpleFunction(description = "List messages in a thread")
public void ListMessages(final String apiKey, final String threadId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadMessageRequest("GET", "https://api.openai.com/v1/threads/" + threadId + "/messages", apiKey, "");
if (responseText != null) {
MessagesListed(responseText);
} else {
ReportError("None");
}
}
}).start();
}
/*
* AUXILIAR METHODS
*/
// Mรฉtodo para mostrar um diรกlogo de reproduรงรฃo de รกudio
@SimpleFunction(description = "Show a dialog with a native audio player.")
public void ShowNativeAudioPlayerDialog(
String title,
final String audioFilePath,
final int titleColor,
final int titleBackgroundColor,
final int dialogBackgroundColor) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
builder.setTitle(title);
// Criar MediaPlayer
final MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(audioFilePath);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
ReportError("Error preparing MediaPlayer: " + e.getMessage());
return;
}
// Criar layout para adicionar os controles
LinearLayout layout = new LinearLayout(container.$context());
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// Barra de tempo
final SeekBar seekBar = new SeekBar(container.$context());
seekBar.setMax(mediaPlayer.getDuration());
layout.addView(seekBar);
// Atualizar SeekBar com o progresso do MediaPlayer
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 0);
// Botรตes de controle
Button playButton = new Button(container.$context());
playButton.setText("Play");
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start();
}
});
Button pauseButton = new Button(container.$context());
pauseButton.setText("Pause");
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.pause();
}
});
layout.addView(playButton);
layout.addView(pauseButton);
builder.setView(layout);
// Adicionar botรฃo de fechar
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
handler.removeCallbacks(runnable); // Parar atualizaรงรฃo da SeekBar
dialog.dismiss();
}
});
// Criar o AlertDialog
final AlertDialog dialog = builder.create();
// Configurar cores
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
TextView titleView = dialog.findViewById(android.R.id.title);
if (titleView != null) {
titleView.setTextColor(titleColor);
}
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(titleBackgroundColor));
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
dialog.show();
}
@SimpleFunction(description = "Shows a dialog with a text input.")
public void ShowTextInputDialog(
String title,
String message,
int textColor,
int editTextBackgroundColor,
final int dialogBackgroundColor,
String hint,
String defaultText,
boolean isFullScreen,
boolean showCancelButton,
boolean showOkButton,
final String type
)
{
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
// Define o tรญtulo e a mensagem do diรกlogo
builder.setTitle(title);
builder.setMessage(message);
// Cria o EditText para entrada de texto
final EditText input = new EditText(container.$context());
input.setTextColor(textColor);
input.setBackgroundColor(editTextBackgroundColor);
input.setHint(hint);
input.setText(defaultText);
// Configuraรงรฃo de layout para o EditText
if (isFullScreen) {
builder.setView(input);
} else {
int margin = 30; // Margem em pixels (ajuste conforme necessรกrio)
FrameLayout frameLayout = new FrameLayout(container.$context());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(margin, margin, margin, margin);
input.setLayoutParams(params);
frameLayout.addView(input);
builder.setView(frameLayout);
}
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botรตes ao diรกlogo
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
if (showOkButton) {
dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String enteredText = input.getText().toString();
TextEntered(enteredText, type);
}
});
}
// Configurar cor de fundo do diรกlogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diรกlogo
dialog.show();
}
@SimpleFunction(description = "Shows a dialog with a list of items.")
public void ShowListDialog(
String title,
YailList items,
final int textColor,
final int listItemBackgroundColor,
final int dialogBackgroundColor,
final boolean isFullScreen,
final boolean showCancelButton,
final String type
) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
builder.setTitle(title);
// Converte YailList para array de Strings
final String[] itemsArray = items.toStringArray();
// Criar ArrayAdapter personalizado
ArrayAdapter<String> adapter = new ArrayAdapter<String>(container.$context(), android.R.layout.simple_list_item_1, itemsArray) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView item = (TextView) super.getView(position, convertView, parent);
item.setTextColor(textColor); // Define a cor do texto
item.setBackgroundColor(listItemBackgroundColor); // Define a cor de fundo
return item;
}
};
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = itemsArray[which];
ListItemSelected(selectedItem, type);
}
});
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botรฃo de cancelamento, se necessรกrio
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
// Configurar cor de fundo do diรกlogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
if (isFullScreen) {
// Aplica a cor de fundo para o modo tela cheia
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diรกlogo
dialog.show();
}
@SimpleFunction(description = "Generate speech from text")
public void GenerateSpeech(
final String prompt,
final String apiKey,
final String audioName,
final String directoryName, | final @Options(VoiceModel.class) String voice, | 2 | 2023-12-14 15:07:14+00:00 | 4k |
MalithShehan/layered-architecture-Malith-Shehan | src/main/java/lk/ijse/layeredarchitecture/bo/BOFactory.java | [
{
"identifier": "CustomerBOImpl",
"path": "src/main/java/lk/ijse/layeredarchitecture/bo/custom/impl/CustomerBOImpl.java",
"snippet": "public class CustomerBOImpl implements CustomerBO {\n CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);\n public boolean saveCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException{\n return customerDAO.save(new Customer(dto.getId(),dto.getName(),dto.getAddress()));\n }\n\n @Override\n public ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException {\n ArrayList<Customer> customers = customerDAO.getAll();\n ArrayList<CustomerDTO> customerDTOS=new ArrayList<>();\n for (Customer customer:customers) {\n customerDTOS.add(new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()));\n }\n return customerDTOS;\n }\n\n @Override\n public boolean updateCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException {\n return customerDAO.update(new Customer(dto.getId(), dto.getName(), dto.getAddress()));\n }\n\n @Override\n public boolean existCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDAO.exist(id);\n }\n\n @Override\n public void deleteCustomer(String id) throws SQLException, ClassNotFoundException {\n customerDAO.delete(id);\n }\n\n @Override\n public String generateIDCustomer() throws SQLException, ClassNotFoundException {\n return customerDAO.generateID();\n }\n\n @Override\n public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException {\n Customer customer=customerDAO.search(id);\n CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress());\n return customerDTO;\n }\n}"
},
{
"identifier": "ItemBOImpl",
"path": "src/main/java/lk/ijse/layeredarchitecture/bo/custom/impl/ItemBOImpl.java",
"snippet": "public class ItemBOImpl implements ItemBO {\n ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM);\n @Override\n public ArrayList<ItemDTO> getAllItem() throws SQLException, ClassNotFoundException {\n ArrayList<Item> items = itemDAO.getAll();\n ArrayList<ItemDTO> itemDTOS =new ArrayList<>();\n for (Item item : items) {\n itemDTOS.add(new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand()));\n }\n return itemDTOS;\n }\n\n @Override\n public void deleteItem(String code) throws SQLException, ClassNotFoundException {\n itemDAO.delete(code);\n }\n\n @Override\n public boolean saveItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return itemDAO.save(new Item(dto.getCode(), dto.getDescription(), dto.getUnitPrice(), dto.getQtyOnHand()));\n }\n\n @Override\n public boolean updateItem(ItemDTO dto) throws SQLException, ClassNotFoundException {\n return itemDAO.update(new Item(dto.getCode(), dto.getDescription(), dto.getUnitPrice(), dto.getQtyOnHand()));\n }\n\n @Override\n public boolean existItem(String code) throws SQLException, ClassNotFoundException {\n return itemDAO.exist(code);\n }\n\n @Override\n public String generateItemID() throws SQLException, ClassNotFoundException {\n return itemDAO.generateID();\n }\n\n @Override\n public ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException {\n Item item = itemDAO.search(code);\n ItemDTO itemDTO = new ItemDTO(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand());\n return itemDTO;\n }\n}"
},
{
"identifier": "PlaceOrderBOImpl",
"path": "src/main/java/lk/ijse/layeredarchitecture/bo/custom/impl/PlaceOrderBOImpl.java",
"snippet": "public class PlaceOrderBOImpl implements PlaceOrderBO {\n CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);\n ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM);\n QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY);\n OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER);\n OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL);\n\n @Override\n public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException {\n Customer customer=customerDAO.search(id);\n CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress());\n return customerDTO;\n }\n\n @Override\n public ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException {\n Item item = itemDAO.search(code);\n ItemDTO itemDTO = new ItemDTO(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand());\n return itemDTO;\n }\n\n @Override\n public boolean existItem(String code) throws SQLException, ClassNotFoundException {\n return itemDAO.exist(code);\n }\n\n @Override\n public boolean existCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDAO.exist(id);\n }\n\n @Override\n public String generateOrderID() throws SQLException, ClassNotFoundException {\n return orderDAO.generateID();\n }\n\n @Override\n public ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException {\n ArrayList<Customer> customers = customerDAO.getAll();\n ArrayList<CustomerDTO> customerDTOS=new ArrayList<>();\n for (Customer customer:customers) {\n customerDTOS.add(new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()));\n }\n return customerDTOS;\n }\n\n @Override\n public ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException {\n ArrayList<Item> items = itemDAO.getAll();\n ArrayList<ItemDTO> itemDTOS =new ArrayList<>();\n for (Item item : items) {\n itemDTOS.add(new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand()));\n }\n return itemDTOS;\n }\n\n @Override\n public boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {\n /*Transaction*/\n Connection connection = null;\n connection= DBConnection.getDbConnection().getConnection();\n\n //Check order id already exist or not\n\n boolean b1 = orderDAO.exist(orderId);\n /*if order id already exist*/\n if (b1) {\n return false;\n }\n\n connection.setAutoCommit(false);\n\n //Save the Order to the order table\n boolean b2 = orderDAO.save(new Order(orderId, orderDate, customerId));\n\n if (!b2) {\n connection.rollback();\n connection.setAutoCommit(true);\n return false;\n }\n\n\n // add data to the Order Details table\n\n for (OrderDetailDTO detail : orderDetails) {\n boolean b3 = orderDetailsDAO.save(new OrderDetails(detail.getOid(),detail.getItemCode(),detail.getQty(),detail.getUnitPrice()));\n if (!b3) {\n connection.rollback();\n connection.setAutoCommit(true);\n return false;\n }\n\n //Search & Update Item\n ItemDTO item = findItem(detail.getItemCode());\n item.setQtyOnHand(item.getQtyOnHand() - detail.getQty());\n\n //update item\n boolean b = itemDAO.update(new Item(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand()));\n\n if (!b) {\n connection.rollback();\n connection.setAutoCommit(true);\n return false;\n }\n }\n\n connection.commit();\n connection.setAutoCommit(true);\n return true;\n }\n public ItemDTO findItem(String code) {\n try {\n Item item = itemDAO.search(code);\n return new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand());\n } catch (SQLException e) {\n throw new RuntimeException(\"Failed to find the Item \" + code, e);\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n return null;\n }\n}"
}
] | import com.example.layeredarchitecture.bo.custom.impl.CustomerBOImpl;
import com.example.layeredarchitecture.bo.custom.impl.ItemBOImpl;
import com.example.layeredarchitecture.bo.custom.impl.PlaceOrderBOImpl; | 2,070 | package com.example.layeredarchitecture.bo;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory == null) ? boFactory = new BOFactory() : boFactory;
}
public enum BOTypes{
CUSTOMER, ITEM, PLACE_ORDER
}
public SuperBO getBO(BOTypes boTypes) {
switch (boTypes) {
case CUSTOMER:
return new CustomerBOImpl();
case ITEM: | package com.example.layeredarchitecture.bo;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory == null) ? boFactory = new BOFactory() : boFactory;
}
public enum BOTypes{
CUSTOMER, ITEM, PLACE_ORDER
}
public SuperBO getBO(BOTypes boTypes) {
switch (boTypes) {
case CUSTOMER:
return new CustomerBOImpl();
case ITEM: | return new ItemBOImpl(); | 1 | 2023-12-16 04:19:09+00:00 | 4k |
f1den/MrCrayfishGunMod | src/main/java/com/mrcrayfish/guns/client/GunEntityRenderers.java | [
{
"identifier": "Reference",
"path": "src/main/java/com/mrcrayfish/guns/Reference.java",
"snippet": "public class Reference\n{\n\tpublic static final String MOD_ID = \"cgm\";\n}"
},
{
"identifier": "GrenadeRenderer",
"path": "src/main/java/com/mrcrayfish/guns/client/render/entity/GrenadeRenderer.java",
"snippet": "public class GrenadeRenderer extends EntityRenderer<GrenadeEntity>\n{\n public GrenadeRenderer(EntityRendererProvider.Context context)\n {\n super(context);\n }\n\n @Override\n public ResourceLocation getTextureLocation(GrenadeEntity entity)\n {\n return null;\n }\n\n @Override\n public void render(GrenadeEntity entity, float entityYaw, float partialTicks, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light)\n {\n if(!entity.getProjectile().isVisible() || entity.tickCount <= 1)\n {\n return;\n }\n\n poseStack.pushPose();\n poseStack.mulPose(Vector3f.YP.rotationDegrees(180F));\n poseStack.mulPose(Vector3f.YP.rotationDegrees(entityYaw));\n poseStack.mulPose(Vector3f.XP.rotationDegrees(entity.getXRot()));\n\n /* Offsets to the center of the grenade before applying rotation */\n float rotation = entity.tickCount + partialTicks;\n poseStack.translate(0, 0.15, 0);\n poseStack.mulPose(Vector3f.XN.rotationDegrees(rotation * 20));\n poseStack.translate(0, -0.15, 0);\n\n poseStack.translate(0.0, 0.5, 0.0);\n\n Minecraft.getInstance().getItemRenderer().renderStatic(entity.getItem(), ItemTransforms.TransformType.NONE, light, OverlayTexture.NO_OVERLAY, poseStack, renderTypeBuffer, 0);\n poseStack.popPose();\n }\n}"
},
{
"identifier": "MissileRenderer",
"path": "src/main/java/com/mrcrayfish/guns/client/render/entity/MissileRenderer.java",
"snippet": "public class MissileRenderer extends EntityRenderer<MissileEntity>\n{\n public MissileRenderer(EntityRendererProvider.Context context)\n {\n super(context);\n }\n\n @Override\n public ResourceLocation getTextureLocation(MissileEntity entity)\n {\n return null;\n }\n\n @Override\n public void render(MissileEntity entity, float entityYaw, float partialTicks, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light)\n {\n if(!entity.getProjectile().isVisible() || entity.tickCount <= 1)\n {\n return;\n }\n\n poseStack.pushPose();\n poseStack.mulPose(Vector3f.YP.rotationDegrees(180F));\n poseStack.mulPose(Vector3f.YP.rotationDegrees(entityYaw));\n poseStack.mulPose(Vector3f.XP.rotationDegrees(entity.getXRot() - 90));\n Minecraft.getInstance().getItemRenderer().renderStatic(entity.getItem(), ItemTransforms.TransformType.NONE, 15728880, OverlayTexture.NO_OVERLAY, poseStack, renderTypeBuffer, 0);\n poseStack.translate(0, -1, 0);\n RenderUtil.renderModel(SpecialModels.FLAME.getModel(), entity.getItem(), poseStack, renderTypeBuffer, 15728880, OverlayTexture.NO_OVERLAY);\n poseStack.popPose();\n }\n}"
},
{
"identifier": "ProjectileRenderer",
"path": "src/main/java/com/mrcrayfish/guns/client/render/entity/ProjectileRenderer.java",
"snippet": "public class ProjectileRenderer extends EntityRenderer<ProjectileEntity>\n{\n public ProjectileRenderer(EntityRendererProvider.Context context)\n {\n super(context);\n }\n\n @Override\n public ResourceLocation getTextureLocation(ProjectileEntity entity)\n {\n return null;\n }\n\n @Override\n public void render(ProjectileEntity entity, float entityYaw, float partialTicks, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light)\n {\n if(!entity.getProjectile().isVisible() || entity.tickCount <= 1)\n {\n return;\n }\n\n poseStack.pushPose();\n\n if(!RenderUtil.getModel(entity.getItem()).isGui3d())\n {\n poseStack.mulPose(this.entityRenderDispatcher.cameraOrientation());\n poseStack.mulPose(Vector3f.YP.rotationDegrees(180.0F));\n Minecraft.getInstance().getItemRenderer().renderStatic(entity.getItem(), ItemTransforms.TransformType.GROUND, light, OverlayTexture.NO_OVERLAY, poseStack, renderTypeBuffer, 0);\n }\n else\n {\n poseStack.mulPose(Vector3f.YP.rotationDegrees(180F));\n poseStack.mulPose(Vector3f.YP.rotationDegrees(entityYaw));\n poseStack.mulPose(Vector3f.XP.rotationDegrees(entity.getXRot()));\n Minecraft.getInstance().getItemRenderer().renderStatic(entity.getItem(), ItemTransforms.TransformType.NONE, light, OverlayTexture.NO_OVERLAY, poseStack, renderTypeBuffer, 0);\n }\n\n poseStack.popPose();\n }\n}"
},
{
"identifier": "ThrowableGrenadeRenderer",
"path": "src/main/java/com/mrcrayfish/guns/client/render/entity/ThrowableGrenadeRenderer.java",
"snippet": "public class ThrowableGrenadeRenderer extends EntityRenderer<ThrowableGrenadeEntity>\n{\n public ThrowableGrenadeRenderer(EntityRendererProvider.Context context)\n {\n super(context);\n }\n\n @Nullable\n @Override\n public ResourceLocation getTextureLocation(ThrowableGrenadeEntity entity)\n {\n return null;\n }\n\n @Override\n public void render(ThrowableGrenadeEntity entity, float entityYaw, float partialTicks, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light)\n {\n poseStack.pushPose();\n\n /* Makes the grenade face in the direction of travel */\n poseStack.mulPose(Vector3f.YP.rotationDegrees(180F));\n poseStack.mulPose(Vector3f.YP.rotationDegrees(entityYaw));\n\n /* Offsets to the center of the grenade before applying rotation */\n float rotation = entity.prevRotation + (entity.rotation - entity.prevRotation) * partialTicks;\n poseStack.translate(0, 0.15, 0);\n poseStack.mulPose(Vector3f.XP.rotationDegrees(-rotation));\n poseStack.translate(0, -0.15, 0);\n\n if(entity instanceof ThrowableStunGrenadeEntity)\n {\n poseStack.translate(0, entity.getDimensions(Pose.STANDING).height / 2, 0);\n poseStack.mulPose(Vector3f.ZP.rotationDegrees(-90F));\n poseStack.translate(0, -entity.getDimensions(Pose.STANDING).height / 2, 0);\n }\n\n /* */\n poseStack.translate(0.0, 0.5, 0.0);\n\n Minecraft.getInstance().getItemRenderer().renderStatic(entity.getItem(), ItemTransforms.TransformType.NONE, light, OverlayTexture.NO_OVERLAY, poseStack, renderTypeBuffer, 0);\n\n poseStack.popPose();\n }\n}"
},
{
"identifier": "ModEntities",
"path": "src/main/java/com/mrcrayfish/guns/init/ModEntities.java",
"snippet": "public class ModEntities\n{\n public static final DeferredRegister<EntityType<?>> REGISTER = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, Reference.MOD_ID);\n\n public static final RegistryObject<EntityType<ProjectileEntity>> PROJECTILE = registerProjectile(\"projectile\", ProjectileEntity::new);\n public static final RegistryObject<EntityType<GrenadeEntity>> GRENADE = registerBasic(\"grenade\", GrenadeEntity::new);\n public static final RegistryObject<EntityType<MissileEntity>> MISSILE = registerBasic(\"missile\", MissileEntity::new);\n public static final RegistryObject<EntityType<ThrowableGrenadeEntity>> THROWABLE_GRENADE = registerBasic(\"throwable_grenade\", ThrowableGrenadeEntity::new);\n public static final RegistryObject<EntityType<ThrowableStunGrenadeEntity>> THROWABLE_STUN_GRENADE = registerBasic(\"throwable_stun_grenade\", ThrowableStunGrenadeEntity::new);\n\n private static <T extends Entity> RegistryObject<EntityType<T>> registerBasic(String id, BiFunction<EntityType<T>, Level, T> function)\n {\n return REGISTER.register(id, () -> EntityType.Builder.of(function::apply, MobCategory.MISC)\n .sized(0.25F, 0.25F)\n .setTrackingRange(100)\n .setUpdateInterval(1)\n .noSummon()\n .fireImmune()\n .setShouldReceiveVelocityUpdates(true).build(id));\n }\n\n /**\n * Entity registration that prevents the entity from being sent and tracked by clients. Projectiles\n * are rendered separately from Minecraft's entity rendering system and their logic is handled\n * exclusively by the server, why send them to the client. Projectiles also have very short time\n * in the world and are spawned many times a tick. There is no reason to send unnecessary packets\n * when it can be avoided to drastically improve the performance of the game.\n *\n * @param id the id of the projectile\n * @param function the factory to spawn the projectile for the server\n * @param <T> an entity that is a projectile entity\n * @return A registry object containing the new entity type\n */\n private static <T extends ProjectileEntity> RegistryObject<EntityType<T>> registerProjectile(String id, BiFunction<EntityType<T>, Level, T> function)\n {\n return REGISTER.register(id, () -> EntityType.Builder.of(function::apply, MobCategory.MISC)\n .sized(0.25F, 0.25F)\n .setTrackingRange(0)\n .noSummon()\n .fireImmune()\n .setShouldReceiveVelocityUpdates(false)\n .setCustomClientFactory((spawnEntity, world) -> null)\n .build(id));\n }\n}"
}
] | import com.mrcrayfish.guns.Reference;
import com.mrcrayfish.guns.client.render.entity.GrenadeRenderer;
import com.mrcrayfish.guns.client.render.entity.MissileRenderer;
import com.mrcrayfish.guns.client.render.entity.ProjectileRenderer;
import com.mrcrayfish.guns.client.render.entity.ThrowableGrenadeRenderer;
import com.mrcrayfish.guns.init.ModEntities;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; | 2,454 | package com.mrcrayfish.guns.client;
/**
* Author: MrCrayfish
*/
@Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class GunEntityRenderers
{
@SubscribeEvent
public static void registerEntityRenders(EntityRenderersEvent.RegisterRenderers event)
{ | package com.mrcrayfish.guns.client;
/**
* Author: MrCrayfish
*/
@Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class GunEntityRenderers
{
@SubscribeEvent
public static void registerEntityRenders(EntityRenderersEvent.RegisterRenderers event)
{ | event.registerEntityRenderer(ModEntities.PROJECTILE.get(), ProjectileRenderer::new); | 5 | 2023-12-18 15:04:35+00:00 | 4k |
JenningsCrane/JDBC-Simple-Chat | Chat/src/main/java/edu/school21/chat/models/Repository/MessageRepositoryJdbcImpl.java | [
{
"identifier": "Chatroom",
"path": "Chat/src/main/java/edu/school21/chat/models/Chat/Chatroom.java",
"snippet": "public class Chatroom {\n private Long chatRoomId;\n private String chatRoomName;\n private User chatRoomOwner;\n private List<Message> chatRoomMessages;\n\n public Chatroom(Long id, String name, User owner, List<Message> messages) {\n this.chatRoomId = id;\n this.chatRoomName = name;\n this.chatRoomOwner = owner;\n this.chatRoomMessages = messages;\n }\n\n public Long getChatRoomId() {\n return chatRoomId;\n }\n\n public void setChatRoomId(Long chatRoomId) {\n this.chatRoomId = chatRoomId;\n }\n\n public String getChatRoomName() {\n return chatRoomName;\n }\n\n public void setChatRoomName(String chatRoomName) {\n this.chatRoomName = chatRoomName;\n }\n\n public User getChatRoomOwner() {\n return chatRoomOwner;\n }\n\n public void setChatRoomOwner(User chatRoomOwner) {\n this.chatRoomOwner = chatRoomOwner;\n }\n\n public List<Message> getChatRoomMessages() {\n return chatRoomMessages;\n }\n\n public void setChatRoomMessages(List<Message> chatRoomMessages) {\n this.chatRoomMessages = chatRoomMessages;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Chatroom chatRoom = (Chatroom) o;\n return Objects.equals(chatRoomId, chatRoom.chatRoomId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(chatRoomId);\n }\n\n @Override\n public String toString() {\n return \"ChatRoom{\" +\n \"id=\" + chatRoomId +\n \", chatName='\" + chatRoomName + '\\'' +\n \", chatOwner='\" + chatRoomOwner + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "Message",
"path": "Chat/src/main/java/edu/school21/chat/models/Chat/Message.java",
"snippet": "public class Message {\n private Long messageId;\n private User messageAuthor;\n private Chatroom messageRoom;\n private String messageText;\n private LocalDateTime dateTime;\n\n public Message(Long id, User author, Chatroom room, String text, LocalDateTime dateTime){\n this.messageId = id;\n this.messageAuthor = author;\n this.messageRoom = room;\n this.messageText = text;\n this.dateTime = dateTime;\n }\n\n public Long getMessageId() {\n return messageId;\n }\n\n public void setMessageId(Long messageId) {\n this.messageId = messageId;\n }\n\n public User getMessageAuthor() {\n return messageAuthor;\n }\n\n public void setMessageAuthor(User messageAuthor) {\n this.messageAuthor = messageAuthor;\n }\n\n public Chatroom getMessageRoom() {\n return messageRoom;\n }\n\n public void setMessageRoom(Chatroom messageRoom) {\n this.messageRoom = messageRoom;\n }\n\n public String getMessageText() {\n return messageText;\n }\n\n public void setMessageText(String messageText) {\n this.messageText = messageText;\n }\n\n public LocalDateTime getDateTime() {\n return dateTime;\n }\n\n public void setDateTime(LocalDateTime dateTime) {\n this.dateTime = dateTime;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Message message = (Message) o;\n return Objects.equals(messageId, message.messageId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(messageId);\n }\n\n @Override\n public String toString() {\n return \"Message{\" +\n \"id=\" + messageId +\n \", messageOwner='\" + messageAuthor + '\\'' +\n \", chatRoom=\" + messageRoom +\n \", messageText='\" + messageText + '\\'' +\n \", dateTime=\" + dateTime +\n '}';\n }\n}"
},
{
"identifier": "User",
"path": "Chat/src/main/java/edu/school21/chat/models/Chat/User.java",
"snippet": "public class User {\n private Long userId;\n private String login;\n private String password;\n private List<Chatroom> createdRooms;\n private List<Chatroom> socializesRooms;\n\n public User(Long id, String login, String password, List<Chatroom> createdRooms, List<Chatroom> socializesRooms) {\n this.userId = id;\n this.login = login;\n this.password = password;\n this.createdRooms = createdRooms;\n this.socializesRooms = socializesRooms;\n }\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long id) {\n this.userId = id;\n }\n\n public String getLogin() {\n return login;\n }\n\n public void setLogin(String login) {\n this.login = login;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public List<Chatroom> getCreatedRooms() {\n return createdRooms;\n }\n\n public void setCreatedRooms(List<Chatroom> createdRooms) {\n this.createdRooms = createdRooms;\n }\n\n public List<Chatroom> getSocializesRooms() {\n return socializesRooms;\n }\n\n public void setSocializesRooms(List<Chatroom> socializesRooms) {\n this.socializesRooms = socializesRooms;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n User user = (User) o;\n return Objects.equals(userId, user.userId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(userId);\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + userId +\n \", login='\" + login + '\\'' +\n \", password='\" + password + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "NotSavedSubEntityException",
"path": "Chat/src/main/java/edu/school21/chat/models/Exception/NotSavedSubEntityException.java",
"snippet": "public class NotSavedSubEntityException extends RuntimeException {\n public NotSavedSubEntityException(String message) {\n super(message);\n }\n}"
}
] | import edu.school21.chat.models.Chat.Chatroom;
import edu.school21.chat.models.Chat.Message;
import edu.school21.chat.models.Chat.User;
import edu.school21.chat.models.Exception.NotSavedSubEntityException;
import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Optional; | 1,971 | package edu.school21.chat.models.Repository;
public class MessageRepositoryJdbcImpl implements MessageRepository {
private static Connection connection;
public MessageRepositoryJdbcImpl(DataSource dataSource) throws SQLException {
MessageRepositoryJdbcImpl.connection = dataSource.getConnection();
}
@Override
public Optional<Message> findById(Long id) throws SQLException {
try(PreparedStatement userStatement = connection.prepareStatement("SELECT * FROM chat.message WHERE messageid = " + id);
ResultSet resultSet = userStatement.executeQuery()) {
resultSet.next();
LocalDateTime date = null;
if(resultSet.getTimestamp(5) != null) {
date = resultSet.getTimestamp(5).toLocalDateTime();
}
System.out.println("Message : {\n" +
" id=" + resultSet.getInt(1) + ",\n" +
" " + findUserById(resultSet.getLong(2)) + ",\n" +
" " + findRoomById(resultSet.getLong(3)) + ",\n" +
" text=\"" + resultSet.getString(4) + "\",\n" +
" dateTime=" + date + "\n" +
"}");
return Optional.of(new Message(resultSet.getLong(1), findUserById(resultSet.getLong(2)), findRoomById(resultSet.getLong(3)),
resultSet.getString(4), date));
} catch (SQLException sqlException) {
throw new SQLException(sqlException);
}
}
| package edu.school21.chat.models.Repository;
public class MessageRepositoryJdbcImpl implements MessageRepository {
private static Connection connection;
public MessageRepositoryJdbcImpl(DataSource dataSource) throws SQLException {
MessageRepositoryJdbcImpl.connection = dataSource.getConnection();
}
@Override
public Optional<Message> findById(Long id) throws SQLException {
try(PreparedStatement userStatement = connection.prepareStatement("SELECT * FROM chat.message WHERE messageid = " + id);
ResultSet resultSet = userStatement.executeQuery()) {
resultSet.next();
LocalDateTime date = null;
if(resultSet.getTimestamp(5) != null) {
date = resultSet.getTimestamp(5).toLocalDateTime();
}
System.out.println("Message : {\n" +
" id=" + resultSet.getInt(1) + ",\n" +
" " + findUserById(resultSet.getLong(2)) + ",\n" +
" " + findRoomById(resultSet.getLong(3)) + ",\n" +
" text=\"" + resultSet.getString(4) + "\",\n" +
" dateTime=" + date + "\n" +
"}");
return Optional.of(new Message(resultSet.getLong(1), findUserById(resultSet.getLong(2)), findRoomById(resultSet.getLong(3)),
resultSet.getString(4), date));
} catch (SQLException sqlException) {
throw new SQLException(sqlException);
}
}
| private User findUserById(Long id) throws SQLException { | 2 | 2023-12-17 05:34:09+00:00 | 4k |
Qzimyion/BucketEm | src/main/java/com/qzimyion/bucketem/Bucketem.java | [
{
"identifier": "DispenserBehaviorRegistry",
"path": "src/main/java/com/qzimyion/bucketem/dispenser/DispenserBehaviorRegistry.java",
"snippet": "public class DispenserBehaviorRegistry {\n\n public static void registerDispenserBehavior(){\n //Buckets\n DispenserBlock.registerBehavior(STRIDER_BUCKET, new ItemDispenserBehavior());\n DispenserBlock.registerBehavior(SQUID_BUCKET, new ItemDispenserBehavior());\n DispenserBlock.registerBehavior(GLOW_SQUID_BUCKET, new ItemDispenserBehavior());\n DispenserBlock.registerBehavior(TEMPERATE_FROG_BUCKET, new ItemDispenserBehavior());\n DispenserBlock.registerBehavior(TROPICAL_FROG_BUCKET, new ItemDispenserBehavior());\n DispenserBlock.registerBehavior(TUNDRA_FROG_BUCKET, new ItemDispenserBehavior());\n DispenserBlock.registerBehavior(TURTLE_BUCKET, new ItemDispenserBehavior());\n\n //Books\n DispenserBlock.registerBehavior(ALLAY_POSSESSED_BOOK, new BookBehavior());\n DispenserBlock.registerBehavior(VEX_POSSESSED_BOOK, new BookBehavior());\n\n //Bottles\n DispenserBlock.registerBehavior(BEE_BOTTLE, new BottleBehavior());\n DispenserBlock.registerBehavior(SILVERFISH_BOTTLE, new BottleBehavior());\n DispenserBlock.registerBehavior(ENDERMITE_BOTTLE, new BottleBehavior());\n DispenserBlock.registerBehavior(SLIME_BOTTLE, new SlimeBottleBehavior());\n DispenserBlock.registerBehavior(MAGMA_CUBE_BOTTLE, new MagmaCubeBottleBehavior());\n\n Bucketem.LOGGER.info(\"Registering mod Dispenser Behaviors\");\n }\n}"
},
{
"identifier": "ModItemGroups",
"path": "src/main/java/com/qzimyion/bucketem/items/ModItemGroups.java",
"snippet": "public class ModItemGroups {\n\n public static void registerItemGroups(){\n ItemGroupEvents.modifyEntriesEvent(net.minecraft.item.ItemGroups.TOOLS).register(content -> {\n content.addAfter(LAVA_BUCKET, STRIDER_BUCKET);\n content.addAfter(TADPOLE_BUCKET, DRY_TEMPERATE_FROG_BUCKET, DRY_TUNDRA_FROG_BUCKET, DRY_TROPICAL_FROG_BUCKET, TEMPERATE_FROG_BUCKET, TUNDRA_FROG_BUCKET, TROPICAL_FROG_BUCKET,\n DRY_TEMPERATE_FROG_BUCKET, DRY_TROPICAL_FROG_BUCKET, DRY_TUNDRA_FROG_BUCKET, GLOW_SQUID_BUCKET, SQUID_BUCKET, TURTLE_BUCKET);\n content.addAfter(MILK_BUCKET, BEE_BOTTLE, SILVERFISH_BOTTLE, ENDERMITE_BOTTLE, SLIME_BOTTLE, MAGMA_CUBE_BOTTLE, ALLAY_POSSESSED_BOOK, VEX_POSSESSED_BOOK);\n });\n\n\n Bucketem.LOGGER.info(\"Registering mod Item Groups\");\n }\n}"
},
{
"identifier": "ModItems",
"path": "src/main/java/com/qzimyion/bucketem/items/ModItems.java",
"snippet": "public class ModItems {\n\n //Buckets\n public static final Item STRIDER_BUCKET = registerItem(\"strider_bucket\", new EntityBucketItem(EntityType.STRIDER, Fluids.LAVA, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, new FabricItemSettings().maxCount(1)));\n public static final Item SQUID_BUCKET = registerItem(\"squid_bucket\", new EntityBucketItem(EntityType.SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1)));\n public static final Item GLOW_SQUID_BUCKET = registerItem(\"glow_squid_bucket\", new EntityBucketItem(EntityType.GLOW_SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1)));\n public static final Item TEMPERATE_FROG_BUCKET = registerItem(\"temperate_frog_bucket\", new TemperateFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1)));\n public static final Item TROPICAL_FROG_BUCKET = registerItem(\"tropical_frog_bucket\", new TropicalFrogBuckets(Fluids.WATER , new FabricItemSettings().maxCount(1)));\n public static final Item TUNDRA_FROG_BUCKET = registerItem(\"tundra_frog_bucket\", new TundraFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1)));\n public static final Item TURTLE_BUCKET = registerItem(\"turtle_bucket\", new EntityBucketItem(EntityType.TURTLE, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1)));\n public static final Item DRY_TEMPERATE_FROG_BUCKET = registerItem(\"dry_temperate_frog_bucket\", new DryTemperateFrogBuckets(new FabricItemSettings().maxCount(1)));\n public static final Item DRY_TROPICAL_FROG_BUCKET = registerItem(\"dry_tropical_frog_bucket\", new DryTropicalFrogBuckets(new FabricItemSettings().maxCount(1)));\n public static final Item DRY_TUNDRA_FROG_BUCKET = registerItem(\"dry_tundra_frog_bucket\", new DryTundraFrogBuckets(new FabricItemSettings().maxCount(1)));\n\n\n //Books\n public static final Item ALLAY_POSSESSED_BOOK = registerItem(\"allay_possessed_book\", new EntityBook(EntityType.ALLAY ,new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON)));\n public static final Item VEX_POSSESSED_BOOK = registerItem(\"vex_possessed_book\", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON)));\n\n //Bottles\n public static final Item BEE_BOTTLE = registerItem(\"bee_bottle\", new EntityBottle(EntityType.BEE ,new FabricItemSettings().maxCount(1)));\n public static final Item SILVERFISH_BOTTLE = registerItem(\"silverfish_bottle\", new EntityBottle(EntityType.SILVERFISH, new FabricItemSettings().maxCount(1)));\n public static final Item ENDERMITE_BOTTLE = registerItem(\"endermite_bottle\", new EntityBottle(EntityType.ENDERMITE, new FabricItemSettings().maxCount(1)));\n public static final Item SLIME_BOTTLE = registerItem(\"slime_bottle\", new SlimeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));\n public static final Item MAGMA_CUBE_BOTTLE = registerItem(\"magma_bottle\", new MagmaCubeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));\n\n\n private static Item registerItem(String name, Item item)\n {\n return Registry.register(Registries.ITEM, new Identifier(Bucketem.MOD_ID, name), item);\n }\n\n public static void registerItems(){\n\n Bucketem.LOGGER.info(\"Registering mod Items\");\n }\n}"
},
{
"identifier": "ModPotionsRegistry",
"path": "src/main/java/com/qzimyion/bucketem/potions/ModPotionsRegistry.java",
"snippet": "public class ModPotionsRegistry {\n\n public static final Potion BLISTERED_VISION_SHORT = Registry.register(Registries.POTION, new Identifier(Bucketem.MOD_ID, \"blistered_vision\"),\n new Potion(new StatusEffectInstance(ModStatusEffectsRegistry.BLISTERED_VISION, 3600, 0)));\n\n public static final Potion BLISTERED_VISION_LONG = Registry.register(Registries.POTION, new Identifier(Bucketem.MOD_ID, \"blistered_vision_long\"),\n new Potion(new StatusEffectInstance(ModStatusEffectsRegistry.BLISTERED_VISION, 9600, 0)));\n\n public static void registerPotions(){\n\n\n Bucketem.LOGGER.info(\"Registering mod Potions\");\n }\n\n public static void registerPotionRecipes(){\n BrewingRecipeRegistry.registerPotionRecipe(Potions.AWKWARD, ModItems.SLIME_BOTTLE, Potions.LEAPING);\n BrewingRecipeRegistry.registerPotionRecipe(Potions.NIGHT_VISION, ModItems.MAGMA_CUBE_BOTTLE, BLISTERED_VISION_SHORT);\n BrewingRecipeRegistry.registerPotionRecipe(Potions.LONG_NIGHT_VISION, ModItems.MAGMA_CUBE_BOTTLE, BLISTERED_VISION_LONG);\n BrewingRecipeRegistry.registerPotionRecipe(BLISTERED_VISION_SHORT, Items.REDSTONE, BLISTERED_VISION_LONG);\n\n Bucketem.LOGGER.info(\"Registering mod Potion Recipes\");\n }\n}"
},
{
"identifier": "ModStatusEffectsRegistry",
"path": "src/main/java/com/qzimyion/bucketem/potions/StatusEffects/ModStatusEffectsRegistry.java",
"snippet": "public class ModStatusEffectsRegistry {\n\n public static final BlisteredVision BLISTERED_VISION = new BlisteredVision();\n\n public static void registerStatusEffects(){\n Registry.register(Registries.STATUS_EFFECT, new Identifier(Bucketem.MOD_ID, \"blistered_vision\"), BLISTERED_VISION);\n\n Bucketem.LOGGER.info(\"Registering mod Status Effects\");\n }\n}"
}
] | import com.qzimyion.bucketem.dispenser.DispenserBehaviorRegistry;
import com.qzimyion.bucketem.items.ModItemGroups;
import com.qzimyion.bucketem.items.ModItems;
import com.qzimyion.bucketem.potions.ModPotionsRegistry;
import com.qzimyion.bucketem.potions.StatusEffects.ModStatusEffectsRegistry;
import net.fabricmc.api.ModInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 2,240 | package com.qzimyion.bucketem;
public class Bucketem implements ModInitializer {
public static final String MOD_ID = "bucketem";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItems.registerItems();
ModItemGroups.registerItemGroups();
ModEvents.registerEvents();
DispenserBehaviorRegistry.registerDispenserBehavior();
ModStatusEffectsRegistry.registerStatusEffects(); | package com.qzimyion.bucketem;
public class Bucketem implements ModInitializer {
public static final String MOD_ID = "bucketem";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItems.registerItems();
ModItemGroups.registerItemGroups();
ModEvents.registerEvents();
DispenserBehaviorRegistry.registerDispenserBehavior();
ModStatusEffectsRegistry.registerStatusEffects(); | ModPotionsRegistry.registerPotions(); | 3 | 2023-12-16 08:12:37+00:00 | 4k |
devOS-Sanity-Edition/blocky-bass | src/main/java/one/devos/nautical/blocky_bass/BlockyBassClient.java | [
{
"identifier": "BlockyBassBlockEntityRenderer",
"path": "src/main/java/one/devos/nautical/blocky_bass/block/BlockyBassBlockEntityRenderer.java",
"snippet": "public class BlockyBassBlockEntityRenderer implements BlockEntityRenderer<BlockyBassBlockEntity> {\n\tprivate final BlockyBassModel model;\n\n\tpublic BlockyBassBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) {\n\t\tthis.model = new BlockyBassModel(ctx.bakeLayer(BlockyBassModel.LAYER_LOCATION));\n\t}\n\n\t@Override\n\tpublic void render(BlockyBassBlockEntity bass, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) {\n\t\tRenderType renderType = this.model.renderType(BlockyBassModel.TEXTURE);\n\t\tVertexConsumer vertices = vertexConsumers.getBuffer(renderType);\n\t\tmatrices.pushPose();\n\t\tmatrices.translate(0.5, 1.5, 0.5);\n\t\tfloat rotation = this.getRotationDeg(bass);\n\t\tmatrices.mulPose(Axis.YP.rotationDegrees(rotation));\n\t\tmatrices.mulPose(Axis.XP.rotationDegrees(180));\n\t\tthis.model.setRotations(bass, tickDelta);\n\t\tthis.model.renderToBuffer(matrices, vertices, light, overlay, 1, 1, 1, 1);\n\t\tmatrices.popPose();\n\t}\n\n\tprivate float getRotationDeg(BlockyBassBlockEntity bass) {\n\t\tDirection facing = bass.getBlockState().getValue(BlockyBassBlock.FACING);\n\t\treturn switch (facing) {\n\t\t\tcase NORTH -> 180;\n\t\t\tcase SOUTH -> 0;\n\t\t\tcase EAST -> 90;\n\t\t\tcase WEST -> 270;\n\t\t\tdefault -> throw new IllegalArgumentException(\"Invalid facing direction\");\n\t\t};\n\t}\n}"
},
{
"identifier": "BlockyBassModel",
"path": "src/main/java/one/devos/nautical/blocky_bass/block/BlockyBassModel.java",
"snippet": "public class BlockyBassModel extends Model {\n\tpublic static final ResourceLocation TEXTURE = BlockyBass.id(\"textures/entity/blocky_bass.png\");\n\tpublic static final ModelLayerLocation LAYER_LOCATION = new ModelLayerLocation(new ResourceLocation(\"modid\", \"blocky_bass\"), \"main\");\n\tprivate final ModelPart le_fishe;\n\tprivate final ModelPart head;\n\tprivate final ModelPart mouth;\n\tprivate final ModelPart tail;\n\n\tpublic BlockyBassModel(ModelPart root) {\n\t\tsuper(RenderType::entityCutout);\n\t\tthis.le_fishe = root.getChild(\"le_fishe\");\n\t\tthis.head = le_fishe.getChild(\"head\");\n\t\tthis.mouth = head.getChild(\"lower_mouth\");\n\t\tthis.tail = le_fishe.getChild(\"tail\");\n\t}\n\n\tpublic static LayerDefinition createBodyLayer() {\n\t\tMeshDefinition meshdefinition = new MeshDefinition();\n\t\tPartDefinition partdefinition = meshdefinition.getRoot();\n\n\t\tPartDefinition le_fishe = partdefinition.addOrReplaceChild(\"le_fishe\", CubeListBuilder.create(), PartPose.offset(0.0F, 16.0F, -1.0F));\n\n\t\tPartDefinition tail = le_fishe.addOrReplaceChild(\"tail\", CubeListBuilder.create().texOffs(12, 11).addBox(0.0F, -2.0F, 0.0F, 5.0F, 4.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offset(2.5F, -0.25F, 7.0F));\n\n\t\tPartDefinition body = le_fishe.addOrReplaceChild(\"body\", CubeListBuilder.create().texOffs(15, 15).addBox(-3.0198F, -2.2226F, -1.0167F, 4.0F, 4.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(1.5198F, -0.0274F, 7.0167F));\n\n\t\tPartDefinition top_front_fin_r1 = body.addOrReplaceChild(\"top_front_fin_r1\", CubeListBuilder.create().texOffs(6, 11).addBox(0.0F, 0.5F, 0.0F, 2.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-2.3948F, -3.7226F, 0.0333F, 0.0F, 0.0F, 0.3927F));\n\n\t\tPartDefinition top_back_fin_r1 = body.addOrReplaceChild(\"top_back_fin_r1\", CubeListBuilder.create().texOffs(6, 13).addBox(-0.5F, -0.5F, 0.0F, 3.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-0.1198F, -2.7226F, 0.0333F, 0.0F, 0.0F, 0.3927F));\n\n\t\tPartDefinition bottom_fin_r1 = body.addOrReplaceChild(\"bottom_fin_r1\", CubeListBuilder.create().texOffs(10, 11).addBox(-0.25F, -1.0F, 0.0F, 1.0F, 2.0F, 0.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(0.2302F, 2.2774F, -0.0167F, 0.0F, 0.0F, -0.7854F));\n\n\t\tPartDefinition head = le_fishe.addOrReplaceChild(\"head\", CubeListBuilder.create().texOffs(0, 15).addBox(-4.0F, -2.0F, -1.0F, 4.0F, 4.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(-1.5F, -0.25F, 7.0F));\n\n\t\tPartDefinition upper_mouth = head.addOrReplaceChild(\"upper_mouth\", CubeListBuilder.create().texOffs(9, 21).addBox(-5.0F, -1.275F, -0.975F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(-1.0F, -0.25F, 0.0F));\n\n\t\tPartDefinition lower_mouth = head.addOrReplaceChild(\"lower_mouth\", CubeListBuilder.create().texOffs(0, 21).addBox(-2.5F, -0.525F, -0.975F, 2.0F, 2.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(-3.5F, 0.0F, 0.0F));\n\n\t\treturn LayerDefinition.create(meshdefinition, 32, 32);\n\t}\n\n\t@Override\n\tpublic void renderToBuffer(PoseStack poseStack, VertexConsumer vertexConsumer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) {\n\t\tle_fishe.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha);\n\t}\n\n\n\tpublic void setRotations(BlockyBassBlockEntity bass, float partialTicks) {\n\t\tthis.head.yRot = -bass.head.value(partialTicks);\n\t\tthis.mouth.zRot = -bass.mouth.value(partialTicks);\n\t\tthis.tail.yRot = bass.tail.value(partialTicks);\n\t}\n}"
}
] | import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.rendering.v1.EntityModelLayerRegistry;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import one.devos.nautical.blocky_bass.block.BlockyBassBlockEntityRenderer;
import one.devos.nautical.blocky_bass.block.BlockyBassModel; | 1,953 | package one.devos.nautical.blocky_bass;
public class BlockyBassClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
BlockEntityRenderers.register(BlockyBass.BLOCK_ENTITY, BlockyBassBlockEntityRenderer::new); | package one.devos.nautical.blocky_bass;
public class BlockyBassClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
BlockEntityRenderers.register(BlockyBass.BLOCK_ENTITY, BlockyBassBlockEntityRenderer::new); | EntityModelLayerRegistry.registerModelLayer(BlockyBassModel.LAYER_LOCATION, BlockyBassModel::createBodyLayer); | 1 | 2023-12-18 05:18:17+00:00 | 4k |
lpyleo/disk-back-end | file-web/src/main/java/com/disk/file/controller/DeptFiletransferController.java | [
{
"identifier": "RestResult",
"path": "file-web/src/main/java/com/disk/file/common/RestResult.java",
"snippet": "@Data\npublic class RestResult<T> {\n private Boolean success = true;\n private Integer code;\n private String message;\n private T data;\n\n // ่ชๅฎไน่ฟๅๆฐๆฎ\n public RestResult data(T param) {\n this.setData(param);\n return this;\n }\n\n // ่ชๅฎไน็ถๆไฟกๆฏ\n public RestResult message(String message) {\n this.setMessage(message);\n return this;\n }\n\n // ่ชๅฎไน็ถๆ็ \n public RestResult code(Integer code) {\n this.setCode(code);\n return this;\n }\n\n // ่ฎพ็ฝฎ็ปๆ๏ผๅฝขๅไธบ็ปๆๆไธพ\n public static RestResult setResult(ResultCodeEnum result) {\n RestResult r = new RestResult();\n r.setSuccess(result.getSuccess());\n r.setCode(result.getCode());\n r.setMessage(result.getMessage());\n return r;\n }\n\n // ้็จ่ฟๅๆๅ\n public static RestResult success() {\n RestResult r = new RestResult();\n r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());\n r.setCode(ResultCodeEnum.SUCCESS.getCode());\n r.setMessage(ResultCodeEnum.SUCCESS.getMessage());\n return r;\n }\n\n // ้็จ่ฟๅๅคฑ่ดฅ๏ผๆช็ฅ้่ฏฏ\n public static RestResult fail() {\n RestResult r = new RestResult();\n r.setSuccess(ResultCodeEnum.UNKNOWN_ERROR.getSuccess());\n r.setCode(ResultCodeEnum.UNKNOWN_ERROR.getCode());\n r.setMessage(ResultCodeEnum.UNKNOWN_ERROR.getMessage());\n return r;\n }\n\n}"
},
{
"identifier": "DownloadDeptFileDTO",
"path": "file-web/src/main/java/com/disk/file/dto/DownloadDeptFileDTO.java",
"snippet": "@Data\n@Schema(name = \"ไธ่ฝฝ้จ้จๆไปถDTO\",required = true)\npublic class DownloadDeptFileDTO {\n private Long deptFileId;\n}"
},
{
"identifier": "DownloadFileDTO",
"path": "file-web/src/main/java/com/disk/file/dto/DownloadFileDTO.java",
"snippet": "@Data\n@Schema(name = \"ไธ่ฝฝๆไปถDTO\",required = true)\npublic class DownloadFileDTO {\n private Long userFileId;\n}"
},
{
"identifier": "UploadFileDTO",
"path": "file-web/src/main/java/com/disk/file/dto/UploadFileDTO.java",
"snippet": "@Data\n@Schema(name = \"ไธไผ ๆไปถDTO\",required = true)\npublic class UploadFileDTO {\n\n @Schema(description = \"ๆไปถ่ทฏๅพ\")\n private String filePath;\n\n @Schema(description = \"ไธไผ ๆถ้ด\")\n private String uploadTime;\n\n @Schema(description = \"ๆฉๅฑๅ\")\n private String extendName;\n\n\n @Schema(description = \"ๆไปถๅ\")\n private String filename;\n\n @Schema(description = \"ๆไปถๅคงๅฐ\")\n private Long fileSize;\n\n @Schema(description = \"ๅ็ๆฐ้\")\n private int chunkNumber;\n\n @Schema(description = \"ๅ็ๅคงๅฐ\")\n private long chunkSize;\n\n @Schema(description = \"ๆๆๅ็\")\n private int totalChunks;\n @Schema(description = \"ๆปๅคงๅฐ\")\n private long totalSize;\n @Schema(description = \"ๅฝๅๅ็ๅคงๅฐ\")\n private long currentChunkSize;\n @Schema(description = \"md5็ \")\n private String identifier;\n\n}"
},
{
"identifier": "DateUtil",
"path": "file-web/src/main/java/com/disk/file/util/DateUtil.java",
"snippet": "public class DateUtil {\n /**\n * ่ทๅ็ณป็ปๅฝๅๆถ้ด\n *\n * @return ็ณป็ปๅฝๅๆถ้ด\n */\n public static String getCurrentTime() {\n Date date = new Date();\n String stringDate = String.format(\"%tF %<tT\", date);\n return stringDate;\n }\n\n}"
},
{
"identifier": "FileUtil",
"path": "file-web/src/main/java/com/disk/file/util/FileUtil.java",
"snippet": "public class FileUtil {\n public static final String[] IMG_FILE = {\"bmp\", \"jpg\", \"png\", \"tif\", \"gif\", \"jpeg\"};\n public static final String[] DOC_FILE = {\"doc\", \"docx\", \"ppt\", \"pptx\", \"xls\", \"xlsx\", \"txt\", \"hlp\", \"wps\", \"rtf\", \"html\", \"pdf\"};\n public static final String[] VIDEO_FILE = {\"avi\", \"mp4\", \"mpg\", \"mov\", \"swf\"};\n public static final String[] MUSIC_FILE = {\"wav\", \"aif\", \"au\", \"mp3\", \"ram\", \"wma\", \"mmf\", \"amr\", \"aac\", \"flac\"};\n public static final int IMAGE_TYPE = 1;\n public static final int DOC_TYPE = 2;\n public static final int VIDEO_TYPE = 3;\n public static final int MUSIC_TYPE = 4;\n public static final int OTHER_TYPE = 5;\n public static final int SHARE_FILE = 6;\n public static final int RECYCLE_FILE = 7;\n /**\n * ๅคๆญๆฏๅฆไธบๅพ็ๆไปถ\n *\n * @param extendName ๆไปถๆฉๅฑๅ\n * @return ๆฏๅฆไธบๅพ็ๆไปถ\n */\n public static boolean isImageFile(String extendName) {\n for (int i = 0; i < IMG_FILE.length; i++) {\n if (extendName.equalsIgnoreCase(IMG_FILE[i])) {\n return true;\n }\n }\n return false;\n }\n /**\n * ่ทๅๆไปถๆฉๅฑๅ๏ผๅฆๆๆฒกๆๆฉๅฑๅ๏ผๅ่ฟๅ็ฉบไธฒ\n * @param fileName ๆไปถๅ\n * @return ๆไปถๆฉๅฑๅ\n */\n public static String getFileExtendName(String fileName) {\n if (fileName.lastIndexOf(\".\") == -1) {\n return \"\";\n }\n return fileName.substring(fileName.lastIndexOf(\".\") + 1);\n }\n\n /**\n * ่ทๅไธๅ
ๅซๆฉๅฑๅ็ๆไปถๅ\n *\n * @param fileName ๆไปถๅ\n * @return ๆไปถๅ๏ผไธๅธฆๆฉๅฑๅ๏ผ\n */\n public static String getFileNameNotExtend(String fileName) {\n String fileType = getFileExtendName(fileName);\n return fileName.replace(\".\" + fileType, \"\");\n }\n}"
},
{
"identifier": "UploadFileVo",
"path": "file-web/src/main/java/com/disk/file/vo/UploadFileVo.java",
"snippet": "@Data\n@Schema(name = \"ๆไปถไธไผ Vo\",required = true)\npublic class UploadFileVo {\n\n @Schema(description = \"ๆถ้ดๆณ\", example = \"123\")\n private String timeStampName;\n @Schema(description = \"่ทณ่ฟไธไผ \", example = \"true\")\n private boolean skipUpload;\n @Schema(description = \"ๆฏๅฆ้่ฆๅๅนถๅ็\", example = \"true\")\n private boolean needMerge;\n @Schema(description = \"ๅทฒ็ปไธไผ ็ๅ็\", example = \"[1,2,3]\")\n private List<Integer> uploaded;\n\n\n}"
}
] | import com.disk.file.common.RestResult;
import com.disk.file.dto.DownloadDeptFileDTO;
import com.disk.file.dto.DownloadFileDTO;
import com.disk.file.dto.UploadFileDTO;
import com.disk.file.model.*;
import com.disk.file.service.*;
import com.disk.file.util.DateUtil;
import com.disk.file.util.FileUtil;
import com.disk.file.vo.UploadFileVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 1,895 | package com.disk.file.controller;
@Tag(name = "deptfiletransfer", description = "่ฏฅๆฅๅฃไธบ้จ้จๆไปถไผ ่พๆฅๅฃ๏ผไธป่ฆ็จๆฅๅ้จ้จๆไปถ็ไธไผ ๅไธ่ฝฝ")
@RestController
@RequestMapping("/deptfiletransfer")
public class DeptFiletransferController {
@Resource
UserService userService;
@Resource
FileService fileService;
@Resource
DepartmentfileService departmentfileService;
@Resource
DeptFiletransferService deptFiletransferService;
@Operation(summary = "ๆ้ไธไผ ", description = "ๆ ก้ชๆไปถMD5ๅคๆญๆไปถๆฏๅฆๅญๅจ๏ผๅฆๆๅญๅจ็ดๆฅไธไผ ๆๅๅนถ่ฟๅskipUpload=true๏ผๅฆๆไธๅญๅจ่ฟๅskipUpload=false้่ฆๅๆฌก่ฐ็จ่ฏฅๆฅๅฃ็POSTๆนๆณ", tags = {"deptfiletransfer"})
@GetMapping(value = "/uploadfile")
@ResponseBody | package com.disk.file.controller;
@Tag(name = "deptfiletransfer", description = "่ฏฅๆฅๅฃไธบ้จ้จๆไปถไผ ่พๆฅๅฃ๏ผไธป่ฆ็จๆฅๅ้จ้จๆไปถ็ไธไผ ๅไธ่ฝฝ")
@RestController
@RequestMapping("/deptfiletransfer")
public class DeptFiletransferController {
@Resource
UserService userService;
@Resource
FileService fileService;
@Resource
DepartmentfileService departmentfileService;
@Resource
DeptFiletransferService deptFiletransferService;
@Operation(summary = "ๆ้ไธไผ ", description = "ๆ ก้ชๆไปถMD5ๅคๆญๆไปถๆฏๅฆๅญๅจ๏ผๅฆๆๅญๅจ็ดๆฅไธไผ ๆๅๅนถ่ฟๅskipUpload=true๏ผๅฆๆไธๅญๅจ่ฟๅskipUpload=false้่ฆๅๆฌก่ฐ็จ่ฏฅๆฅๅฃ็POSTๆนๆณ", tags = {"deptfiletransfer"})
@GetMapping(value = "/uploadfile")
@ResponseBody | public RestResult<UploadFileVo> uploadFileSpeed(UploadFileDTO uploadFileDto, @RequestHeader("token") String token) { | 3 | 2023-12-17 05:12:43+00:00 | 4k |
ReChronoRain/HyperCeiler | app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/base/SettingsPreferenceFragment.java | [
{
"identifier": "BaseActivity",
"path": "app/src/main/java/com/sevtinge/hyperceiler/ui/base/BaseActivity.java",
"snippet": "public abstract class BaseActivity extends AppCompatActivity {\n\n protected BaseSettingsProxy mProxy;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n mProxy = new SettingsProxy(this);\n super.onCreate(savedInstanceState);\n initActionBar();\n registerObserver();\n }\n\n protected void initActionBar() {\n setDisplayHomeAsUpEnabled(!(this instanceof NavigationActivity));\n }\n\n public void setDisplayHomeAsUpEnabled(boolean isEnable) {\n getAppCompatActionBar().setDisplayHomeAsUpEnabled(isEnable);\n }\n\n public void setActionBarEndView(View view) {\n getAppCompatActionBar().setEndView(view);\n }\n\n public void setActionBarEndIcon(@DrawableRes int resId, View.OnClickListener listener) {\n ImageView mRestartView = new ImageView(this);\n mRestartView.setImageResource(resId);\n mRestartView.setOnClickListener(listener);\n setActionBarEndView(mRestartView);\n }\n\n public void setRestartView(View.OnClickListener listener) {\n if (listener != null) setActionBarEndIcon(R.drawable.ic_reboot_small, listener);\n }\n\n private void registerObserver() {\n PrefsUtils.mSharedPreferences.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);\n Helpers.fixPermissionsAsync(getApplicationContext());\n registerFileObserver();\n }\n\n SharedPreferences.OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = (sharedPreferences, s) -> {\n Log.i(\"prefs\", \"Changed: \" + s);\n requestBackup();\n Object val = sharedPreferences.getAll().get(s);\n String path = \"\";\n if (val instanceof String)\n path = \"string/\";\n else if (val instanceof Set<?>)\n path = \"stringset/\";\n else if (val instanceof Integer)\n path = \"integer/\";\n else if (val instanceof Boolean)\n path = \"boolean/\";\n getContentResolver().notifyChange(Uri.parse(\"content://\" + SharedPrefsProvider.AUTHORITY + \"/\" + path + s), null);\n if (!path.equals(\"\")) getContentResolver().notifyChange(Uri.parse(\"content://\" + SharedPrefsProvider.AUTHORITY + \"/pref/\" + path + s), null);\n };\n\n private void registerFileObserver() {\n try {\n FileObserver mFileObserver = new FileObserver(PrefsUtils.getSharedPrefsPath(), FileObserver.CLOSE_WRITE) {\n @Override\n public void onEvent(int event, String path) {\n Helpers.fixPermissionsAsync(getApplicationContext());\n }\n };\n mFileObserver.startWatching();\n } catch (Throwable t) {\n Log.e(\"prefs\", \"Failed to start FileObserver!\");\n }\n }\n\n public void requestBackup() {\n new BackupManager(getApplicationContext()).dataChanged();\n }\n}"
},
{
"identifier": "PrefsUtils",
"path": "app/src/main/java/com/sevtinge/hyperceiler/utils/PrefsUtils.java",
"snippet": "public class PrefsUtils {\n\n public static SharedPreferences mSharedPreferences = null;\n\n public static String mPrefsPathCurrent = null;\n public static String mPrefsFileCurrent = null;\n public static String mPrefsName = \"hyperceiler_prefs\";\n public static String mPrefsPath = \"/data/user_de/0/\" + ProjectApi.mAppModulePkg + \"/shared_prefs\";\n public static String mPrefsFile = mPrefsPath + \"/\" + mPrefsName + \".xml\";\n\n\n public static SharedPreferences getSharedPrefs(Context context, boolean multiProcess) {\n context = Helpers.getProtectedContext(context);\n try {\n return context.getSharedPreferences(mPrefsName, multiProcess ? Context.MODE_MULTI_PROCESS | Context.MODE_WORLD_READABLE : Context.MODE_WORLD_READABLE);\n } catch (Throwable t) {\n return context.getSharedPreferences(mPrefsName, multiProcess ? Context.MODE_MULTI_PROCESS | Context.MODE_PRIVATE : Context.MODE_PRIVATE);\n }\n }\n\n public static SharedPreferences getSharedPrefs(Context context) {\n return getSharedPrefs(context, false);\n }\n\n\n public static String getSharedPrefsPath() {\n if (mPrefsPathCurrent == null) try {\n Field mFile = mSharedPreferences.getClass().getDeclaredField(\"mFile\");\n mFile.setAccessible(true);\n mPrefsPathCurrent = ((File) mFile.get(mSharedPreferences)).getParentFile().getAbsolutePath();\n return mPrefsPathCurrent;\n } catch (Throwable t) {\n System.out.print(\"Test\" + t);\n return mPrefsPath;\n }\n else return mPrefsPathCurrent;\n }\n\n public static String getSharedPrefsFile() {\n if (mPrefsFileCurrent == null) try {\n Field fFile = mSharedPreferences.getClass().getDeclaredField(\"mFile\");\n fFile.setAccessible(true);\n mPrefsFileCurrent = ((File) fFile.get(mSharedPreferences)).getAbsolutePath();\n System.out.println(\"Test: mPrefsFileCurrent\");\n return mPrefsFileCurrent;\n } catch (Throwable t) {\n System.out.println(\"Test: mPrefsFile\" + t);\n return mPrefsFile;\n }\n else\n System.out.println(\"Test: mPrefsFileCurrent2\");\n return mPrefsFileCurrent;\n }\n\n\n public static boolean contains(String key) {\n return mSharedPreferences.contains(key);\n }\n\n public static SharedPreferences.Editor editor() {\n return mSharedPreferences.edit();\n }\n\n\n public static String getSharedStringPrefs(Context context, String name, String defValue) {\n Uri uri = PrefToUri.stringPrefToUri(name, defValue);\n try {\n Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);\n if (cursor != null && cursor.moveToFirst()) {\n String prefValue = cursor.getString(0);\n cursor.close();\n return prefValue;\n } else XposedLogUtils.logI(\"ContentResolver\", \"[\" + name + \"] Cursor fail: \" + cursor);\n } catch (Throwable t) {\n XposedBridge.log(t);\n }\n\n if (XposedInit.mPrefsMap.containsKey(name))\n return (String) XposedInit.mPrefsMap.getObject(name, defValue);\n else return defValue;\n }\n\n public static Set<String> getSharedStringSetPrefs(Context context, String name) {\n Uri uri = PrefToUri.stringSetPrefToUri(name);\n try {\n Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);\n if (cursor != null) {\n Set<String> prefValue = new LinkedHashSet<>();\n while (cursor.moveToNext()) {\n prefValue.add(cursor.getString(0));\n }\n cursor.close();\n return prefValue;\n } else {\n XposedLogUtils.logI(\"ContentResolver\", \"[\" + name + \"] Cursor fail: null\");\n }\n } catch (Throwable t) {\n XposedBridge.log(t);\n }\n\n LinkedHashSet<String> empty = new LinkedHashSet<>();\n if (XposedInit.mPrefsMap.containsKey(name)) {\n return (Set<String>) XposedInit.mPrefsMap.getObject(name, empty);\n } else {\n return empty;\n }\n }\n\n\n public static int getSharedIntPrefs(Context context, String name, int defValue) {\n Uri uri = PrefToUri.intPrefToUri(name, defValue);\n try {\n Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);\n if (cursor != null && cursor.moveToFirst()) {\n int prefValue = cursor.getInt(0);\n cursor.close();\n return prefValue;\n } else XposedLogUtils.logI(\"ContentResolver\", \"[\" + name + \"] Cursor fail: \" + cursor);\n } catch (Throwable t) {\n XposedBridge.log(t);\n }\n\n if (XposedInit.mPrefsMap.containsKey(name))\n return (int) XposedInit.mPrefsMap.getObject(name, defValue);\n else return defValue;\n }\n\n\n public static boolean getSharedBoolPrefs(Context context, String name, boolean defValue) {\n Uri uri = PrefToUri.boolPrefToUri(name, defValue);\n try {\n Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);\n if (cursor != null && cursor.moveToFirst()) {\n int prefValue = cursor.getInt(0);\n cursor.close();\n return prefValue == 1;\n } else XposedLogUtils.logI(\"ContentResolver\", \"[\" + name + \"] Cursor fail: \" + cursor);\n } catch (Throwable t) {\n XposedBridge.log(t);\n }\n\n if (XposedInit.mPrefsMap.containsKey(name))\n return (boolean) XposedInit.mPrefsMap.getObject(name, false);\n else\n return defValue;\n }\n}"
}
] | import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.sevtinge.hyperceiler.ui.base.BaseActivity;
import com.sevtinge.hyperceiler.utils.PrefsUtils; | 2,444 | package com.sevtinge.hyperceiler.ui.fragment.base;
public abstract class SettingsPreferenceFragment extends BasePreferenceFragment {
public String mTitle;
public String mPreferenceKey;
public int mContentResId = 0;
public int mTitleResId = 0;
private boolean mPreferenceHighlighted = false;
private final String SAVE_HIGHLIGHTED_KEY = "android:preference_highlighted";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
highlightPreferenceIfNeeded(mPreferenceKey);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mPreferenceHighlighted = savedInstanceState.getBoolean(SAVE_HIGHLIGHTED_KEY);
}
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
super.onCreatePreferences(bundle, s);
Bundle args = getArguments();
if (args != null) {
mTitle = args.getString(":fragment:show_title");
mTitleResId = args.getInt(":fragment:show_title_resid");
mPreferenceKey = args.getString(":settings:fragment_args_key");
mContentResId = args.getInt("contentResId");
}
if (mTitleResId != 0) setTitle(mTitleResId);
if (!TextUtils.isEmpty(mTitle)) setTitle(mTitle);
mContentResId = mContentResId != 0 ? mContentResId : getContentResId();
if (mContentResId != 0) {
setPreferencesFromResource(mContentResId, s);
initPrefs();
} | package com.sevtinge.hyperceiler.ui.fragment.base;
public abstract class SettingsPreferenceFragment extends BasePreferenceFragment {
public String mTitle;
public String mPreferenceKey;
public int mContentResId = 0;
public int mTitleResId = 0;
private boolean mPreferenceHighlighted = false;
private final String SAVE_HIGHLIGHTED_KEY = "android:preference_highlighted";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
highlightPreferenceIfNeeded(mPreferenceKey);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mPreferenceHighlighted = savedInstanceState.getBoolean(SAVE_HIGHLIGHTED_KEY);
}
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
super.onCreatePreferences(bundle, s);
Bundle args = getArguments();
if (args != null) {
mTitle = args.getString(":fragment:show_title");
mTitleResId = args.getInt(":fragment:show_title_resid");
mPreferenceKey = args.getString(":settings:fragment_args_key");
mContentResId = args.getInt("contentResId");
}
if (mTitleResId != 0) setTitle(mTitleResId);
if (!TextUtils.isEmpty(mTitle)) setTitle(mTitle);
mContentResId = mContentResId != 0 ? mContentResId : getContentResId();
if (mContentResId != 0) {
setPreferencesFromResource(mContentResId, s);
initPrefs();
} | ((BaseActivity) getActivity()).setRestartView(addRestartListener()); | 0 | 2023-10-27 17:17:42+00:00 | 4k |
thebatmanfuture/fofa_search | src/main/java/org/fofaviewer/utils/DataUtil.java | [
{
"identifier": "BaseBean",
"path": "src/main/java/org/fofaviewer/bean/BaseBean.java",
"snippet": "public class BaseBean {\n}"
},
{
"identifier": "ExcelBean",
"path": "src/main/java/org/fofaviewer/bean/ExcelBean.java",
"snippet": "@Getter\n@Setter\n@EqualsAndHashCode\npublic class ExcelBean extends BaseBean {\n private String host;\n private String title;\n private String domain;\n\n private String certCN;\n\n private String ip;\n\n private Integer port;\n\n private String protocol;\n\n private String server;\n\n private String fid;\n\n public ExcelBean(String host, String title, String ip, String domain, Integer port, String protocol, String server, String fid, String certCN) {\n this.host = host;\n this.title = title;\n this.ip = ip;\n this.domain = domain;\n this.port = port;\n this.protocol = protocol;\n this.server = server;\n this.fid = fid;\n this.certCN = certCN;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof ExcelBean))\n return false;\n if (this == obj)\n return true;\n ExcelBean instance = (ExcelBean) obj;\n boolean port = this.port.equals(instance.port);\n boolean host = this.host.equals(instance.host);\n if(port){\n if(this.port == 443 && (this.host.contains(\":443\") || instance.host.contains(\":443\"))){\n host = true;\n }\n if(this.port == 80 && (this.host.contains(\":80\") || instance.host.contains(\":80\"))){\n host = true;\n }\n }\n boolean ip = this.ip.equals(instance.ip);\n\n return host && ip && port;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(ip, port);\n }\n}"
},
{
"identifier": "TabDataBean",
"path": "src/main/java/org/fofaviewer/bean/TabDataBean.java",
"snippet": "public class TabDataBean {\n /**\n * ๆฅ่ฏขๆกไปถๅฏนๅบtab้กตไธญๅทฒๅ ่ฝฝ็ๆฐ้\n */\n public int count;\n /**\n * ๆฅ่ฏขๆกไปถๅฏนๅบtab้กตๅฏ่ทๅ็ๆปๆฐ\n */\n public int total;\n /**\n * ๅฏผๅบๆฅ่ฏขๆกไปถๅฏนๅบtab้กตไธญ็url๏ผ็จไบๅ็ปญๆซๆ\n */\n public HashSet<String> dataList;\n /**\n * ๆฏๅฆ่ฟๆๆชๅ ่ฝฝ็ๆฐๆฎ\n */\n public boolean hasMoreData = true;\n /**\n * ๅฝๅๅทฒๅ ่ฝฝ็้กตๆฐ\n */\n public int page = 1;\n\n public TabDataBean(int count, HashSet<String> dataList) {\n this.count = count;\n this.dataList = dataList;\n }\n public TabDataBean(){\n this.count = 0;\n this.dataList = new HashSet<>();\n }\n}"
},
{
"identifier": "TableBean",
"path": "src/main/java/org/fofaviewer/bean/TableBean.java",
"snippet": "public class TableBean extends BaseBean{\n public SimpleIntegerProperty num = new SimpleIntegerProperty();\n public SimpleStringProperty host = new SimpleStringProperty();\n public SimpleStringProperty title = new SimpleStringProperty();\n public SimpleStringProperty ip = new SimpleStringProperty();\n public SimpleStringProperty domain = new SimpleStringProperty();\n public SimpleIntegerProperty port = new SimpleIntegerProperty();\n public SimpleStringProperty protocol = new SimpleStringProperty();\n public SimpleStringProperty server = new SimpleStringProperty();\n public SimpleStringProperty fid = new SimpleStringProperty();\n public SimpleStringProperty cert = new SimpleStringProperty();\n public SimpleStringProperty certCN = new SimpleStringProperty();\n public SimpleStringProperty status = new SimpleStringProperty();\n\n public TableBean(int num, String host, String title, String ip, String domain, int port, String protocol,\n String server, String fid, String cert, String certCN) {\n this.num.set(num);\n this.host.set(host);\n this.title.set(title);\n this.ip.set(ip);\n this.domain.set(domain);\n this.port.set(port);\n this.protocol.set(protocol);\n this.server.set(server);\n this.fid.set(fid);\n this.cert.set(cert);\n this.certCN.set(certCN);\n this.status.set(\"\");\n }\n\n public void setNum(SimpleIntegerProperty numValue){\n this.num = numValue;\n }\n\n public void setDomain(String value){\n this.domain = new SimpleStringProperty(value);\n }\n\n public int getIntNum(){\n return num.intValue();\n }\n\n public SimpleIntegerProperty getNum() {\n return num;\n }\n\n public SimpleStringProperty getHost() {\n return host;\n }\n\n public SimpleStringProperty getTitle() {\n return title;\n }\n\n public SimpleStringProperty getIp() {\n return ip;\n }\n\n public SimpleStringProperty getDomain() {\n return domain;\n }\n\n public SimpleIntegerProperty getPort() {\n return port;\n }\n\n public SimpleStringProperty getProtocol() {\n return protocol;\n }\n\n public SimpleStringProperty getServer(){\n return server;\n }\n\n public SimpleStringProperty getFid() {\n return fid;\n }\n\n public SimpleStringProperty getCert() {\n return cert;\n }\n\n public SimpleStringProperty getCertCN() {\n return certCN;\n }\n\n public SimpleStringProperty getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status.set(status);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof TableBean))\n return false;\n if (this == obj)\n return true;\n TableBean instance = (TableBean) obj;\n boolean bool_host = this.host.getValue().equals(instance.host.getValue());\n boolean bool_port = this.port.getValue().equals(instance.port.getValue());\n if(bool_port){\n if(this.port.getValue() == 443 && (this.host.getValue().contains(\":443\") || instance.host.getValue().contains(\":443\"))){\n bool_host = true;\n }\n if(this.port.getValue() == 80 && (this.host.getValue().contains(\":80\") || instance.host.getValue().contains(\":80\"))){\n bool_host = true;\n }\n }\n boolean bool_ip = this.ip.getValue().equals(instance.ip.getValue());\n return bool_host && bool_ip && bool_port;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(ip.getValue(), port.getValue());\n }\n}"
},
{
"identifier": "SetConfiDialog",
"path": "src/main/java/org/fofaviewer/controls/SetConfiDialog.java",
"snippet": "public class SetConfiDialog extends Dialog<ButtonType> {\n public SetConfiDialog(String title) {\n try{\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"/fxml/SetConfigDialog.fxml\"));\n Pane pane = loader.load();\n this.setTitle(title);\n DialogPane dialogPane = this.getDialogPane();\n dialogPane.setContent(pane);\n dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);\n SetConfigDialogController controller = loader.getController();\n controller.setAction(dialogPane);\n }catch (IOException e){\n Logger.error(e);\n }\n }\n}"
},
{
"identifier": "FofaConfig",
"path": "src/main/java/org/fofaviewer/main/FofaConfig.java",
"snippet": "public class FofaConfig {\n private static FofaConfig config = null;\n private boolean checkStatus;\n private String email;\n private String key;\n private final String page = \"1\";\n public final int max = 10000;\n private String size = \"1000\";\n public String API = \"https://fofa.info\";\n public String personalInfoAPI = \"https://fofa.info/api/v1/info/my?email=%s&key=%s\";\n public final String path = \"/api/v1/search/all\";\n public static final String TIP_API = \"https://api.fofa.info/v1/search/tip?q=\";\n //public static final String TIP_API = Locale.getDefault()==Locale.CHINA ? \"https://api.fofa.so/v1/search/tip?q=\"\n public ArrayList<String> fields = new ArrayList<String>(){{add(\"host\");add(\"ip\");add(\"domain\");add(\"port\");add(\"protocol\");add(\"server\");}};//title,cert\";\n\n private FofaConfig(){\n this.email = \"\";\n this.key = \"\";\n }\n\n public static FofaConfig getInstance(){\n if (config == null) {\n config = new FofaConfig();\n }\n return config;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public void setAPI(String API) {\n this.API = API;\n }\n\n public String getSize() {\n return this.size;\n }\n\n public void setSize(String size){\n this.size = size;\n }\n\n public String getParam(String page, boolean isAll) {\n String all = isAll ? \"&full=true\" : \"\";\n StringBuilder builder = new StringBuilder(API).append(path).append(\"?email=\").append(email).append(\"&key=\").append(key).append(all).append(\"&page=\");\n if(page != null) {\n return builder.append(page).append(\"&size=\").append(size).append(\"&fields=\").append(getFields()).append(\"&qbase64=\").toString();\n }else{\n return builder.append(this.page).append(\"&size=\").append(size).append(\"&fields=\").append(getFields()).append(\"&qbase64=\").toString();\n }\n }\n\n public String getFields(){\n StringBuilder builder = new StringBuilder();\n for(String i : this.fields){\n builder.append(i).append(\",\");\n }\n String a = builder.toString();\n return a.substring(0,a.length()-1);\n }\n\n public boolean getCheckStatus() {\n return checkStatus;\n }\n\n public void setCheckStatus(boolean checkStatus) {\n this.checkStatus = checkStatus;\n }\n}"
},
{
"identifier": "ProxyConfig",
"path": "src/main/java/org/fofaviewer/main/ProxyConfig.java",
"snippet": "public class ProxyConfig {\n public enum ProxyType {HTTP, SOCKS5 }\n private static ProxyConfig config;\n private boolean status;\n private ProxyType proxy_type;\n private String proxy_ip;\n private String proxy_port;\n private String proxy_user;\n private String proxy_password;\n\n private ProxyConfig() {\n status = false;\n proxy_type = ProxyType.HTTP;\n proxy_ip = \"\";\n proxy_port = \"\";\n proxy_password = \"\";\n proxy_user = \"\";\n }\n public static ProxyConfig getInstance(){\n if (config == null) {\n config = new ProxyConfig();\n }\n return config;\n }\n\n public Proxy getProxy() {\n if(!this.proxy_user.equals(\"\") && !this.proxy_password.equals(\"\")){\n Authenticator.setDefault(new Authenticator(){\n public PasswordAuthentication getPasswordAuthentication() {\n return (new PasswordAuthentication(proxy_user, proxy_password.toCharArray()));\n }\n });\n }else{\n Authenticator.setDefault(null);\n }\n switch (this.proxy_type){\n case HTTP: return Proxies.httpProxy(this.proxy_ip, Integer.parseInt(this.proxy_port));\n case SOCKS5: return Proxies.socksProxy(this.proxy_ip, Integer.parseInt(this.proxy_port));\n }\n return null;\n }\n\n public void setProxy_type(ProxyType proxy_type) {\n this.proxy_type = proxy_type;\n }\n\n public String getProxy_ip() {\n return proxy_ip;\n }\n\n public void setProxy_ip(String proxy_ip) {\n this.proxy_ip = proxy_ip;\n }\n\n public String getProxy_port() {\n return proxy_port;\n }\n\n public void setProxy_port(String proxy_port) {\n this.proxy_port = proxy_port;\n }\n\n public String getProxy_user() {\n return proxy_user;\n }\n\n public void setProxy_user(String proxy_user) {\n this.proxy_user = proxy_user;\n }\n\n public String getProxy_password() {\n return proxy_password;\n }\n\n public void setProxy_password(String proxy_password) {\n this.proxy_password = proxy_password;\n }\n\n public boolean getStatus() {\n return status;\n }\n\n public void setStatus(boolean status) {\n this.status = status;\n }\n}"
}
] | import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Platform;
import javafx.scene.control.*;
import org.fofaviewer.bean.BaseBean;
import org.fofaviewer.bean.ExcelBean;
import org.fofaviewer.bean.TabDataBean;
import org.fofaviewer.bean.TableBean;
import org.fofaviewer.controls.SetConfiDialog;
import org.fofaviewer.main.FofaConfig;
import org.fofaviewer.main.ProxyConfig;
import org.tinylog.Logger;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 3,329 | package org.fofaviewer.utils;
public class DataUtil {
private static final RequestUtil helper = RequestUtil.getInstance();
private static final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private static final Pattern portPattern1 = Pattern.compile(":443$");
private static final Pattern portPattern2 = Pattern.compile(":80$");
/**
* ๅฏน่ฏๆก้
็ฝฎ
* @param type dialog type
* @param header dialog title
* @param content content of dialog
*/
public static Alert showAlert(Alert.AlertType type, String header, String content){
Alert alert = new Alert(type);
alert.setTitle("ๆ็คบ");
alert.setHeaderText(header);
alert.setContentText(content);
return alert;
}
| package org.fofaviewer.utils;
public class DataUtil {
private static final RequestUtil helper = RequestUtil.getInstance();
private static final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private static final Pattern portPattern1 = Pattern.compile(":443$");
private static final Pattern portPattern2 = Pattern.compile(":80$");
/**
* ๅฏน่ฏๆก้
็ฝฎ
* @param type dialog type
* @param header dialog title
* @param content content of dialog
*/
public static Alert showAlert(Alert.AlertType type, String header, String content){
Alert alert = new Alert(type);
alert.setTitle("ๆ็คบ");
alert.setHeaderText(header);
alert.setContentText(content);
return alert;
}
| public static void exportToExcel(String fileName, String tabTitle, List<ExcelBean> totalData, List<List<String>> urls, StringBuilder errorPage) { | 1 | 2023-10-25 11:13:47+00:00 | 4k |
qguangyao/MySound | src/main/java/com/jvspiano/sound/resolver/AppoggiaturaResolverIMPL.java | [
{
"identifier": "MyNoteIMPL",
"path": "src/main/java/com/jvspiano/sound/note/MyNoteIMPL.java",
"snippet": "public class MyNoteIMPL implements MyNote {\n\n /**\n * ็ธๅฏนไบ็ฎ่ฐฑ็ไธป่ฐ\n */\n private Major major;\n /**\n * ไธไธช่ๆ้้ขๆๅ ไธชtick\n */\n private String ppq;\n /**\n * ๆฒ่ฐฑ้ๅบฆ,beat per minute\n */\n private int bpm;\n /**\n * ๆญๆพ้ข้\n */\n private int channel = 0;\n /**\n * ไนๅจ๏ผ2็ต้ข็ด๏ผ40ๅฐๆ็ด\n */\n private int instrument = InstrumentEnum.ACOUSTIC_GRAND_PIANO.value;\n// private int instrument = InstrumentEnum.ELECTRIC_GRAND_PIANO.value;\n// private int instrument = InstrumentEnum.VIOLIN.value;\n /**\n * ้ณ็ฌฆไน้ด็ๅ้็ฌฆ\n */\n private String explan;\n /**\n * ๅณๆtickๆ ่ฎฐ\n */\n private boolean rightStart;\n /**\n * ๅทฆๆtickๆ ่ฎฐ\n */\n private boolean leftStart;\n\n private final int baseTick = 32;\n /**\n * ๆฏไธชๅฐ่็้ฟๅบฆ\n */\n private int barTick = baseTick;\n private OnMajorChangedListener majorChangedListener;\n private OnPPQChangedListener ppqChangedListener;\n private OnBPMChangedListener bpmChangedListener;\n\n public int getInstrument() {\n return instrument;\n }\n\n public void setInstrument(int instrument) {\n this.instrument = instrument;\n }\n\n public Major getMajor() {\n return major;\n }\n\n public MyNoteIMPL() {\n this.major = Major.C;\n }\n\n public String getExplan() {\n return explan;\n }\n\n public void setExplan(String explan) {\n this.explan = explan;\n }\n\n public void setMajorChangedListener(OnMajorChangedListener majorChangedListener) {\n this.majorChangedListener = majorChangedListener;\n }\n\n public void setPpqChangedListener(OnPPQChangedListener ppqChangedListener) {\n this.ppqChangedListener = ppqChangedListener;\n }\n\n public void setBpmChangedListener(OnBPMChangedListener bpmChangedListener) {\n this.bpmChangedListener = bpmChangedListener;\n }\n\n\n public String getPpq() {\n return ppq;\n }\n\n public int getBpm() {\n return bpm;\n }\n\n public boolean isRightStart() {\n return rightStart;\n }\n\n public boolean isLeftStart() {\n return leftStart;\n }\n\n public MyNoteIMPL(Major major, OnMajorChangedListener listener) {\n this.majorChangedListener = listener;\n if (majorChangedListener != null) {\n majorChangedListener.onMajorChange(this.major, major);\n }\n this.major = major;\n }\n\n @Override\n public MyNote setMajor(Major major) {\n if (majorChangedListener != null) {\n majorChangedListener.onMajorChange(this.major, major);\n }\n this.major = major;\n return this;\n }\n\n @Override\n public MyNote setPPQ(String ppq) {\n if (ppqChangedListener != null) {\n ppqChangedListener.onPPQChanged(this.ppq, ppq);\n }\n this.ppq = ppq;\n return this;\n }\n\n @Override\n public MyNote setBPM(int bpm) {\n if (bpmChangedListener != null) {\n bpmChangedListener.OnBPMChanged(this.bpm, bpm);\n }\n this.bpm = bpm;\n return this;\n }\n\n @Override\n public MyNote setRightStart(boolean rightStart) {\n this.rightStart = rightStart;\n return this;\n }\n\n @Override\n public MyNote setLeftStart(boolean leftStart) {\n this.leftStart = leftStart;\n return this;\n }\n\n /**\n * @param area ๅบไบไธญๅคฎๅบๅ้ๅ ไธชๅบๅ\n * @return\n */\n public int getDo(int area) {\n return major.value + 12 * area;\n }\n\n public int getDoUp(int area) {\n return major.value + 1 + 12 * area;\n }\n\n public int getRe(int area) {\n return major.value + 2 + 12 * area;\n }\n\n public int getReUp(int area) {\n return major.value + 3 + 12 * area;\n }\n\n public int getMi(int area) {\n return major.value + 4 + 12 * area;\n }\n\n public int getFa(int area) {\n return major.value + 5 + 12 * area;\n }\n\n public int getFaUp(int area) {\n return major.value + 6 + 12 * area;\n }\n\n public int getSol(int area) {\n return major.value + 7 + 12 * area;\n }\n\n public int getSolUp(int area) {\n return major.value + 8 + 12 * area;\n }\n\n public int getLa(int area) {\n return major.value + 9 + 12 * area;\n }\n\n public int getLaUp(int area) {\n return major.value + 10 + 12 * area;\n }\n\n public int getSi(int area) {\n return major.value + 11 + 12 * area;\n }\n\n public MyNoteIMPL setMajor(String major) {\n if (major == null) return this;\n major = major.toLowerCase();\n switch (major) {\n case \"a\":\n setMajor(Major.A);\n break;\n case \"a#\":\n setMajor(Major.AUp);\n break;\n case \"b\":\n setMajor(Major.B);\n break;\n case \"c\":\n setMajor(Major.C);\n break;\n case \"c#\":\n setMajor(Major.CUp);\n break;\n case \"d\":\n setMajor(Major.D);\n break;\n case \"d#\":\n setMajor(Major.DUp);\n break;\n case \"e\":\n setMajor(Major.E);\n break;\n case \"f\":\n setMajor(Major.F);\n break;\n case \"f#\":\n setMajor(Major.FUp);\n break;\n case \"g\":\n setMajor(Major.G);\n break;\n case \"g#\":\n setMajor(Major.GUp);\n break;\n default:\n throw new RuntimeException(\"้ๆณ็้ณ่ฐ\");\n }\n return this;\n }\n\n public String calNote(int code) {\n if (code == 0) {\n return \"0\";\n }\n int res = code - 57;\n int note = res % 12;\n int area = 0;\n String prin = \"\";\n if (res < 0) {\n area = (res - 12) / 12;\n for (int i = 0; i < Math.abs(area); i++) {\n prin += \"l\";\n }\n } else {\n area = res / 12;\n for (int i = 0; i < area; i++) {\n prin += \"h\";\n }\n }\n switch (Math.abs(note)) {\n case 0:\n prin += \"a \";\n break;\n case 1:\n prin += \"a#\";\n break;\n case 2:\n prin += \"b \";\n break;\n case 3:\n prin += \"c \";\n break;\n case 4:\n prin += \"c#\";\n break;\n case 5:\n prin += \"d \";\n break;\n case 6:\n prin += \"d#\";\n break;\n case 7:\n prin += \"e \";\n break;\n case 8:\n prin += \"f \";\n break;\n case 9:\n prin += \"f#\";\n break;\n case 10:\n prin += \"g \";\n break;\n case 11:\n prin += \"g#\";\n break;\n }\n return prin;\n }\n\n public String calNoteNum(int code) {\n if (code == 0) {\n return \"0\";\n }\n int res = code - major.value;\n int note = res % 12;\n int area = 0;\n String prin = \"\";\n if (res < 0) {\n area = (res - 12) / 12;\n for (int i = 0; i < Math.abs(area); i++) {\n prin += \"l\";\n }\n } else {\n area = res / 12;\n for (int i = 0; i < area; i++) {\n prin += \"h\";\n }\n }\n if (note < 0)\n note += 12;\n switch (Math.abs(note)) {\n case 0:\n prin += \"1\";\n break;\n case 1:\n prin += \"1#\";\n break;\n case 2:\n prin += \"2\";\n break;\n case 3:\n prin += \"2#\";\n break;\n case 4:\n prin += \"3\";\n break;\n case 5:\n prin += \"4\";\n break;\n case 6:\n prin += \"4#\";\n break;\n case 7:\n prin += \"5\";\n break;\n case 8:\n prin += \"5#\";\n break;\n case 9:\n prin += \"6\";\n break;\n case 10:\n prin += \"6#\";\n break;\n case 11:\n prin += \"7\";\n break;\n }\n return prin;\n }\n\n public int getBaseTick() {\n return baseTick;\n }\n\n public int getBarTick() {\n return barTick;\n }\n\n public void setBarTick(int barTick) {\n this.barTick = barTick;\n }\n\n public int getChannel() {\n return channel;\n }\n\n public void setChannel(int channel) {\n this.channel = channel;\n }\n}"
},
{
"identifier": "NoteInfo",
"path": "src/main/java/com/jvspiano/sound/note/NoteInfo.java",
"snippet": "public class NoteInfo implements Comparable<NoteInfo> {\n /**\n * ้ณ็ฌฆๅผๅง\n */\n public long originTick;\n /**\n * ้ณ็ฌฆ้ณ้ซ\n */\n public int note = -1;\n /**\n * ้ณ็ฌฆ้ฟๅบฆ\n */\n public int noteTick = 0;\n /**\n * ้ณ็ฌฆไป @originTickๅผๅงๅ็ป่ฟ @muteTickไธช่ๆ้้ณ\n */\n public int muteTick = 0;\n /**\n * ้ณ็ฌฆ้ณ้\n */\n public int volume = 100;\n /**\n * ๆญๆพ็ๆถ้ด็น\n */\n public long playTime = 0;\n\n /**\n * @return\n */\n public int bpm = -1;\n /**\n * ๅจๅชไธช้ข้\n */\n public int channel = 0;\n /**\n * ไนๅจ๏ผ\n */\n public int instrument = 0;\n\n public int getNoteLength() {\n if (muteTick == 0) {\n return noteTick;\n } else {\n return Math.min(noteTick, muteTick);\n }\n\n }\n\n @Override\n public int compareTo(NoteInfo o) {\n return (int) (originTick - o.originTick);\n }\n\n\n public long getOriginTick() {\n return originTick;\n }\n\n public void setOriginTick(long originTick) {\n this.originTick = originTick;\n }\n\n public int getNote() {\n return note;\n }\n\n public void setNote(int note) {\n this.note = note;\n }\n\n public int getNoteTick() {\n return noteTick;\n }\n\n public void setNoteTick(int noteTick) {\n this.noteTick = noteTick;\n }\n\n public int getMuteTick() {\n return muteTick;\n }\n\n public void setMuteTick(int muteTick) {\n this.muteTick = muteTick;\n }\n\n public int getVolume() {\n return volume;\n }\n\n public void setVolume(int volume) {\n this.volume = volume;\n }\n\n public long getPlayTime() {\n return playTime;\n }\n\n public void setPlayTime(long playTime) {\n this.playTime = playTime;\n }\n\n public void setBpm(int bpm) {\n this.bpm = bpm;\n }\n}"
}
] | import com.jvspiano.sound.note.MyNoteIMPL;
import com.jvspiano.sound.note.NoteInfo; | 3,490 | package com.jvspiano.sound.resolver;
/**
* ้ข็ดๆๆณ,ๅ้ณๅฎ็ฐ็ฑป
*/
public class AppoggiaturaResolverIMPL implements AppoggiaturaResolver {
/**
* ้ข็ดๆๆณ,ๅ้ณ็ๅฎ็ฐ,ๆญคๅคๅฎไนๅ้ณไธบไธๅไธๅ(ๅจ้ณไน้ขๅไธไธๅฎๆฏ่ฟๆ ท็,ๆฒก็ ็ฉถ่ฟ)
* @param noteFrontString ๅ้ณๅ่พน้ณ็ฌฆ
* @param noteAfterString ๅ้ณๅ่พน้ณ็ฌฆ
* @param noteStart ้ณ็ฌฆๅผๅง็ๆถ้ด,็ธๅฏนไบๆด้ฆๆฒๅญ
* @param myNoteIMPL ้ณ็ฌฆๆ ๅฐ็ฑป
* @param singleNoteResolver ๅไธช้ณ็ฌฆ่งฃๆๅจ
* @return ้ณ็ฌฆไฟกๆฏ็ๆฐ็ป
*/
@Override | package com.jvspiano.sound.resolver;
/**
* ้ข็ดๆๆณ,ๅ้ณๅฎ็ฐ็ฑป
*/
public class AppoggiaturaResolverIMPL implements AppoggiaturaResolver {
/**
* ้ข็ดๆๆณ,ๅ้ณ็ๅฎ็ฐ,ๆญคๅคๅฎไนๅ้ณไธบไธๅไธๅ(ๅจ้ณไน้ขๅไธไธๅฎๆฏ่ฟๆ ท็,ๆฒก็ ็ฉถ่ฟ)
* @param noteFrontString ๅ้ณๅ่พน้ณ็ฌฆ
* @param noteAfterString ๅ้ณๅ่พน้ณ็ฌฆ
* @param noteStart ้ณ็ฌฆๅผๅง็ๆถ้ด,็ธๅฏนไบๆด้ฆๆฒๅญ
* @param myNoteIMPL ้ณ็ฌฆๆ ๅฐ็ฑป
* @param singleNoteResolver ๅไธช้ณ็ฌฆ่งฃๆๅจ
* @return ้ณ็ฌฆไฟกๆฏ็ๆฐ็ป
*/
@Override | public NoteInfo[] appoggiatura(String noteFrontString, String noteAfterString, int noteStart, MyNoteIMPL myNoteIMPL, SingleNoteResolver singleNoteResolver) { | 0 | 2023-10-27 11:07:06+00:00 | 4k |
amithkoujalgi/ollama4j | src/main/java/io/github/amithkoujalgi/ollama4j/core/OllamaAPI.java | [
{
"identifier": "OllamaBaseException",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/exceptions/OllamaBaseException.java",
"snippet": "public class OllamaBaseException extends Exception {\n\n public OllamaBaseException(String s) {\n super(s);\n }\n}"
},
{
"identifier": "CustomModelFileContentsRequest",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/CustomModelFileContentsRequest.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class CustomModelFileContentsRequest {\n private String name;\n private String modelfile;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "CustomModelFilePathRequest",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/CustomModelFilePathRequest.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class CustomModelFilePathRequest {\n private String name;\n private String path;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "ModelEmbeddingsRequest",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/ModelEmbeddingsRequest.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class ModelEmbeddingsRequest {\n private String model;\n private String prompt;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "ModelRequest",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/ModelRequest.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class ModelRequest {\n private String name;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "Options",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/utils/Options.java",
"snippet": "@Data\npublic class Options {\n\n private final Map<String, Object> optionsMap;\n}"
},
{
"identifier": "Utils",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/utils/Utils.java",
"snippet": "public class Utils {\n public static ObjectMapper getObjectMapper() {\n return new ObjectMapper();\n }\n}"
}
] | import io.github.amithkoujalgi.ollama4j.core.exceptions.OllamaBaseException;
import io.github.amithkoujalgi.ollama4j.core.models.*;
import io.github.amithkoujalgi.ollama4j.core.models.request.CustomModelFileContentsRequest;
import io.github.amithkoujalgi.ollama4j.core.models.request.CustomModelFilePathRequest;
import io.github.amithkoujalgi.ollama4j.core.models.request.ModelEmbeddingsRequest;
import io.github.amithkoujalgi.ollama4j.core.models.request.ModelRequest;
import io.github.amithkoujalgi.ollama4j.core.utils.Options;
import io.github.amithkoujalgi.ollama4j.core.utils.Utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpConnectTimeoutException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 3,200 | getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 200) {
return Utils.getObjectMapper().readValue(responseBody, ModelDetail.class);
} else {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFilePath the path to model file that exists on the Ollama server.
*/
public void createModelWithFilePath(String modelName, String modelFilePath)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFilePathRequest(modelName, modelFilePath).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
// FIXME: Ollama API returns HTTP status code 200 for model creation failure cases. Correct this
// if the issue is fixed in the Ollama API server.
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFileContents the path to model file that exists on the Ollama server.
*/
public void createModelWithModelFileContents(String modelName, String modelFileContents)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFileContentsRequest(modelName, modelFileContents).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Delete a model from Ollama server.
*
* @param modelName the name of the model to be deleted.
* @param ignoreIfNotPresent ignore errors if the specified model is not present on Ollama server.
*/
public void deleteModel(String modelName, boolean ignoreIfNotPresent)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/delete";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.method("DELETE", HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 404 && responseBody.contains("model") && responseBody.contains("not found")) {
return;
}
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Generate embeddings for a given text from a model
*
* @param model name of model to generate embeddings from
* @param prompt text to generate embeddings for
* @return embeddings
*/
public List<Double> generateEmbeddings(String model, String prompt)
throws IOException, InterruptedException, OllamaBaseException {
URI uri = URI.create(this.host + "/api/embeddings"); | package io.github.amithkoujalgi.ollama4j.core;
/** The base Ollama API class. */
@SuppressWarnings("DuplicatedCode")
public class OllamaAPI {
private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class);
private final String host;
private long requestTimeoutSeconds = 3;
private boolean verbose = true;
private BasicAuth basicAuth;
/**
* Instantiates the Ollama API.
*
* @param host the host address of Ollama server
*/
public OllamaAPI(String host) {
if (host.endsWith("/")) {
this.host = host.substring(0, host.length() - 1);
} else {
this.host = host;
}
}
/**
* Set request timeout in seconds. Default is 3 seconds.
*
* @param requestTimeoutSeconds the request timeout in seconds
*/
public void setRequestTimeoutSeconds(long requestTimeoutSeconds) {
this.requestTimeoutSeconds = requestTimeoutSeconds;
}
/**
* Set/unset logging of responses
*
* @param verbose true/false
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* Set basic authentication for accessing Ollama server that's behind a reverse-proxy/gateway.
*
* @param username the username
* @param password the password
*/
public void setBasicAuth(String username, String password) {
this.basicAuth = new BasicAuth(username, password);
}
/**
* API to check the reachability of Ollama server.
*
* @return true if the server is reachable, false otherwise.
*/
public boolean ping() {
String url = this.host + "/api/tags";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = null;
try {
httpRequest =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.GET()
.build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
HttpResponse<String> response = null;
try {
response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
} catch (HttpConnectTimeoutException e) {
return false;
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
int statusCode = response.statusCode();
return statusCode == 200;
}
/**
* List available models from Ollama server.
*
* @return the list
*/
public List<Model> listModels()
throws OllamaBaseException, IOException, InterruptedException, URISyntaxException {
String url = this.host + "/api/tags";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.GET()
.build();
HttpResponse<String> response =
httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode == 200) {
return Utils.getObjectMapper()
.readValue(responseString, ListModelsResponse.class)
.getModels();
} else {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
}
/**
* Pull a model on the Ollama server from the list of <a
* href="https://ollama.ai/library">available models</a>.
*
* @param modelName the name of the model
*/
public void pullModel(String modelName)
throws OllamaBaseException, IOException, URISyntaxException, InterruptedException {
String url = this.host + "/api/pull";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<InputStream> response =
client.send(request, HttpResponse.BodyHandlers.ofInputStream());
int statusCode = response.statusCode();
InputStream responseBodyStream = response.body();
String responseString = "";
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
ModelPullResponse modelPullResponse =
Utils.getObjectMapper().readValue(line, ModelPullResponse.class);
if (verbose) {
logger.info(modelPullResponse.getStatus());
}
}
}
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
}
/**
* Gets model details from the Ollama server.
*
* @param modelName the model
* @return the model details
*/
public ModelDetail getModelDetails(String modelName)
throws IOException, OllamaBaseException, InterruptedException, URISyntaxException {
String url = this.host + "/api/show";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 200) {
return Utils.getObjectMapper().readValue(responseBody, ModelDetail.class);
} else {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFilePath the path to model file that exists on the Ollama server.
*/
public void createModelWithFilePath(String modelName, String modelFilePath)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFilePathRequest(modelName, modelFilePath).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
// FIXME: Ollama API returns HTTP status code 200 for model creation failure cases. Correct this
// if the issue is fixed in the Ollama API server.
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFileContents the path to model file that exists on the Ollama server.
*/
public void createModelWithModelFileContents(String modelName, String modelFileContents)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFileContentsRequest(modelName, modelFileContents).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Delete a model from Ollama server.
*
* @param modelName the name of the model to be deleted.
* @param ignoreIfNotPresent ignore errors if the specified model is not present on Ollama server.
*/
public void deleteModel(String modelName, boolean ignoreIfNotPresent)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/delete";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.method("DELETE", HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 404 && responseBody.contains("model") && responseBody.contains("not found")) {
return;
}
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Generate embeddings for a given text from a model
*
* @param model name of model to generate embeddings from
* @param prompt text to generate embeddings for
* @return embeddings
*/
public List<Double> generateEmbeddings(String model, String prompt)
throws IOException, InterruptedException, OllamaBaseException {
URI uri = URI.create(this.host + "/api/embeddings"); | String jsonData = new ModelEmbeddingsRequest(model, prompt).toString(); | 3 | 2023-10-26 19:12:14+00:00 | 4k |
rweisleder/archunit-spring | src/test/java/de/rweisleder/archunit/spring/SpringComponentRulesTest.java | [
{
"identifier": "ControllerWithDependencyToConfiguration",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithDependencyToConfiguration {\n @SuppressWarnings(\"unused\")\n public ControllerWithDependencyToConfiguration(ConfigurationWithoutDependency configuration) {\n }\n}"
},
{
"identifier": "ControllerWithDependencyToController",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithDependencyToController {\n @SuppressWarnings(\"unused\")\n public ControllerWithDependencyToController(ControllerWithoutDependency controller) {\n }\n}"
},
{
"identifier": "ControllerWithDependencyToRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithDependencyToRepository {\n @SuppressWarnings(\"unused\")\n public ControllerWithDependencyToRepository(RepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "ControllerWithDependencyToService",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithDependencyToService {\n @SuppressWarnings(\"unused\")\n public ControllerWithDependencyToService(ServiceWithoutDependency service) {\n }\n}"
},
{
"identifier": "ControllerWithDependencyToSpringDataRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithDependencyToSpringDataRepository {\n @SuppressWarnings(\"unused\")\n public ControllerWithDependencyToSpringDataRepository(SpringDataRepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "ControllerWithoutDependency",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithoutDependency {\n}"
},
{
"identifier": "RepositoryWithDependencyToConfiguration",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Repository\npublic static class RepositoryWithDependencyToConfiguration {\n @SuppressWarnings(\"unused\")\n public RepositoryWithDependencyToConfiguration(ConfigurationWithoutDependency configuration) {\n }\n}"
},
{
"identifier": "RepositoryWithDependencyToController",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Repository\npublic static class RepositoryWithDependencyToController {\n @SuppressWarnings(\"unused\")\n public RepositoryWithDependencyToController(ControllerWithoutDependency controller) {\n }\n}"
},
{
"identifier": "RepositoryWithDependencyToRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Repository\npublic static class RepositoryWithDependencyToRepository {\n @SuppressWarnings(\"unused\")\n public RepositoryWithDependencyToRepository(RepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "RepositoryWithDependencyToService",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Repository\npublic static class RepositoryWithDependencyToService {\n @SuppressWarnings(\"unused\")\n public RepositoryWithDependencyToService(ServiceWithoutDependency service) {\n }\n}"
},
{
"identifier": "RepositoryWithDependencyToSpringDataRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Repository\npublic static class RepositoryWithDependencyToSpringDataRepository {\n @SuppressWarnings(\"unused\")\n public RepositoryWithDependencyToSpringDataRepository(SpringDataRepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "RepositoryWithoutDependency",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Repository\npublic static class RepositoryWithoutDependency {\n}"
},
{
"identifier": "ServiceWithDependencyToConfiguration",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Service\npublic static class ServiceWithDependencyToConfiguration {\n @SuppressWarnings(\"unused\")\n public ServiceWithDependencyToConfiguration(ConfigurationWithoutDependency configuration) {\n }\n}"
},
{
"identifier": "ServiceWithDependencyToController",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Service\npublic static class ServiceWithDependencyToController {\n @SuppressWarnings(\"unused\")\n public ServiceWithDependencyToController(ControllerWithoutDependency controller) {\n }\n}"
},
{
"identifier": "ServiceWithDependencyToRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Service\npublic static class ServiceWithDependencyToRepository {\n @SuppressWarnings(\"unused\")\n public ServiceWithDependencyToRepository(RepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "ServiceWithDependencyToService",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Service\npublic static class ServiceWithDependencyToService {\n @SuppressWarnings(\"unused\")\n public ServiceWithDependencyToService(ServiceWithoutDependency service) {\n }\n}"
},
{
"identifier": "ServiceWithDependencyToSpringDataRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Service\npublic static class ServiceWithDependencyToSpringDataRepository {\n @SuppressWarnings(\"unused\")\n public ServiceWithDependencyToSpringDataRepository(SpringDataRepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "ServiceWithoutDependency",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Service\npublic static class ServiceWithoutDependency {\n}"
},
{
"identifier": "SpringDataRepositoryWithDependencyToConfiguration",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "public abstract static class SpringDataRepositoryWithDependencyToConfiguration implements CrudRepository<Object, Object> {\n @SuppressWarnings(\"unused\")\n public SpringDataRepositoryWithDependencyToConfiguration(ConfigurationWithoutDependency configuration) {\n }\n}"
},
{
"identifier": "SpringDataRepositoryWithDependencyToController",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "public abstract static class SpringDataRepositoryWithDependencyToController implements CrudRepository<Object, Object> {\n @SuppressWarnings(\"unused\")\n public SpringDataRepositoryWithDependencyToController(ControllerWithoutDependency controller) {\n }\n}"
},
{
"identifier": "SpringDataRepositoryWithDependencyToRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "public abstract static class SpringDataRepositoryWithDependencyToRepository implements CrudRepository<Object, Object> {\n @SuppressWarnings(\"unused\")\n public SpringDataRepositoryWithDependencyToRepository(RepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "SpringDataRepositoryWithDependencyToService",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "public abstract static class SpringDataRepositoryWithDependencyToService implements CrudRepository<Object, Object> {\n @SuppressWarnings(\"unused\")\n public SpringDataRepositoryWithDependencyToService(ServiceWithoutDependency service) {\n }\n}"
},
{
"identifier": "SpringDataRepositoryWithDependencyToSpringDataRepository",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "public abstract static class SpringDataRepositoryWithDependencyToSpringDataRepository implements CrudRepository<Object, Object> {\n @SuppressWarnings(\"unused\")\n public SpringDataRepositoryWithDependencyToSpringDataRepository(SpringDataRepositoryWithoutDependency repository) {\n }\n}"
},
{
"identifier": "SpringDataRepositoryWithoutDependency",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "public abstract static class SpringDataRepositoryWithoutDependency implements CrudRepository<Object, Object> {\n}"
},
{
"identifier": "importClasses",
"path": "src/test/java/de/rweisleder/archunit/spring/TestUtils.java",
"snippet": "public static JavaClasses importClasses(Class<?>... classes) {\n return new ClassFileImporter().importClasses(classes);\n}"
}
] | import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.lang.EvaluationResult;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithoutDependency;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithoutDependency;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithoutDependency;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithoutDependency;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static de.rweisleder.archunit.spring.TestUtils.importClasses;
import static org.assertj.core.api.Assertions.assertThat; | 3,028 | /*
* #%L
* ArchUnit Spring Integration
* %%
* Copyright (C) 2023 Roland Weisleder
* %%
* 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.
* #L%
*/
package de.rweisleder.archunit.spring;
@SuppressWarnings("CodeBlock2Expr")
class SpringComponentRulesTest {
@Nested
class Rule_DependenciesOfControllers {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfControllers.getDescription();
assertThat(description).isEqualTo("Spring controller should only depend on other Spring components that are services or repositories");
}
@Test
void controller_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_other_controller_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToController.class.getName());
});
}
@Test
void controller_with_dependency_to_service_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToService.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_configuration_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName());
});
}
}
@Nested
class Rule_DependenciesOfServices {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfServices.getDescription();
assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories");
}
@Test
void service_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ServiceWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void service_with_dependency_to_controller_is_a_violation() {
JavaClasses classes = importClasses(ServiceWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ServiceWithDependencyToController.class.getName());
});
}
@Test
void service_with_dependency_to_other_service_is_not_a_violation() { | /*
* #%L
* ArchUnit Spring Integration
* %%
* Copyright (C) 2023 Roland Weisleder
* %%
* 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.
* #L%
*/
package de.rweisleder.archunit.spring;
@SuppressWarnings("CodeBlock2Expr")
class SpringComponentRulesTest {
@Nested
class Rule_DependenciesOfControllers {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfControllers.getDescription();
assertThat(description).isEqualTo("Spring controller should only depend on other Spring components that are services or repositories");
}
@Test
void controller_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_other_controller_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToController.class.getName());
});
}
@Test
void controller_with_dependency_to_service_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToService.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_configuration_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName());
});
}
}
@Nested
class Rule_DependenciesOfServices {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfServices.getDescription();
assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories");
}
@Test
void service_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ServiceWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void service_with_dependency_to_controller_is_a_violation() {
JavaClasses classes = importClasses(ServiceWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ServiceWithDependencyToController.class.getName());
});
}
@Test
void service_with_dependency_to_other_service_is_not_a_violation() { | JavaClasses classes = importClasses(ServiceWithDependencyToService.class); | 15 | 2023-10-29 10:50:24+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.